content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
from flask import Flask, Request, jsonify, request
from src.driver import FirestoreDriverImpl
from src.interactor import SolverInteractor
from src.repository import RoomRepositoryImpl
from src.rest import BaseException, ClientException, SolverResource
solver_resource = SolverResource(
solver_usecase=SolverInteractor(
room_repository=RoomRepositoryImpl(
firestore_driver=FirestoreDriverImpl()
)
)
)
def solve(request: Request):
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600',
}
return '', 204, headers
headers = {'Access-Control-Allow-Origin': '*'}
try:
if "content-type" not in request.headers:
raise ClientException("Require HTTP header 'Content-Type'")
content_type = request.headers["content-type"]
if content_type == "application/json":
request_json = request.get_json(silent=True)
if request_json and "room_id" in request_json and "time_limit" in request_json:
room_id = request_json["room_id"]
time_limit = request_json["time_limit"]
c_weight = request_json["c_weight"] if "c_weight" in request_json else 3
timeout = request_json["timeout"] if "timeout" in request_json else 3000
num_unit_step = request_json["num_unit_step"] if "num_unit_step" in request_json else 10
else:
raise ClientException("JSON is invalid. Missing a 'room_id' or 'time_limit' property.")
else:
raise ClientException(f"Unknown content type: {content_type}")
return solver_resource.solve(room_id, time_limit, c_weight, timeout, num_unit_step), 200, headers
except BaseException as e:
return jsonify({"error": e.message}), e.code, headers
if __name__ == "__main__":
app = Flask(__name__)
@app.route("/setlist_solver", methods=["POST"])
def index():
return solve(request)
app.run("127.0.0.1", 8000, debug=True)
|
python
|
import netifaces
import time
from collections import namedtuple
from aplus import Promise
from openmtc_server.exc import InterfaceNotFoundException
from openmtc_server.transportdomain.NetworkManager import NetworkManager
Interface = namedtuple("Interface", ("name", "addresses", "hwaddress"))
Address = namedtuple("Address", ("address", "family"))
class GEventNetworkManager(NetworkManager):
def __init__(self, config, *args, **kw):
super(GEventNetworkManager, self).__init__(*args, **kw)
self._api = None
self.config = config
self.polling = True
self.logger.info("GEventNetworkManager loaded")
def initialize(self, api):
self._api = api
self.logger.info("GEventNetworkManager initialized")
self.start()
def start(self):
# self.api.register_connectivity_handler(self.connectivity_request)
self.polling = True
self._api.run_task(self.start_polling)
self.logger.info("GEventNetworkManager started")
def stop(self):
self.polling = False
self.logger.info("GEventNetworkManager stopped")
def connectivity_request(self):
"""Handles connectivity requests"""
# please note: normally we get an rcat argument, default: rcat=0
with Promise() as p:
blacklist = ['lo']
interfaces = netifaces.interfaces()
interface = next((x for x in interfaces if (x not in blacklist)),
None)
if interface is None:
p.reject(InterfaceNotFoundException(
"No interfaces found matching request"))
else:
p.fulfill((self._get_interface(interface), 0))
return p
def start_polling(self, timeout=1):
"""Poll netifaces information and check for differences, for as long as
self.polling == True.
:param timeout: Amount of time to wait between polling
"""
last_interfaces = cur_interfaces = netifaces.interfaces()
cur_interfaces_copy = list(cur_interfaces)
last_ifaddresses = {}
for iface in last_interfaces:
last_ifaddresses[iface] = netifaces.ifaddresses(iface)
self.logger.debug("polling started")
while self.polling:
try:
cur_interfaces = netifaces.interfaces()
cur_interfaces_copy = list(cur_interfaces)
intersection = set(last_interfaces) ^ set(cur_interfaces)
if len(intersection) > 0:
self.logger.debug("difference detected")
self.logger.debug("last interfaces: %s", last_interfaces)
self.logger.debug("current interfaces: %s", cur_interfaces)
for isetface in intersection:
if isetface in cur_interfaces:
# new interface
self.logger.debug("Firing %s event for %s",
"interface_created", isetface)
self._api.events.interface_created.fire(
self._create_interface(
isetface, netifaces.ifaddresses(isetface)))
else:
# removed interface
self.logger.debug("Firing %s event for %s",
"interface_removed", isetface)
self._api.events.interface_removed.fire(
self._create_interface(
isetface, last_ifaddresses[isetface]))
for iface in cur_interfaces:
cur_ifaddresses = netifaces.ifaddresses(iface)
if (iface in last_ifaddresses and
last_ifaddresses[iface] != cur_ifaddresses):
self._check_ifaddresses_diff(last_ifaddresses[iface],
cur_ifaddresses, iface)
last_ifaddresses[iface] = cur_ifaddresses
except Exception as e:
self.logger.exception("Something went wrong during polling: %s",
e)
finally:
# updating last stuff to current stuff
last_interfaces = cur_interfaces_copy
time.sleep(timeout)
self.logger.debug("polling done")
def get_interfaces(self):
"""Returns all known network interfaces
:return Promise([Interface]): a promise for a list of interfaces
"""
with Promise() as p:
interfaces = []
for iface in netifaces.interfaces():
interfaces.append(self._get_interface(iface))
# check if array has duplicates
# does this even work with namedtuple(s)?
# interfaces = list(set(interfaces))
p.fulfill(interfaces)
return p
def get_interface(self, name):
"""Returns an Interface object identified by name
:param name: name of interface
:return Promise(Interface): a promise for an interface
:raise InterfaceNotFoundException: if interface was not found
"""
with Promise() as p:
if name not in netifaces.interfaces():
p.reject(InterfaceNotFoundException("%s was not found" % name))
else:
p.fulfill(self._get_interface(name))
return p
def get_addresses(self, interface=None):
"""Get addresses of a given interface or all addresses if :interface: is
None
:param interface: name of interface
:return: Promise([Address]): a promise for a list of addresses
"""
with Promise() as p:
p.fulfill(self._get_addresses(interface))
return p
def _get_addresses_from_ifaddresses(self, ifaddresses):
"""Get addresses of a given interface
:param ifaddresses: raw addresses of interface (from netifaces)
:return: list of addresses
"""
addresses = []
for family in ifaddresses:
if family != netifaces.AF_LINK: # no hwaddr
for addr in ifaddresses[family]:
a = addr["addr"]
if family == netifaces.AF_INET6:
a = self._remove_ipv6_special_stuff(a)
addresses.append(
Address(address=a, family=family))
return addresses
def _get_addresses(self, iface=None):
"""Get addresses of a given interface
:param iface: name of interface
:return: list of addresses
"""
if iface is None:
interfaces = netifaces.interfaces()
else:
interfaces = [iface]
addresses = []
for interface in interfaces:
n_addresses = netifaces.ifaddresses(interface)
addresses += self._get_addresses_from_ifaddresses(n_addresses)
# check if array has duplicates
# addresses = list(set(addresses))
return addresses
def _create_interface(self, name, ifaddresses):
"""Create Interface tuple based on given interfaces addresses. (function
independent of netifaces)
:param name:
:param ifaddresses:
:return:
"""
addresses = self._get_addresses_from_ifaddresses(ifaddresses)
try:
hwaddress = ifaddresses[netifaces.AF_LINK][0]["addr"]
except (IndexError, KeyError):
self.logger.debug("No hardware address found for %s!", name)
hwaddress = None
return Interface(name=name,
addresses=addresses,
hwaddress=hwaddress)
def _get_interface(self, name):
"""Returns an Interface object identified by name
:param name: name of interface
:return Interface: interface
:raise UnknownInterface: if interface was not found
"""
if name not in netifaces.interfaces():
raise InterfaceNotFoundException("%s was not found" % name)
else:
ifaddresses = netifaces.ifaddresses(name)
addresses = self._get_addresses_from_ifaddresses(ifaddresses)
try:
hwaddress = ifaddresses[netifaces.AF_LINK][0]["addr"]
except (IndexError, KeyError):
self.logger.debug("No hardware address found for %s!", name)
hwaddress = None
return Interface(name=name,
addresses=addresses,
hwaddress=hwaddress)
def _check_ifaddresses_diff(self, lifaddr, cifaddr, iface):
"""parses last and current interface addresses of a given interface and
fires events for discovered differences
:param lifaddr: dict of family:addresses (last addresses)
:param cifaddr: dict of family:addresses (curr addresses)
:param iface: str name of interface (needed only to create interface for
event firing)
"""
self.logger.debug("checking difference of \r\n%s vs \r\n%s", lifaddr,
cifaddr)
intersection = set(lifaddr.keys()) ^ set(cifaddr.keys())
if len(intersection) > 0:
self.logger.debug(
"Sensing a change in address families of interface %s", iface)
# first check if new address family
self.logger.debug("Iterating through %s", intersection)
for isectkey in intersection:
if isectkey in cifaddr.keys():
for addr in cifaddr.get(isectkey, []):
self.logger.debug("Firing %s event for %s of %s",
"address_created", addr, iface)
a = Address(address=addr["addr"], family=isectkey)
self._api.events.address_created.fire(iface, a)
elif isectkey in lifaddr.keys():
for addr in lifaddr.get(isectkey, []):
self.logger.debug("Firing %s event for %s of %s",
"address_removed", addr, iface)
a = Address(address=addr["addr"], family=isectkey)
self._api.events.address_removed.fire(iface, a)
else:
for key in lifaddr.keys():
# check for removed addresses (contained only in lifaddr)
removed_addr = []
for laddr in lifaddr.get(key):
for caddr in cifaddr.get(key):
d = DictDiffer(caddr, laddr)
if len(d.changed()) == 0:
# this means both addresses are the same -> remove
# from removed_addr list
if laddr in removed_addr:
removed_addr.remove(laddr)
break
else:
# else add address to unknown/removed addresses
if laddr not in removed_addr:
removed_addr.append(laddr)
if len(removed_addr) > 0:
self.logger.debug("removed addresses found: %s",
removed_addr)
for raddr in removed_addr:
self.logger.debug("Firing %s event for %s of %s",
"address_removed", raddr, iface)
a = Address(address=raddr["addr"], family=key)
self._api.events.address_removed.fire(iface, a)
# now check for added addresses (contained only in cifaddr)
added_addr = []
for caddr in cifaddr.get(key):
for laddr in lifaddr.get(key):
d = DictDiffer(caddr, laddr)
if len(d.changed()) == 0:
# this means both addresses are the same -> remove
# from added_addr list
if caddr in added_addr:
added_addr.remove(caddr)
break
else:
# else add address to unknown/added addresses
if caddr not in added_addr:
added_addr.append(caddr)
if len(added_addr) > 0:
self.logger.debug("added addresses found: %s", added_addr)
for aaddr in added_addr:
self.logger.debug("Firing %s event for %s of %s",
"address_created", aaddr, iface)
a = Address(address=aaddr["addr"], family=key)
self._api.events.address_created.fire(iface, a)
@staticmethod
def _remove_ipv6_special_stuff(address):
return address.split("%")[0]
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(
past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if
self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if
self.past_dict[o] == self.current_dict[o])
|
python
|
import elasticsearch
import json
import click
from toolz import iterate, curry, take
from csv import DictReader
from elasticsearch.helpers import streaming_bulk
nuforc_report_index_name = 'nuforc'
nuforc_report_index_body = {
"mappings": {
"properties": {
"text": {
"type": "text"
},
"stats": {
"type": "text"
},
"date_time": {
"type": "date",
"format": "date_hour_minute_second",
"ignore_malformed": True
},
"report_link": {
"type": "text"
},
"city": {
"type": "keyword"
},
"state": {
"type": "keyword"
},
"shape": {
"type": "keyword"
},
"duration": {
"type": "text"
},
"summary": {
"type": "text"
},
"posted": {
"type": "date",
"format": "date_hour_minute_second",
"ignore_malformed": True
},
"city_latitude": {
"type": "float"
},
"city_longitude": {
"type": "float"
},
"location": {
"type": "geo_point"
}
}
}
}
def nuforc_bulk_action(doc, doc_id):
""" Binds a document / id to an action for use with the _bulk endpoint.
"""
return {
"_op_type": "index",
"_index": nuforc_report_index_name,
"_id": doc_id,
"_source": {
"location": {
"lat": float(doc["city_latitude"]),
"lon": float(doc["city_longitude"])
} if doc["city_latitude"] and doc["city_longitude"] else None,
**doc
}
}
@click.command()
@click.argument("report_file", type=click.File('r'))
def main(report_file):
""" Creates an Elasticsearch index for the NUFORC reports and loads the
processed CSV file into it.
"""
client = elasticsearch.Elasticsearch()
index_client = elasticsearch.client.IndicesClient(client)
# Drop the index if it exists; it will be replaced. This is the most efficient
# way to delete the data from an index according to ES documentation.
if index_client.exists(nuforc_report_index_name):
index_client.delete(nuforc_report_index_name)
# Create the index with the appropriate mapping.
index_client.create(nuforc_report_index_name, nuforc_report_index_body)
reports = DictReader(report_file)
# Zip the reports with an id generator, embedding them in the actions.
report_actions = map(nuforc_bulk_action, reports, iterate(lambda x: x+1, 0))
# Stream the reports into the ES database.
for ok,resp in elasticsearch.helpers.streaming_bulk(client, report_actions):
if not ok:
print(resp)
if __name__ == "__main__":
main()
|
python
|
import numpy as np
import sys
class RobotData:
"""
Stores sensor data at a particular frame
Attributes
----------
position : tuple
(x,y) tuple of the robot position
rotation : float
angle of robot heading clockwise relative to up (north)
forward_dir : tuple
(x,y) unit vector indicating the forward direction of the robot
right_dir : tuple
(x,y) unit vector indicating the right side direction of the robot
delta_time : float
timestep between current frame and the previous frame in seconds
sensor : int[]
radial distances from the robot from 0 to 360 deg with 1 deg steps
degrees are measured clockwise from the positive vertical axis
ex) sensor_array[90] gives the radial distance to any object located at
the right side of the robot
"""
def __init__(self, json_object):
self.position = np.fromiter(json_object["player_position"].values(), dtype = float)
#self.rotation = json_object["player_heading"]
#self.forward_dir = np.fromiter(json_object["player_forward"].values(), dtype = float)
#self.right_dir = np.fromiter(json_object["player_right"].values(), dtype = float)
self.object_sensor = self.formatObjectSensorData(json_object)
#self.delta_time = json_object["delta_time"]
#print(sys.getsizeof(self.object_sensor))
def position(self):
"""
Return the position of the player in the currently accessed data point.
"""
return self.position
def sensor(self, heading):
"""
Return the distance of any object in the specified angle from the forward direction of the user.
Parameters
----------
heading
n int
Angle representing line of sight measured clockwise from the positive vertical axis.
i.e. Given any rotation of the robot, 0 degrees refers to the positive vertical axis.
"""
# Round heading to nearest multiple of 5
canonical_angle = 5*round(heading/5)
canonical_angle = int(canonical_angle % 360 / 5)
return self.object_sensor[canonical_angle]
def __repr__(self):
return (f"Position: {self.position}\n")
#def formatObjectSensorData(self, json_object):
# detected_objects = json_object["object_sensor_data"]["detected_objects"]
# object_data = []
# for object in detected_objects:
# object_data += [GameObject(object)]
# return object_data
def formatObjectSensorData(self, json_object):
vector2_array = np.array(json_object["object_sensor_data"]["detected_objects"])
res = []
for object_info in vector2_array:
pos = np.fromiter(object_info['position'].values(), dtype=float)
name = object_info['name']
res += [GameObject(pos, name)]
return res
class GameObject():
def __init__(self, position, name):
# object_data_json has format
# {"position":{"x":0, "y":0}, "name": "example"}
# Convert {"x":x, "y":y} to and numpy array (x, y)
self.position = position
self.type = name
def __repr__(self):
return (f"(Position: {self.position}, "
f"Name: {self.type})\n")
|
python
|
from makeit.utilities.fastfilter_utilities import Highway_self, pos_ct, true_pos, real_pos, set_keras_backend
from makeit.utilities.fingerprinting import create_rxn_Morgan2FP_separately
from rdkit import Chem
from rdkit.Chem import AllChem, DataStructs
from makeit.interfaces.scorer import Scorer
import numpy as np
import csv
from pymongo import MongoClient
from tqdm import tqdm
from keras.models import load_model
from keras import backend as K
import makeit.global_config as gc
from makeit.utilities.io.logger import MyLogger
import os
fast_filter_loc = 'fast_filter'
class FastFilterScorer(Scorer):
def __init__(self):
self.model = None
def set_keras_backend(self, backend):
if K.backend() != backend:
os.environ['KERAS_BACKEND'] = backend
reload(K)
assert K.backend() == backend
def load(self, model_path):
MyLogger.print_and_log('Starting to load fast filter', fast_filter_loc)
self.model = load_model(model_path, custom_objects={
'Highway_self': Highway_self, 'pos_ct': pos_ct, 'true_pos': true_pos, 'real_pos': real_pos})
self.model._make_predict_function()
MyLogger.print_and_log('Done loading fast filter', fast_filter_loc)
def evaluate(self, reactant_smiles, target, **kwargs):
# Strip chirality
# rmol = Chem.MolFromSmiles(reactant_smiles)
# pmol = Chem.MolFromSmiles(target)
# reactant_smiles = Chem.MolToSmiles(rmol, False)
# target = Chem.MolToSmiles(pmol, False)
[pfp, rfp] = create_rxn_Morgan2FP_separately(
reactant_smiles, target, rxnfpsize=2048, pfpsize=2048, useFeatures=False)
pfp = np.asarray(pfp, dtype='float32')
rfp = np.asarray(rfp, dtype='float32')
rxnfp = pfp - rfp
score = self.model.predict(
[pfp.reshape(1, 2048), rxnfp.reshape(1, 2048)])
outcome = {'smiles': target,
'template_ids': [],
'num_examples': 0
}
all_outcomes = []
all_outcomes.append([{'rank': 1.0,
'outcome': outcome,
'score': float(score[0][0]),
'prob': float(score[0][0]),
}])
return all_outcomes
def filter_with_threshold(self, reactant_smiles, target, threshold):
[pfp, rfp] = create_rxn_Morgan2FP_separately(
reactant_smiles, target, rxnfpsize=2048, pfpsize=2048, useFeatures=False)
pfp = np.asarray(pfp, dtype='float32')
rfp = np.asarray(rfp, dtype='float32')
rxnfp = pfp - rfp
score = self.model.predict([pfp.reshape(1, 2048), rxnfp.reshape(1, 2048)])
filter_flag = (score > threshold)
return filter_flag, float(score)
if __name__ == "__main__":
ff = FastFilterScorer()
ff.load(model_path=gc.FAST_FILTER_MODEL['trained_model_path'])
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O=C[C@H](/C=C(/CO)\O)O.O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O[C@@H]1C(=O)[C@H]([C@@H]([C@H]1O)O)O.[H][H]')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'OC[C@@H](CC(C=O)(O)O)O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'OCO[C@@H]([C@H](CO)O)C=O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'OC[C@@H]1OC(=O)[C@H]([C@H]1O)O.[H][H]')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O=C[C@H](C[C@H](C(O)O)O)O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'OCC[C@@H](C(C=O)(O)O)O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O[C@H]1CC(=O)[C@H]([C@@H]1O)O.O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O[C@@H]([C@H](CO)O)OCC=O')
print(score)
score = ff.evaluate('OCC(C(C(C=O)O)O)O', 'O=CO[C@H]([C@@H](CO)O)CO')
print(score)
"""
flag, sco = ff.filter_with_threshold('CCO.CC(=O)O', 'CCOC(=O)C', 0.75)
print(flag)
print(sco)
"""
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from distutils.core import setup
import glob
from setuptools import setup
readme = open('README.md').read()
setup(
name='ReMoTE',
version='0.1',
description='Registration of Mobyle Tools in Elixir',
long_description=readme,
author='Hervé Ménager',
author_email='[email protected]',
url='https://github.com/bioinfo-center-pasteur-fr/ReMoTE.git',
packages=['remote'],
install_requires=[
'lxml','requests'
],
license="BSD",
entry_points={
'console_scripts': ['remote=remote:main'],
},
include_package_data=True,
zip_safe=False
)
|
python
|
class StateMachine:
"""A simple state machine"""
def __init__(self):
self.__states = {} #:dict[string] -> [(check, event, next)]
self.actions = {} #:dict[string] -> action
self.currentState = "start" #:string
self.addState("start")
def addState(self, name):
"""register a state name"""
if name not in self.__states:
self.__states[name] = []
def addTransition(self, fromState, toState, condition, event):
transition = (condition, event, toState)
self.__states[fromState].append(transition)
def update(self):
"""Update the state machine"""
transitions = self.__states[self.currentState]
for (check, event, nextState) in transitions:
if check():
self.currentState = nextState
print "sm new state: ", nextState
event()
action = self.actions.get(self.currentState)
if action is not None:
action()
|
python
|
import numpy as np
def meshTensor(value):
"""**meshTensor** takes a list of numbers and tuples
that have the form::
mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ]
For example, a time domain mesh code needs
many time steps at one time::
[(1e-5, 30), (1e-4, 30), 1e-3]
Means take 30 steps at 1e-5 and then 30 more at 1e-4,
and then one step of 1e-3.
Tensor meshes can also be created by increase factors::
[(10.0, 5, -1.3), (10.0, 50), (10.0, 5, 1.3)]
When there is a third number in the tuple, it
refers to the increase factor, if this number
is negative this section of the tensor is flipped right-to-left.
"""
if type(value) is not list:
raise Exception('meshTensor must be a list of scalars and tuples.')
proposed = []
for v in value:
if np.isscalar(v):
proposed += [float(v)]
elif type(v) is tuple and len(v) == 2:
proposed += [float(v[0])]*int(v[1])
elif type(v) is tuple and len(v) == 3:
start = float(v[0])
num = int(v[1])
factor = float(v[2])
pad = ((np.ones(num)*np.abs(factor))**(np.arange(num)+1))*start
if factor < 0: pad = pad[::-1]
proposed += pad.tolist()
else:
raise Exception('meshTensor must contain only scalars and len(2) or len(3) tuples.')
return np.array(proposed)
|
python
|
import numpy
C_3 = numpy.array([1, 2]) / 3
a_3 = numpy.array([[3, -1], [1, 1]]) / 2
sigma_3 = numpy.array([[[1, 0], [-2, 1]], [[1, 0], [-2, 1]]])
C_5 = numpy.array([1, 6, 3]) / 10
a_5 = numpy.array([[11, -7, 2], [2, 5, -1], [-1, 5, 2]]) / 6
sigma_5 = numpy.array([[[40, 0, 0],
[-124, 100, 0],
[44, -76, 16] ],
[[16, 0, 0],
[-52, 52, 0],
[20, -52, 16] ],
[[16, 0, 0],
[-76, 44, 0],
[100, -124, 40] ] ]) / 12
C_all = { 2 : C_3,
3 : C_5 }
a_all = { 2 : a_3,
3 : a_5 }
sigma_all = { 2 : sigma_3,
3 : sigma_5 }
def weno3_upwind(q):
order = 2
epsilon = 1e-16
alpha = numpy.zeros(order)
beta = numpy.zeros(order)
q_stencils = numpy.zeros(order)
for k in range(order):
for l in range(order):
for m in range(l):
beta[k] += sigma_3[k, l, m] * q[1 + k - l] * q[1 + k - m]
alpha[k] = C_3[k] / (epsilon + beta[k]**2)
for l in range(order):
q_stencils[k] += a_3[k, l] * q[1 + k - l]
w = alpha / numpy.sum(alpha)
return numpy.dot(w, q_stencils)
def weno3(q, simulation):
Nvars, Npoints = q.shape
q_minus = numpy.zeros_like(q)
q_plus = numpy.zeros_like(q)
for i in range(2, Npoints-2):
for Nv in range(Nvars):
q_plus [Nv, i] = weno3_upwind(q[Nv, i-1:i+2])
q_minus[Nv, i] = weno3_upwind(q[Nv, i+1:i-2:-1])
return q_minus, q_plus
def weno5_upwind(q):
order = 3
epsilon = 1e-16
alpha = numpy.zeros(order)
beta = numpy.zeros(order)
q_stencils = numpy.zeros(order)
for k in range(order):
for l in range(order):
for m in range(l):
beta[k] += sigma_5[k, l, m] * q[2 + k - l] * q[2 + k - m]
alpha[k] = C_5[k] / (epsilon + beta[k]**2)
for l in range(order):
q_stencils[k] += a_5[k, l] * q[2 + k - l]
w = alpha / numpy.sum(alpha)
return numpy.dot(w, q_stencils)
def weno5(q, simulation):
Nvars, Npoints = q.shape
q_minus = numpy.zeros_like(q)
q_plus = numpy.zeros_like(q)
for i in range(3, Npoints-3):
for Nv in range(Nvars):
q_plus [Nv, i] = weno5_upwind(q[Nv, i-2:i+3])
q_minus[Nv, i] = weno5_upwind(q[Nv, i+2:i-3:-1])
return q_minus, q_plus
def weno_upwind(q, order):
a = a_all[order]
C = C_all[order]
sigma = sigma_all[order]
epsilon = 1e-16
alpha = numpy.zeros(order)
beta = numpy.zeros(order)
q_stencils = numpy.zeros(order)
for k in range(order):
for l in range(order):
for m in range(l):
beta[k] += sigma[k, l, m] * q[order-1+k-l] * q[order-1+k-m]
alpha[k] = C[k] / (epsilon + beta[k]**2)
for l in range(order):
q_stencils[k] += a[k, l] * q[order-1+k-l]
w = alpha / numpy.sum(alpha)
return numpy.dot(w, q_stencils)
def weno(q, simulation, order):
Nvars, Npoints = q.shape
q_minus = numpy.zeros_like(q)
q_plus = numpy.zeros_like(q)
for i in range(order, Npoints-order):
for Nv in range(Nvars):
q_plus [Nv, i] = weno_upwind(q[Nv, i+1-order:i+order], order)
q_minus[Nv, i] = weno_upwind(q[Nv, i+order-1:i-order:-1], order)
return q_minus, q_plus
|
python
|
from bs4 import BeautifulSoup
import urllib, requests, re
import json
import datetime
from datetime import date
def cnt1():
year=datetime.datetime.now().year
month=datetime.datetime.now().month
month=str(month)
day=datetime.datetime.now().day
if len(str(month)) == 1 :
month="0"+str(month)
fanta=str(year)+str(month)+str(day)
url="http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19SidoInfStateJson?serviceKey=JGMlPMEcTuNV8sbu5JRfjhwjPXMdCv1OJ1qQefm0vVuKWGKtGHAcJEWtm63GOVyMQYAcI%2BoXUBe0nsJ4w3RiZw%3D%3D&pageNo=1&numOfRows=10&startCreateDt="+fanta+"&endCreateDt="+fanta #call back url
test_url="http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19SidoInfStateJson?serviceKey=JGMlPMEcTuNV8sbu5JRfjhwjPXMdCv1OJ1qQefm0vVuKWGKtGHAcJEWtm63GOVyMQYAcI%2BoXUBe0nsJ4w3RiZw%3D%3D&pageNo=1&numOfRows=10&startCreateDt=20200821&endCreateDt=20200821"
print(url)
cola=requests.get(url).text
sida=BeautifulSoup(cola, "html.parser")
items=sida.find("items")
result = [0, 0, 0]
for item in items :
try:
hapgae=item.find("gubun").string
except:
continue
if hapgae == "합계" :
try:
incdec=item.find("incdec").string
result[0]=incdec
except:
pass
if hapgae == "부산" :
try:
incdec=item.find("incdec").string
result[1]=incdec
except:
pass
if hapgae == "합계" :
try:
deathcnt=item.find("deathcnt").string
result[2]=deathcnt
except:
pass
return result
def cnt2():
year=datetime.datetime.now().year
month=datetime.datetime.now().month
month=str(month)
day=datetime.datetime.now().day
if len(str(month)) == 1 :
month="0"+str(month)
fanta=str(year)+str(month)+str(day)
if (day == 1):
fanta1 = str(year)+str(month)+"28"
else:
fanta1 = str(year)+str(month)+str(int(day)-1)
url="http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=0XeO7nbthbiRoMUkYGGah20%2BfXizwc0A6BfjrkL6qhh2%2Fsl8j9PzfSLGKnqR%2F1v%2F%2B6AunxntpLfoB3Ryd3OInQ%3D%3D&pageNo=1&numOfRows=10&startCreateDt="+fanta1+"&endCreateDt="+fanta #call back url
test_url="http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=0XeO7nbthbiRoMUkYGGah20%2BfXizwc0A6BfjrkL6qhh2%2Fsl8j9PzfSLGKnqR%2F1v%2F%2B6AunxntpLfoB3Ryd3OInQ%3D%3D&pageNo=1&numOfRows=10&startCreateDt=20200821&endCreateDt=20200822"
cola=requests.get(url).text
sida=BeautifulSoup(cola, "html.parser")
items=sida.find("items")
result = [0, 0, 0]
for item in items :
try:
decidecnt=item.find("decidecnt").string
result[0]=decidecnt
except:
pass
try:
clearcnt=item.find("clearcnt").string
result[1]=clearcnt
except:
pass
try:
deathcnt=item.find("deathcnt").string
result[2]=deathcnt
except:
pass
return result
if __name__ == "__main__":
print(cnt1())
print(cnt2())
|
python
|
"""Time
Calculate the time of a code to run.
Code example: product of the first 100.000 numbers.
"""
import time
def product():
p = 1
for i in range(1, 100000):
p = p * i
return p
start = time.time()
prod = product()
end = time.time()
print('The result is %s digits long.' % len(str(prod)))
print('Took %s seconds to calculate.' % (end - start))
# The result is 456569 digits long.
# Took 3.54418683052063 seconds to calculate.
|
python
|
from roboclaw import Roboclaw
from time import sleep
rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address=0x80
#rc.ForwardM1(address, 50)
# sleep (5)
rc.ForwardM1(address, 0)
|
python
|
from pathlib import Path
from typing import Optional
import config # type: ignore
import hvac
from aiohttp_micro import AppConfig as BaseConfig # type: ignore
from config.abc import Field
from passport.client import PassportConfig
class StorageConfig(config.PostgresConfig):
host = config.StrField(default="localhost", env="POSTGRES_HOST")
port = config.IntField(default=5432, env="POSTGRES_PORT")
user = config.StrField(default="postgres", vault_path="micro/wallet/postgres:user", env="POSTGRES_USER")
password = config.StrField(default="postgres", vault_path="micro/wallet/postgres:password", env="POSTGRES_PASSWORD")
database = config.StrField(default="postgres", env="POSTGRES_DATABASE")
min_pool_size = config.IntField(default=1, env="POSTGRES_MIN_POOL_SIZE")
max_pool_size = config.IntField(default=2, env="POSTGRES_MAX_POOL_SIZE")
@property
def uri(self) -> str:
return "postgresql://{user}:{password}@{host}:{port}/{database}".format(
user=self.user, password=self.password, host=self.host, port=self.port, database=self.database,
)
class AppConfig(BaseConfig):
db = config.NestedField[StorageConfig](StorageConfig)
passport = config.NestedField[PassportConfig](PassportConfig)
sentry_dsn = config.StrField(vault_path="micro/wallet/sentry:dsn", env="SENTRY_DSN")
class VaultConfig(config.Config):
enabled = config.BoolField(default=False, env="VAULT_ENABLED")
host = config.StrField(env="VAULT_HOST")
auth_method = config.StrField(default="approle", env="VAULT_AUTH_METHOD")
service_name = config.StrField(default=None, env="VAULT_SERVICE_NAME")
role_id = config.StrField(default=None, env="VAULT_ROLE_ID")
secret_id = config.StrField(default=None, env="VAULT_SECRET_ID")
class VaultProvider(config.ValueProvider):
def __init__(self, config: VaultConfig, mount_point: str) -> None:
self.client = hvac.Client(url=config.host)
self.mount_point = mount_point
if config.auth_method == "approle":
self.client.auth.approle.login(role_id=config.role_id, secret_id=config.secret_id)
elif config.auth_method == "kubernetes":
path = Path("/var/run/secrets/kubernetes.io/serviceaccount/token")
with path.open("r") as fp:
token = fp.read()
self.client.auth.kubernetes.login(role=config.service_name, jwt=token)
def load(self, field: Field) -> Optional[str]:
value = None
if field.vault_path:
path, key = field.vault_path, None
if ":" in field.vault_path:
path, key = field.vault_path.split(":")
secret_response = self.client.secrets.kv.v2.read_secret_version(path=path, mount_point=self.mount_point)
if key:
value = secret_response["data"]["data"][key]
return value
|
python
|
import uuid
from operator import attrgetter
from typing import List
from confluent_kafka import Consumer, TopicPartition
from confluent_kafka.admin import AdminClient, TopicMetadata
from kaskade.config import Config
from kaskade.kafka import TIMEOUT
from kaskade.kafka.group_service import GroupService
from kaskade.kafka.mappers import metadata_to_partition, metadata_to_topic
from kaskade.kafka.models import Topic
class TopicService:
def __init__(self, config: Config) -> None:
if config is None or config.kafka is None:
raise Exception("Config not found")
self.config = config
def list(self) -> List[Topic]:
config = self.config.kafka.copy()
config["group.id"] = str(uuid.uuid4())
consumer = Consumer(config)
admin_client = AdminClient(self.config.kafka)
groups_service = GroupService(self.config)
raw_topics: List[TopicMetadata] = list(
admin_client.list_topics(timeout=TIMEOUT).topics.values()
)
topics = []
for raw_topic in raw_topics:
topic = metadata_to_topic(raw_topic)
topics.append(topic)
topic.groups = groups_service.find_by_topic_name(topic.name)
topic.partitions = []
for raw_partition in raw_topic.partitions.values():
partition = metadata_to_partition(raw_partition)
topic.partitions.append(partition)
low, high = consumer.get_watermark_offsets(
TopicPartition(topic.name, raw_partition.id),
timeout=TIMEOUT,
cached=False,
)
partition.low = low
partition.high = high
return sorted(topics, key=attrgetter("name"))
if __name__ == "__main__":
config = Config("../../kaskade.yml")
topic_service = TopicService(config)
topic_list = topic_service.list()
print(topic_list)
|
python
|
#!/usr/bin/env python
from __future__ import print_function, division
import os
import sys
sys.path.append(os.path.dirname(sys.path[0]))
try:
import cPickle as pickle # python 2
except ImportError:
import pickle # python 3
import socket
import argparse
from random import randint
from numpy import unravel_index, log, maximum
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.widgets import Slider
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from cryoio import mrc
from geometry import gen_dense_beamstop_mask
from notimplemented import correlation
def plot_projs(mrcs_files, log_scale=True, plot_randomly=True):
for mrcs in mrcs_files:
image_stack = mrc.readMRCimgs(mrcs, 0)
size = image_stack.shape
N = size[0]
mask = gen_dense_beamstop_mask(N, 2, 0.003, psize=9)
print('image size: {0}x{1}, number of images: {2}'.format(*size))
print('Select indices randomly:', plot_randomly)
fig, axes = plt.subplots(3, 3, figsize=(12.9, 9.6))
for i, ax in enumerate(axes.flat):
row, col = unravel_index(i, (3, 3))
if plot_randomly:
num = randint(0, size[2])
else:
num = i
print('index:', num)
if log_scale:
img = log(maximum(image_stack[:, :, num], 1e-6)) * mask
else:
img = image_stack[:, :, num] * mask
im = ax.imshow(img, origin='lower') # cmap='Greys'
ticks = [0, int(N/4.0), int(N/2.0), int(N*3.0/4.0), int(N-1)]
if row == 2:
ax.set_xticks([])
else:
ax.set_xticks(ticks)
if col == 0:
ax.set_yticks([])
else:
ax.set_yticks(ticks)
fig.subplots_adjust(right=0.8)
cbarar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbarar_ax)
fig.suptitle('{} before normalization'.format(mrcs))
# fig.tight_layout()
plt.show()
def plot_projs_with_slider(mrcs_files, log_scale=True, show_ac_image=False):
for mrcs in mrcs_files:
image_stack = mrc.readMRCimgs(mrcs, 0)
size = image_stack.shape
N = size[0]
mask = gen_dense_beamstop_mask(N, 2, 0.003, psize=9)
print('image size: {0}x{1}, number of images: {2}'.format(*size))
# plot projections
fig = plt.figure(figsize=(8, 8))
gs = GridSpec(2, 2, width_ratios=[1, 0.075], height_ratios=[1, 0.075], )
# original
ax = fig.add_subplot(gs[0, 0])
curr_img = image_stack[:, :, 0] * mask
if show_ac_image:
curr_ac_img = correlation.calc_full_ac(curr_img, 0.95) * mask
curr_img = curr_ac_img
if log_scale:
curr_img = log(curr_img)
im = ax.imshow(curr_img, origin='lower')
ticks = [0, int(N/4.0), int(N/2.0), int(N/4.0*3), int(N-1)]
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_title('Slice Viewer (log scale: {}) for {}'.format(log_scale, os.path.basename(mrcs)))
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="7%", pad="2%")
cbar = fig.colorbar(im, cax=cax) # colorbar
# slider
ax_slider = fig.add_subplot(gs[1, 0])
idx_slider = Slider(ax_slider, 'index:', 0, size[2]-1, valinit=0, valfmt='%d')
def update(val):
idx = int(idx_slider.val)
curr_img = image_stack[:, :, idx] * mask
if show_ac_image:
curr_ac_img = correlation.calc_full_ac(curr_img, 0.95) * mask
curr_img = curr_ac_img
if log_scale:
curr_img = log(curr_img)
im.set_data(curr_img)
cbar.set_clim(vmin=curr_img.min(), vmax=curr_img.max())
cbar.draw_all()
fig.canvas.draw_idle()
idx_slider.on_changed(update)
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("mrcs_files", help="list of mrcs files.", nargs='+')
parser.add_argument("-l", "--log_scale", help="show image in log scale.",
action="store_true")
parser.add_argument("-r", "--plot_randomly", help="plot image with random index.",
action="store_true")
parser.add_argument("-a", "--show_ac_image", help="plot image with angular correlation.",
action="store_true")
args = parser.parse_args()
log_scale = args.log_scale
mrcs_files = args.mrcs_files
plot_randomly = args.plot_randomly
show_ac_image = args.show_ac_image
print('mrcs_files:', mrcs_files)
print('log_scale:', log_scale)
print('plot_randomly:', plot_randomly)
print('show_ac_image', show_ac_image)
if plot_randomly:
plot_projs(mrcs_files, log_scale=log_scale)
else:
plot_projs_with_slider(
mrcs_files, log_scale=log_scale, show_ac_image=show_ac_image)
|
python
|
from highton.models import Party
from highton.highton_constants import HightonConstants
class AssociatedParty(
Party,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar author_id: fields.IntegerField(name=HightonConstants.AUTHOR_ID)
:ivar background: fields.StringField(name=HightonConstants.BACKGROUND)
:ivar company_id: fields.IntegerField(name=HightonConstants.COMPANY_ID)
:ivar created_at: fields.DatetimeField(name=HightonConstants.CREATED_AT)
:ivar first_name: fields.StringField(name=HightonConstants.FIRST_NAME)
:ivar name: fields.StringField(name=HightonConstants.NAME)
:ivar group_id: fields.IntegerField(name=HightonConstants.GROUP_ID)
:ivar last_name: fields.StringField(name=HightonConstants.LAST_NAME)
:ivar owner_id: fields.IntegerField(name=HightonConstants.OWNER_ID)
:ivar title: fields.StringField(name=HightonConstants.TITLE)
:ivar updated_at: fields.DatetimeField(name=HightonConstants.UPDATED_AT)
:ivar visible_to: fields.StringField(name=HightonConstants.VISIBLE_TO)
:ivar company_name: fields.StringField(name=HightonConstants.COMPANY_NAME)
:ivar linkedin_url: fields.StringField(name=HightonConstants.LINKEDIN_URL)
:ivar avatar_url: fields.StringField(name=HightonConstants.AVATAR_URL)
:ivar type: fields.StringField(name=HightonConstants.TYPE)
:ivar tags: fields.ListField(name=HightonConstants.TAGS, init_class=Tag)
:ivar contact_data: fields.ObjectField(name=HightonConstants.CONTACT_DATA, init_class=ContactData)
:ivar subject_datas: fields.ListField(name=HightonConstants.SUBJECT_DATAS, init_class=SubjectData)
"""
TAG_NAME = HightonConstants.ASSOCIATED_PARTY
|
python
|
import unittest
from column import *
class ColumnTest(unittest.TestCase):
def test_polar2coord(self):
# test55
self.assertEqual(polar2coord( (46, 2.808) ), (1.9506007042488642, -2.019906159350932) )
self.assertEqual(polar2coord( (196, 1.194) ), (-1.1477464649503528, 0.32911100284549705) )
self.assertEqual(polar2coord( (89, 1.762) ), (0.030751140142492875, -1.7617316388655615) )
self.assertEqual(polar2coord( (269, 1.21) ), (-0.021117411789113007, 1.2098157111392334) )
def test_col_dist(self):
self.assertAlmostEqual(col_dist( (89, 1.762), (269, 1.21) ), 2.972)
self.assertAlmostEqual(col_dist( (46, 2.808), (196, 1.194) ), 3.888, 3) # hmmm, probably bug??
def test_analyse_pose(self):
p = analyse_pose(prev_pose=None, new_data=[(89, 1.762), (269, 1.21)])
self.assertEqual(p[0], (2.6194324487249787e-16, 0.2760000000000001, -0.017453292519943098))
# select best matching pair
p = analyse_pose(None, [(46, 2.8080000000000003), (169, 5.9500000000000002), (196, 1.194)])
self.assertEqual(p[0], (0.43115108250453843, 0.8306320134455586, -0.922098513045361))
if __name__ == "__main__":
unittest.main()
# vim: expandtab sw=4 ts=4
|
python
|
from helpers import *
import shutil
league_info_file = 'league_info.json'
ros_URL = 'https://5ahmbwl5qg.execute-api.us-east-1.amazonaws.com/dev/rankings'
def_expert = 'subvertadown'
kick_expert = 'subvertadown'
weekly_method = 'borischen'
yaml_config_temp = '_config_template.yml'
output_file = 'summary.txt'
yaml_config = '_config.yml'
league_info = parse_league_info(league_info_file)
# ros_ranks,ros_ranked_dudes = parse_ros_ranks(ros_file)
ros_ranked_dudes,ros_ranks = get_ros_stuff(ros_URL)
# def_rank = parse_simple_file(def_file)
# kick_rank = parse_simple_file(kick_file)
def_rank = get_reddit_expert_rank(def_expert,'DEF')
kick_rank = get_reddit_expert_rank(kick_expert,'K')
summary = []
shutil.copy(yaml_config_temp,yaml_config)
for l in league_info:
my_dudes,my_pos,rostered_dudes,my_def,rostered_def,my_kick,rostered_kick,starters = get_dudes(l)
my_ros_dudes,my_ros_ranks,unowned_ros_dudes,unowned_ros_ranks = get_ranks(my_dudes, rostered_dudes, ros_ranked_dudes, ros_ranks)
stream_def_advice = get_stream(my_def,rostered_def,def_rank)
stream_kick_advice = get_stream(my_kick,rostered_kick,kick_rank)
weekly_team,weekly_tiers,potential_stream_names,potential_stream_pos,potential_stream_tiers = get_weekly(my_dudes,rostered_dudes,weekly_method)
txt = get_summary_text(l,my_ros_dudes,my_ros_ranks,unowned_ros_dudes,unowned_ros_ranks,stream_def_advice,stream_kick_advice,weekly_team,weekly_tiers,potential_stream_names,potential_stream_pos,potential_stream_tiers,starters)
summary.extend(txt)
md_file = write_league_md(l,my_ros_dudes,my_ros_ranks,unowned_ros_dudes,unowned_ros_ranks,stream_def_advice,stream_kick_advice,weekly_team,weekly_tiers,potential_stream_names,potential_stream_pos,potential_stream_tiers,starters)
with open(yaml_config, 'a') as f:
f.writelines([' - title: ' + l['nickname'] + '\n',' url: ' + md_file + '\n'])
with open(output_file,'w') as f:
f.writelines(summary)
print('Done')
|
python
|
import re
from typing import List
import pytest
from ja_timex.pattern.place import Pattern
from ja_timex.tag import TIMEX
from ja_timex.tagger import BaseTagger
from ja_timex.timex import TimexParser
@pytest.fixture(scope="module")
def p():
# Custom Taggerで必要となる要素と、TimexParserの指定
def parse_kouki(re_match: re.Match, pattern: Pattern) -> TIMEX:
args = re_match.groupdict()
span = re_match.span()
year = int(args["calendar_year"]) - 660
return TIMEX(
type="DATE",
value=f"{year}-XX-XX",
text=re_match.group(),
mod=pattern.option.get("mod"),
parsed=args,
span=span,
pattern=pattern,
)
custom_pattern = [
Pattern(
re_pattern="皇紀(?P<calendar_year>[0-9]{1,4})年",
parse_func=parse_kouki,
option={},
)
]
class CustomTagger(BaseTagger):
def __init__(self, patterns: List[Pattern] = custom_pattern) -> None:
self.patterns = patterns
return TimexParser(custom_tagger=CustomTagger())
def test_custom_tagger_kouki(p):
# Custom Taggerあり
timexes = p.parse("西暦2021年は皇紀2681年です")
assert len(timexes) == 2
assert timexes[0].value == "2021-XX-XX"
assert timexes[0].text == "西暦2021年"
assert timexes[1].value == "2021-XX-XX"
assert timexes[1].text == "皇紀2681年"
assert timexes[1].parsed == {"calendar_year": "2681"}
def test_without_custom_tagger():
# Custom Taggerなし
p = TimexParser()
timexes = p.parse("西暦2021年は皇紀2681年です")
assert len(timexes) == 2
assert timexes[0].value == "2021-XX-XX"
assert timexes[0].text == "西暦2021年"
# そのまま2681年と解釈される
assert timexes[1].value == "2681-XX-XX"
assert timexes[1].text == "2681年"
assert timexes[1].parsed == {"calendar_day": "XX", "calendar_month": "XX", "calendar_year": "2681"}
|
python
|
from patternpieces import PatternPieces
from piece import Piece
from piecesbank import PiecesBank
from ui import UI
from board import Board
from arbiter import Arbiter
from ai import Ai
import json
import random
def main():
pb = PiecesBank()
app = UI()
### DO NOT FUCKING REMOVE THIS. I DARE YOU. ###
app.preloadPieces(pb.pieceslist)
ai = Ai()
arbiter = Arbiter()
board = Board()
app.setBatchMethod(lambda loop, fitness, mutation: ai.main_function(pb, app, arbiter, board, loop, fitness, mutation))
# app.drawTable(board)
app.drawTable(generatedSolvedPuzzle(pb))
### DO NOT FUCKING REMOVE THIS EITHER. ###
app.mainloop()
def generatedSolvedPuzzle(pb):
ret = Board()
for y in range(16):
for x in range(16):
ret[x, y] = pb.pieceslist[x + y * 16]
if (y != 0):
if (y % 2 == 0):
ret[x, y].upEdge = PatternPieces.YELLOWFLOWERINBLUE
else:
ret[x, y].upEdge = PatternPieces.BLUESTARINYELLOW
else:
ret[x, y].upEdge = PatternPieces.EDGE
if (x != 15):
if (x % 2 == 0):
ret[x, y].rightEdge = PatternPieces.BLUEGEARINPINK
else:
ret[x, y].rightEdge = PatternPieces.YELLOWSTARINPURPLE
else:
ret[x, y].rightEdge = PatternPieces.EDGE
if (y != 15):
if (y % 2 == 1):
ret[x, y].downEdge = PatternPieces.YELLOWFLOWERINBLUE
else:
ret[x, y].downEdge = PatternPieces.BLUESTARINYELLOW
else:
ret[x, y].downEdge = PatternPieces.EDGE
if (x != 0):
if (x % 2 == 1):
ret[x, y].leftEdge = PatternPieces.BLUEGEARINPINK
else:
ret[x, y].leftEdge = PatternPieces.YELLOWSTARINPURPLE
else:
ret[x, y].leftEdge = PatternPieces.EDGE
return ret
if __name__ == '__main__':
main()
|
python
|
import re
import wrapt
from .bash import CommandBlock
class ConfigurationError(Exception):
pass
def add_comment(action):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
def _execute(*args, **kwargs):
return CommandBlock() + '' + 'echo "{} {}"'.format(action, instance.description) + wrapped(*args, **kwargs)
return _execute(*args, **kwargs)
return wrapper
class Entity:
__shortname = 'x'
def __init__(self):
self.links = []
def add_to(self, master):
master.entities.append(self)
return self # chaining ;)
@property
def endpoints(self):
endpoints = []
for l in self.links:
if l.e1.entity == self:
endpoints.append(l.e1)
if l.e2.entity == self:
endpoints.append(l.e2)
return endpoints
@add_comment('creating')
def create(self):
self.check_configuration()
return CommandBlock()
@add_comment('configuring')
def configure(self):
return CommandBlock()
@add_comment('destroying')
def destroy(self):
return CommandBlock()
def check_configuration(self):
if self.name is None:
raise ConfigurationError("name is missing")
@property
def entity_type_name(self):
hierarchy = []
ccls = self.__class__
while ccls is not object:
try:
hierarchy.append(getattr(ccls, '_' + ccls.__name__ + '__shortname'))
except AttributeError:
pass
ccls = ccls.__bases__[0]
return '-'.join(reversed(hierarchy))
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
try:
self.name_id = re.search(r'(\d+)$', self.__name).group()
except:
self.name_id = None
@property
def description(self):
return self.name
def __str__(self):
return self.description
def __repr__(self):
return self.__str__()
class Netns(Entity):
__shortname = 'ns'
def __init__(self, name=None):
super().__init__()
self.name = name
self.routes = []
self.configure_commands = []
def add_route(self, destination, endpoint):
self.routes.append((destination, endpoint))
def add_configure_command(self, command, inside_ns=True):
if inside_ns:
self.configure_commands.append("ip netns exec {self.name} " + command)
else:
self.configure_commands.append(command)
def create(self):
return super().create() + "ip netns add {self.name}".format(self=self)
def configure(self):
cmds = CommandBlock()
for r in self.routes:
cmds += "ip netns exec {self.name} ip route add " + r[0] + " via " + r[1].ip_address + " proto static"
for c in self.configure_commands:
cmds += c
return super().configure() + cmds.format(self=self)
def destroy(self):
return super().destroy() + "ip netns delete {self.name}".format(self=self)
class DockerContainer(Entity):
pass
class OVS(Entity):
__shortname = 'ovs'
def __init__(self, name=None):
super().__init__()
self.name = name
def create(self):
return super().create() + "ovs-vsctl add-br {self.name}".format(self=self)
def configure(self):
return None
def destroy(self):
return super().destroy() + "ovs-vsctl del-br {self.name}".format(self=self)
class Endpoint:
@classmethod
def get(cls, arg):
if isinstance(arg, cls):
return arg
if isinstance(arg, Entity):
return cls(arg)
if isinstance(arg, tuple):
return cls(*arg)
def __init__(self, entity, ip_address=None, name=None):
self.entity = entity
self.name = name
self.ip_address = None
self.ip_size = None
if ip_address is not None:
if '/' in ip_address:
parts = ip_address.split('/')
self.ip_address = parts[0]
self.ip_size = int(parts[1])
else:
self.ip_address = ip_address
self.ip_size = 24
def __str__(self):
return '{self.name} ({self.ip_address}/{self.ip_size})'.format(self=self)
def __repr__(self):
return self.__str__()
def disable_offloading(self):
return 'ethtool -K {self.name} tx off gso off sg off gro off'.format(self=self)
class Link:
@staticmethod
def declare(e1, e2, link_type=None, **kwargs):
e1 = Endpoint.get(e1)
e2 = Endpoint.get(e2)
if type(e1.entity) is OVS and type(e2.entity) is OVS:
if link_type is None:
link_type = 'patch'
if link_type == 'veth':
return Link_OVS_OVS_veth(e1, e2, **kwargs)
elif link_type == 'patch':
return Link_OVS_OVS_patch(e1, e2, **kwargs)
else:
raise ConfigurationError('unrecognized type: {}'.format(link_type))
if (type(e1.entity) is OVS and type(e2.entity) is Netns) or (type(e1.entity) is Netns and type(e2.entity) is OVS):
# make sure e1 is the OVS
if type(e1.entity) is Netns and type(e2.entity) is OVS:
e2, e1 = e1, e2
if link_type is None:
link_type = 'port'
if link_type == 'veth':
return Link_OVS_Netns_veth(e1, e2, **kwargs)
elif link_type == 'port':
return Link_OVS_Netns_port(e1, e2, **kwargs)
else:
raise ConfigurationError('unrecognized type: {}'.format(link_type))
if type(e1.entity) is Netns and type(e2.entity) is Netns:
if link_type is not None and link_type != 'veth':
raise ConfigurationError('unrecognized type: {}'.format(link_type))
return Link_Netns_Netns_veth(e1, e2, **kwargs)
def __init__(self, e1, e2, disable_offloading=False, **kwargs):
self.e1 = e1
self.e2 = e2
self.disable_offloading = disable_offloading
e1.entity.links.append(self)
e2.entity.links.append(self)
@add_comment('creating')
def create(self):
return CommandBlock()
@add_comment('destroying')
def destroy(self):
return CommandBlock()
@property
def description(self):
return "link between {self.e1.entity.name} and {self.e2.entity.name} of type {self.__class__.__name__} ({self.e1.name} to {self.e2.name})".format(self=self)
def __str__(self):
return self.description
def __repr__(self):
return self.__str__()
# ensure no double links are configured (they'll be skipped by Master)
# links will be skipped EVEN IF they're of DIFFERENT TYPES
# but they are NOT skipped if they have different ip addresses
def __key(self):
return tuple(sorted([hash(self.e1), hash(self.e2)]))
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.__key() == other.__key()
def __ne__(self, other):
return not self.__eq__(other)
class Link_OVS_OVS_veth(Link):
def __init__(self, e1, e2, **kwargs):
super().__init__(e1, e2, **kwargs)
def assign_attributes(self):
# veth names are limited to 15 chars(!)
if self.e1.name is None:
self.e1.name = 'veth-ovs-{e1.entity.name_id}-{e2.entity.name_id}'.format(**self.__dict__)
if self.e2.name is None:
self.e2.name = 'veth-ovs-{e2.entity.name_id}-{e1.entity.name_id}'.format(**self.__dict__)
def create(self):
self.assign_attributes()
cmds = CommandBlock()
# create the links
cmds += "ip link add {e1.name} type veth peer name {e2.name}"
# configure one side
cmds += "ovs-vsctl add-port {e1.entity.name} {e1.name}"
cmds += "ip link set {e1.name} up"
if self.disable_offloading:
cmds += self.e1.disable_offloading()
# configure the other side
cmds += "ovs-vsctl add-port {e2.entity.name} {e2.name}"
cmds += "ip link set {e2.name} up"
if self.disable_offloading:
cmds += self.e2.disable_offloading()
return super().create() + cmds.format(**self.__dict__)
def destroy(self):
self.assign_attributes()
return super().destroy() + "ip link delete {e1.name}".format(**self.__dict__)
class Link_OVS_OVS_patch(Link):
def __init__(self, e1, e2, **kwargs):
super().__init__(e1, e2, **kwargs)
def assign_attributes(self):
if self.e1.name is None:
self.e1.name = 'patch-{e2.entity.name}-{e1.entity.name_id}'.format(**self.__dict__)
if self.e2.name is None:
self.e2.name = 'patch-{e1.entity.name}-{e2.entity.name_id}'.format(**self.__dict__)
def create(self):
self.assign_attributes()
cmds = CommandBlock()
cmds += "ovs-vsctl add-port {e1.entity.name} {e1.name} -- set Interface {e1.name} type=patch options:peer={e2.name}"
cmds += "ovs-vsctl add-port {e2.entity.name} {e2.name} -- set Interface {e2.name} type=patch options:peer={e1.name}"
return super().create() + cmds.format(**self.__dict__)
def destroy(self):
return None # destroyed by the bridge
class Link_OVS_Netns_veth(Link):
# e1 is the ovs, e2 is the netns
def __init__(self, e1, e2, **kwargs):
super().__init__(e1, e2, **kwargs)
def assign_attributes(self):
if self.e1.name is None:
self.e1.name = 'v-ovs{e1.entity.name_id}-ns{e2.entity.name_id}'.format(**self.__dict__)
if self.e2.name is None:
self.e2.name = 'v-ns{e2.entity.name_id}-ovs{e1.entity.name_id}'.format(**self.__dict__)
def create(self):
self.assign_attributes()
cmds = CommandBlock()
# create the links
cmds += "ip link add {e1.name} type veth peer name {e2.name}"
# configure ovs side
cmds += "ovs-vsctl add-port {e1.entity.name} {e1.name}"
cmds += "ip link set {e1.name} up"
if self.disable_offloading:
cmds += self.e1.disable_offloading()
# configure namespace side
cmds += "ip link set {e2.name} netns {e2.entity.name}"
cmds += "ip netns exec {e2.entity.name} ip link set dev {e2.name} up"
if self.e2.ip_address is not None:
cmds += "ip netns exec {e2.entity.name} ip address add {e2.ip_address}/{e2.ip_size} dev {e2.name}"
if self.disable_offloading:
cmds += ("ip netns exec {e2.entity.name} " + self.e2.disable_offloading())
return super().create() + cmds.format(**self.__dict__)
def destroy(self):
self.assign_attributes()
return super().destroy() + "ip link delete {e1.name}".format(**self.__dict__)
class Link_OVS_Netns_port(Link):
# e1 is the ovs, e2 is the netns
def __init__(self, e1, e2, **kwargs):
super().__init__(e1, e2, **kwargs)
def assign_attributes(self):
if self.e2.name is None:
self.e2.name = 'p-{e1.entity.name}-{e2.entity.name_id}'.format(**self.__dict__)
def create(self):
self.assign_attributes()
cmds = CommandBlock()
cmds += "ovs-vsctl add-port {e1.entity.name} {e2.name} -- set Interface {e2.name} type=internal"
cmds += "ip link set {e2.name} netns {e2.entity.name}"
cmds += "ip netns exec {e2.entity.name} ip link set dev {e2.name} up"
if self.e2.ip_address is not None:
cmds += "ip netns exec {e2.entity.name} ip address add {e2.ip_address}/{e2.ip_size} dev {e2.name}"
if self.disable_offloading:
cmds += ("ip netns exec {e2.entity.name} " + self.e2.disable_offloading())
return super().create() + cmds.format(**self.__dict__)
def destroy(self):
return None # destroyed by the bridge
class Link_Netns_Netns_veth(Link):
def __init__(self, e1, e2, **kwargs):
super().__init__(e1, e2, **kwargs)
def assign_attributes(self):
# veth names are limited to 15 chars(!)
if self.e1.name is None:
self.e1.name = 'veth-ns-{e1.entity.name_id}-{e2.entity.name_id}'.format(**self.__dict__)
if self.e2.name is None:
self.e2.name = 'veth-ns-{e2.entity.name_id}-{e1.entity.name_id}'.format(**self.__dict__)
def create(self):
self.assign_attributes()
cmds = CommandBlock()
# create the links
cmds += "ip link add {e1.name} type veth peer name {e2.name}"
# configure one side
cmds += "ip link set {e1.name} netns {e1.entity.name}"
cmds += "ip netns exec {e1.entity.name} ip link set dev {e1.name} up"
if self.e1.ip_address is not None:
cmds += "ip netns exec {e1.entity.name} ip address add {e1.ip_address}/{e1.ip_size} dev {e1.name}"
if self.disable_offloading:
cmds += ("ip netns exec {e1.entity.name} " + self.e1.disable_offloading())
# configure the other side
cmds += "ip link set {e2.name} netns {e2.entity.name}"
cmds += "ip netns exec {e2.entity.name} ip link set dev {e2.name} up"
if self.e2.ip_address is not None:
cmds += "ip netns exec {e2.entity.name} ip address add {e2.ip_address}/{e2.ip_size} dev {e2.name}"
if self.disable_offloading:
cmds += ("ip netns exec {e2.entity.name} " + self.e2.disable_offloading())
return super().create() + cmds.format(**self.__dict__)
def destroy(self):
self.assign_attributes()
return super().destroy() + "ip netns exec {e1.entity.name} ip link delete {e1.name}".format(**self.__dict__)
class Master:
def __init__(self):
self.entities = []
def add(self, entity):
self.entities.append(entity)
def find_unique_attribute(self, entity, attribute_name, fmt, n_limit=None):
if getattr(entity, attribute_name) is not None:
return
n = 1
good_attr = False
while not good_attr:
proposed_attr = fmt.format(entity=entity, n=n)
good_attr = all([getattr(e, attribute_name) != proposed_attr for e in self.entities])
n += 1
if n_limit is not None and n > n_limit:
raise ConfigurationError('unable to find a good value')
setattr(entity, attribute_name, proposed_attr)
def assign_attributes(self):
for entity in self.entities:
self.find_unique_attribute(entity, 'name', '{entity.entity_type_name}{n}')
# self.find_unique_attribute(entity, 'ip_address', '10.112.{n}.1', 255)
@property
def links(self):
links = []
links_set = set()
links_set_add = links_set.add
for e in self.entities:
links += [l for l in e.links if not (l in links_set or links_set_add(l))]
return links
def __get_commands(self, collection, fn):
commands = CommandBlock()
for obj in collection:
commands += getattr(obj, fn)()
return commands
def setup(self):
self.assign_attributes()
return self.__get_commands(self.entities, 'create') + self.__get_commands(self.links, 'create') + self.__get_commands(self.entities, 'configure')
def cleanup(self):
return self.__get_commands(self.links, 'destroy') + self.__get_commands(self.entities, 'destroy')
def get_script(self, enable_routing=True, include_calls=True):
res = CommandBlock.root_check()
res += 'function opg_setup {'
res += 'set -e'
if enable_routing:
res += 'sysctl -w net.ipv4.ip_forward=1'
res += self.setup()
res += ''
res += 'set +e'
res += 'sleep 1'
res += '}'
res += ''
res += 'function opg_cleanup {'
res += 'set +e'
res += self.cleanup()
res += ''
if enable_routing:
res += 'sysctl -w net.ipv4.ip_forward=0'
res += 'sleep 1'
res += '}'
if include_calls:
res += ''
res += 'trap opg_cleanup EXIT'
res += 'opg_setup'
return res
|
python
|
import logging
from .registry import Registry
from .parsers import RegistryPDFParser
from .securityhandler import security_handler_factory
from .types import IndirectObject, Stream, Array, Dictionary, IndirectReference, obj_factory
from .utils import cached_property, from_pdf_datetime
class PDFDocument(object):
"""
Represents PDF document structure
:param fobj: file-like object: binary file descriptor, BytesIO stream etc.
:param password: Optional. Password to access PDF content. Defaults to the empty string.
"""
#: contains PDF file header data
header = None
#: contains PDF file trailer data
trailer = None
#: references to document's Catalog instance
root = None
def __init__(self, fobj, password=''):
""" Constructor method
"""
self.registry = Registry()
self.parser = RegistryPDFParser(fobj, self.registry)
self.header = self.parser.header
self.trailer = self.parser.trailer
if self.encrypt and self.encrypt.Filter != "Standard":
raise ValueError("Unsupported encryption handler {}".format(self.encrypt.Filter))
self.root = self.obj_by_ref(self.trailer.root)
if self.encrypt:
sec_handler = security_handler_factory(self.trailer.id, self.encrypt, password)
self.parser.set_security_handler(sec_handler)
@cached_property
def encrypt(self):
"""
Document's Encrypt dictionary (if present)
:return: dict or None
"""
res = None
obj = self.trailer.encrypt
if obj:
res = self.obj_by_ref(obj) if isinstance(obj, IndirectReference) else obj
return res
def build(self, obj, visited=None, lazy=True):
"""
Resolves all indirect references for the object.
:param obj: an object from the document
:type obj: one of supported PDF types
:param lazy: don't resolve subsequent indirect references if True (default).
:type lazy: bool
:param visited: Shouldn't be used. Internal param containing already resolved objects
to not fall into infinite loops
"""
logging.debug("Buliding {}".format(obj))
if visited is None:
visited = []
on_return = None
if isinstance(obj, IndirectReference):
if obj not in visited:
visited.append(obj)
on_return = visited.pop
obj = self.obj_by_ref(obj)
# resolve subsequent references for Arrays, Dictionaries and Streams
if isinstance(obj, Array):
obj = [self.build(o, visited, lazy) for o in obj]
elif isinstance(obj, Dictionary):
if not lazy:
obj = {k: self.build(o, visited, lazy) for k, o in obj.items()}
obj = obj_factory(self, obj)
elif isinstance(obj, Stream):
if not lazy:
obj.dictionary = {k: (self.build(o, visited, lazy)) for k, o in obj.dictionary.items()}
obj = obj_factory(self, obj)
elif isinstance(obj, IndirectObject):
# normally this shouldn't happen, but ponentially we can build it
logging.warning("Attempt to build an indirect object. Possibly a bug.")
obj = self.build(obj.val, visited, lazy)
if on_return:
on_return()
return obj
def locate_object(self, num, gen):
return self.parser.locate_object(num, gen)
def obj_by_ref(self, objref):
obj = self.parser.locate_object(objref.num, objref.gen)
return obj_factory(self, obj)
def deep_obj_by_ref(self, obj, maxdepth=100):
counter = maxdepth
while isinstance(obj, IndirectObject) and counter:
obj = self.obj_by_ref(obj)
counter -= 1
if isinstance(obj, IndirectObject):
raise ValueError("Max reference depth exceeded")
return obj
def pages(self):
"""
Yields document pages one by one.
:return: :class:`~pdfreader.types.objects.Page` generator.
"""
return self.root.Pages.pages()
@property
def metadata(self):
"""
Returns document metadata from file's trailer info dict
:return: dict, if metadata exists `None` otherwise.
"""
res = None
info = self.trailer.info
if info:
res = self.locate_object(info.num, info.gen)
for k, v in res.items():
if isinstance(v, bytes):
try:
res[k] = v.decode()
if k in ('CreationDate', 'ModDate'):
res[k] = from_pdf_datetime(res[k])
except (UnicodeDecodeError, ValueError, TypeError):
pass
return res
if __name__ == "__main__":
import doctest
doctest.testmod()
|
python
|
from __future__ import print_function
import logging
import re
from datetime import datetime
from collections import Counter
from itertools import chain
import json
import boto3
import spacy
import textacy
from lxml import etree
from fuzzywuzzy import process
from django.utils.functional import cached_property
from django.conf import settings
from botocore.exceptions import ClientError
from cwapi.models import SpeakerWordCounts
from cwapi.es_docs import CRECDoc
# from cwapi.es_docs import AttributedSegmentDoc
import parser.text_utils as text_utils
from scraper.crec_scraper import crec_s3_key
logger = logging.getLogger(__name__)
DEFAULT_XML_NS = {'ns': 'http://www.loc.gov/mods/v3'}
SPACY_NLP = spacy.load('en')
APPROX_MATCH_THRESHOLD = 90
HOUSE_GENERIC_SPEAKERS = [
'The CLERK', 'The Acting CLERK', 'The ACTING CLERK',
'The SPEAKER pro tempore', 'The SPEAKER'
'The Acting SPEAKER pro tempore', 'The ACTING SPEAKER pro tempore',
'The Acting CHAIR', 'The ACTING CHAIR', 'The Acting CHAIRMAN',
'The ACTING CHAIRMAN', 'The CHAIRMAN', 'The CHAIRWOMAN',
]
SENATE_GENERIC_SPEAKERS = [
'The PRESIDING OFFICER', 'The PRESIDENT pro tempore',
'The Acting PRESIDENT pro tempore', 'The ACTING PRESIDENT pro tempore',
'The VICE PRESIDENT', 'The CHIEF JUSTICE', 'Mr. Counsel', 'Mrs. Counsel',
'Ms. Counsel'
]
GENERIC_SPEAKERS = HOUSE_GENERIC_SPEAKERS + SENATE_GENERIC_SPEAKERS
class CRECParser(object):
def __init__(self,
xml_tree,
date_issued,
xml_namespace=DEFAULT_XML_NS):
self._xml_tree = xml_tree
self._xml_namespace = xml_namespace
self.date_issued = date_issued
self.s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
def _get_by_xpath(self, xml_tree, xpath):
return xml_tree.xpath(xpath, namespaces=self._xml_namespace)
@cached_property
def id(self):
"""@ID field in mods metadata, usually corresponds to filename minus the
file extension.
Example:
"id-CREC-2017-01-20-pt1-PgD55"
"""
return self._get_by_xpath(self._xml_tree, 'string(@ID)')
@cached_property
def title(self):
"""Title of CREC document.
"""
return self._get_by_xpath(
self._xml_tree, 'string(ns:titleInfo/ns:title)'
)
@cached_property
def title_part(self):
"""Section of daily batch of CREC docs, usually one of "Daily Digest",
"Extensions of Remarks", "House", "Senate".
"""
return self._get_by_xpath(
self._xml_tree, 'string(ns:titleInfo/ns:partName)'
)
@cached_property
def pdf_url(self):
"""Location on gpo.gov for the pdf version of this CREC doc.
"""
return self._get_by_xpath(
self._xml_tree,
'string(ns:location/ns:url[@displayLabel="PDF rendition"])'
)
@cached_property
def html_url(self):
"""Location on gpo.gov for the html version of this CREC doc.
"""
return self._get_by_xpath(
self._xml_tree,
'string(ns:location/ns:url[@displayLabel="HTML rendition"])'
)
@cached_property
def page_start(self):
"""CREC docs are grouped into one large pdf each day, this indicates the
page on which this document starts (a single page can include more than
one doc).
"""
return self._get_by_xpath(
self._xml_tree,
'string(ns:part[@type="article"]/ns:extent/ns:start)'
)
@cached_property
def page_end(self):
"""CREC docs are grouped into one large pdf each day, this indicates the
page on which this document ends (a single page can include more than
one doc).
"""
return self._get_by_xpath(
self._xml_tree,
'string(ns:part[@type="article"]/ns:extent/ns:end)'
)
@cached_property
def speakers(self):
"""List of names of people identified as speakers in this doc. Names
usually corrrespond to the ``official_full`` field in bioguide data.
Can be empty.
Examples:
``['Mitch McConnell', 'Roy Blunt', 'Charles E. Schumer']``
``['Charles E. Schumer']``
``[]``
"""
return self._get_by_xpath(
self._xml_tree, 'ns:name[@type="personal"]/ns:namePart/text()'
)
@cached_property
def speaker_ids(self):
"""Maps a short name version of a speaker's name with their bioguideid,
this is used for matching segments within this doc to the speaker for
that segment. Can be empty.
Examples:
``{'Mr. GALLEGO': 'G000574'}``
``{'Mr. SMITH': 'S000583', 'Mr. LATTA': 'L000566'}``
``{}``
"""
speaker_ids_ = {}
persons = self._get_by_xpath(
self._xml_tree, 'ns:extension/ns:congMember'
)
for person in persons:
parsed_name = self._get_by_xpath(
person, 'string(ns:name[@type="parsed"])'
)
sanitized_name = re.sub(' of .*$', '', parsed_name)
if person.get('role') == 'SPEAKING':
speaker_ids_[sanitized_name] = person.get('bioGuideId')
return speaker_ids_
@cached_property
def content(self):
"""The text of this CREC doc (may be plain text or html).
"""
s3_key = crec_s3_key(self.id.strip('id-') + '.htm', self.date_issued)
try:
response = self.s3.get_object(
Bucket=settings.CREC_STAGING_S3_BUCKET, Key=s3_key
)
content = response['Body'].read().decode('utf-8')
return content
except ClientError as e:
# TODO: Proper error handling for missing CREC file.
print(s3_key)
@cached_property
def is_daily_digest(self):
"""True if this doc is a daily digest. The Daily Digest is an
aggregation of all CREC docs for a day, we omit it in favor of parsing
each individually.
"""
tokens = self.id.split('-')
return any([
tokens[-1].startswith('PgD'),
tokens[-2].startswith('PgD'),
(self.title_part and self.title_part.startswith('Daily Digest'))
])
@cached_property
def is_front_matter(self):
"""True if this is a front matter page. These are effectively cover
pages and do not contain relevant data.
"""
tokens = self.id.split('-')
if len(tokens) > 0:
return self.id.split('-')[-1].startswith('FrontMatter')
else:
return False
def is_skippable(self):
"""Returns True if this is one of the type of documents in the daily
aggregation of CREC docs that does not contain relevant data and should
not be uploaded to elasticsearch.
"""
return self.is_daily_digest or self.is_front_matter
@cached_property
def textacy_text(self):
"""An instance of ``textacy.Doc`` containing preprocessed data from the
``content`` field.
"""
text = text_utils.preprocess(self.content)
return textacy.Doc(SPACY_NLP(text))
@cached_property
def named_entity_counts(self):
"""A nested-dict mapping named entity type to a histogram dict of any
named entities of that type contained within ``content``. See
`https://spacy.io/usage/linguistic-features#section-named-entities`_
for a list and decriptions of these types.
Example:
::
{
'PERSON': {
'Benjamin S. Carson': 1, 'Elaine L. Chao': 1
},
'ORG': {
'Senate': 15, 'Chamber Action Routine Proceedings': 1
}
}
"""
named_entities = text_utils.get_named_entities(self.textacy_text)
named_entity_counts_ = {}
if any(named_entities):
named_entity_types = text_utils.get_named_entity_types(
named_entities
)
named_entity_freqs = text_utils.get_named_entity_frequencies(
named_entities
)
for ne_type in named_entity_types.keys():
# TODO: Better type name for type == ''?
if ne_type == 'PERSON':
named_entity_counts_[ne_type] = {
text_utils.camel_case(ne, force=False): named_entity_freqs[ne]
for ne in named_entity_types[ne_type]
}
else:
named_entity_counts_[ne_type] = {
ne: named_entity_freqs[ne]
for ne in named_entity_types[ne_type]
}
return named_entity_counts_
@cached_property
def noun_chunks_counts(self):
"""A dict mapping noun chunks type to number of occurrences within
``content``.
Example:
::
{
'united states trade representative': 1,
'unanimous consent agreement': 1,
}
"""
noun_chunks = text_utils.get_noun_chunks(self.textacy_text)
noun_chunks = text_utils.named_entity_dedupe(
noun_chunks,
chain(*[d.keys() for d in self.named_entity_counts.values()])
)
return dict(Counter(noun_chunks))
@cached_property
def segments(self):
"""List of segments of ``content`` attributed to individual speakers.
Speakers can be indviduals identified by name (and usually bioGuideId)
or generic speakers (roles). A sentence containing an individual or
generic speaker (exact or approximate match) marks the beginning of
new segment.
Example:
::
[
{
'id': 'id-CREC-2017-01-20-pt1-PgS348-1',
'speaker': 'Mr. McCONNELL',
'text': 'THANKING FORMER PRESIDENT OBAMA. Mr. McCONNELL.Mr. President, I wish to offer a few words regarding...',
'bioguide_id': 'M000355'
},
{
'id': 'id-CREC-2017-01-20-pt1-PgS348-2-1',
'speaker': 'Mr. DURBIN',
'text': 'NOMINATIONS. Mr. DURBIN. Mr. President, I listened carefully to the statement by theRepublican lead...',
'bioguide_id': 'D000563'
}
]
"""
sents = (sent.string for sent in self.textacy_text.spacy_doc.sents)
previous = None
current = None
segment_index = 0
segment_sents = []
segments_ = []
individual_speakers = self.speaker_ids.keys()
for sent in chain(sents, ('<EOF>',)):
speaker = next(
filter(lambda person: person in sent, chain(
individual_speakers, GENERIC_SPEAKERS)), None)
if speaker is not None:
current = speaker
logger.debug(
'Found speaker: {}, previous speaker {}'.format(current, previous))
else:
speaker, score = process.extractOne(sent, chain(
individual_speakers, GENERIC_SPEAKERS))
if score > APPROX_MATCH_THRESHOLD:
current = speaker
logger.debug(
'Found speaker: {} (approx. score {}/100), previous speaker: {}'.format(
current, score, previous))
if previous != current or sent == '<EOF>':
if segment_sents:
segment_index += 1
segment = {
'id': '{}-{}'.format(self.id, segment_index),
'speaker': previous,
'text': ' '.join(segment_sents),
'bioguide_id': None,
}
if segment['speaker'] in self.speaker_ids:
segment['bioguide_id'] = self.speaker_ids[segment['speaker']]
segments_.append(segment)
previous = current
segment_sents = [sent]
else:
segment_sents.append(sent)
return segments_
def to_es_doc(self):
"""Returns the CRECParser as a dict ready to be uploaded to
elasticsearch.
Returns:
dict: A dict representation of this document.
"""
return CRECDoc(
title=self.title,
title_part=self.title_part,
date_issued=self.date_issued,
content=self.content,
crec_id=self.id,
pdf_url=self.pdf_url,
html_url=self.html_url,
page_start=self.page_start,
page_end=self.page_end,
speakers=','.join(self.speakers),
segments=self.segments,
)
def upload_speaker_word_counts(crec_parser):
"""Creates new entries of the SpeakerWordCounts ORM model containing
counts of named entities and noun chunks within this document.
Args:
crec_parser (:class:`parser.crec_parser.CRECParser`): A CRECParser
instance representing a single CREC document.
"""
if crec_parser.speaker_ids:
named_entities = {'named_entities_{0}'.format(ne_type): counts
for ne_type, counts in crec_parser.named_entity_counts.items()}
for bioguide_id in crec_parser.speaker_ids.values():
speaker_counts = SpeakerWordCounts(
bioguide_id=bioguide_id,
crec_id=crec_parser.id,
date=crec_parser.date_issued,
named_entities=json.dumps(crec_parser.named_entity_counts),
noun_chunks=json.dumps(crec_parser.noun_chunks_counts)
)
speaker_counts.save()
def extract_crecs_from_mods(mods_file_obj, xml_namespace=DEFAULT_XML_NS):
"""Takes a file-like object containing mods.xml data for a single day,
extracts each "constituent" (a single CREC document from that day) and
creates a new CRECParser instance for that document. Returns all CRECParser
instances created for a single day as a list.
Args:
mods_file_obj (file): An open file, StringIO or BytesIO buffer
containing mods.xml data.
xml_namespace (dict): The xml_namespaces argument to use with the lxml
parser.
Returns:
list of :class:`parser.crec_parser.CRECParser`: A list of parsed CREC
docs for a single day.
"""
xml_tree = None
xml_tree = etree.parse(mods_file_obj)
constituents = xml_tree.xpath(
'//ns:relatedItem[@type="constituent"]',
namespaces=xml_namespace,
)
date_issued_str = xml_tree.xpath(
'string(//ns:originInfo/ns:dateIssued)',
namespaces=xml_namespace,
)
date_issued = datetime.strptime(date_issued_str, '%Y-%m-%d')
return [CRECParser(c, date_issued) for c in constituents]
|
python
|
#!/usr/bin/env python
import time
import datetime
from web3.exceptions import TransactionNotFound, BlockNotFound
from web3.middleware import construct_sign_and_send_raw_middleware
from config import (
CONFIRMATIONS,
TARGET,
TARGET_TIME,
ACCOUNT,
BASE_PRICE,
web3,
INSTANCE,
)
def get_transaction_and_receipt(tx_hash):
""" Function that tries to get the transaction receipt.
Args:
hash (hex string) - Hash of transaction to be checked.
Return:
Tuple - Transaction and receipt or (None, None) if it doesn't
exist.
"""
try:
tx_inst = web3.eth.getTransaction(tx_hash)
tx_receipt = web3.eth.getTransactionReceipt(tx_hash)
return tx_inst, tx_receipt
except TransactionNotFound:
return None, None
except TypeError as error:
if "Exactly one of the passed values can be specified." in str(error):
return None, None
except Exception:
print("Unpredicted exception has occured")
raise
def await_confirmations(block_hash):
""" Function that waits for enough confirmations of block and decides to
start over again in case of fork.
Args:
block_hash (hex string) - Hash of block to be checked.
Return:
(Bool) - Returns 'True' in case of succeeding in getting enough
confirmations. Returns 'False' in case of block outdating.
"""
while True:
try:
block_number = web3.eth.getBlock(block_hash).number
except BlockNotFound:
# Fork occured.
return False
except Exception:
print("Unpredicted exception has occured")
raise
last_block = web3.eth.blockNumber
if (last_block - block_number) >= CONFIRMATIONS:
return True
time.sleep(3)
def increase_price(current_price, current_nonce, pending):
""" Function that increases the gas price. Is called periodically
according to time spent in this iteration.
Args:
current_price (int) - Current gas price in Wei;
current_nonce (int) - Current nonce;
pending[] - Array of transactions sent with this nonce (in case if
transaction with lower price would be mined before).
Return:
current_price (int) - New gas price;
pending[] - Array of transactions with same nonce with added one.
"""
try:
current_price += int(current_price / 10)
tx_hash = process_transaction(current_price, current_nonce)
if tx_hash is not None:
pending.append(tx_hash)
except ValueError as error:
# One of the txs in pending was mined during increasing process.
if "nonce too low" in str(error):
return current_price, pending
if "known transaction" in str(error):
current_price += int(current_price / 10)
return current_price, pending
except Exception:
print("Unpredicted exception has occured")
raise
return current_price, pending
def adjust_price(iteration, current_price, global_start, last_tx_time):
""" Function that decides to lower or increase the price, according to the
time of previous transaction and the progress in reaching TARGET in
TARGET_TIME.
Args:
iteration (int) - Number of previous successful transactions. Iterator
which changes with the changing of nonce;
current_price (int) - Current gas price in Wei;
global_start (float/Unix format) - The start of the whole process;
last_tx_time (float/Unix format) - Time spent in previous iteration.
Return:
current_price (int) - New gas price after adjustments.
"""
if iteration > 0:
target_ratio = TARGET_TIME / TARGET
actual_ratio = (time.time() - global_start) / iteration
# If we check only the duration of the latest tx, it will increase
# the price very rapidly, ignoring the global progress.
# So it is necessary to control the price according to plan.
if actual_ratio < target_ratio:
current_price -= int(current_price / 10)
elif last_tx_time >= target_ratio:
current_price += int(current_price / 10)
return current_price
def process_transaction(gas_price, nonce):
""" Function that tries to form, sign and send the transaction with given
parameters.
Args:
gas_price (int) - Desired gas price;
nonce (int) - Desired nonce.
Return:
(Hex string) or None - Transaction hash or None if error occured.
"""
try:
tx_builder = INSTANCE.functions.increment().buildTransaction(
{"gasPrice": gas_price, "nonce": nonce}
)
return web3.eth.sendTransaction(tx_builder)
except ValueError as error:
# Web3 hasn't updated the nonce yet.
if "replacement transaction underpriced" in str(error):
return None
if "nonce too low" in str(error):
return None
raise error
def process_iteration(iteration, current_price, global_start, last_tx_time):
""" Function that deals with the processing of transactions with same
nonce till it's farmed and confirmed. Sub-main function of program.
Args:
iteration (int) - Number of previous successful transactions. Iterator
which changes with the changing of nonce;
current_price (int) - Current gas price in Wei;
global_start (float/Unix format) - The start of the whole process;
last_tx_time (float/Unix format) - Time spent in previous iteration.
Return:
current_price (int) - The price of successful transaction among the
others with same nonce;
time.time() - time_start (float/Unix format) - Time spent in this
iteration.
"""
in_pending = 1
current_progress = iteration + 1
current_price = adjust_price(
iteration, current_price, global_start, last_tx_time
)
while True:
# Checking whether web3 updated the nonce after previous transaction.
current_nonce = web3.eth.getTransactionCount(ACCOUNT.address)
pending = [process_transaction(current_price, current_nonce)]
if pending[0] is None:
pending = []
else:
break
time_start = time.time()
if ((current_progress % 10 == 0) and (iteration is not (TARGET - 1))) or (
iteration == 0
):
status = "Header"
else:
status = "Pending"
print_log(
current_progress,
time.ctime(),
current_nonce,
current_price,
status,
pending[-1],
)
while True:
for some_tx in pending:
tx_inst, tx_receipt = get_transaction_and_receipt(some_tx)
if tx_receipt is not None:
current_price = tx_inst.gasPrice
print_log(
current_progress,
time.ctime(),
current_nonce,
current_price,
"Mined",
some_tx,
)
tx_block_hash = tx_receipt.blockHash
if not await_confirmations(tx_block_hash):
# The fork occured. Rolling back to txs in pending
continue
current_time = time.ctime()
print_log(
current_progress,
current_time,
current_nonce,
current_price,
"Success",
some_tx,
)
return current_price, time.time() - time_start
# Increasing of price is available once in 25 seconds.
if (time.time() - time_start) >= 25 * in_pending:
in_pending += 1
current_price, pending = increase_price(
current_price, current_nonce, pending
)
print_log(
current_progress,
time.ctime(),
current_nonce,
current_price,
"Pending",
pending[-1],
)
time.sleep(1)
def print_log(progress, time, nonce, price, status, tx_hash):
""" Function that deals with printing the log in particular format.
Args:
progress (int) - The biased value representing the current iteration
in format understandable to man (iteration + 1);
time (float/Unix format) - The time of event;
current_nonce (int) - Current nonce;
current_price (int) - Current gas price in Wei;
status (string) - String value representing the type of event;
tx_hash (hex string) - The hash of event transaction.
"""
# If "Header" status is present, it prints the string twice.
# First time it print the header itself, second - the information itself.
if status == "Header":
print(
" {} | {} | {} | {} | {} | {} ".format(
"#".ljust(len(str(progress))),
"Date & Time".ljust(len(time)),
"Nonce".ljust(7),
"Gas Price".ljust(10),
"Status".ljust(7),
"Tx hash",
)
)
status = "Pending"
print(
" {} | {} | {} | {} | {} | {}".format(
progress,
time,
str(nonce).ljust(7),
str(price).ljust(10),
status.ljust(7),
web3.toHex(tx_hash),
)
)
if __name__ == "__main__":
web3.middleware_onion.add(construct_sign_and_send_raw_middleware(ACCOUNT))
web3.eth.defaultAccount = ACCOUNT.address
current_price = BASE_PRICE
last_tx_time = 0
global_start = time.time()
print("Started at {}.".format(time.ctime()))
for iteration in range(TARGET):
current_price, last_tx_time = process_iteration(
iteration, current_price, global_start, last_tx_time
)
print(
"Finished {} transactions in {}.".format(
TARGET,
str(datetime.timedelta(seconds=(time.time() - global_start))),
)
)
|
python
|
from pirate_sources.models import VideoSource, URLSource, IMGSource
from django.contrib import admin
admin.site.register(VideoSource)
admin.site.register(URLSource)
admin.site.register(IMGSource)
|
python
|
import os
import sys
import numpy as np
import cv2
import ailia
from logging import getLogger
logger = getLogger(__name__)
def preprocessing_img(img):
if len(img.shape) < 3:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGRA)
elif img.shape[2] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
elif img.shape[2] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGRA)
return img
def load_image(image_path):
if os.path.isfile(image_path):
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
else:
logger.error(f'{image_path} not found.')
sys.exit()
return preprocessing_img(img)
def hsv_to_rgb(h, s, v):
bgr = cv2.cvtColor(
np.array([[[h, s, v]]], dtype=np.uint8), cv2.COLOR_HSV2BGR)[0][0]
return (int(bgr[0]), int(bgr[1]), int(bgr[2]), 255)
def letterbox_convert(frame, det_shape):
"""
Adjust the size of the frame from the webcam to the ailia input shape.
Parameters
----------
frame: numpy array
det_shape: tuple
ailia model input (height,width)
Returns
-------
resized_img: numpy array
Resized `img` as well as adapt the scale
"""
height, width = det_shape[0], det_shape[1]
f_height, f_width = frame.shape[0], frame.shape[1]
scale = np.max((f_height / height, f_width / width))
# padding base
img = np.zeros(
(int(round(scale * height)), int(round(scale * width)), 3),
np.uint8
)
start = (np.array(img.shape) - np.array(frame.shape)) // 2
img[
start[0]: start[0] + f_height,
start[1]: start[1] + f_width
] = frame
resized_img = cv2.resize(img, (width, height))
return resized_img
def reverse_letterbox(detections, img, det_shape):
h, w = img.shape[0], img.shape[1]
pad_x = pad_y = 0
if det_shape != None:
scale = np.max((h / det_shape[0], w / det_shape[1]))
start = (det_shape[0:2] - np.array(img.shape[0:2]) / scale) // 2
pad_x = start[1]*scale
pad_y = start[0]*scale
new_detections = []
for detection in detections:
logger.debug(detection)
r = ailia.DetectorObject(
category=detection.category,
prob=detection.prob,
x=(detection.x*(w+pad_x*2) - pad_x)/w,
y=(detection.y*(h+pad_y*2) - pad_y)/h,
w=(detection.w*(w+pad_x*2))/w,
h=(detection.h*(h+pad_y*2))/h,
)
new_detections.append(r)
return new_detections
def plot_results(detector, img, category, segm_masks=None, logging=True):
"""
:param detector: ailia.Detector, or list of ailia.DetectorObject
:param img: ndarray data of image
:param category: list of category_name
:param segm_masks:
:param logging: output log flg
:return:
"""
h, w = img.shape[0], img.shape[1]
count = detector.get_object_count() if hasattr(detector, 'get_object_count') else len(detector)
if logging:
print(f'object_count={count}')
# prepare color data
colors = []
for idx in range(count):
obj = detector.get_object(idx) if hasattr(detector, 'get_object') else detector[idx]
# print result
if logging:
print(f'+ idx={idx}')
print(
f' category={obj.category}[ {category[obj.category]} ]'
)
print(f' prob={obj.prob}')
print(f' x={obj.x}')
print(f' y={obj.y}')
print(f' w={obj.w}')
print(f' h={obj.h}')
color = hsv_to_rgb(256 * obj.category / (len(category) + 1), 255, 255)
colors.append(color)
# draw segmentation area
if segm_masks:
for idx in range(count):
mask = np.repeat(np.expand_dims(segm_masks[idx], 2), 3, 2).astype(np.bool)
color = colors[idx][:3]
fill = np.repeat(np.repeat([[color]], img.shape[0], 0), img.shape[1], 1)
img[:, :, :3][mask] = img[:, :, :3][mask] * 0.7 + fill[mask] * 0.3
# draw bounding box
for idx in range(count):
obj = detector.get_object(idx) if hasattr(detector, 'get_object') else detector[idx]
top_left = (int(w * obj.x), int(h * obj.y))
bottom_right = (int(w * (obj.x + obj.w)), int(h * (obj.y + obj.h)))
color = colors[idx]
cv2.rectangle(img, top_left, bottom_right, color, 4)
# draw label
for idx in range(count):
obj = detector.get_object(idx) if hasattr(detector, 'get_object') else detector[idx]
fontScale = w / 2048
text = category[obj.category] + " " + str(int(obj.prob*100)/100)
textsize = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fontScale, 1)[0]
tw = textsize[0]
th = textsize[1]
margin = 3
top_left = (int(w * obj.x), int(h * obj.y))
bottom_right = (int(w * obj.x) + tw + margin, int(h * obj.y) + th + margin)
color = colors[idx]
cv2.rectangle(img, top_left, bottom_right, color, thickness=-1)
text_color = (255,255,255,255)
cv2.putText(
img,
text,
(top_left[0], top_left[1] + th),
cv2.FONT_HERSHEY_SIMPLEX,
fontScale,
text_color,
1
)
return img
def write_predictions(file_name, detector, img=None, category=None):
h, w = (img.shape[0], img.shape[1]) if img is not None else (1, 1)
count = detector.get_object_count() if hasattr(detector, 'get_object_count') else len(detector)
with open(file_name, 'w') as f:
for idx in range(count):
obj = detector.get_object(idx) if hasattr(detector, 'get_object') else detector[idx]
label = category[obj.category] if category else obj.category
f.write('%s %f %d %d %d %d\n' % (
label.replace(' ', '_'),
obj.prob,
int(w * obj.x), int(h * obj.y),
int(w * obj.w), int(h * obj.h),
))
|
python
|
import sys
import os
import logging
import time
import gdb
# https://pro.arcgis.com/en/pro-app/latest/help/data/geodatabases/manage-oracle/rebuild-system-table-indexes.htm
if __name__ == '__main__':
geodatabase = gdb.Gdb()
timestr = time.strftime("%Y%m%d-%H%M%S")
targetlog = os.path.join(os.environ['TARGETLOGDIR']
,'maintaingeodatabase-{0}-{1}.log'.format('SDE'
,timestr))
logging.basicConfig(filename=targetlog
,level=logging.INFO)
retval = 0
states_removed = 0
try:
states_removed = geodatabase.compress()
logging.info('Compression removed {0} states from: {1}'.format(states_removed, geodatabase.sdeconn))
except:
logging.error('Failed to compress: {0}'.format(geodatabase.sdeconn))
retval = 1
if retval == 0:
try:
retval = geodatabase.rebuildindexes()
logging.info('Rebuilt geodatabase administrator indexes on {0}'.format(geodatabase.sdeconn))
except:
logging.error('Failed to rebuild indexes on: {0}'.format(geodatabase.sdeconn))
retval = 1
exit(retval)
|
python
|
#!/usr/bin/python
import sys
import getopt
import random
import writer
# Increase maximum recursion depth
sys.setrecursionlimit(100 * sys.getrecursionlimit())
# Generate CNF, order, and schedule files to compare two trees of xor's over a common set of inputs
def usage(name):
print("Usage: %s [-h] [-v] [-f] [-r ROOT] -n N -m M1M2" % name)
print(" -h Print this message")
print(" -v Run in verbose mode")
print(" -O (f|r) Specify order of nodes (f = flipped, r = random)")
print(" -r ROOT Specify root name for files. Will generate ROOT.cnf, ROOT.order, and ROOT.schedule")
print(" -n N Specify number of tree inputs")
print(" -m M1M2 Specify modes for the two trees: ")
print(" B=balanced, L=left linear, R=right linear, X=random, P=permuted")
# General/leaf tree node
class Node:
isLeaf = True
output = 0 # Identity of Output variable
height = 0
def __init__(self, output):
self.isLeaf = True
self.height = 0
self.output = output
def emitClauses(self, writer):
pass
def emitSchedule(self, writer):
pass
def getVariables(self, heightDict):
pass
def show(self, maxHeight = None, spacing = 4):
if maxHeight is None:
maxHeight = self.height
indent = " " * spacing * (maxHeight-self.height)
print("%sL%d" % (indent, self.output))
class TreeNode(Node):
left = None
right = None
clauseIds = []
def __init__(self, output, left, right):
Node.__init__(self, output)
self.left = left
self.right = right
self.isLeaf = False
self.height = max(left.height, right.height) + 1
self.clauseIds = []
def emitClauses(self, writer):
self.left.emitClauses(writer)
self.right.emitClauses(writer)
A = self.left.output
B = self.right.output
C = self.output
writer.doComment("Xor(%d, %d) --> %d" % (A, B, C))
self.clauseIds.append(writer.doClause([-A, -B, -C]))
self.clauseIds.append(writer.doClause([-A, B, C]))
self.clauseIds.append(writer.doClause([ A, -B, C]))
self.clauseIds.append(writer.doClause([ A, B, -C]))
def emitSchedule(self, writer):
self.left.emitSchedule(writer)
self.right.emitSchedule(writer)
writer.getClauses(self.clauseIds)
writer.doAnd(len(self.clauseIds))
quants = []
if not self.left.isLeaf:
quants.append(self.left.output)
if not self.right.isLeaf:
quants.append(self.right.output)
if len(quants) > 0:
writer.doQuantify(quants)
# Gather all non-input variables into dictionary, indexed by height
def getVariables(self, heightDict):
if self.height not in heightDict:
heightDict[self.height] = [self.output]
else:
heightDict[self.height].append(self.output)
self.left.getVariables(heightDict)
self.right.getVariables(heightDict)
def show(self, maxHeight = None, spacing = 4):
if maxHeight is None:
maxHeight = self.height
indent = " " * spacing * (maxHeight-self.height)
self.left.show(maxHeight, spacing)
print("%sT%d (%d, %d)" % (indent, self.output, self.left.output, self.right.output))
self.right.show(maxHeight, spacing)
class TreeBuilder:
(modeLeft, modeRight, modeBalanced, modeRandom, modePermute) = range(5)
# Number of inputs
inputCount = 1
variableCount = 0
roots = []
rootClauses = []
modes = []
leafTrees = []
cnfWriter = None
scheduleWriter = None
orderWriter = None
verbose = False
def __init__(self, count, rootName, verbose = False):
self.verbose = verbose
self.inputCount = count
# Leaves + 2 binary trees
fullCount = 3 * count - 2
self.leafTrees = [Node(v) for v in range(1, count+1)]
self.variableCount = count
self.roots = []
self.modes = []
self.cnfWriter = writer.CnfWriter(fullCount, rootName, self.verbose)
self.scheduleWriter = writer.ScheduleWriter(fullCount, rootName, self.verbose)
self.orderWriter = writer.OrderWriter(fullCount, rootName, self.verbose)
def findMode(self, shortName):
names = {"L": self.modeLeft,
"R": self.modeRight,
"B": self.modeBalanced,
"X": self.modeRandom,
"P": self.modePermute}
if shortName in names:
return names[shortName]
print("Unknown mode '%s'. Aborting" % shortName)
sys.exit(1)
def getModeName(self, mode):
return ["Left", "Right", "Balanced", "Random", "Permuted"][mode]
def addRoot(self, mode):
subtrees = self.leafTrees
if mode == self.modeLeft:
root = self.buildSplit(subtrees, self.chooseMost)
elif mode == self.modeRight:
root = self.buildSplit(subtrees, self.chooseLeast)
elif mode == self.modeBalanced:
root = self.buildSplit(subtrees, self.chooseHalf)
elif mode == self.modeRandom:
root = self.buildRandom(subtrees)
else:
# Permuted mode: Left tree with permuted leaves
random.shuffle(subtrees)
root = self.buildSplit(subtrees, self.chooseMost)
self.roots.append(root)
self.modes.append(mode)
def buildSplit(self, subtrees, leftChooser):
if len(subtrees) == 1:
return subtrees[0]
leftCount = leftChooser(len(subtrees))
leftTrees = subtrees[:leftCount]
rightTrees = subtrees[leftCount:]
leftRoot = self.buildSplit(leftTrees, leftChooser)
rightRoot = self.buildSplit(rightTrees, leftChooser)
self.variableCount += 1
root = TreeNode(self.variableCount, leftRoot, rightRoot)
return root
def chooseLeast(self, count):
return 1
def chooseMost(self, count):
return count-1
def chooseHalf(self, count):
return count // 2
def buildRandom(self, subtrees):
while len(subtrees) > 1:
id1 = random.choice(list(range(len(subtrees))))
t1 = subtrees[id1]
subtrees = subtrees[:id1] + subtrees[id1+1:]
id2 = random.choice(list(range(len(subtrees))))
t2 = subtrees[id2]
subtrees = subtrees[:id2] + subtrees[id2+1:]
self.variableCount += 1
tn = TreeNode(self.variableCount, t1, t2)
subtrees.append(tn)
return subtrees[0]
def emitCnf(self):
if len(self.roots) != 2:
print("Fatal: Must have two roots.")
sys.exit(1)
for root in self.roots:
root.emitClauses(self.cnfWriter)
# Emit comparator
id1 = self.roots[0].output
id2 = self.roots[1].output
self.rootClauses = []
self.cnfWriter.doComment("Comparison of two tree roots")
self.rootClauses.append(self.cnfWriter.doClause([id1, id2]))
self.rootClauses.append(self.cnfWriter.doClause([-id1, -id2]))
self.cnfWriter.finish()
def emitSchedule(self):
if len(self.roots) != 2:
print("Fatal: Must have two roots.")
sys.exit(1)
for root in self.roots:
self.scheduleWriter.newTree()
root.emitSchedule(self.scheduleWriter)
# Final steps. Have two roots on stack
self.scheduleWriter.getClauses(self.rootClauses)
self.scheduleWriter.doAnd(3)
self.scheduleWriter.finish()
def emitOrder(self, doFlip = False, doRandom = False):
if doRandom:
vars = list(range(1, self.variableCount+1))
random.shuffle(vars)
self.orderWriter.doOrder(vars)
self.orderWriter.finish()
return
varDict1 = {}
self.roots[0].getVariables(varDict1)
keyFun = (lambda h : h) if doFlip else (lambda h : -h)
h1list = sorted(varDict1.keys(), key = keyFun)
for k in h1list:
self.orderWriter.doOrder(varDict1[k])
varDict2 = {}
self.roots[1].getVariables(varDict2)
h2list = sorted(varDict2.keys(), key = keyFun)
for k in h2list:
self.orderWriter.doOrder(varDict2[k])
leaves = list(range(1, self.inputCount+1))
if self.modeLeft in self.modes or self.modePermute in self.modes:
leaves.reverse()
self.orderWriter.doOrder(leaves)
self.orderWriter.finish()
def run(name, args):
verbose = False
count = 0
rootName = None
mstring = ""
doFlip = False
doRandom = False
optlist, args = getopt.getopt(args, "hvr:n:m:O:")
for (opt, val) in optlist:
if opt == '-h':
usage(name)
return
elif opt == '-O':
if val == 'f':
doFlip = True
elif val == 'r':
doRandom = True
else:
print("Unknown ordering mode '%s'" % val)
return
elif opt == '-v':
verbose = True
elif opt == '-r':
rootName = val
elif opt == '-n':
count = int(val)
elif opt == '-m':
if len(val) != 2:
print("Must specify two tree building modes")
usage(name)
return
mstring = val
if count == 0:
print("Count required")
return
if rootName is None:
print("Root name required")
return
t = TreeBuilder(count, rootName, verbose)
for m in mstring:
mode = t.findMode(m)
t.addRoot(mode)
t.emitCnf()
t.emitOrder(doFlip = doFlip, doRandom = doRandom)
t.emitSchedule()
if __name__ == "__main__":
run(sys.argv[0], sys.argv[1:])
|
python
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = [
'ClientAddonsArgs',
'ClientAddonsSamlpArgs',
'ClientAddonsSamlpLogoutArgs',
'ClientJwtConfigurationArgs',
'ClientMobileArgs',
'ClientMobileAndroidArgs',
'ClientMobileIosArgs',
'ClientRefreshTokenArgs',
'ConnectionOptionsArgs',
'ConnectionOptionsIdpInitiatedArgs',
'ConnectionOptionsMfaArgs',
'ConnectionOptionsPasswordComplexityOptionsArgs',
'ConnectionOptionsPasswordDictionaryArgs',
'ConnectionOptionsPasswordHistoryArgs',
'ConnectionOptionsPasswordNoPersonalInfoArgs',
'ConnectionOptionsTotpArgs',
'ConnectionOptionsValidationArgs',
'ConnectionOptionsValidationUsernameArgs',
'CustomDomainVerificationArgs',
'EmailCredentialsArgs',
'GlobalClientAddonsArgs',
'GlobalClientAddonsSamlpArgs',
'GlobalClientAddonsSamlpLogoutArgs',
'GlobalClientJwtConfigurationArgs',
'GlobalClientMobileArgs',
'GlobalClientMobileAndroidArgs',
'GlobalClientMobileIosArgs',
'GlobalClientRefreshTokenArgs',
'GuardianPhoneArgs',
'GuardianPhoneOptionsArgs',
'LogStreamSinkArgs',
'ResourceServerScopeArgs',
'RolePermissionArgs',
'TenantChangePasswordArgs',
'TenantErrorPageArgs',
'TenantFlagsArgs',
'TenantGuardianMfaPageArgs',
'TenantUniversalLoginArgs',
'TenantUniversalLoginColorsArgs',
]
@pulumi.input_type
class ClientAddonsArgs:
def __init__(__self__, *,
aws: Optional[pulumi.Input[Mapping[str, Any]]] = None,
azure_blob: Optional[pulumi.Input[Mapping[str, Any]]] = None,
azure_sb: Optional[pulumi.Input[Mapping[str, Any]]] = None,
box: Optional[pulumi.Input[Mapping[str, Any]]] = None,
cloudbees: Optional[pulumi.Input[Mapping[str, Any]]] = None,
concur: Optional[pulumi.Input[Mapping[str, Any]]] = None,
dropbox: Optional[pulumi.Input[Mapping[str, Any]]] = None,
echosign: Optional[pulumi.Input[Mapping[str, Any]]] = None,
egnyte: Optional[pulumi.Input[Mapping[str, Any]]] = None,
firebase: Optional[pulumi.Input[Mapping[str, Any]]] = None,
layer: Optional[pulumi.Input[Mapping[str, Any]]] = None,
mscrm: Optional[pulumi.Input[Mapping[str, Any]]] = None,
newrelic: Optional[pulumi.Input[Mapping[str, Any]]] = None,
office365: Optional[pulumi.Input[Mapping[str, Any]]] = None,
rms: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce_sandbox_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
samlp: Optional[pulumi.Input['ClientAddonsSamlpArgs']] = None,
sap_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
sentry: Optional[pulumi.Input[Mapping[str, Any]]] = None,
sharepoint: Optional[pulumi.Input[Mapping[str, Any]]] = None,
slack: Optional[pulumi.Input[Mapping[str, Any]]] = None,
springcm: Optional[pulumi.Input[Mapping[str, Any]]] = None,
wams: Optional[pulumi.Input[Mapping[str, Any]]] = None,
wsfed: Optional[pulumi.Input[Mapping[str, Any]]] = None,
zendesk: Optional[pulumi.Input[Mapping[str, Any]]] = None,
zoom: Optional[pulumi.Input[Mapping[str, Any]]] = None):
"""
:param pulumi.Input[Mapping[str, Any]] aws: String
:param pulumi.Input[Mapping[str, Any]] azure_blob: String
:param pulumi.Input[Mapping[str, Any]] azure_sb: String
:param pulumi.Input[Mapping[str, Any]] box: String
:param pulumi.Input[Mapping[str, Any]] cloudbees: String
:param pulumi.Input[Mapping[str, Any]] concur: String
:param pulumi.Input[Mapping[str, Any]] dropbox: String
:param pulumi.Input[Mapping[str, Any]] echosign: String
:param pulumi.Input[Mapping[str, Any]] egnyte: String
:param pulumi.Input[Mapping[str, Any]] firebase: String
:param pulumi.Input[Mapping[str, Any]] layer: String
:param pulumi.Input[Mapping[str, Any]] mscrm: String
:param pulumi.Input[Mapping[str, Any]] newrelic: String
:param pulumi.Input[Mapping[str, Any]] office365: String
:param pulumi.Input[Mapping[str, Any]] rms: String
:param pulumi.Input[Mapping[str, Any]] salesforce: String
:param pulumi.Input[Mapping[str, Any]] salesforce_api: String
:param pulumi.Input[Mapping[str, Any]] salesforce_sandbox_api: String
:param pulumi.Input['ClientAddonsSamlpArgs'] samlp: List(Resource). Configuration settings for a SAML add-on. For details, see SAML.
:param pulumi.Input[Mapping[str, Any]] sap_api: String
:param pulumi.Input[Mapping[str, Any]] sentry: String
:param pulumi.Input[Mapping[str, Any]] sharepoint: String
:param pulumi.Input[Mapping[str, Any]] slack: String
:param pulumi.Input[Mapping[str, Any]] springcm: String
:param pulumi.Input[Mapping[str, Any]] wams: String
:param pulumi.Input[Mapping[str, Any]] wsfed: String
:param pulumi.Input[Mapping[str, Any]] zendesk: String
:param pulumi.Input[Mapping[str, Any]] zoom: String
"""
if aws is not None:
pulumi.set(__self__, "aws", aws)
if azure_blob is not None:
pulumi.set(__self__, "azure_blob", azure_blob)
if azure_sb is not None:
pulumi.set(__self__, "azure_sb", azure_sb)
if box is not None:
pulumi.set(__self__, "box", box)
if cloudbees is not None:
pulumi.set(__self__, "cloudbees", cloudbees)
if concur is not None:
pulumi.set(__self__, "concur", concur)
if dropbox is not None:
pulumi.set(__self__, "dropbox", dropbox)
if echosign is not None:
pulumi.set(__self__, "echosign", echosign)
if egnyte is not None:
pulumi.set(__self__, "egnyte", egnyte)
if firebase is not None:
pulumi.set(__self__, "firebase", firebase)
if layer is not None:
pulumi.set(__self__, "layer", layer)
if mscrm is not None:
pulumi.set(__self__, "mscrm", mscrm)
if newrelic is not None:
pulumi.set(__self__, "newrelic", newrelic)
if office365 is not None:
pulumi.set(__self__, "office365", office365)
if rms is not None:
pulumi.set(__self__, "rms", rms)
if salesforce is not None:
pulumi.set(__self__, "salesforce", salesforce)
if salesforce_api is not None:
pulumi.set(__self__, "salesforce_api", salesforce_api)
if salesforce_sandbox_api is not None:
pulumi.set(__self__, "salesforce_sandbox_api", salesforce_sandbox_api)
if samlp is not None:
pulumi.set(__self__, "samlp", samlp)
if sap_api is not None:
pulumi.set(__self__, "sap_api", sap_api)
if sentry is not None:
pulumi.set(__self__, "sentry", sentry)
if sharepoint is not None:
pulumi.set(__self__, "sharepoint", sharepoint)
if slack is not None:
pulumi.set(__self__, "slack", slack)
if springcm is not None:
pulumi.set(__self__, "springcm", springcm)
if wams is not None:
pulumi.set(__self__, "wams", wams)
if wsfed is not None:
pulumi.set(__self__, "wsfed", wsfed)
if zendesk is not None:
pulumi.set(__self__, "zendesk", zendesk)
if zoom is not None:
pulumi.set(__self__, "zoom", zoom)
@property
@pulumi.getter
def aws(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "aws")
@aws.setter
def aws(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "aws", value)
@property
@pulumi.getter(name="azureBlob")
def azure_blob(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "azure_blob")
@azure_blob.setter
def azure_blob(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "azure_blob", value)
@property
@pulumi.getter(name="azureSb")
def azure_sb(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "azure_sb")
@azure_sb.setter
def azure_sb(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "azure_sb", value)
@property
@pulumi.getter
def box(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "box")
@box.setter
def box(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "box", value)
@property
@pulumi.getter
def cloudbees(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "cloudbees")
@cloudbees.setter
def cloudbees(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "cloudbees", value)
@property
@pulumi.getter
def concur(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "concur")
@concur.setter
def concur(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "concur", value)
@property
@pulumi.getter
def dropbox(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "dropbox")
@dropbox.setter
def dropbox(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "dropbox", value)
@property
@pulumi.getter
def echosign(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "echosign")
@echosign.setter
def echosign(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "echosign", value)
@property
@pulumi.getter
def egnyte(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "egnyte")
@egnyte.setter
def egnyte(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "egnyte", value)
@property
@pulumi.getter
def firebase(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "firebase")
@firebase.setter
def firebase(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "firebase", value)
@property
@pulumi.getter
def layer(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "layer")
@layer.setter
def layer(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "layer", value)
@property
@pulumi.getter
def mscrm(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "mscrm")
@mscrm.setter
def mscrm(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "mscrm", value)
@property
@pulumi.getter
def newrelic(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "newrelic")
@newrelic.setter
def newrelic(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "newrelic", value)
@property
@pulumi.getter
def office365(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "office365")
@office365.setter
def office365(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "office365", value)
@property
@pulumi.getter
def rms(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "rms")
@rms.setter
def rms(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "rms", value)
@property
@pulumi.getter
def salesforce(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "salesforce")
@salesforce.setter
def salesforce(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce", value)
@property
@pulumi.getter(name="salesforceApi")
def salesforce_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "salesforce_api")
@salesforce_api.setter
def salesforce_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce_api", value)
@property
@pulumi.getter(name="salesforceSandboxApi")
def salesforce_sandbox_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "salesforce_sandbox_api")
@salesforce_sandbox_api.setter
def salesforce_sandbox_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce_sandbox_api", value)
@property
@pulumi.getter
def samlp(self) -> Optional[pulumi.Input['ClientAddonsSamlpArgs']]:
"""
List(Resource). Configuration settings for a SAML add-on. For details, see SAML.
"""
return pulumi.get(self, "samlp")
@samlp.setter
def samlp(self, value: Optional[pulumi.Input['ClientAddonsSamlpArgs']]):
pulumi.set(self, "samlp", value)
@property
@pulumi.getter(name="sapApi")
def sap_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "sap_api")
@sap_api.setter
def sap_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sap_api", value)
@property
@pulumi.getter
def sentry(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "sentry")
@sentry.setter
def sentry(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sentry", value)
@property
@pulumi.getter
def sharepoint(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "sharepoint")
@sharepoint.setter
def sharepoint(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sharepoint", value)
@property
@pulumi.getter
def slack(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "slack")
@slack.setter
def slack(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "slack", value)
@property
@pulumi.getter
def springcm(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "springcm")
@springcm.setter
def springcm(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "springcm", value)
@property
@pulumi.getter
def wams(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "wams")
@wams.setter
def wams(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "wams", value)
@property
@pulumi.getter
def wsfed(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "wsfed")
@wsfed.setter
def wsfed(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "wsfed", value)
@property
@pulumi.getter
def zendesk(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "zendesk")
@zendesk.setter
def zendesk(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "zendesk", value)
@property
@pulumi.getter
def zoom(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
String
"""
return pulumi.get(self, "zoom")
@zoom.setter
def zoom(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "zoom", value)
@pulumi.input_type
class ClientAddonsSamlpArgs:
def __init__(__self__, *,
audience: Optional[pulumi.Input[str]] = None,
authn_context_class_ref: Optional[pulumi.Input[str]] = None,
binding: Optional[pulumi.Input[str]] = None,
create_upn_claim: Optional[pulumi.Input[bool]] = None,
destination: Optional[pulumi.Input[str]] = None,
digest_algorithm: Optional[pulumi.Input[str]] = None,
include_attribute_name_format: Optional[pulumi.Input[bool]] = None,
lifetime_in_seconds: Optional[pulumi.Input[int]] = None,
logout: Optional[pulumi.Input['ClientAddonsSamlpLogoutArgs']] = None,
map_identities: Optional[pulumi.Input[bool]] = None,
map_unknown_claims_as_is: Optional[pulumi.Input[bool]] = None,
mappings: Optional[pulumi.Input[Mapping[str, Any]]] = None,
name_identifier_format: Optional[pulumi.Input[str]] = None,
name_identifier_probes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
passthrough_claims_with_no_mapping: Optional[pulumi.Input[bool]] = None,
recipient: Optional[pulumi.Input[str]] = None,
sign_response: Optional[pulumi.Input[bool]] = None,
signature_algorithm: Optional[pulumi.Input[str]] = None,
typed_attributes: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[str] audience: String. Audience of the SAML Assertion. Default will be the Issuer on SAMLRequest.
:param pulumi.Input[str] authn_context_class_ref: String. Class reference of the authentication context.
:param pulumi.Input[str] binding: String. Protocol binding used for SAML logout responses.
:param pulumi.Input[bool] create_upn_claim: Boolean, (Default=true) Indicates whether or not a UPN claim should be created.
:param pulumi.Input[str] destination: String. Destination of the SAML Response. If not specified, it will be AssertionConsumerUrlof SAMLRequest or Callback URL if there was no SAMLRequest.
:param pulumi.Input[str] digest_algorithm: String, (Default=`sha1`). Algorithm used to calculate the digest of the SAML Assertion or response. Options include `defaultsha1` and `sha256`.
:param pulumi.Input[bool] include_attribute_name_format: Boolean,(Default=true). Indicates whether or not we should infer the NameFormat based on the attribute name. If set to false, the attribute NameFormat is not set in the assertion.
:param pulumi.Input[int] lifetime_in_seconds: Integer, (Default=3600). Number of seconds during which the token is valid.
:param pulumi.Input['ClientAddonsSamlpLogoutArgs'] logout: Map(Resource). Configuration settings for logout. For details, see Logout.
:param pulumi.Input[bool] map_identities: Boolean, (Default=true). Indicates whether or not to add additional identity information in the token, such as the provider used and the access_token, if available.
:param pulumi.Input[bool] map_unknown_claims_as_is: Boolean, (Default=false). Indicates whether or not to add a prefix of `http://schema.auth0.com` to any claims that are not mapped to the common profile when passed through in the output assertion.
:param pulumi.Input[Mapping[str, Any]] mappings: Map(String). Mappings between the Auth0 user profile property name (`name`) and the output attributes on the SAML attribute in the assertion (`value`).
:param pulumi.Input[str] name_identifier_format: String, (Default=`urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified`). Format of the name identifier.
:param pulumi.Input[Sequence[pulumi.Input[str]]] name_identifier_probes: List(String). Attributes that can be used for Subject/NameID. Auth0 will try each of the attributes of this array in order and use the first value it finds.
:param pulumi.Input[bool] passthrough_claims_with_no_mapping: Boolean, (Default=true). Indicates whether or not to passthrough claims that are not mapped to the common profile in the output assertion.
:param pulumi.Input[str] recipient: String. Recipient of the SAML Assertion (SubjectConfirmationData). Default is AssertionConsumerUrl on SAMLRequest or Callback URL if no SAMLRequest was sent.
:param pulumi.Input[bool] sign_response: Boolean. Indicates whether or not the SAML Response should be signed instead of the SAML Assertion.
:param pulumi.Input[str] signature_algorithm: String, (Default=`rsa-sha1`). Algorithm used to sign the SAML Assertion or response. Options include `rsa-sha1` and `rsa-sha256`.
:param pulumi.Input[bool] typed_attributes: Boolean, (Default=true). Indicates whether or not we should infer the `xs:type` of the element. Types include `xs:string`, `xs:boolean`, `xs:double`, and `xs:anyType`. When set to false, all `xs:type` are `xs:anyType`.
"""
if audience is not None:
pulumi.set(__self__, "audience", audience)
if authn_context_class_ref is not None:
pulumi.set(__self__, "authn_context_class_ref", authn_context_class_ref)
if binding is not None:
pulumi.set(__self__, "binding", binding)
if create_upn_claim is not None:
pulumi.set(__self__, "create_upn_claim", create_upn_claim)
if destination is not None:
pulumi.set(__self__, "destination", destination)
if digest_algorithm is not None:
pulumi.set(__self__, "digest_algorithm", digest_algorithm)
if include_attribute_name_format is not None:
pulumi.set(__self__, "include_attribute_name_format", include_attribute_name_format)
if lifetime_in_seconds is not None:
pulumi.set(__self__, "lifetime_in_seconds", lifetime_in_seconds)
if logout is not None:
pulumi.set(__self__, "logout", logout)
if map_identities is not None:
pulumi.set(__self__, "map_identities", map_identities)
if map_unknown_claims_as_is is not None:
pulumi.set(__self__, "map_unknown_claims_as_is", map_unknown_claims_as_is)
if mappings is not None:
pulumi.set(__self__, "mappings", mappings)
if name_identifier_format is not None:
pulumi.set(__self__, "name_identifier_format", name_identifier_format)
if name_identifier_probes is not None:
pulumi.set(__self__, "name_identifier_probes", name_identifier_probes)
if passthrough_claims_with_no_mapping is not None:
pulumi.set(__self__, "passthrough_claims_with_no_mapping", passthrough_claims_with_no_mapping)
if recipient is not None:
pulumi.set(__self__, "recipient", recipient)
if sign_response is not None:
pulumi.set(__self__, "sign_response", sign_response)
if signature_algorithm is not None:
pulumi.set(__self__, "signature_algorithm", signature_algorithm)
if typed_attributes is not None:
pulumi.set(__self__, "typed_attributes", typed_attributes)
@property
@pulumi.getter
def audience(self) -> Optional[pulumi.Input[str]]:
"""
String. Audience of the SAML Assertion. Default will be the Issuer on SAMLRequest.
"""
return pulumi.get(self, "audience")
@audience.setter
def audience(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "audience", value)
@property
@pulumi.getter(name="authnContextClassRef")
def authn_context_class_ref(self) -> Optional[pulumi.Input[str]]:
"""
String. Class reference of the authentication context.
"""
return pulumi.get(self, "authn_context_class_ref")
@authn_context_class_ref.setter
def authn_context_class_ref(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "authn_context_class_ref", value)
@property
@pulumi.getter
def binding(self) -> Optional[pulumi.Input[str]]:
"""
String. Protocol binding used for SAML logout responses.
"""
return pulumi.get(self, "binding")
@binding.setter
def binding(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "binding", value)
@property
@pulumi.getter(name="createUpnClaim")
def create_upn_claim(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=true) Indicates whether or not a UPN claim should be created.
"""
return pulumi.get(self, "create_upn_claim")
@create_upn_claim.setter
def create_upn_claim(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "create_upn_claim", value)
@property
@pulumi.getter
def destination(self) -> Optional[pulumi.Input[str]]:
"""
String. Destination of the SAML Response. If not specified, it will be AssertionConsumerUrlof SAMLRequest or Callback URL if there was no SAMLRequest.
"""
return pulumi.get(self, "destination")
@destination.setter
def destination(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "destination", value)
@property
@pulumi.getter(name="digestAlgorithm")
def digest_algorithm(self) -> Optional[pulumi.Input[str]]:
"""
String, (Default=`sha1`). Algorithm used to calculate the digest of the SAML Assertion or response. Options include `defaultsha1` and `sha256`.
"""
return pulumi.get(self, "digest_algorithm")
@digest_algorithm.setter
def digest_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "digest_algorithm", value)
@property
@pulumi.getter(name="includeAttributeNameFormat")
def include_attribute_name_format(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean,(Default=true). Indicates whether or not we should infer the NameFormat based on the attribute name. If set to false, the attribute NameFormat is not set in the assertion.
"""
return pulumi.get(self, "include_attribute_name_format")
@include_attribute_name_format.setter
def include_attribute_name_format(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "include_attribute_name_format", value)
@property
@pulumi.getter(name="lifetimeInSeconds")
def lifetime_in_seconds(self) -> Optional[pulumi.Input[int]]:
"""
Integer, (Default=3600). Number of seconds during which the token is valid.
"""
return pulumi.get(self, "lifetime_in_seconds")
@lifetime_in_seconds.setter
def lifetime_in_seconds(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lifetime_in_seconds", value)
@property
@pulumi.getter
def logout(self) -> Optional[pulumi.Input['ClientAddonsSamlpLogoutArgs']]:
"""
Map(Resource). Configuration settings for logout. For details, see Logout.
"""
return pulumi.get(self, "logout")
@logout.setter
def logout(self, value: Optional[pulumi.Input['ClientAddonsSamlpLogoutArgs']]):
pulumi.set(self, "logout", value)
@property
@pulumi.getter(name="mapIdentities")
def map_identities(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=true). Indicates whether or not to add additional identity information in the token, such as the provider used and the access_token, if available.
"""
return pulumi.get(self, "map_identities")
@map_identities.setter
def map_identities(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "map_identities", value)
@property
@pulumi.getter(name="mapUnknownClaimsAsIs")
def map_unknown_claims_as_is(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=false). Indicates whether or not to add a prefix of `http://schema.auth0.com` to any claims that are not mapped to the common profile when passed through in the output assertion.
"""
return pulumi.get(self, "map_unknown_claims_as_is")
@map_unknown_claims_as_is.setter
def map_unknown_claims_as_is(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "map_unknown_claims_as_is", value)
@property
@pulumi.getter
def mappings(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
"""
Map(String). Mappings between the Auth0 user profile property name (`name`) and the output attributes on the SAML attribute in the assertion (`value`).
"""
return pulumi.get(self, "mappings")
@mappings.setter
def mappings(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "mappings", value)
@property
@pulumi.getter(name="nameIdentifierFormat")
def name_identifier_format(self) -> Optional[pulumi.Input[str]]:
"""
String, (Default=`urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified`). Format of the name identifier.
"""
return pulumi.get(self, "name_identifier_format")
@name_identifier_format.setter
def name_identifier_format(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name_identifier_format", value)
@property
@pulumi.getter(name="nameIdentifierProbes")
def name_identifier_probes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
List(String). Attributes that can be used for Subject/NameID. Auth0 will try each of the attributes of this array in order and use the first value it finds.
"""
return pulumi.get(self, "name_identifier_probes")
@name_identifier_probes.setter
def name_identifier_probes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "name_identifier_probes", value)
@property
@pulumi.getter(name="passthroughClaimsWithNoMapping")
def passthrough_claims_with_no_mapping(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=true). Indicates whether or not to passthrough claims that are not mapped to the common profile in the output assertion.
"""
return pulumi.get(self, "passthrough_claims_with_no_mapping")
@passthrough_claims_with_no_mapping.setter
def passthrough_claims_with_no_mapping(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "passthrough_claims_with_no_mapping", value)
@property
@pulumi.getter
def recipient(self) -> Optional[pulumi.Input[str]]:
"""
String. Recipient of the SAML Assertion (SubjectConfirmationData). Default is AssertionConsumerUrl on SAMLRequest or Callback URL if no SAMLRequest was sent.
"""
return pulumi.get(self, "recipient")
@recipient.setter
def recipient(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "recipient", value)
@property
@pulumi.getter(name="signResponse")
def sign_response(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the SAML Response should be signed instead of the SAML Assertion.
"""
return pulumi.get(self, "sign_response")
@sign_response.setter
def sign_response(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "sign_response", value)
@property
@pulumi.getter(name="signatureAlgorithm")
def signature_algorithm(self) -> Optional[pulumi.Input[str]]:
"""
String, (Default=`rsa-sha1`). Algorithm used to sign the SAML Assertion or response. Options include `rsa-sha1` and `rsa-sha256`.
"""
return pulumi.get(self, "signature_algorithm")
@signature_algorithm.setter
def signature_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "signature_algorithm", value)
@property
@pulumi.getter(name="typedAttributes")
def typed_attributes(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=true). Indicates whether or not we should infer the `xs:type` of the element. Types include `xs:string`, `xs:boolean`, `xs:double`, and `xs:anyType`. When set to false, all `xs:type` are `xs:anyType`.
"""
return pulumi.get(self, "typed_attributes")
@typed_attributes.setter
def typed_attributes(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "typed_attributes", value)
@pulumi.input_type
class ClientAddonsSamlpLogoutArgs:
def __init__(__self__, *,
callback: Optional[pulumi.Input[str]] = None,
slo_enabled: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[str] callback: String. Service provider's Single Logout Service URL, to which Auth0 will send logout requests and responses.
:param pulumi.Input[bool] slo_enabled: Boolean. Indicates whether or not Auth0 should notify service providers of session termination.
"""
if callback is not None:
pulumi.set(__self__, "callback", callback)
if slo_enabled is not None:
pulumi.set(__self__, "slo_enabled", slo_enabled)
@property
@pulumi.getter
def callback(self) -> Optional[pulumi.Input[str]]:
"""
String. Service provider's Single Logout Service URL, to which Auth0 will send logout requests and responses.
"""
return pulumi.get(self, "callback")
@callback.setter
def callback(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "callback", value)
@property
@pulumi.getter(name="sloEnabled")
def slo_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not Auth0 should notify service providers of session termination.
"""
return pulumi.get(self, "slo_enabled")
@slo_enabled.setter
def slo_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "slo_enabled", value)
@pulumi.input_type
class ClientJwtConfigurationArgs:
def __init__(__self__, *,
alg: Optional[pulumi.Input[str]] = None,
lifetime_in_seconds: Optional[pulumi.Input[int]] = None,
scopes: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
secret_encoded: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[str] alg: String. Algorithm used to sign JWTs.
:param pulumi.Input[int] lifetime_in_seconds: Integer. Number of seconds during which the JWT will be valid.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] scopes: Map(String). Permissions (scopes) included in JWTs.
:param pulumi.Input[bool] secret_encoded: Boolean. Indicates whether or not the client secret is base64 encoded.
"""
if alg is not None:
pulumi.set(__self__, "alg", alg)
if lifetime_in_seconds is not None:
pulumi.set(__self__, "lifetime_in_seconds", lifetime_in_seconds)
if scopes is not None:
pulumi.set(__self__, "scopes", scopes)
if secret_encoded is not None:
pulumi.set(__self__, "secret_encoded", secret_encoded)
@property
@pulumi.getter
def alg(self) -> Optional[pulumi.Input[str]]:
"""
String. Algorithm used to sign JWTs.
"""
return pulumi.get(self, "alg")
@alg.setter
def alg(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "alg", value)
@property
@pulumi.getter(name="lifetimeInSeconds")
def lifetime_in_seconds(self) -> Optional[pulumi.Input[int]]:
"""
Integer. Number of seconds during which the JWT will be valid.
"""
return pulumi.get(self, "lifetime_in_seconds")
@lifetime_in_seconds.setter
def lifetime_in_seconds(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lifetime_in_seconds", value)
@property
@pulumi.getter
def scopes(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Map(String). Permissions (scopes) included in JWTs.
"""
return pulumi.get(self, "scopes")
@scopes.setter
def scopes(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "scopes", value)
@property
@pulumi.getter(name="secretEncoded")
def secret_encoded(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the client secret is base64 encoded.
"""
return pulumi.get(self, "secret_encoded")
@secret_encoded.setter
def secret_encoded(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "secret_encoded", value)
@pulumi.input_type
class ClientMobileArgs:
def __init__(__self__, *,
android: Optional[pulumi.Input['ClientMobileAndroidArgs']] = None,
ios: Optional[pulumi.Input['ClientMobileIosArgs']] = None):
"""
:param pulumi.Input['ClientMobileAndroidArgs'] android: List(Resource). Configuration settings for Android native apps. For details, see Android.
:param pulumi.Input['ClientMobileIosArgs'] ios: List(Resource). Configuration settings for i0S native apps. For details, see iOS.
"""
if android is not None:
pulumi.set(__self__, "android", android)
if ios is not None:
pulumi.set(__self__, "ios", ios)
@property
@pulumi.getter
def android(self) -> Optional[pulumi.Input['ClientMobileAndroidArgs']]:
"""
List(Resource). Configuration settings for Android native apps. For details, see Android.
"""
return pulumi.get(self, "android")
@android.setter
def android(self, value: Optional[pulumi.Input['ClientMobileAndroidArgs']]):
pulumi.set(self, "android", value)
@property
@pulumi.getter
def ios(self) -> Optional[pulumi.Input['ClientMobileIosArgs']]:
"""
List(Resource). Configuration settings for i0S native apps. For details, see iOS.
"""
return pulumi.get(self, "ios")
@ios.setter
def ios(self, value: Optional[pulumi.Input['ClientMobileIosArgs']]):
pulumi.set(self, "ios", value)
@pulumi.input_type
class ClientMobileAndroidArgs:
def __init__(__self__, *,
app_package_name: Optional[pulumi.Input[str]] = None,
sha256_cert_fingerprints: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None):
"""
:param pulumi.Input[str] app_package_name: String
:param pulumi.Input[Sequence[pulumi.Input[str]]] sha256_cert_fingerprints: List(String)
"""
if app_package_name is not None:
pulumi.set(__self__, "app_package_name", app_package_name)
if sha256_cert_fingerprints is not None:
pulumi.set(__self__, "sha256_cert_fingerprints", sha256_cert_fingerprints)
@property
@pulumi.getter(name="appPackageName")
def app_package_name(self) -> Optional[pulumi.Input[str]]:
"""
String
"""
return pulumi.get(self, "app_package_name")
@app_package_name.setter
def app_package_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_package_name", value)
@property
@pulumi.getter(name="sha256CertFingerprints")
def sha256_cert_fingerprints(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
List(String)
"""
return pulumi.get(self, "sha256_cert_fingerprints")
@sha256_cert_fingerprints.setter
def sha256_cert_fingerprints(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "sha256_cert_fingerprints", value)
@pulumi.input_type
class ClientMobileIosArgs:
def __init__(__self__, *,
app_bundle_identifier: Optional[pulumi.Input[str]] = None,
team_id: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] app_bundle_identifier: String
:param pulumi.Input[str] team_id: String
"""
if app_bundle_identifier is not None:
pulumi.set(__self__, "app_bundle_identifier", app_bundle_identifier)
if team_id is not None:
pulumi.set(__self__, "team_id", team_id)
@property
@pulumi.getter(name="appBundleIdentifier")
def app_bundle_identifier(self) -> Optional[pulumi.Input[str]]:
"""
String
"""
return pulumi.get(self, "app_bundle_identifier")
@app_bundle_identifier.setter
def app_bundle_identifier(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_bundle_identifier", value)
@property
@pulumi.getter(name="teamId")
def team_id(self) -> Optional[pulumi.Input[str]]:
"""
String
"""
return pulumi.get(self, "team_id")
@team_id.setter
def team_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "team_id", value)
@pulumi.input_type
class ClientRefreshTokenArgs:
def __init__(__self__, *,
expiration_type: pulumi.Input[str],
rotation_type: pulumi.Input[str],
idle_token_lifetime: Optional[pulumi.Input[int]] = None,
infinite_idle_token_lifetime: Optional[pulumi.Input[bool]] = None,
infinite_token_lifetime: Optional[pulumi.Input[bool]] = None,
leeway: Optional[pulumi.Input[int]] = None,
token_lifetime: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[str] expiration_type: String. Options include `expiring`, `non-expiring`. Whether a refresh token will expire based on an absolute lifetime, after which the token can no longer be used. If rotation is `rotating`, this must be set to `expiring`.
:param pulumi.Input[str] rotation_type: String. Options include `rotating`, `non-rotating`. When `rotating`, exchanging a refresh token will cause a new refresh token to be issued and the existing token will be invalidated. This allows for automatic detection of token reuse if the token is leaked.
:param pulumi.Input[int] idle_token_lifetime: Integer. The time in seconds after which inactive refresh tokens will expire.
:param pulumi.Input[bool] infinite_idle_token_lifetime: Boolean, (Default=false) Whether or not inactive refresh tokens should be remain valid indefinitely.
:param pulumi.Input[bool] infinite_token_lifetime: Boolean, (Default=false) Whether or not refresh tokens should remain valid indefinitely. If false, `token_lifetime` should also be set
:param pulumi.Input[int] leeway: Integer. The amount of time in seconds in which a refresh token may be reused without trigging reuse detection.
:param pulumi.Input[int] token_lifetime: Integer. The absolute lifetime of a refresh token in seconds.
"""
pulumi.set(__self__, "expiration_type", expiration_type)
pulumi.set(__self__, "rotation_type", rotation_type)
if idle_token_lifetime is not None:
pulumi.set(__self__, "idle_token_lifetime", idle_token_lifetime)
if infinite_idle_token_lifetime is not None:
pulumi.set(__self__, "infinite_idle_token_lifetime", infinite_idle_token_lifetime)
if infinite_token_lifetime is not None:
pulumi.set(__self__, "infinite_token_lifetime", infinite_token_lifetime)
if leeway is not None:
pulumi.set(__self__, "leeway", leeway)
if token_lifetime is not None:
pulumi.set(__self__, "token_lifetime", token_lifetime)
@property
@pulumi.getter(name="expirationType")
def expiration_type(self) -> pulumi.Input[str]:
"""
String. Options include `expiring`, `non-expiring`. Whether a refresh token will expire based on an absolute lifetime, after which the token can no longer be used. If rotation is `rotating`, this must be set to `expiring`.
"""
return pulumi.get(self, "expiration_type")
@expiration_type.setter
def expiration_type(self, value: pulumi.Input[str]):
pulumi.set(self, "expiration_type", value)
@property
@pulumi.getter(name="rotationType")
def rotation_type(self) -> pulumi.Input[str]:
"""
String. Options include `rotating`, `non-rotating`. When `rotating`, exchanging a refresh token will cause a new refresh token to be issued and the existing token will be invalidated. This allows for automatic detection of token reuse if the token is leaked.
"""
return pulumi.get(self, "rotation_type")
@rotation_type.setter
def rotation_type(self, value: pulumi.Input[str]):
pulumi.set(self, "rotation_type", value)
@property
@pulumi.getter(name="idleTokenLifetime")
def idle_token_lifetime(self) -> Optional[pulumi.Input[int]]:
"""
Integer. The time in seconds after which inactive refresh tokens will expire.
"""
return pulumi.get(self, "idle_token_lifetime")
@idle_token_lifetime.setter
def idle_token_lifetime(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "idle_token_lifetime", value)
@property
@pulumi.getter(name="infiniteIdleTokenLifetime")
def infinite_idle_token_lifetime(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=false) Whether or not inactive refresh tokens should be remain valid indefinitely.
"""
return pulumi.get(self, "infinite_idle_token_lifetime")
@infinite_idle_token_lifetime.setter
def infinite_idle_token_lifetime(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "infinite_idle_token_lifetime", value)
@property
@pulumi.getter(name="infiniteTokenLifetime")
def infinite_token_lifetime(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean, (Default=false) Whether or not refresh tokens should remain valid indefinitely. If false, `token_lifetime` should also be set
"""
return pulumi.get(self, "infinite_token_lifetime")
@infinite_token_lifetime.setter
def infinite_token_lifetime(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "infinite_token_lifetime", value)
@property
@pulumi.getter
def leeway(self) -> Optional[pulumi.Input[int]]:
"""
Integer. The amount of time in seconds in which a refresh token may be reused without trigging reuse detection.
"""
return pulumi.get(self, "leeway")
@leeway.setter
def leeway(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "leeway", value)
@property
@pulumi.getter(name="tokenLifetime")
def token_lifetime(self) -> Optional[pulumi.Input[int]]:
"""
Integer. The absolute lifetime of a refresh token in seconds.
"""
return pulumi.get(self, "token_lifetime")
@token_lifetime.setter
def token_lifetime(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "token_lifetime", value)
@pulumi.input_type
class ConnectionOptionsArgs:
def __init__(__self__, *,
adfs_server: Optional[pulumi.Input[str]] = None,
allowed_audiences: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
api_enable_users: Optional[pulumi.Input[bool]] = None,
app_domain: Optional[pulumi.Input[str]] = None,
app_id: Optional[pulumi.Input[str]] = None,
authorization_endpoint: Optional[pulumi.Input[str]] = None,
brute_force_protection: Optional[pulumi.Input[bool]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_secret: Optional[pulumi.Input[str]] = None,
community_base_url: Optional[pulumi.Input[str]] = None,
configuration: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
custom_scripts: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
debug: Optional[pulumi.Input[bool]] = None,
digest_algorithm: Optional[pulumi.Input[str]] = None,
disable_cache: Optional[pulumi.Input[bool]] = None,
disable_signup: Optional[pulumi.Input[bool]] = None,
discovery_url: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
domain_aliases: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
enabled_database_customization: Optional[pulumi.Input[bool]] = None,
fields_map: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
from_: Optional[pulumi.Input[str]] = None,
icon_url: Optional[pulumi.Input[str]] = None,
identity_api: Optional[pulumi.Input[str]] = None,
idp_initiated: Optional[pulumi.Input['ConnectionOptionsIdpInitiatedArgs']] = None,
import_mode: Optional[pulumi.Input[bool]] = None,
ips: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
issuer: Optional[pulumi.Input[str]] = None,
jwks_uri: Optional[pulumi.Input[str]] = None,
key_id: Optional[pulumi.Input[str]] = None,
max_groups_to_retrieve: Optional[pulumi.Input[str]] = None,
messaging_service_sid: Optional[pulumi.Input[str]] = None,
mfa: Optional[pulumi.Input['ConnectionOptionsMfaArgs']] = None,
name: Optional[pulumi.Input[str]] = None,
non_persistent_attrs: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
password_complexity_options: Optional[pulumi.Input['ConnectionOptionsPasswordComplexityOptionsArgs']] = None,
password_dictionary: Optional[pulumi.Input['ConnectionOptionsPasswordDictionaryArgs']] = None,
password_histories: Optional[pulumi.Input[Sequence[pulumi.Input['ConnectionOptionsPasswordHistoryArgs']]]] = None,
password_no_personal_info: Optional[pulumi.Input['ConnectionOptionsPasswordNoPersonalInfoArgs']] = None,
password_policy: Optional[pulumi.Input[str]] = None,
protocol_binding: Optional[pulumi.Input[str]] = None,
request_template: Optional[pulumi.Input[str]] = None,
requires_username: Optional[pulumi.Input[bool]] = None,
scopes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
scripts: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
set_user_root_attributes: Optional[pulumi.Input[str]] = None,
should_trust_email_verified_connection: Optional[pulumi.Input[str]] = None,
sign_in_endpoint: Optional[pulumi.Input[str]] = None,
sign_out_endpoint: Optional[pulumi.Input[str]] = None,
sign_saml_request: Optional[pulumi.Input[bool]] = None,
signature_algorithm: Optional[pulumi.Input[str]] = None,
signing_cert: Optional[pulumi.Input[str]] = None,
strategy_version: Optional[pulumi.Input[int]] = None,
subject: Optional[pulumi.Input[str]] = None,
syntax: Optional[pulumi.Input[str]] = None,
team_id: Optional[pulumi.Input[str]] = None,
template: Optional[pulumi.Input[str]] = None,
tenant_domain: Optional[pulumi.Input[str]] = None,
token_endpoint: Optional[pulumi.Input[str]] = None,
totp: Optional[pulumi.Input['ConnectionOptionsTotpArgs']] = None,
twilio_sid: Optional[pulumi.Input[str]] = None,
twilio_token: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input[str]] = None,
use_cert_auth: Optional[pulumi.Input[bool]] = None,
use_kerberos: Optional[pulumi.Input[bool]] = None,
use_wsfed: Optional[pulumi.Input[bool]] = None,
user_id_attribute: Optional[pulumi.Input[str]] = None,
userinfo_endpoint: Optional[pulumi.Input[str]] = None,
validation: Optional[pulumi.Input['ConnectionOptionsValidationArgs']] = None,
waad_common_endpoint: Optional[pulumi.Input[bool]] = None,
waad_protocol: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] adfs_server: ADFS Metadata source.
:param pulumi.Input[Sequence[pulumi.Input[str]]] allowed_audiences: List of allowed audiences.
:param pulumi.Input[str] app_domain: Azure AD domain name.
:param pulumi.Input[str] app_id: Azure AD app ID.
:param pulumi.Input[bool] brute_force_protection: Indicates whether or not to enable brute force protection, which will limit the number of signups and failed logins from a suspicious IP address.
:param pulumi.Input[str] client_id: OIDC provider client ID.
:param pulumi.Input[str] client_secret: OIDC provider client secret.
:param pulumi.Input[str] community_base_url: String.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] configuration: A case-sensitive map of key value pairs used as configuration variables for the `custom_script`.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] custom_scripts: Custom database action scripts. For more information, read [Custom Database Action Script Templates](https://auth0.com/docs/connections/database/custom-db/templates).
:param pulumi.Input[bool] debug: (Boolean) When enabled additional debugging information will be generated.
:param pulumi.Input[str] digest_algorithm: Sign Request Algorithm Digest
:param pulumi.Input[bool] disable_signup: Boolean. Indicates whether or not to allow user sign-ups to your application.
:param pulumi.Input[str] discovery_url: OpenID discovery URL. E.g. `https://auth.example.com/.well-known/openid-configuration`.
:param pulumi.Input[Sequence[pulumi.Input[str]]] domain_aliases: List of the domains that can be authenticated using the Identity Provider. Only needed for Identifier First authentication flows.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] fields_map: SAML Attributes mapping. If you're configuring a SAML enterprise connection for a non-standard PingFederate Server, you must update the attribute mappings.
:param pulumi.Input[str] from_: SMS number for the sender. Used when SMS Source is From.
:param pulumi.Input[bool] import_mode: Indicates whether or not you have a legacy user store and want to gradually migrate those users to the Auth0 user store. [Learn more](https://auth0.com/docs/users/guides/configure-automatic-migration).
:param pulumi.Input[str] issuer: Issuer URL. E.g. `https://auth.example.com`
:param pulumi.Input[str] key_id: Key ID.
:param pulumi.Input[str] max_groups_to_retrieve: Maximum number of groups to retrieve.
:param pulumi.Input[str] messaging_service_sid: SID for Copilot. Used when SMS Source is Copilot.
:param pulumi.Input['ConnectionOptionsMfaArgs'] mfa: Configuration settings Options for multifactor authentication. For details, see MFA Options.
:param pulumi.Input[str] name: Name of the connection.
:param pulumi.Input[Sequence[pulumi.Input[str]]] non_persistent_attrs: If there are user fields that should not be stored in Auth0 databases due to privacy reasons, you can add them to the denylist. See [here](https://auth0.com/docs/security/denylist-user-attributes) for more info.
:param pulumi.Input['ConnectionOptionsPasswordComplexityOptionsArgs'] password_complexity_options: Configuration settings for password complexity. For details, see Password Complexity Options.
:param pulumi.Input['ConnectionOptionsPasswordDictionaryArgs'] password_dictionary: Configuration settings for the password dictionary check, which does not allow passwords that are part of the password dictionary. For details, see Password Dictionary.
:param pulumi.Input[Sequence[pulumi.Input['ConnectionOptionsPasswordHistoryArgs']]] password_histories: Configuration settings for the password history that is maintained for each user to prevent the reuse of passwords. For details, see Password History.
:param pulumi.Input['ConnectionOptionsPasswordNoPersonalInfoArgs'] password_no_personal_info: Configuration settings for the password personal info check, which does not allow passwords that contain any part of the user's personal data, including user's name, username, nickname, user_metadata.name, user_metadata.first, user_metadata.last, user's email, or first part of the user's email. For details, see Password No Personal Info.
:param pulumi.Input[str] password_policy: Indicates level of password strength to enforce during authentication. A strong password policy will make it difficult, if not improbable, for someone to guess a password through either manual or automated means. Options include `none`, `low`, `fair`, `good`, `excellent`.
:param pulumi.Input[str] protocol_binding: The SAML Response Binding - how the SAML token is received by Auth0 from IdP. Two possible values are `urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect` (default) and `urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST`
:param pulumi.Input[str] request_template: Template that formats the SAML request
:param pulumi.Input[bool] requires_username: Indicates whether or not the user is required to provide a username in addition to an email address.
:param pulumi.Input[Sequence[pulumi.Input[str]]] scopes: Scopes required by the connection. The value must be a list, for example `["openid", "profile", "email"]`.
:param pulumi.Input[str] set_user_root_attributes: Determines whether the 'name', 'given_name', 'family_name', 'nickname', and 'picture' attributes can be independently updated when using the external IdP. Default is `on_each_login` and can be set to `on_first_login`.
:param pulumi.Input[str] should_trust_email_verified_connection: Determines how Auth0 sets the email_verified field in the user profile. Can either be set to `never_set_emails_as_verified` or `always_set_emails_as_verified`.
:param pulumi.Input[str] sign_in_endpoint: SAML single login URL for the connection.
:param pulumi.Input[str] sign_out_endpoint: SAML single logout URL for the connection.
:param pulumi.Input[bool] sign_saml_request: (Boolean) When enabled, the SAML authentication request will be signed.
:param pulumi.Input[str] signature_algorithm: Sign Request Algorithm
:param pulumi.Input[str] signing_cert: The X.509 signing certificate (encoded in PEM or CER) you retrieved from the IdP, Base64-encoded
:param pulumi.Input[int] strategy_version: Version 1 is deprecated, use version 2.
:param pulumi.Input[str] syntax: Syntax of the SMS. Options include `markdown` and `liquid`.
:param pulumi.Input[str] team_id: Team ID.
:param pulumi.Input[str] template: Template for the SMS. You can use `@@password@@` as a placeholder for the password value.
:param pulumi.Input['ConnectionOptionsTotpArgs'] totp: Configuration options for one-time passwords. For details, see TOTP.
:param pulumi.Input[str] twilio_sid: SID for your Twilio account.
:param pulumi.Input[str] twilio_token: AuthToken for your Twilio account.
:param pulumi.Input[str] type: Value can be `back_channel` or `front_channel`.
:param pulumi.Input[str] user_id_attribute: Attribute in the SAML token that will be mapped to the user_id property in Auth0.
:param pulumi.Input['ConnectionOptionsValidationArgs'] validation: Validation of the minimum and maximum values allowed for a user to have as username. For details, see Validation.
:param pulumi.Input[bool] waad_common_endpoint: Indicates whether or not to use the common endpoint rather than the default endpoint. Typically enabled if you're using this for a multi-tenant application in Azure AD.
"""
if adfs_server is not None:
pulumi.set(__self__, "adfs_server", adfs_server)
if allowed_audiences is not None:
pulumi.set(__self__, "allowed_audiences", allowed_audiences)
if api_enable_users is not None:
pulumi.set(__self__, "api_enable_users", api_enable_users)
if app_domain is not None:
warnings.warn("""use domain instead""", DeprecationWarning)
pulumi.log.warn("""app_domain is deprecated: use domain instead""")
if app_domain is not None:
pulumi.set(__self__, "app_domain", app_domain)
if app_id is not None:
pulumi.set(__self__, "app_id", app_id)
if authorization_endpoint is not None:
pulumi.set(__self__, "authorization_endpoint", authorization_endpoint)
if brute_force_protection is not None:
pulumi.set(__self__, "brute_force_protection", brute_force_protection)
if client_id is not None:
pulumi.set(__self__, "client_id", client_id)
if client_secret is not None:
pulumi.set(__self__, "client_secret", client_secret)
if community_base_url is not None:
pulumi.set(__self__, "community_base_url", community_base_url)
if configuration is not None:
pulumi.set(__self__, "configuration", configuration)
if custom_scripts is not None:
pulumi.set(__self__, "custom_scripts", custom_scripts)
if debug is not None:
pulumi.set(__self__, "debug", debug)
if digest_algorithm is not None:
pulumi.set(__self__, "digest_algorithm", digest_algorithm)
if disable_cache is not None:
pulumi.set(__self__, "disable_cache", disable_cache)
if disable_signup is not None:
pulumi.set(__self__, "disable_signup", disable_signup)
if discovery_url is not None:
pulumi.set(__self__, "discovery_url", discovery_url)
if domain is not None:
pulumi.set(__self__, "domain", domain)
if domain_aliases is not None:
pulumi.set(__self__, "domain_aliases", domain_aliases)
if enabled_database_customization is not None:
pulumi.set(__self__, "enabled_database_customization", enabled_database_customization)
if fields_map is not None:
pulumi.set(__self__, "fields_map", fields_map)
if from_ is not None:
pulumi.set(__self__, "from_", from_)
if icon_url is not None:
pulumi.set(__self__, "icon_url", icon_url)
if identity_api is not None:
pulumi.set(__self__, "identity_api", identity_api)
if idp_initiated is not None:
pulumi.set(__self__, "idp_initiated", idp_initiated)
if import_mode is not None:
pulumi.set(__self__, "import_mode", import_mode)
if ips is not None:
pulumi.set(__self__, "ips", ips)
if issuer is not None:
pulumi.set(__self__, "issuer", issuer)
if jwks_uri is not None:
pulumi.set(__self__, "jwks_uri", jwks_uri)
if key_id is not None:
pulumi.set(__self__, "key_id", key_id)
if max_groups_to_retrieve is not None:
pulumi.set(__self__, "max_groups_to_retrieve", max_groups_to_retrieve)
if messaging_service_sid is not None:
pulumi.set(__self__, "messaging_service_sid", messaging_service_sid)
if mfa is not None:
pulumi.set(__self__, "mfa", mfa)
if name is not None:
pulumi.set(__self__, "name", name)
if non_persistent_attrs is not None:
pulumi.set(__self__, "non_persistent_attrs", non_persistent_attrs)
if password_complexity_options is not None:
pulumi.set(__self__, "password_complexity_options", password_complexity_options)
if password_dictionary is not None:
pulumi.set(__self__, "password_dictionary", password_dictionary)
if password_histories is not None:
pulumi.set(__self__, "password_histories", password_histories)
if password_no_personal_info is not None:
pulumi.set(__self__, "password_no_personal_info", password_no_personal_info)
if password_policy is not None:
pulumi.set(__self__, "password_policy", password_policy)
if protocol_binding is not None:
pulumi.set(__self__, "protocol_binding", protocol_binding)
if request_template is not None:
pulumi.set(__self__, "request_template", request_template)
if requires_username is not None:
pulumi.set(__self__, "requires_username", requires_username)
if scopes is not None:
pulumi.set(__self__, "scopes", scopes)
if scripts is not None:
pulumi.set(__self__, "scripts", scripts)
if set_user_root_attributes is not None:
pulumi.set(__self__, "set_user_root_attributes", set_user_root_attributes)
if should_trust_email_verified_connection is not None:
pulumi.set(__self__, "should_trust_email_verified_connection", should_trust_email_verified_connection)
if sign_in_endpoint is not None:
pulumi.set(__self__, "sign_in_endpoint", sign_in_endpoint)
if sign_out_endpoint is not None:
pulumi.set(__self__, "sign_out_endpoint", sign_out_endpoint)
if sign_saml_request is not None:
pulumi.set(__self__, "sign_saml_request", sign_saml_request)
if signature_algorithm is not None:
pulumi.set(__self__, "signature_algorithm", signature_algorithm)
if signing_cert is not None:
pulumi.set(__self__, "signing_cert", signing_cert)
if strategy_version is not None:
pulumi.set(__self__, "strategy_version", strategy_version)
if subject is not None:
pulumi.set(__self__, "subject", subject)
if syntax is not None:
pulumi.set(__self__, "syntax", syntax)
if team_id is not None:
pulumi.set(__self__, "team_id", team_id)
if template is not None:
pulumi.set(__self__, "template", template)
if tenant_domain is not None:
pulumi.set(__self__, "tenant_domain", tenant_domain)
if token_endpoint is not None:
pulumi.set(__self__, "token_endpoint", token_endpoint)
if totp is not None:
pulumi.set(__self__, "totp", totp)
if twilio_sid is not None:
pulumi.set(__self__, "twilio_sid", twilio_sid)
if twilio_token is not None:
pulumi.set(__self__, "twilio_token", twilio_token)
if type is not None:
pulumi.set(__self__, "type", type)
if use_cert_auth is not None:
pulumi.set(__self__, "use_cert_auth", use_cert_auth)
if use_kerberos is not None:
pulumi.set(__self__, "use_kerberos", use_kerberos)
if use_wsfed is not None:
pulumi.set(__self__, "use_wsfed", use_wsfed)
if user_id_attribute is not None:
pulumi.set(__self__, "user_id_attribute", user_id_attribute)
if userinfo_endpoint is not None:
pulumi.set(__self__, "userinfo_endpoint", userinfo_endpoint)
if validation is not None:
pulumi.set(__self__, "validation", validation)
if waad_common_endpoint is not None:
pulumi.set(__self__, "waad_common_endpoint", waad_common_endpoint)
if waad_protocol is not None:
pulumi.set(__self__, "waad_protocol", waad_protocol)
@property
@pulumi.getter(name="adfsServer")
def adfs_server(self) -> Optional[pulumi.Input[str]]:
"""
ADFS Metadata source.
"""
return pulumi.get(self, "adfs_server")
@adfs_server.setter
def adfs_server(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "adfs_server", value)
@property
@pulumi.getter(name="allowedAudiences")
def allowed_audiences(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
List of allowed audiences.
"""
return pulumi.get(self, "allowed_audiences")
@allowed_audiences.setter
def allowed_audiences(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "allowed_audiences", value)
@property
@pulumi.getter(name="apiEnableUsers")
def api_enable_users(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "api_enable_users")
@api_enable_users.setter
def api_enable_users(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "api_enable_users", value)
@property
@pulumi.getter(name="appDomain")
def app_domain(self) -> Optional[pulumi.Input[str]]:
"""
Azure AD domain name.
"""
return pulumi.get(self, "app_domain")
@app_domain.setter
def app_domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_domain", value)
@property
@pulumi.getter(name="appId")
def app_id(self) -> Optional[pulumi.Input[str]]:
"""
Azure AD app ID.
"""
return pulumi.get(self, "app_id")
@app_id.setter
def app_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_id", value)
@property
@pulumi.getter(name="authorizationEndpoint")
def authorization_endpoint(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "authorization_endpoint")
@authorization_endpoint.setter
def authorization_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "authorization_endpoint", value)
@property
@pulumi.getter(name="bruteForceProtection")
def brute_force_protection(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether or not to enable brute force protection, which will limit the number of signups and failed logins from a suspicious IP address.
"""
return pulumi.get(self, "brute_force_protection")
@brute_force_protection.setter
def brute_force_protection(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "brute_force_protection", value)
@property
@pulumi.getter(name="clientId")
def client_id(self) -> Optional[pulumi.Input[str]]:
"""
OIDC provider client ID.
"""
return pulumi.get(self, "client_id")
@client_id.setter
def client_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_id", value)
@property
@pulumi.getter(name="clientSecret")
def client_secret(self) -> Optional[pulumi.Input[str]]:
"""
OIDC provider client secret.
"""
return pulumi.get(self, "client_secret")
@client_secret.setter
def client_secret(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_secret", value)
@property
@pulumi.getter(name="communityBaseUrl")
def community_base_url(self) -> Optional[pulumi.Input[str]]:
"""
String.
"""
return pulumi.get(self, "community_base_url")
@community_base_url.setter
def community_base_url(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "community_base_url", value)
@property
@pulumi.getter
def configuration(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A case-sensitive map of key value pairs used as configuration variables for the `custom_script`.
"""
return pulumi.get(self, "configuration")
@configuration.setter
def configuration(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "configuration", value)
@property
@pulumi.getter(name="customScripts")
def custom_scripts(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Custom database action scripts. For more information, read [Custom Database Action Script Templates](https://auth0.com/docs/connections/database/custom-db/templates).
"""
return pulumi.get(self, "custom_scripts")
@custom_scripts.setter
def custom_scripts(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "custom_scripts", value)
@property
@pulumi.getter
def debug(self) -> Optional[pulumi.Input[bool]]:
"""
(Boolean) When enabled additional debugging information will be generated.
"""
return pulumi.get(self, "debug")
@debug.setter
def debug(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "debug", value)
@property
@pulumi.getter(name="digestAlgorithm")
def digest_algorithm(self) -> Optional[pulumi.Input[str]]:
"""
Sign Request Algorithm Digest
"""
return pulumi.get(self, "digest_algorithm")
@digest_algorithm.setter
def digest_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "digest_algorithm", value)
@property
@pulumi.getter(name="disableCache")
def disable_cache(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "disable_cache")
@disable_cache.setter
def disable_cache(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_cache", value)
@property
@pulumi.getter(name="disableSignup")
def disable_signup(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not to allow user sign-ups to your application.
"""
return pulumi.get(self, "disable_signup")
@disable_signup.setter
def disable_signup(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_signup", value)
@property
@pulumi.getter(name="discoveryUrl")
def discovery_url(self) -> Optional[pulumi.Input[str]]:
"""
OpenID discovery URL. E.g. `https://auth.example.com/.well-known/openid-configuration`.
"""
return pulumi.get(self, "discovery_url")
@discovery_url.setter
def discovery_url(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "discovery_url", value)
@property
@pulumi.getter
def domain(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "domain")
@domain.setter
def domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "domain", value)
@property
@pulumi.getter(name="domainAliases")
def domain_aliases(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
List of the domains that can be authenticated using the Identity Provider. Only needed for Identifier First authentication flows.
"""
return pulumi.get(self, "domain_aliases")
@domain_aliases.setter
def domain_aliases(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "domain_aliases", value)
@property
@pulumi.getter(name="enabledDatabaseCustomization")
def enabled_database_customization(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "enabled_database_customization")
@enabled_database_customization.setter
def enabled_database_customization(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enabled_database_customization", value)
@property
@pulumi.getter(name="fieldsMap")
def fields_map(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
SAML Attributes mapping. If you're configuring a SAML enterprise connection for a non-standard PingFederate Server, you must update the attribute mappings.
"""
return pulumi.get(self, "fields_map")
@fields_map.setter
def fields_map(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "fields_map", value)
@property
@pulumi.getter(name="from")
def from_(self) -> Optional[pulumi.Input[str]]:
"""
SMS number for the sender. Used when SMS Source is From.
"""
return pulumi.get(self, "from_")
@from_.setter
def from_(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "from_", value)
@property
@pulumi.getter(name="iconUrl")
def icon_url(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "icon_url")
@icon_url.setter
def icon_url(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "icon_url", value)
@property
@pulumi.getter(name="identityApi")
def identity_api(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "identity_api")
@identity_api.setter
def identity_api(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "identity_api", value)
@property
@pulumi.getter(name="idpInitiated")
def idp_initiated(self) -> Optional[pulumi.Input['ConnectionOptionsIdpInitiatedArgs']]:
return pulumi.get(self, "idp_initiated")
@idp_initiated.setter
def idp_initiated(self, value: Optional[pulumi.Input['ConnectionOptionsIdpInitiatedArgs']]):
pulumi.set(self, "idp_initiated", value)
@property
@pulumi.getter(name="importMode")
def import_mode(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether or not you have a legacy user store and want to gradually migrate those users to the Auth0 user store. [Learn more](https://auth0.com/docs/users/guides/configure-automatic-migration).
"""
return pulumi.get(self, "import_mode")
@import_mode.setter
def import_mode(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "import_mode", value)
@property
@pulumi.getter
def ips(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "ips")
@ips.setter
def ips(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "ips", value)
@property
@pulumi.getter
def issuer(self) -> Optional[pulumi.Input[str]]:
"""
Issuer URL. E.g. `https://auth.example.com`
"""
return pulumi.get(self, "issuer")
@issuer.setter
def issuer(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "issuer", value)
@property
@pulumi.getter(name="jwksUri")
def jwks_uri(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "jwks_uri")
@jwks_uri.setter
def jwks_uri(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "jwks_uri", value)
@property
@pulumi.getter(name="keyId")
def key_id(self) -> Optional[pulumi.Input[str]]:
"""
Key ID.
"""
return pulumi.get(self, "key_id")
@key_id.setter
def key_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "key_id", value)
@property
@pulumi.getter(name="maxGroupsToRetrieve")
def max_groups_to_retrieve(self) -> Optional[pulumi.Input[str]]:
"""
Maximum number of groups to retrieve.
"""
return pulumi.get(self, "max_groups_to_retrieve")
@max_groups_to_retrieve.setter
def max_groups_to_retrieve(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "max_groups_to_retrieve", value)
@property
@pulumi.getter(name="messagingServiceSid")
def messaging_service_sid(self) -> Optional[pulumi.Input[str]]:
"""
SID for Copilot. Used when SMS Source is Copilot.
"""
return pulumi.get(self, "messaging_service_sid")
@messaging_service_sid.setter
def messaging_service_sid(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "messaging_service_sid", value)
@property
@pulumi.getter
def mfa(self) -> Optional[pulumi.Input['ConnectionOptionsMfaArgs']]:
"""
Configuration settings Options for multifactor authentication. For details, see MFA Options.
"""
return pulumi.get(self, "mfa")
@mfa.setter
def mfa(self, value: Optional[pulumi.Input['ConnectionOptionsMfaArgs']]):
pulumi.set(self, "mfa", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Name of the connection.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="nonPersistentAttrs")
def non_persistent_attrs(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
If there are user fields that should not be stored in Auth0 databases due to privacy reasons, you can add them to the denylist. See [here](https://auth0.com/docs/security/denylist-user-attributes) for more info.
"""
return pulumi.get(self, "non_persistent_attrs")
@non_persistent_attrs.setter
def non_persistent_attrs(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "non_persistent_attrs", value)
@property
@pulumi.getter(name="passwordComplexityOptions")
def password_complexity_options(self) -> Optional[pulumi.Input['ConnectionOptionsPasswordComplexityOptionsArgs']]:
"""
Configuration settings for password complexity. For details, see Password Complexity Options.
"""
return pulumi.get(self, "password_complexity_options")
@password_complexity_options.setter
def password_complexity_options(self, value: Optional[pulumi.Input['ConnectionOptionsPasswordComplexityOptionsArgs']]):
pulumi.set(self, "password_complexity_options", value)
@property
@pulumi.getter(name="passwordDictionary")
def password_dictionary(self) -> Optional[pulumi.Input['ConnectionOptionsPasswordDictionaryArgs']]:
"""
Configuration settings for the password dictionary check, which does not allow passwords that are part of the password dictionary. For details, see Password Dictionary.
"""
return pulumi.get(self, "password_dictionary")
@password_dictionary.setter
def password_dictionary(self, value: Optional[pulumi.Input['ConnectionOptionsPasswordDictionaryArgs']]):
pulumi.set(self, "password_dictionary", value)
@property
@pulumi.getter(name="passwordHistories")
def password_histories(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ConnectionOptionsPasswordHistoryArgs']]]]:
"""
Configuration settings for the password history that is maintained for each user to prevent the reuse of passwords. For details, see Password History.
"""
return pulumi.get(self, "password_histories")
@password_histories.setter
def password_histories(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ConnectionOptionsPasswordHistoryArgs']]]]):
pulumi.set(self, "password_histories", value)
@property
@pulumi.getter(name="passwordNoPersonalInfo")
def password_no_personal_info(self) -> Optional[pulumi.Input['ConnectionOptionsPasswordNoPersonalInfoArgs']]:
"""
Configuration settings for the password personal info check, which does not allow passwords that contain any part of the user's personal data, including user's name, username, nickname, user_metadata.name, user_metadata.first, user_metadata.last, user's email, or first part of the user's email. For details, see Password No Personal Info.
"""
return pulumi.get(self, "password_no_personal_info")
@password_no_personal_info.setter
def password_no_personal_info(self, value: Optional[pulumi.Input['ConnectionOptionsPasswordNoPersonalInfoArgs']]):
pulumi.set(self, "password_no_personal_info", value)
@property
@pulumi.getter(name="passwordPolicy")
def password_policy(self) -> Optional[pulumi.Input[str]]:
"""
Indicates level of password strength to enforce during authentication. A strong password policy will make it difficult, if not improbable, for someone to guess a password through either manual or automated means. Options include `none`, `low`, `fair`, `good`, `excellent`.
"""
return pulumi.get(self, "password_policy")
@password_policy.setter
def password_policy(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "password_policy", value)
@property
@pulumi.getter(name="protocolBinding")
def protocol_binding(self) -> Optional[pulumi.Input[str]]:
"""
The SAML Response Binding - how the SAML token is received by Auth0 from IdP. Two possible values are `urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect` (default) and `urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST`
"""
return pulumi.get(self, "protocol_binding")
@protocol_binding.setter
def protocol_binding(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "protocol_binding", value)
@property
@pulumi.getter(name="requestTemplate")
def request_template(self) -> Optional[pulumi.Input[str]]:
"""
Template that formats the SAML request
"""
return pulumi.get(self, "request_template")
@request_template.setter
def request_template(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "request_template", value)
@property
@pulumi.getter(name="requiresUsername")
def requires_username(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether or not the user is required to provide a username in addition to an email address.
"""
return pulumi.get(self, "requires_username")
@requires_username.setter
def requires_username(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "requires_username", value)
@property
@pulumi.getter
def scopes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Scopes required by the connection. The value must be a list, for example `["openid", "profile", "email"]`.
"""
return pulumi.get(self, "scopes")
@scopes.setter
def scopes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "scopes", value)
@property
@pulumi.getter
def scripts(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
return pulumi.get(self, "scripts")
@scripts.setter
def scripts(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "scripts", value)
@property
@pulumi.getter(name="setUserRootAttributes")
def set_user_root_attributes(self) -> Optional[pulumi.Input[str]]:
"""
Determines whether the 'name', 'given_name', 'family_name', 'nickname', and 'picture' attributes can be independently updated when using the external IdP. Default is `on_each_login` and can be set to `on_first_login`.
"""
return pulumi.get(self, "set_user_root_attributes")
@set_user_root_attributes.setter
def set_user_root_attributes(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "set_user_root_attributes", value)
@property
@pulumi.getter(name="shouldTrustEmailVerifiedConnection")
def should_trust_email_verified_connection(self) -> Optional[pulumi.Input[str]]:
"""
Determines how Auth0 sets the email_verified field in the user profile. Can either be set to `never_set_emails_as_verified` or `always_set_emails_as_verified`.
"""
return pulumi.get(self, "should_trust_email_verified_connection")
@should_trust_email_verified_connection.setter
def should_trust_email_verified_connection(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "should_trust_email_verified_connection", value)
@property
@pulumi.getter(name="signInEndpoint")
def sign_in_endpoint(self) -> Optional[pulumi.Input[str]]:
"""
SAML single login URL for the connection.
"""
return pulumi.get(self, "sign_in_endpoint")
@sign_in_endpoint.setter
def sign_in_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "sign_in_endpoint", value)
@property
@pulumi.getter(name="signOutEndpoint")
def sign_out_endpoint(self) -> Optional[pulumi.Input[str]]:
"""
SAML single logout URL for the connection.
"""
return pulumi.get(self, "sign_out_endpoint")
@sign_out_endpoint.setter
def sign_out_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "sign_out_endpoint", value)
@property
@pulumi.getter(name="signSamlRequest")
def sign_saml_request(self) -> Optional[pulumi.Input[bool]]:
"""
(Boolean) When enabled, the SAML authentication request will be signed.
"""
return pulumi.get(self, "sign_saml_request")
@sign_saml_request.setter
def sign_saml_request(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "sign_saml_request", value)
@property
@pulumi.getter(name="signatureAlgorithm")
def signature_algorithm(self) -> Optional[pulumi.Input[str]]:
"""
Sign Request Algorithm
"""
return pulumi.get(self, "signature_algorithm")
@signature_algorithm.setter
def signature_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "signature_algorithm", value)
@property
@pulumi.getter(name="signingCert")
def signing_cert(self) -> Optional[pulumi.Input[str]]:
"""
The X.509 signing certificate (encoded in PEM or CER) you retrieved from the IdP, Base64-encoded
"""
return pulumi.get(self, "signing_cert")
@signing_cert.setter
def signing_cert(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "signing_cert", value)
@property
@pulumi.getter(name="strategyVersion")
def strategy_version(self) -> Optional[pulumi.Input[int]]:
"""
Version 1 is deprecated, use version 2.
"""
return pulumi.get(self, "strategy_version")
@strategy_version.setter
def strategy_version(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "strategy_version", value)
@property
@pulumi.getter
def subject(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "subject")
@subject.setter
def subject(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "subject", value)
@property
@pulumi.getter
def syntax(self) -> Optional[pulumi.Input[str]]:
"""
Syntax of the SMS. Options include `markdown` and `liquid`.
"""
return pulumi.get(self, "syntax")
@syntax.setter
def syntax(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "syntax", value)
@property
@pulumi.getter(name="teamId")
def team_id(self) -> Optional[pulumi.Input[str]]:
"""
Team ID.
"""
return pulumi.get(self, "team_id")
@team_id.setter
def team_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "team_id", value)
@property
@pulumi.getter
def template(self) -> Optional[pulumi.Input[str]]:
"""
Template for the SMS. You can use `@@password@@` as a placeholder for the password value.
"""
return pulumi.get(self, "template")
@template.setter
def template(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "template", value)
@property
@pulumi.getter(name="tenantDomain")
def tenant_domain(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "tenant_domain")
@tenant_domain.setter
def tenant_domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "tenant_domain", value)
@property
@pulumi.getter(name="tokenEndpoint")
def token_endpoint(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "token_endpoint")
@token_endpoint.setter
def token_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "token_endpoint", value)
@property
@pulumi.getter
def totp(self) -> Optional[pulumi.Input['ConnectionOptionsTotpArgs']]:
"""
Configuration options for one-time passwords. For details, see TOTP.
"""
return pulumi.get(self, "totp")
@totp.setter
def totp(self, value: Optional[pulumi.Input['ConnectionOptionsTotpArgs']]):
pulumi.set(self, "totp", value)
@property
@pulumi.getter(name="twilioSid")
def twilio_sid(self) -> Optional[pulumi.Input[str]]:
"""
SID for your Twilio account.
"""
return pulumi.get(self, "twilio_sid")
@twilio_sid.setter
def twilio_sid(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "twilio_sid", value)
@property
@pulumi.getter(name="twilioToken")
def twilio_token(self) -> Optional[pulumi.Input[str]]:
"""
AuthToken for your Twilio account.
"""
return pulumi.get(self, "twilio_token")
@twilio_token.setter
def twilio_token(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "twilio_token", value)
@property
@pulumi.getter
def type(self) -> Optional[pulumi.Input[str]]:
"""
Value can be `back_channel` or `front_channel`.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "type", value)
@property
@pulumi.getter(name="useCertAuth")
def use_cert_auth(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "use_cert_auth")
@use_cert_auth.setter
def use_cert_auth(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "use_cert_auth", value)
@property
@pulumi.getter(name="useKerberos")
def use_kerberos(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "use_kerberos")
@use_kerberos.setter
def use_kerberos(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "use_kerberos", value)
@property
@pulumi.getter(name="useWsfed")
def use_wsfed(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "use_wsfed")
@use_wsfed.setter
def use_wsfed(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "use_wsfed", value)
@property
@pulumi.getter(name="userIdAttribute")
def user_id_attribute(self) -> Optional[pulumi.Input[str]]:
"""
Attribute in the SAML token that will be mapped to the user_id property in Auth0.
"""
return pulumi.get(self, "user_id_attribute")
@user_id_attribute.setter
def user_id_attribute(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "user_id_attribute", value)
@property
@pulumi.getter(name="userinfoEndpoint")
def userinfo_endpoint(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "userinfo_endpoint")
@userinfo_endpoint.setter
def userinfo_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "userinfo_endpoint", value)
@property
@pulumi.getter
def validation(self) -> Optional[pulumi.Input['ConnectionOptionsValidationArgs']]:
"""
Validation of the minimum and maximum values allowed for a user to have as username. For details, see Validation.
"""
return pulumi.get(self, "validation")
@validation.setter
def validation(self, value: Optional[pulumi.Input['ConnectionOptionsValidationArgs']]):
pulumi.set(self, "validation", value)
@property
@pulumi.getter(name="waadCommonEndpoint")
def waad_common_endpoint(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether or not to use the common endpoint rather than the default endpoint. Typically enabled if you're using this for a multi-tenant application in Azure AD.
"""
return pulumi.get(self, "waad_common_endpoint")
@waad_common_endpoint.setter
def waad_common_endpoint(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "waad_common_endpoint", value)
@property
@pulumi.getter(name="waadProtocol")
def waad_protocol(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "waad_protocol")
@waad_protocol.setter
def waad_protocol(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "waad_protocol", value)
@pulumi.input_type
class ConnectionOptionsIdpInitiatedArgs:
def __init__(__self__, *,
client_authorize_query: Optional[pulumi.Input[str]] = None,
client_id: Optional[pulumi.Input[str]] = None,
client_protocol: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] client_id: Google client ID.
"""
if client_authorize_query is not None:
pulumi.set(__self__, "client_authorize_query", client_authorize_query)
if client_id is not None:
pulumi.set(__self__, "client_id", client_id)
if client_protocol is not None:
pulumi.set(__self__, "client_protocol", client_protocol)
@property
@pulumi.getter(name="clientAuthorizeQuery")
def client_authorize_query(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "client_authorize_query")
@client_authorize_query.setter
def client_authorize_query(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_authorize_query", value)
@property
@pulumi.getter(name="clientId")
def client_id(self) -> Optional[pulumi.Input[str]]:
"""
Google client ID.
"""
return pulumi.get(self, "client_id")
@client_id.setter
def client_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_id", value)
@property
@pulumi.getter(name="clientProtocol")
def client_protocol(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "client_protocol")
@client_protocol.setter
def client_protocol(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "client_protocol", value)
@pulumi.input_type
class ConnectionOptionsMfaArgs:
def __init__(__self__, *,
active: Optional[pulumi.Input[bool]] = None,
return_enroll_settings: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[bool] active: Indicates whether multifactor authentication is enabled for this connection.
:param pulumi.Input[bool] return_enroll_settings: Indicates whether multifactor authentication enrollment settings will be returned.
"""
if active is not None:
pulumi.set(__self__, "active", active)
if return_enroll_settings is not None:
pulumi.set(__self__, "return_enroll_settings", return_enroll_settings)
@property
@pulumi.getter
def active(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether multifactor authentication is enabled for this connection.
"""
return pulumi.get(self, "active")
@active.setter
def active(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "active", value)
@property
@pulumi.getter(name="returnEnrollSettings")
def return_enroll_settings(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether multifactor authentication enrollment settings will be returned.
"""
return pulumi.get(self, "return_enroll_settings")
@return_enroll_settings.setter
def return_enroll_settings(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "return_enroll_settings", value)
@pulumi.input_type
class ConnectionOptionsPasswordComplexityOptionsArgs:
def __init__(__self__, *,
min_length: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[int] min_length: Minimum number of characters allowed in passwords.
"""
if min_length is not None:
pulumi.set(__self__, "min_length", min_length)
@property
@pulumi.getter(name="minLength")
def min_length(self) -> Optional[pulumi.Input[int]]:
"""
Minimum number of characters allowed in passwords.
"""
return pulumi.get(self, "min_length")
@min_length.setter
def min_length(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "min_length", value)
@pulumi.input_type
class ConnectionOptionsPasswordDictionaryArgs:
def __init__(__self__, *,
dictionaries: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
enable: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[Sequence[pulumi.Input[str]]] dictionaries: Customized contents of the password dictionary. By default, the password dictionary contains a list of the [10,000 most common passwords](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt); your customized content is used in addition to the default password dictionary. Matching is not case-sensitive.
:param pulumi.Input[bool] enable: Indicates whether password history is enabled for the connection. When enabled, any existing users in this connection will be unaffected; the system will maintain their password history going forward.
"""
if dictionaries is not None:
pulumi.set(__self__, "dictionaries", dictionaries)
if enable is not None:
pulumi.set(__self__, "enable", enable)
@property
@pulumi.getter
def dictionaries(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Customized contents of the password dictionary. By default, the password dictionary contains a list of the [10,000 most common passwords](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt); your customized content is used in addition to the default password dictionary. Matching is not case-sensitive.
"""
return pulumi.get(self, "dictionaries")
@dictionaries.setter
def dictionaries(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "dictionaries", value)
@property
@pulumi.getter
def enable(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether password history is enabled for the connection. When enabled, any existing users in this connection will be unaffected; the system will maintain their password history going forward.
"""
return pulumi.get(self, "enable")
@enable.setter
def enable(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable", value)
@pulumi.input_type
class ConnectionOptionsPasswordHistoryArgs:
def __init__(__self__, *,
enable: Optional[pulumi.Input[bool]] = None,
size: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[bool] enable: Indicates whether password history is enabled for the connection. When enabled, any existing users in this connection will be unaffected; the system will maintain their password history going forward.
:param pulumi.Input[int] size: Indicates the number of passwords to keep in history with a maximum of 24.
"""
if enable is not None:
pulumi.set(__self__, "enable", enable)
if size is not None:
pulumi.set(__self__, "size", size)
@property
@pulumi.getter
def enable(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether password history is enabled for the connection. When enabled, any existing users in this connection will be unaffected; the system will maintain their password history going forward.
"""
return pulumi.get(self, "enable")
@enable.setter
def enable(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable", value)
@property
@pulumi.getter
def size(self) -> Optional[pulumi.Input[int]]:
"""
Indicates the number of passwords to keep in history with a maximum of 24.
"""
return pulumi.get(self, "size")
@size.setter
def size(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "size", value)
@pulumi.input_type
class ConnectionOptionsPasswordNoPersonalInfoArgs:
def __init__(__self__, *,
enable: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[bool] enable: Indicates whether the password personal info check is enabled for this connection.
"""
if enable is not None:
pulumi.set(__self__, "enable", enable)
@property
@pulumi.getter
def enable(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether the password personal info check is enabled for this connection.
"""
return pulumi.get(self, "enable")
@enable.setter
def enable(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable", value)
@pulumi.input_type
class ConnectionOptionsTotpArgs:
def __init__(__self__, *,
length: Optional[pulumi.Input[int]] = None,
time_step: Optional[pulumi.Input[int]] = None):
"""
:param pulumi.Input[int] length: Integer. Length of the one-time password.
:param pulumi.Input[int] time_step: Integer. Seconds between allowed generation of new passwords.
"""
if length is not None:
pulumi.set(__self__, "length", length)
if time_step is not None:
pulumi.set(__self__, "time_step", time_step)
@property
@pulumi.getter
def length(self) -> Optional[pulumi.Input[int]]:
"""
Integer. Length of the one-time password.
"""
return pulumi.get(self, "length")
@length.setter
def length(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "length", value)
@property
@pulumi.getter(name="timeStep")
def time_step(self) -> Optional[pulumi.Input[int]]:
"""
Integer. Seconds between allowed generation of new passwords.
"""
return pulumi.get(self, "time_step")
@time_step.setter
def time_step(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "time_step", value)
@pulumi.input_type
class ConnectionOptionsValidationArgs:
def __init__(__self__, *,
username: Optional[pulumi.Input['ConnectionOptionsValidationUsernameArgs']] = None):
"""
:param pulumi.Input['ConnectionOptionsValidationUsernameArgs'] username: Specifies the `min` and `max` values of username length. `min` and `max` are integers.
"""
if username is not None:
pulumi.set(__self__, "username", username)
@property
@pulumi.getter
def username(self) -> Optional[pulumi.Input['ConnectionOptionsValidationUsernameArgs']]:
"""
Specifies the `min` and `max` values of username length. `min` and `max` are integers.
"""
return pulumi.get(self, "username")
@username.setter
def username(self, value: Optional[pulumi.Input['ConnectionOptionsValidationUsernameArgs']]):
pulumi.set(self, "username", value)
@pulumi.input_type
class ConnectionOptionsValidationUsernameArgs:
def __init__(__self__, *,
max: Optional[pulumi.Input[int]] = None,
min: Optional[pulumi.Input[int]] = None):
if max is not None:
pulumi.set(__self__, "max", max)
if min is not None:
pulumi.set(__self__, "min", min)
@property
@pulumi.getter
def max(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "max")
@max.setter
def max(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "max", value)
@property
@pulumi.getter
def min(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "min")
@min.setter
def min(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "min", value)
@pulumi.input_type
class CustomDomainVerificationArgs:
def __init__(__self__, *,
methods: Optional[pulumi.Input[Sequence[Any]]] = None):
"""
:param pulumi.Input[Sequence[Any]] methods: List(Map). Verification methods for the domain.
"""
if methods is not None:
pulumi.set(__self__, "methods", methods)
@property
@pulumi.getter
def methods(self) -> Optional[pulumi.Input[Sequence[Any]]]:
"""
List(Map). Verification methods for the domain.
"""
return pulumi.get(self, "methods")
@methods.setter
def methods(self, value: Optional[pulumi.Input[Sequence[Any]]]):
pulumi.set(self, "methods", value)
@pulumi.input_type
class EmailCredentialsArgs:
def __init__(__self__, *,
access_key_id: Optional[pulumi.Input[str]] = None,
api_key: Optional[pulumi.Input[str]] = None,
api_user: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
region: Optional[pulumi.Input[str]] = None,
secret_access_key: Optional[pulumi.Input[str]] = None,
smtp_host: Optional[pulumi.Input[str]] = None,
smtp_pass: Optional[pulumi.Input[str]] = None,
smtp_port: Optional[pulumi.Input[int]] = None,
smtp_user: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] access_key_id: String, Case-sensitive. AWS Access Key ID. Used only for AWS.
:param pulumi.Input[str] api_key: String, Case-sensitive. API Key for your email service. Will always be encrypted in our database.
:param pulumi.Input[str] api_user: String. API User for your email service.
:param pulumi.Input[str] region: String. Default region. Used only for AWS, Mailgun, and SparkPost.
:param pulumi.Input[str] secret_access_key: String, Case-sensitive. AWS Secret Key. Will always be encrypted in our database. Used only for AWS.
:param pulumi.Input[str] smtp_host: String. Hostname or IP address of your SMTP server. Used only for SMTP.
:param pulumi.Input[str] smtp_pass: String, Case-sensitive. SMTP password. Used only for SMTP.
:param pulumi.Input[int] smtp_port: Integer. Port used by your SMTP server. Please avoid using port 25 if possible because many providers have limitations on this port. Used only for SMTP.
:param pulumi.Input[str] smtp_user: String. SMTP username. Used only for SMTP.
"""
if access_key_id is not None:
pulumi.set(__self__, "access_key_id", access_key_id)
if api_key is not None:
pulumi.set(__self__, "api_key", api_key)
if api_user is not None:
pulumi.set(__self__, "api_user", api_user)
if domain is not None:
pulumi.set(__self__, "domain", domain)
if region is not None:
pulumi.set(__self__, "region", region)
if secret_access_key is not None:
pulumi.set(__self__, "secret_access_key", secret_access_key)
if smtp_host is not None:
pulumi.set(__self__, "smtp_host", smtp_host)
if smtp_pass is not None:
pulumi.set(__self__, "smtp_pass", smtp_pass)
if smtp_port is not None:
pulumi.set(__self__, "smtp_port", smtp_port)
if smtp_user is not None:
pulumi.set(__self__, "smtp_user", smtp_user)
@property
@pulumi.getter(name="accessKeyId")
def access_key_id(self) -> Optional[pulumi.Input[str]]:
"""
String, Case-sensitive. AWS Access Key ID. Used only for AWS.
"""
return pulumi.get(self, "access_key_id")
@access_key_id.setter
def access_key_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "access_key_id", value)
@property
@pulumi.getter(name="apiKey")
def api_key(self) -> Optional[pulumi.Input[str]]:
"""
String, Case-sensitive. API Key for your email service. Will always be encrypted in our database.
"""
return pulumi.get(self, "api_key")
@api_key.setter
def api_key(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "api_key", value)
@property
@pulumi.getter(name="apiUser")
def api_user(self) -> Optional[pulumi.Input[str]]:
"""
String. API User for your email service.
"""
return pulumi.get(self, "api_user")
@api_user.setter
def api_user(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "api_user", value)
@property
@pulumi.getter
def domain(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "domain")
@domain.setter
def domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "domain", value)
@property
@pulumi.getter
def region(self) -> Optional[pulumi.Input[str]]:
"""
String. Default region. Used only for AWS, Mailgun, and SparkPost.
"""
return pulumi.get(self, "region")
@region.setter
def region(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "region", value)
@property
@pulumi.getter(name="secretAccessKey")
def secret_access_key(self) -> Optional[pulumi.Input[str]]:
"""
String, Case-sensitive. AWS Secret Key. Will always be encrypted in our database. Used only for AWS.
"""
return pulumi.get(self, "secret_access_key")
@secret_access_key.setter
def secret_access_key(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "secret_access_key", value)
@property
@pulumi.getter(name="smtpHost")
def smtp_host(self) -> Optional[pulumi.Input[str]]:
"""
String. Hostname or IP address of your SMTP server. Used only for SMTP.
"""
return pulumi.get(self, "smtp_host")
@smtp_host.setter
def smtp_host(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "smtp_host", value)
@property
@pulumi.getter(name="smtpPass")
def smtp_pass(self) -> Optional[pulumi.Input[str]]:
"""
String, Case-sensitive. SMTP password. Used only for SMTP.
"""
return pulumi.get(self, "smtp_pass")
@smtp_pass.setter
def smtp_pass(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "smtp_pass", value)
@property
@pulumi.getter(name="smtpPort")
def smtp_port(self) -> Optional[pulumi.Input[int]]:
"""
Integer. Port used by your SMTP server. Please avoid using port 25 if possible because many providers have limitations on this port. Used only for SMTP.
"""
return pulumi.get(self, "smtp_port")
@smtp_port.setter
def smtp_port(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "smtp_port", value)
@property
@pulumi.getter(name="smtpUser")
def smtp_user(self) -> Optional[pulumi.Input[str]]:
"""
String. SMTP username. Used only for SMTP.
"""
return pulumi.get(self, "smtp_user")
@smtp_user.setter
def smtp_user(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "smtp_user", value)
@pulumi.input_type
class GlobalClientAddonsArgs:
def __init__(__self__, *,
aws: Optional[pulumi.Input[Mapping[str, Any]]] = None,
azure_blob: Optional[pulumi.Input[Mapping[str, Any]]] = None,
azure_sb: Optional[pulumi.Input[Mapping[str, Any]]] = None,
box: Optional[pulumi.Input[Mapping[str, Any]]] = None,
cloudbees: Optional[pulumi.Input[Mapping[str, Any]]] = None,
concur: Optional[pulumi.Input[Mapping[str, Any]]] = None,
dropbox: Optional[pulumi.Input[Mapping[str, Any]]] = None,
echosign: Optional[pulumi.Input[Mapping[str, Any]]] = None,
egnyte: Optional[pulumi.Input[Mapping[str, Any]]] = None,
firebase: Optional[pulumi.Input[Mapping[str, Any]]] = None,
layer: Optional[pulumi.Input[Mapping[str, Any]]] = None,
mscrm: Optional[pulumi.Input[Mapping[str, Any]]] = None,
newrelic: Optional[pulumi.Input[Mapping[str, Any]]] = None,
office365: Optional[pulumi.Input[Mapping[str, Any]]] = None,
rms: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
salesforce_sandbox_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
samlp: Optional[pulumi.Input['GlobalClientAddonsSamlpArgs']] = None,
sap_api: Optional[pulumi.Input[Mapping[str, Any]]] = None,
sentry: Optional[pulumi.Input[Mapping[str, Any]]] = None,
sharepoint: Optional[pulumi.Input[Mapping[str, Any]]] = None,
slack: Optional[pulumi.Input[Mapping[str, Any]]] = None,
springcm: Optional[pulumi.Input[Mapping[str, Any]]] = None,
wams: Optional[pulumi.Input[Mapping[str, Any]]] = None,
wsfed: Optional[pulumi.Input[Mapping[str, Any]]] = None,
zendesk: Optional[pulumi.Input[Mapping[str, Any]]] = None,
zoom: Optional[pulumi.Input[Mapping[str, Any]]] = None):
if aws is not None:
pulumi.set(__self__, "aws", aws)
if azure_blob is not None:
pulumi.set(__self__, "azure_blob", azure_blob)
if azure_sb is not None:
pulumi.set(__self__, "azure_sb", azure_sb)
if box is not None:
pulumi.set(__self__, "box", box)
if cloudbees is not None:
pulumi.set(__self__, "cloudbees", cloudbees)
if concur is not None:
pulumi.set(__self__, "concur", concur)
if dropbox is not None:
pulumi.set(__self__, "dropbox", dropbox)
if echosign is not None:
pulumi.set(__self__, "echosign", echosign)
if egnyte is not None:
pulumi.set(__self__, "egnyte", egnyte)
if firebase is not None:
pulumi.set(__self__, "firebase", firebase)
if layer is not None:
pulumi.set(__self__, "layer", layer)
if mscrm is not None:
pulumi.set(__self__, "mscrm", mscrm)
if newrelic is not None:
pulumi.set(__self__, "newrelic", newrelic)
if office365 is not None:
pulumi.set(__self__, "office365", office365)
if rms is not None:
pulumi.set(__self__, "rms", rms)
if salesforce is not None:
pulumi.set(__self__, "salesforce", salesforce)
if salesforce_api is not None:
pulumi.set(__self__, "salesforce_api", salesforce_api)
if salesforce_sandbox_api is not None:
pulumi.set(__self__, "salesforce_sandbox_api", salesforce_sandbox_api)
if samlp is not None:
pulumi.set(__self__, "samlp", samlp)
if sap_api is not None:
pulumi.set(__self__, "sap_api", sap_api)
if sentry is not None:
pulumi.set(__self__, "sentry", sentry)
if sharepoint is not None:
pulumi.set(__self__, "sharepoint", sharepoint)
if slack is not None:
pulumi.set(__self__, "slack", slack)
if springcm is not None:
pulumi.set(__self__, "springcm", springcm)
if wams is not None:
pulumi.set(__self__, "wams", wams)
if wsfed is not None:
pulumi.set(__self__, "wsfed", wsfed)
if zendesk is not None:
pulumi.set(__self__, "zendesk", zendesk)
if zoom is not None:
pulumi.set(__self__, "zoom", zoom)
@property
@pulumi.getter
def aws(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "aws")
@aws.setter
def aws(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "aws", value)
@property
@pulumi.getter(name="azureBlob")
def azure_blob(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "azure_blob")
@azure_blob.setter
def azure_blob(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "azure_blob", value)
@property
@pulumi.getter(name="azureSb")
def azure_sb(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "azure_sb")
@azure_sb.setter
def azure_sb(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "azure_sb", value)
@property
@pulumi.getter
def box(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "box")
@box.setter
def box(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "box", value)
@property
@pulumi.getter
def cloudbees(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "cloudbees")
@cloudbees.setter
def cloudbees(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "cloudbees", value)
@property
@pulumi.getter
def concur(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "concur")
@concur.setter
def concur(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "concur", value)
@property
@pulumi.getter
def dropbox(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "dropbox")
@dropbox.setter
def dropbox(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "dropbox", value)
@property
@pulumi.getter
def echosign(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "echosign")
@echosign.setter
def echosign(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "echosign", value)
@property
@pulumi.getter
def egnyte(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "egnyte")
@egnyte.setter
def egnyte(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "egnyte", value)
@property
@pulumi.getter
def firebase(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "firebase")
@firebase.setter
def firebase(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "firebase", value)
@property
@pulumi.getter
def layer(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "layer")
@layer.setter
def layer(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "layer", value)
@property
@pulumi.getter
def mscrm(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "mscrm")
@mscrm.setter
def mscrm(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "mscrm", value)
@property
@pulumi.getter
def newrelic(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "newrelic")
@newrelic.setter
def newrelic(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "newrelic", value)
@property
@pulumi.getter
def office365(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "office365")
@office365.setter
def office365(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "office365", value)
@property
@pulumi.getter
def rms(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "rms")
@rms.setter
def rms(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "rms", value)
@property
@pulumi.getter
def salesforce(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "salesforce")
@salesforce.setter
def salesforce(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce", value)
@property
@pulumi.getter(name="salesforceApi")
def salesforce_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "salesforce_api")
@salesforce_api.setter
def salesforce_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce_api", value)
@property
@pulumi.getter(name="salesforceSandboxApi")
def salesforce_sandbox_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "salesforce_sandbox_api")
@salesforce_sandbox_api.setter
def salesforce_sandbox_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "salesforce_sandbox_api", value)
@property
@pulumi.getter
def samlp(self) -> Optional[pulumi.Input['GlobalClientAddonsSamlpArgs']]:
return pulumi.get(self, "samlp")
@samlp.setter
def samlp(self, value: Optional[pulumi.Input['GlobalClientAddonsSamlpArgs']]):
pulumi.set(self, "samlp", value)
@property
@pulumi.getter(name="sapApi")
def sap_api(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "sap_api")
@sap_api.setter
def sap_api(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sap_api", value)
@property
@pulumi.getter
def sentry(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "sentry")
@sentry.setter
def sentry(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sentry", value)
@property
@pulumi.getter
def sharepoint(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "sharepoint")
@sharepoint.setter
def sharepoint(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "sharepoint", value)
@property
@pulumi.getter
def slack(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "slack")
@slack.setter
def slack(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "slack", value)
@property
@pulumi.getter
def springcm(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "springcm")
@springcm.setter
def springcm(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "springcm", value)
@property
@pulumi.getter
def wams(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "wams")
@wams.setter
def wams(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "wams", value)
@property
@pulumi.getter
def wsfed(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "wsfed")
@wsfed.setter
def wsfed(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "wsfed", value)
@property
@pulumi.getter
def zendesk(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "zendesk")
@zendesk.setter
def zendesk(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "zendesk", value)
@property
@pulumi.getter
def zoom(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "zoom")
@zoom.setter
def zoom(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "zoom", value)
@pulumi.input_type
class GlobalClientAddonsSamlpArgs:
def __init__(__self__, *,
audience: Optional[pulumi.Input[str]] = None,
authn_context_class_ref: Optional[pulumi.Input[str]] = None,
binding: Optional[pulumi.Input[str]] = None,
create_upn_claim: Optional[pulumi.Input[bool]] = None,
destination: Optional[pulumi.Input[str]] = None,
digest_algorithm: Optional[pulumi.Input[str]] = None,
include_attribute_name_format: Optional[pulumi.Input[bool]] = None,
lifetime_in_seconds: Optional[pulumi.Input[int]] = None,
logout: Optional[pulumi.Input['GlobalClientAddonsSamlpLogoutArgs']] = None,
map_identities: Optional[pulumi.Input[bool]] = None,
map_unknown_claims_as_is: Optional[pulumi.Input[bool]] = None,
mappings: Optional[pulumi.Input[Mapping[str, Any]]] = None,
name_identifier_format: Optional[pulumi.Input[str]] = None,
name_identifier_probes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
passthrough_claims_with_no_mapping: Optional[pulumi.Input[bool]] = None,
recipient: Optional[pulumi.Input[str]] = None,
sign_response: Optional[pulumi.Input[bool]] = None,
signature_algorithm: Optional[pulumi.Input[str]] = None,
typed_attributes: Optional[pulumi.Input[bool]] = None):
if audience is not None:
pulumi.set(__self__, "audience", audience)
if authn_context_class_ref is not None:
pulumi.set(__self__, "authn_context_class_ref", authn_context_class_ref)
if binding is not None:
pulumi.set(__self__, "binding", binding)
if create_upn_claim is not None:
pulumi.set(__self__, "create_upn_claim", create_upn_claim)
if destination is not None:
pulumi.set(__self__, "destination", destination)
if digest_algorithm is not None:
pulumi.set(__self__, "digest_algorithm", digest_algorithm)
if include_attribute_name_format is not None:
pulumi.set(__self__, "include_attribute_name_format", include_attribute_name_format)
if lifetime_in_seconds is not None:
pulumi.set(__self__, "lifetime_in_seconds", lifetime_in_seconds)
if logout is not None:
pulumi.set(__self__, "logout", logout)
if map_identities is not None:
pulumi.set(__self__, "map_identities", map_identities)
if map_unknown_claims_as_is is not None:
pulumi.set(__self__, "map_unknown_claims_as_is", map_unknown_claims_as_is)
if mappings is not None:
pulumi.set(__self__, "mappings", mappings)
if name_identifier_format is not None:
pulumi.set(__self__, "name_identifier_format", name_identifier_format)
if name_identifier_probes is not None:
pulumi.set(__self__, "name_identifier_probes", name_identifier_probes)
if passthrough_claims_with_no_mapping is not None:
pulumi.set(__self__, "passthrough_claims_with_no_mapping", passthrough_claims_with_no_mapping)
if recipient is not None:
pulumi.set(__self__, "recipient", recipient)
if sign_response is not None:
pulumi.set(__self__, "sign_response", sign_response)
if signature_algorithm is not None:
pulumi.set(__self__, "signature_algorithm", signature_algorithm)
if typed_attributes is not None:
pulumi.set(__self__, "typed_attributes", typed_attributes)
@property
@pulumi.getter
def audience(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "audience")
@audience.setter
def audience(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "audience", value)
@property
@pulumi.getter(name="authnContextClassRef")
def authn_context_class_ref(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "authn_context_class_ref")
@authn_context_class_ref.setter
def authn_context_class_ref(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "authn_context_class_ref", value)
@property
@pulumi.getter
def binding(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "binding")
@binding.setter
def binding(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "binding", value)
@property
@pulumi.getter(name="createUpnClaim")
def create_upn_claim(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "create_upn_claim")
@create_upn_claim.setter
def create_upn_claim(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "create_upn_claim", value)
@property
@pulumi.getter
def destination(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "destination")
@destination.setter
def destination(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "destination", value)
@property
@pulumi.getter(name="digestAlgorithm")
def digest_algorithm(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "digest_algorithm")
@digest_algorithm.setter
def digest_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "digest_algorithm", value)
@property
@pulumi.getter(name="includeAttributeNameFormat")
def include_attribute_name_format(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "include_attribute_name_format")
@include_attribute_name_format.setter
def include_attribute_name_format(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "include_attribute_name_format", value)
@property
@pulumi.getter(name="lifetimeInSeconds")
def lifetime_in_seconds(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "lifetime_in_seconds")
@lifetime_in_seconds.setter
def lifetime_in_seconds(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lifetime_in_seconds", value)
@property
@pulumi.getter
def logout(self) -> Optional[pulumi.Input['GlobalClientAddonsSamlpLogoutArgs']]:
return pulumi.get(self, "logout")
@logout.setter
def logout(self, value: Optional[pulumi.Input['GlobalClientAddonsSamlpLogoutArgs']]):
pulumi.set(self, "logout", value)
@property
@pulumi.getter(name="mapIdentities")
def map_identities(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "map_identities")
@map_identities.setter
def map_identities(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "map_identities", value)
@property
@pulumi.getter(name="mapUnknownClaimsAsIs")
def map_unknown_claims_as_is(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "map_unknown_claims_as_is")
@map_unknown_claims_as_is.setter
def map_unknown_claims_as_is(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "map_unknown_claims_as_is", value)
@property
@pulumi.getter
def mappings(self) -> Optional[pulumi.Input[Mapping[str, Any]]]:
return pulumi.get(self, "mappings")
@mappings.setter
def mappings(self, value: Optional[pulumi.Input[Mapping[str, Any]]]):
pulumi.set(self, "mappings", value)
@property
@pulumi.getter(name="nameIdentifierFormat")
def name_identifier_format(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "name_identifier_format")
@name_identifier_format.setter
def name_identifier_format(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name_identifier_format", value)
@property
@pulumi.getter(name="nameIdentifierProbes")
def name_identifier_probes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "name_identifier_probes")
@name_identifier_probes.setter
def name_identifier_probes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "name_identifier_probes", value)
@property
@pulumi.getter(name="passthroughClaimsWithNoMapping")
def passthrough_claims_with_no_mapping(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "passthrough_claims_with_no_mapping")
@passthrough_claims_with_no_mapping.setter
def passthrough_claims_with_no_mapping(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "passthrough_claims_with_no_mapping", value)
@property
@pulumi.getter
def recipient(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "recipient")
@recipient.setter
def recipient(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "recipient", value)
@property
@pulumi.getter(name="signResponse")
def sign_response(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "sign_response")
@sign_response.setter
def sign_response(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "sign_response", value)
@property
@pulumi.getter(name="signatureAlgorithm")
def signature_algorithm(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "signature_algorithm")
@signature_algorithm.setter
def signature_algorithm(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "signature_algorithm", value)
@property
@pulumi.getter(name="typedAttributes")
def typed_attributes(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "typed_attributes")
@typed_attributes.setter
def typed_attributes(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "typed_attributes", value)
@pulumi.input_type
class GlobalClientAddonsSamlpLogoutArgs:
def __init__(__self__, *,
callback: Optional[pulumi.Input[str]] = None,
slo_enabled: Optional[pulumi.Input[bool]] = None):
if callback is not None:
pulumi.set(__self__, "callback", callback)
if slo_enabled is not None:
pulumi.set(__self__, "slo_enabled", slo_enabled)
@property
@pulumi.getter
def callback(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "callback")
@callback.setter
def callback(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "callback", value)
@property
@pulumi.getter(name="sloEnabled")
def slo_enabled(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "slo_enabled")
@slo_enabled.setter
def slo_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "slo_enabled", value)
@pulumi.input_type
class GlobalClientJwtConfigurationArgs:
def __init__(__self__, *,
alg: Optional[pulumi.Input[str]] = None,
lifetime_in_seconds: Optional[pulumi.Input[int]] = None,
scopes: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
secret_encoded: Optional[pulumi.Input[bool]] = None):
if alg is not None:
pulumi.set(__self__, "alg", alg)
if lifetime_in_seconds is not None:
pulumi.set(__self__, "lifetime_in_seconds", lifetime_in_seconds)
if scopes is not None:
pulumi.set(__self__, "scopes", scopes)
if secret_encoded is not None:
pulumi.set(__self__, "secret_encoded", secret_encoded)
@property
@pulumi.getter
def alg(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "alg")
@alg.setter
def alg(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "alg", value)
@property
@pulumi.getter(name="lifetimeInSeconds")
def lifetime_in_seconds(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "lifetime_in_seconds")
@lifetime_in_seconds.setter
def lifetime_in_seconds(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lifetime_in_seconds", value)
@property
@pulumi.getter
def scopes(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
return pulumi.get(self, "scopes")
@scopes.setter
def scopes(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "scopes", value)
@property
@pulumi.getter(name="secretEncoded")
def secret_encoded(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "secret_encoded")
@secret_encoded.setter
def secret_encoded(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "secret_encoded", value)
@pulumi.input_type
class GlobalClientMobileArgs:
def __init__(__self__, *,
android: Optional[pulumi.Input['GlobalClientMobileAndroidArgs']] = None,
ios: Optional[pulumi.Input['GlobalClientMobileIosArgs']] = None):
if android is not None:
pulumi.set(__self__, "android", android)
if ios is not None:
pulumi.set(__self__, "ios", ios)
@property
@pulumi.getter
def android(self) -> Optional[pulumi.Input['GlobalClientMobileAndroidArgs']]:
return pulumi.get(self, "android")
@android.setter
def android(self, value: Optional[pulumi.Input['GlobalClientMobileAndroidArgs']]):
pulumi.set(self, "android", value)
@property
@pulumi.getter
def ios(self) -> Optional[pulumi.Input['GlobalClientMobileIosArgs']]:
return pulumi.get(self, "ios")
@ios.setter
def ios(self, value: Optional[pulumi.Input['GlobalClientMobileIosArgs']]):
pulumi.set(self, "ios", value)
@pulumi.input_type
class GlobalClientMobileAndroidArgs:
def __init__(__self__, *,
app_package_name: Optional[pulumi.Input[str]] = None,
sha256_cert_fingerprints: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None):
if app_package_name is not None:
pulumi.set(__self__, "app_package_name", app_package_name)
if sha256_cert_fingerprints is not None:
pulumi.set(__self__, "sha256_cert_fingerprints", sha256_cert_fingerprints)
@property
@pulumi.getter(name="appPackageName")
def app_package_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "app_package_name")
@app_package_name.setter
def app_package_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_package_name", value)
@property
@pulumi.getter(name="sha256CertFingerprints")
def sha256_cert_fingerprints(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "sha256_cert_fingerprints")
@sha256_cert_fingerprints.setter
def sha256_cert_fingerprints(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "sha256_cert_fingerprints", value)
@pulumi.input_type
class GlobalClientMobileIosArgs:
def __init__(__self__, *,
app_bundle_identifier: Optional[pulumi.Input[str]] = None,
team_id: Optional[pulumi.Input[str]] = None):
if app_bundle_identifier is not None:
pulumi.set(__self__, "app_bundle_identifier", app_bundle_identifier)
if team_id is not None:
pulumi.set(__self__, "team_id", team_id)
@property
@pulumi.getter(name="appBundleIdentifier")
def app_bundle_identifier(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "app_bundle_identifier")
@app_bundle_identifier.setter
def app_bundle_identifier(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "app_bundle_identifier", value)
@property
@pulumi.getter(name="teamId")
def team_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "team_id")
@team_id.setter
def team_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "team_id", value)
@pulumi.input_type
class GlobalClientRefreshTokenArgs:
def __init__(__self__, *,
expiration_type: pulumi.Input[str],
rotation_type: pulumi.Input[str],
idle_token_lifetime: Optional[pulumi.Input[int]] = None,
infinite_idle_token_lifetime: Optional[pulumi.Input[bool]] = None,
infinite_token_lifetime: Optional[pulumi.Input[bool]] = None,
leeway: Optional[pulumi.Input[int]] = None,
token_lifetime: Optional[pulumi.Input[int]] = None):
pulumi.set(__self__, "expiration_type", expiration_type)
pulumi.set(__self__, "rotation_type", rotation_type)
if idle_token_lifetime is not None:
pulumi.set(__self__, "idle_token_lifetime", idle_token_lifetime)
if infinite_idle_token_lifetime is not None:
pulumi.set(__self__, "infinite_idle_token_lifetime", infinite_idle_token_lifetime)
if infinite_token_lifetime is not None:
pulumi.set(__self__, "infinite_token_lifetime", infinite_token_lifetime)
if leeway is not None:
pulumi.set(__self__, "leeway", leeway)
if token_lifetime is not None:
pulumi.set(__self__, "token_lifetime", token_lifetime)
@property
@pulumi.getter(name="expirationType")
def expiration_type(self) -> pulumi.Input[str]:
return pulumi.get(self, "expiration_type")
@expiration_type.setter
def expiration_type(self, value: pulumi.Input[str]):
pulumi.set(self, "expiration_type", value)
@property
@pulumi.getter(name="rotationType")
def rotation_type(self) -> pulumi.Input[str]:
return pulumi.get(self, "rotation_type")
@rotation_type.setter
def rotation_type(self, value: pulumi.Input[str]):
pulumi.set(self, "rotation_type", value)
@property
@pulumi.getter(name="idleTokenLifetime")
def idle_token_lifetime(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "idle_token_lifetime")
@idle_token_lifetime.setter
def idle_token_lifetime(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "idle_token_lifetime", value)
@property
@pulumi.getter(name="infiniteIdleTokenLifetime")
def infinite_idle_token_lifetime(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "infinite_idle_token_lifetime")
@infinite_idle_token_lifetime.setter
def infinite_idle_token_lifetime(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "infinite_idle_token_lifetime", value)
@property
@pulumi.getter(name="infiniteTokenLifetime")
def infinite_token_lifetime(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "infinite_token_lifetime")
@infinite_token_lifetime.setter
def infinite_token_lifetime(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "infinite_token_lifetime", value)
@property
@pulumi.getter
def leeway(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "leeway")
@leeway.setter
def leeway(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "leeway", value)
@property
@pulumi.getter(name="tokenLifetime")
def token_lifetime(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "token_lifetime")
@token_lifetime.setter
def token_lifetime(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "token_lifetime", value)
@pulumi.input_type
class GuardianPhoneArgs:
def __init__(__self__, *,
message_types: pulumi.Input[Sequence[pulumi.Input[str]]],
provider: pulumi.Input[str],
options: Optional[pulumi.Input['GuardianPhoneOptionsArgs']] = None):
"""
:param pulumi.Input[Sequence[pulumi.Input[str]]] message_types: List(String). Message types to use, array of `phone` and or `voice`. Adding both to array should enable the user to choose.
:param pulumi.Input[str] provider: String, Case-sensitive. Provider to use, one of `auth0`, `twilio` or `phone-message-hook`.
:param pulumi.Input['GuardianPhoneOptionsArgs'] options: List(Resource). Options for the various providers. See Options.
"""
pulumi.set(__self__, "message_types", message_types)
pulumi.set(__self__, "provider", provider)
if options is not None:
pulumi.set(__self__, "options", options)
@property
@pulumi.getter(name="messageTypes")
def message_types(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:
"""
List(String). Message types to use, array of `phone` and or `voice`. Adding both to array should enable the user to choose.
"""
return pulumi.get(self, "message_types")
@message_types.setter
def message_types(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]):
pulumi.set(self, "message_types", value)
@property
@pulumi.getter
def provider(self) -> pulumi.Input[str]:
"""
String, Case-sensitive. Provider to use, one of `auth0`, `twilio` or `phone-message-hook`.
"""
return pulumi.get(self, "provider")
@provider.setter
def provider(self, value: pulumi.Input[str]):
pulumi.set(self, "provider", value)
@property
@pulumi.getter
def options(self) -> Optional[pulumi.Input['GuardianPhoneOptionsArgs']]:
"""
List(Resource). Options for the various providers. See Options.
"""
return pulumi.get(self, "options")
@options.setter
def options(self, value: Optional[pulumi.Input['GuardianPhoneOptionsArgs']]):
pulumi.set(self, "options", value)
@pulumi.input_type
class GuardianPhoneOptionsArgs:
def __init__(__self__, *,
auth_token: Optional[pulumi.Input[str]] = None,
enrollment_message: Optional[pulumi.Input[str]] = None,
from_: Optional[pulumi.Input[str]] = None,
messaging_service_sid: Optional[pulumi.Input[str]] = None,
sid: Optional[pulumi.Input[str]] = None,
verification_message: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] auth_token: String.
:param pulumi.Input[str] enrollment_message: String. This message will be sent whenever a user enrolls a new device for the first time using MFA. Supports liquid syntax, see [Auth0 docs](https://auth0.com/docs/mfa/customize-sms-or-voice-messages).
:param pulumi.Input[str] from_: String.
:param pulumi.Input[str] messaging_service_sid: String.
:param pulumi.Input[str] sid: String.
:param pulumi.Input[str] verification_message: String. This message will be sent whenever a user logs in after the enrollment. Supports liquid syntax, see [Auth0 docs](https://auth0.com/docs/mfa/customize-sms-or-voice-messages).
"""
if auth_token is not None:
pulumi.set(__self__, "auth_token", auth_token)
if enrollment_message is not None:
pulumi.set(__self__, "enrollment_message", enrollment_message)
if from_ is not None:
pulumi.set(__self__, "from_", from_)
if messaging_service_sid is not None:
pulumi.set(__self__, "messaging_service_sid", messaging_service_sid)
if sid is not None:
pulumi.set(__self__, "sid", sid)
if verification_message is not None:
pulumi.set(__self__, "verification_message", verification_message)
@property
@pulumi.getter(name="authToken")
def auth_token(self) -> Optional[pulumi.Input[str]]:
"""
String.
"""
return pulumi.get(self, "auth_token")
@auth_token.setter
def auth_token(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "auth_token", value)
@property
@pulumi.getter(name="enrollmentMessage")
def enrollment_message(self) -> Optional[pulumi.Input[str]]:
"""
String. This message will be sent whenever a user enrolls a new device for the first time using MFA. Supports liquid syntax, see [Auth0 docs](https://auth0.com/docs/mfa/customize-sms-or-voice-messages).
"""
return pulumi.get(self, "enrollment_message")
@enrollment_message.setter
def enrollment_message(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "enrollment_message", value)
@property
@pulumi.getter(name="from")
def from_(self) -> Optional[pulumi.Input[str]]:
"""
String.
"""
return pulumi.get(self, "from_")
@from_.setter
def from_(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "from_", value)
@property
@pulumi.getter(name="messagingServiceSid")
def messaging_service_sid(self) -> Optional[pulumi.Input[str]]:
"""
String.
"""
return pulumi.get(self, "messaging_service_sid")
@messaging_service_sid.setter
def messaging_service_sid(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "messaging_service_sid", value)
@property
@pulumi.getter
def sid(self) -> Optional[pulumi.Input[str]]:
"""
String.
"""
return pulumi.get(self, "sid")
@sid.setter
def sid(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "sid", value)
@property
@pulumi.getter(name="verificationMessage")
def verification_message(self) -> Optional[pulumi.Input[str]]:
"""
String. This message will be sent whenever a user logs in after the enrollment. Supports liquid syntax, see [Auth0 docs](https://auth0.com/docs/mfa/customize-sms-or-voice-messages).
"""
return pulumi.get(self, "verification_message")
@verification_message.setter
def verification_message(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "verification_message", value)
@pulumi.input_type
class LogStreamSinkArgs:
def __init__(__self__, *,
aws_account_id: Optional[pulumi.Input[str]] = None,
aws_partner_event_source: Optional[pulumi.Input[str]] = None,
aws_region: Optional[pulumi.Input[str]] = None,
azure_partner_topic: Optional[pulumi.Input[str]] = None,
azure_region: Optional[pulumi.Input[str]] = None,
azure_resource_group: Optional[pulumi.Input[str]] = None,
azure_subscription_id: Optional[pulumi.Input[str]] = None,
datadog_api_key: Optional[pulumi.Input[str]] = None,
datadog_region: Optional[pulumi.Input[str]] = None,
http_authorization: Optional[pulumi.Input[str]] = None,
http_content_format: Optional[pulumi.Input[str]] = None,
http_content_type: Optional[pulumi.Input[str]] = None,
http_custom_headers: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
http_endpoint: Optional[pulumi.Input[str]] = None,
splunk_domain: Optional[pulumi.Input[str]] = None,
splunk_port: Optional[pulumi.Input[str]] = None,
splunk_secure: Optional[pulumi.Input[bool]] = None,
splunk_token: Optional[pulumi.Input[str]] = None,
sumo_source_address: Optional[pulumi.Input[str]] = None):
if aws_account_id is not None:
pulumi.set(__self__, "aws_account_id", aws_account_id)
if aws_partner_event_source is not None:
pulumi.set(__self__, "aws_partner_event_source", aws_partner_event_source)
if aws_region is not None:
pulumi.set(__self__, "aws_region", aws_region)
if azure_partner_topic is not None:
pulumi.set(__self__, "azure_partner_topic", azure_partner_topic)
if azure_region is not None:
pulumi.set(__self__, "azure_region", azure_region)
if azure_resource_group is not None:
pulumi.set(__self__, "azure_resource_group", azure_resource_group)
if azure_subscription_id is not None:
pulumi.set(__self__, "azure_subscription_id", azure_subscription_id)
if datadog_api_key is not None:
pulumi.set(__self__, "datadog_api_key", datadog_api_key)
if datadog_region is not None:
pulumi.set(__self__, "datadog_region", datadog_region)
if http_authorization is not None:
pulumi.set(__self__, "http_authorization", http_authorization)
if http_content_format is not None:
pulumi.set(__self__, "http_content_format", http_content_format)
if http_content_type is not None:
pulumi.set(__self__, "http_content_type", http_content_type)
if http_custom_headers is not None:
pulumi.set(__self__, "http_custom_headers", http_custom_headers)
if http_endpoint is not None:
pulumi.set(__self__, "http_endpoint", http_endpoint)
if splunk_domain is not None:
pulumi.set(__self__, "splunk_domain", splunk_domain)
if splunk_port is not None:
pulumi.set(__self__, "splunk_port", splunk_port)
if splunk_secure is not None:
pulumi.set(__self__, "splunk_secure", splunk_secure)
if splunk_token is not None:
pulumi.set(__self__, "splunk_token", splunk_token)
if sumo_source_address is not None:
pulumi.set(__self__, "sumo_source_address", sumo_source_address)
@property
@pulumi.getter(name="awsAccountId")
def aws_account_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "aws_account_id")
@aws_account_id.setter
def aws_account_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "aws_account_id", value)
@property
@pulumi.getter(name="awsPartnerEventSource")
def aws_partner_event_source(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "aws_partner_event_source")
@aws_partner_event_source.setter
def aws_partner_event_source(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "aws_partner_event_source", value)
@property
@pulumi.getter(name="awsRegion")
def aws_region(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "aws_region")
@aws_region.setter
def aws_region(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "aws_region", value)
@property
@pulumi.getter(name="azurePartnerTopic")
def azure_partner_topic(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "azure_partner_topic")
@azure_partner_topic.setter
def azure_partner_topic(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "azure_partner_topic", value)
@property
@pulumi.getter(name="azureRegion")
def azure_region(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "azure_region")
@azure_region.setter
def azure_region(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "azure_region", value)
@property
@pulumi.getter(name="azureResourceGroup")
def azure_resource_group(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "azure_resource_group")
@azure_resource_group.setter
def azure_resource_group(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "azure_resource_group", value)
@property
@pulumi.getter(name="azureSubscriptionId")
def azure_subscription_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "azure_subscription_id")
@azure_subscription_id.setter
def azure_subscription_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "azure_subscription_id", value)
@property
@pulumi.getter(name="datadogApiKey")
def datadog_api_key(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "datadog_api_key")
@datadog_api_key.setter
def datadog_api_key(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "datadog_api_key", value)
@property
@pulumi.getter(name="datadogRegion")
def datadog_region(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "datadog_region")
@datadog_region.setter
def datadog_region(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "datadog_region", value)
@property
@pulumi.getter(name="httpAuthorization")
def http_authorization(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "http_authorization")
@http_authorization.setter
def http_authorization(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "http_authorization", value)
@property
@pulumi.getter(name="httpContentFormat")
def http_content_format(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "http_content_format")
@http_content_format.setter
def http_content_format(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "http_content_format", value)
@property
@pulumi.getter(name="httpContentType")
def http_content_type(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "http_content_type")
@http_content_type.setter
def http_content_type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "http_content_type", value)
@property
@pulumi.getter(name="httpCustomHeaders")
def http_custom_headers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "http_custom_headers")
@http_custom_headers.setter
def http_custom_headers(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "http_custom_headers", value)
@property
@pulumi.getter(name="httpEndpoint")
def http_endpoint(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "http_endpoint")
@http_endpoint.setter
def http_endpoint(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "http_endpoint", value)
@property
@pulumi.getter(name="splunkDomain")
def splunk_domain(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "splunk_domain")
@splunk_domain.setter
def splunk_domain(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "splunk_domain", value)
@property
@pulumi.getter(name="splunkPort")
def splunk_port(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "splunk_port")
@splunk_port.setter
def splunk_port(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "splunk_port", value)
@property
@pulumi.getter(name="splunkSecure")
def splunk_secure(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "splunk_secure")
@splunk_secure.setter
def splunk_secure(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "splunk_secure", value)
@property
@pulumi.getter(name="splunkToken")
def splunk_token(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "splunk_token")
@splunk_token.setter
def splunk_token(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "splunk_token", value)
@property
@pulumi.getter(name="sumoSourceAddress")
def sumo_source_address(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "sumo_source_address")
@sumo_source_address.setter
def sumo_source_address(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "sumo_source_address", value)
@pulumi.input_type
class ResourceServerScopeArgs:
def __init__(__self__, *,
value: pulumi.Input[str],
description: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] value: String. Name of the permission (scope). Examples include `read:appointments` or `delete:appointments`.
:param pulumi.Input[str] description: String. Description of the permission (scope).
"""
pulumi.set(__self__, "value", value)
if description is not None:
pulumi.set(__self__, "description", description)
@property
@pulumi.getter
def value(self) -> pulumi.Input[str]:
"""
String. Name of the permission (scope). Examples include `read:appointments` or `delete:appointments`.
"""
return pulumi.get(self, "value")
@value.setter
def value(self, value: pulumi.Input[str]):
pulumi.set(self, "value", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
String. Description of the permission (scope).
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@pulumi.input_type
class RolePermissionArgs:
def __init__(__self__, *,
name: pulumi.Input[str],
resource_server_identifier: pulumi.Input[str]):
"""
:param pulumi.Input[str] name: String. Name of the permission (scope).
:param pulumi.Input[str] resource_server_identifier: String. Unique identifier for the resource server.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "resource_server_identifier", resource_server_identifier)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
String. Name of the permission (scope).
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="resourceServerIdentifier")
def resource_server_identifier(self) -> pulumi.Input[str]:
"""
String. Unique identifier for the resource server.
"""
return pulumi.get(self, "resource_server_identifier")
@resource_server_identifier.setter
def resource_server_identifier(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_server_identifier", value)
@pulumi.input_type
class TenantChangePasswordArgs:
def __init__(__self__, *,
enabled: pulumi.Input[bool],
html: pulumi.Input[str]):
"""
:param pulumi.Input[bool] enabled: Boolean. Indicates whether or not to use the custom change password page.
:param pulumi.Input[str] html: String, HTML format with supported Liquid syntax. Customized content of the change password page.
"""
pulumi.set(__self__, "enabled", enabled)
pulumi.set(__self__, "html", html)
@property
@pulumi.getter
def enabled(self) -> pulumi.Input[bool]:
"""
Boolean. Indicates whether or not to use the custom change password page.
"""
return pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: pulumi.Input[bool]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter
def html(self) -> pulumi.Input[str]:
"""
String, HTML format with supported Liquid syntax. Customized content of the change password page.
"""
return pulumi.get(self, "html")
@html.setter
def html(self, value: pulumi.Input[str]):
pulumi.set(self, "html", value)
@pulumi.input_type
class TenantErrorPageArgs:
def __init__(__self__, *,
html: pulumi.Input[str],
show_log_link: pulumi.Input[bool],
url: pulumi.Input[str]):
"""
:param pulumi.Input[str] html: String, HTML format with supported Liquid syntax. Customized content of the error page.
:param pulumi.Input[bool] show_log_link: Boolean. Indicates whether or not to show the link to logs as part of the default error page.
:param pulumi.Input[str] url: String. URL to redirect to when an error occurs rather than showing the default error page.
"""
pulumi.set(__self__, "html", html)
pulumi.set(__self__, "show_log_link", show_log_link)
pulumi.set(__self__, "url", url)
@property
@pulumi.getter
def html(self) -> pulumi.Input[str]:
"""
String, HTML format with supported Liquid syntax. Customized content of the error page.
"""
return pulumi.get(self, "html")
@html.setter
def html(self, value: pulumi.Input[str]):
pulumi.set(self, "html", value)
@property
@pulumi.getter(name="showLogLink")
def show_log_link(self) -> pulumi.Input[bool]:
"""
Boolean. Indicates whether or not to show the link to logs as part of the default error page.
"""
return pulumi.get(self, "show_log_link")
@show_log_link.setter
def show_log_link(self, value: pulumi.Input[bool]):
pulumi.set(self, "show_log_link", value)
@property
@pulumi.getter
def url(self) -> pulumi.Input[str]:
"""
String. URL to redirect to when an error occurs rather than showing the default error page.
"""
return pulumi.get(self, "url")
@url.setter
def url(self, value: pulumi.Input[str]):
pulumi.set(self, "url", value)
@pulumi.input_type
class TenantFlagsArgs:
def __init__(__self__, *,
change_pwd_flow_v1: Optional[pulumi.Input[bool]] = None,
disable_clickjack_protection_headers: Optional[pulumi.Input[bool]] = None,
enable_apis_section: Optional[pulumi.Input[bool]] = None,
enable_client_connections: Optional[pulumi.Input[bool]] = None,
enable_custom_domain_in_emails: Optional[pulumi.Input[bool]] = None,
enable_dynamic_client_registration: Optional[pulumi.Input[bool]] = None,
enable_legacy_logs_search_v2: Optional[pulumi.Input[bool]] = None,
enable_pipeline2: Optional[pulumi.Input[bool]] = None,
enable_public_signup_user_exists_error: Optional[pulumi.Input[bool]] = None,
universal_login: Optional[pulumi.Input[bool]] = None,
use_scope_descriptions_for_consent: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[bool] change_pwd_flow_v1: Boolean. Indicates whether or not to use the older v1 change password flow. Not recommended except for backward compatibility.
:param pulumi.Input[bool] disable_clickjack_protection_headers: Boolean. Indicated whether or not classic Universal Login prompts include additional security headers to prevent clickjacking.
:param pulumi.Input[bool] enable_apis_section: Boolean. Indicates whether or not the APIs section is enabled for the tenant.
:param pulumi.Input[bool] enable_client_connections: Boolean. Indicates whether or not all current connections should be enabled when a new client is created.
:param pulumi.Input[bool] enable_custom_domain_in_emails: Boolean. Indicates whether or not the tenant allows custom domains in emails.
:param pulumi.Input[bool] enable_dynamic_client_registration: Boolean. Indicates whether or not the tenant allows dynamic client registration.
:param pulumi.Input[bool] enable_legacy_logs_search_v2: Boolean. Indicates whether or not to use the older v2 legacy logs search.
:param pulumi.Input[bool] enable_pipeline2: Boolean. Indicates whether or not advanced API Authorization scenarios are enabled.
:param pulumi.Input[bool] enable_public_signup_user_exists_error: Boolean. Indicates whether or not the public sign up process shows a user_exists error if the user already exists.
:param pulumi.Input[bool] universal_login: Boolean. Indicates whether or not the tenant uses universal login.
"""
if change_pwd_flow_v1 is not None:
pulumi.set(__self__, "change_pwd_flow_v1", change_pwd_flow_v1)
if disable_clickjack_protection_headers is not None:
pulumi.set(__self__, "disable_clickjack_protection_headers", disable_clickjack_protection_headers)
if enable_apis_section is not None:
pulumi.set(__self__, "enable_apis_section", enable_apis_section)
if enable_client_connections is not None:
pulumi.set(__self__, "enable_client_connections", enable_client_connections)
if enable_custom_domain_in_emails is not None:
pulumi.set(__self__, "enable_custom_domain_in_emails", enable_custom_domain_in_emails)
if enable_dynamic_client_registration is not None:
pulumi.set(__self__, "enable_dynamic_client_registration", enable_dynamic_client_registration)
if enable_legacy_logs_search_v2 is not None:
pulumi.set(__self__, "enable_legacy_logs_search_v2", enable_legacy_logs_search_v2)
if enable_pipeline2 is not None:
pulumi.set(__self__, "enable_pipeline2", enable_pipeline2)
if enable_public_signup_user_exists_error is not None:
pulumi.set(__self__, "enable_public_signup_user_exists_error", enable_public_signup_user_exists_error)
if universal_login is not None:
pulumi.set(__self__, "universal_login", universal_login)
if use_scope_descriptions_for_consent is not None:
pulumi.set(__self__, "use_scope_descriptions_for_consent", use_scope_descriptions_for_consent)
@property
@pulumi.getter(name="changePwdFlowV1")
def change_pwd_flow_v1(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not to use the older v1 change password flow. Not recommended except for backward compatibility.
"""
return pulumi.get(self, "change_pwd_flow_v1")
@change_pwd_flow_v1.setter
def change_pwd_flow_v1(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "change_pwd_flow_v1", value)
@property
@pulumi.getter(name="disableClickjackProtectionHeaders")
def disable_clickjack_protection_headers(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicated whether or not classic Universal Login prompts include additional security headers to prevent clickjacking.
"""
return pulumi.get(self, "disable_clickjack_protection_headers")
@disable_clickjack_protection_headers.setter
def disable_clickjack_protection_headers(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "disable_clickjack_protection_headers", value)
@property
@pulumi.getter(name="enableApisSection")
def enable_apis_section(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the APIs section is enabled for the tenant.
"""
return pulumi.get(self, "enable_apis_section")
@enable_apis_section.setter
def enable_apis_section(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_apis_section", value)
@property
@pulumi.getter(name="enableClientConnections")
def enable_client_connections(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not all current connections should be enabled when a new client is created.
"""
return pulumi.get(self, "enable_client_connections")
@enable_client_connections.setter
def enable_client_connections(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_client_connections", value)
@property
@pulumi.getter(name="enableCustomDomainInEmails")
def enable_custom_domain_in_emails(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the tenant allows custom domains in emails.
"""
return pulumi.get(self, "enable_custom_domain_in_emails")
@enable_custom_domain_in_emails.setter
def enable_custom_domain_in_emails(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_custom_domain_in_emails", value)
@property
@pulumi.getter(name="enableDynamicClientRegistration")
def enable_dynamic_client_registration(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the tenant allows dynamic client registration.
"""
return pulumi.get(self, "enable_dynamic_client_registration")
@enable_dynamic_client_registration.setter
def enable_dynamic_client_registration(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_dynamic_client_registration", value)
@property
@pulumi.getter(name="enableLegacyLogsSearchV2")
def enable_legacy_logs_search_v2(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not to use the older v2 legacy logs search.
"""
return pulumi.get(self, "enable_legacy_logs_search_v2")
@enable_legacy_logs_search_v2.setter
def enable_legacy_logs_search_v2(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_legacy_logs_search_v2", value)
@property
@pulumi.getter(name="enablePipeline2")
def enable_pipeline2(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not advanced API Authorization scenarios are enabled.
"""
return pulumi.get(self, "enable_pipeline2")
@enable_pipeline2.setter
def enable_pipeline2(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_pipeline2", value)
@property
@pulumi.getter(name="enablePublicSignupUserExistsError")
def enable_public_signup_user_exists_error(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the public sign up process shows a user_exists error if the user already exists.
"""
return pulumi.get(self, "enable_public_signup_user_exists_error")
@enable_public_signup_user_exists_error.setter
def enable_public_signup_user_exists_error(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enable_public_signup_user_exists_error", value)
@property
@pulumi.getter(name="universalLogin")
def universal_login(self) -> Optional[pulumi.Input[bool]]:
"""
Boolean. Indicates whether or not the tenant uses universal login.
"""
return pulumi.get(self, "universal_login")
@universal_login.setter
def universal_login(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "universal_login", value)
@property
@pulumi.getter(name="useScopeDescriptionsForConsent")
def use_scope_descriptions_for_consent(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "use_scope_descriptions_for_consent")
@use_scope_descriptions_for_consent.setter
def use_scope_descriptions_for_consent(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "use_scope_descriptions_for_consent", value)
@pulumi.input_type
class TenantGuardianMfaPageArgs:
def __init__(__self__, *,
enabled: pulumi.Input[bool],
html: pulumi.Input[str]):
"""
:param pulumi.Input[bool] enabled: Boolean. Indicates whether or not to use the custom Guardian page.
:param pulumi.Input[str] html: String, HTML format with supported Liquid syntax. Customized content of the Guardian page.
"""
pulumi.set(__self__, "enabled", enabled)
pulumi.set(__self__, "html", html)
@property
@pulumi.getter
def enabled(self) -> pulumi.Input[bool]:
"""
Boolean. Indicates whether or not to use the custom Guardian page.
"""
return pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: pulumi.Input[bool]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter
def html(self) -> pulumi.Input[str]:
"""
String, HTML format with supported Liquid syntax. Customized content of the Guardian page.
"""
return pulumi.get(self, "html")
@html.setter
def html(self, value: pulumi.Input[str]):
pulumi.set(self, "html", value)
@pulumi.input_type
class TenantUniversalLoginArgs:
def __init__(__self__, *,
colors: Optional[pulumi.Input['TenantUniversalLoginColorsArgs']] = None):
"""
:param pulumi.Input['TenantUniversalLoginColorsArgs'] colors: List(Resource). Configuration settings for Universal Login colors. See Universal Login - Colors.
"""
if colors is not None:
pulumi.set(__self__, "colors", colors)
@property
@pulumi.getter
def colors(self) -> Optional[pulumi.Input['TenantUniversalLoginColorsArgs']]:
"""
List(Resource). Configuration settings for Universal Login colors. See Universal Login - Colors.
"""
return pulumi.get(self, "colors")
@colors.setter
def colors(self, value: Optional[pulumi.Input['TenantUniversalLoginColorsArgs']]):
pulumi.set(self, "colors", value)
@pulumi.input_type
class TenantUniversalLoginColorsArgs:
def __init__(__self__, *,
page_background: Optional[pulumi.Input[str]] = None,
primary: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] page_background: String, Hexadecimal. Background color of login pages.
:param pulumi.Input[str] primary: String, Hexadecimal. Primary button background color.
"""
if page_background is not None:
pulumi.set(__self__, "page_background", page_background)
if primary is not None:
pulumi.set(__self__, "primary", primary)
@property
@pulumi.getter(name="pageBackground")
def page_background(self) -> Optional[pulumi.Input[str]]:
"""
String, Hexadecimal. Background color of login pages.
"""
return pulumi.get(self, "page_background")
@page_background.setter
def page_background(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "page_background", value)
@property
@pulumi.getter
def primary(self) -> Optional[pulumi.Input[str]]:
"""
String, Hexadecimal. Primary button background color.
"""
return pulumi.get(self, "primary")
@primary.setter
def primary(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "primary", value)
|
python
|
#!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import imp
import optparse
import os
from os.path import join, dirname, abspath, basename, isdir, exists
import platform
import re
import signal
import subprocess
import sys
import tempfile
import time
import threading
import utils
from Queue import Queue, Empty
VERBOSE = False
# ---------------------------------------------
# --- P r o g r e s s I n d i c a t o r s ---
# ---------------------------------------------
class ProgressIndicator(object):
def __init__(self, cases):
self.cases = cases
self.queue = Queue(len(cases))
for case in cases:
self.queue.put_nowait(case)
self.succeeded = 0
self.remaining = len(cases)
self.total = len(cases)
self.failed = [ ]
self.crashed = 0
self.terminate = False
self.lock = threading.Lock()
def PrintFailureHeader(self, test):
if test.IsNegative():
negative_marker = '[negative] '
else:
negative_marker = ''
print "=== %(label)s %(negative)s===" % {
'label': test.GetLabel(),
'negative': negative_marker
}
print "Path: %s" % "/".join(test.path)
def Run(self, tasks):
self.Starting()
threads = []
# Spawn N-1 threads and then use this thread as the last one.
# That way -j1 avoids threading altogether which is a nice fallback
# in case of threading problems.
for i in xrange(tasks - 1):
thread = threading.Thread(target=self.RunSingle, args=[])
threads.append(thread)
thread.start()
try:
self.RunSingle()
# Wait for the remaining threads
for thread in threads:
# Use a timeout so that signals (ctrl-c) will be processed.
thread.join(timeout=10000000)
except Exception, e:
# If there's an exception we schedule an interruption for any
# remaining threads.
self.terminate = True
# ...and then reraise the exception to bail out
raise
self.Done()
return not self.failed
def RunSingle(self):
while not self.terminate:
try:
test = self.queue.get_nowait()
except Empty:
return
case = test.case
self.lock.acquire()
self.AboutToRun(case)
self.lock.release()
try:
start = time.time()
output = case.Run()
case.duration = (time.time() - start)
except BreakNowException:
self.terminate = True
except IOError, e:
assert self.terminate
return
if self.terminate:
return
self.lock.acquire()
if output.UnexpectedOutput():
self.failed.append(output)
if output.HasCrashed():
self.crashed += 1
else:
self.succeeded += 1
self.remaining -= 1
self.HasRun(output)
self.lock.release()
def EscapeCommand(command):
parts = []
for part in command:
if ' ' in part:
# Escape spaces. We may need to escape more characters for this
# to work properly.
parts.append('"%s"' % part)
else:
parts.append(part)
return " ".join(parts)
class SimpleProgressIndicator(ProgressIndicator):
def Starting(self):
print 'Running %i tests' % len(self.cases)
def Done(self):
print
for failed in self.failed:
self.PrintFailureHeader(failed.test)
if failed.output.stderr:
print "--- stderr ---"
print failed.output.stderr.strip()
if failed.output.stdout:
print "--- stdout ---"
print failed.output.stdout.strip()
print "Command: %s" % EscapeCommand(failed.command)
if failed.HasCrashed():
print "--- CRASHED ---"
if failed.HasTimedOut():
print "--- TIMEOUT ---"
if len(self.failed) == 0:
print "==="
print "=== All tests succeeded"
print "==="
else:
print
print "==="
print "=== %i tests failed" % len(self.failed)
if self.crashed > 0:
print "=== %i tests CRASHED" % self.crashed
print "==="
class VerboseProgressIndicator(SimpleProgressIndicator):
def AboutToRun(self, case):
print 'Starting %s...' % case.GetLabel()
sys.stdout.flush()
def HasRun(self, output):
if output.UnexpectedOutput():
if output.HasCrashed():
outcome = 'CRASH'
else:
outcome = 'FAIL'
else:
outcome = 'pass'
print 'Done running %s: %s' % (output.test.GetLabel(), outcome)
class DotsProgressIndicator(SimpleProgressIndicator):
def AboutToRun(self, case):
pass
def HasRun(self, output):
total = self.succeeded + len(self.failed)
if (total > 1) and (total % 50 == 1):
sys.stdout.write('\n')
if output.UnexpectedOutput():
if output.HasCrashed():
sys.stdout.write('C')
sys.stdout.flush()
elif output.HasTimedOut():
sys.stdout.write('T')
sys.stdout.flush()
else:
sys.stdout.write('F')
sys.stdout.flush()
else:
sys.stdout.write('.')
sys.stdout.flush()
class CompactProgressIndicator(ProgressIndicator):
def __init__(self, cases, templates):
super(CompactProgressIndicator, self).__init__(cases)
self.templates = templates
self.last_status_length = 0
self.start_time = time.time()
def Starting(self):
pass
def Done(self):
self.PrintProgress('Done')
def AboutToRun(self, case):
self.PrintProgress(case.GetLabel())
def HasRun(self, output):
if output.UnexpectedOutput():
self.ClearLine(self.last_status_length)
self.PrintFailureHeader(output.test)
stdout = output.output.stdout.strip()
if len(stdout):
print self.templates['stdout'] % stdout
stderr = output.output.stderr.strip()
if len(stderr):
print self.templates['stderr'] % stderr
print "Command: %s" % EscapeCommand(output.command)
if output.HasCrashed():
print "--- CRASHED ---"
if output.HasTimedOut():
print "--- TIMEOUT ---"
def Truncate(self, str, length):
if length and (len(str) > (length - 3)):
return str[:(length-3)] + "..."
else:
return str
def PrintProgress(self, name):
self.ClearLine(self.last_status_length)
elapsed = time.time() - self.start_time
status = self.templates['status_line'] % {
'passed': self.succeeded,
'remaining': (((self.total - self.remaining) * 100) // self.total),
'failed': len(self.failed),
'test': name,
'mins': int(elapsed) / 60,
'secs': int(elapsed) % 60
}
status = self.Truncate(status, 78)
self.last_status_length = len(status)
print status,
sys.stdout.flush()
class ColorProgressIndicator(CompactProgressIndicator):
def __init__(self, cases):
templates = {
'status_line': "[%(mins)02i:%(secs)02i|\033[34m%%%(remaining) 4d\033[0m|\033[32m+%(passed) 4d\033[0m|\033[31m-%(failed) 4d\033[0m]: %(test)s",
'stdout': "\033[1m%s\033[0m",
'stderr': "\033[31m%s\033[0m",
}
super(ColorProgressIndicator, self).__init__(cases, templates)
def ClearLine(self, last_line_length):
print "\033[1K\r",
class MonochromeProgressIndicator(CompactProgressIndicator):
def __init__(self, cases):
templates = {
'status_line': "[%(mins)02i:%(secs)02i|%%%(remaining) 4d|+%(passed) 4d|-%(failed) 4d]: %(test)s",
'stdout': '%s',
'stderr': '%s',
'clear': lambda last_line_length: ("\r" + (" " * last_line_length) + "\r"),
'max_length': 78
}
super(MonochromeProgressIndicator, self).__init__(cases, templates)
def ClearLine(self, last_line_length):
print ("\r" + (" " * last_line_length) + "\r"),
PROGRESS_INDICATORS = {
'verbose': VerboseProgressIndicator,
'dots': DotsProgressIndicator,
'color': ColorProgressIndicator,
'mono': MonochromeProgressIndicator
}
# -------------------------
# --- F r a m e w o r k ---
# -------------------------
class BreakNowException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class CommandOutput(object):
def __init__(self, exit_code, timed_out, stdout, stderr):
self.exit_code = exit_code
self.timed_out = timed_out
self.stdout = stdout
self.stderr = stderr
self.failed = None
class TestCase(object):
def __init__(self, context, path, mode):
self.path = path
self.context = context
self.duration = None
self.mode = mode
def IsNegative(self):
return False
def TestsIsolates(self):
return False
def CompareTime(self, other):
return cmp(other.duration, self.duration)
def DidFail(self, output):
if output.failed is None:
output.failed = self.IsFailureOutput(output)
return output.failed
def IsFailureOutput(self, output):
return output.exit_code != 0
def GetSource(self):
return "(no source available)"
def RunCommand(self, command):
full_command = self.context.processor(command)
output = Execute(full_command,
self.context,
self.context.GetTimeout(self, self.mode))
self.Cleanup()
return TestOutput(self,
full_command,
output,
self.context.store_unexpected_output)
def BeforeRun(self):
pass
def AfterRun(self, result):
pass
def GetCustomFlags(self, mode):
return None
def Run(self):
self.BeforeRun()
result = None
try:
result = self.RunCommand(self.GetCommand())
except:
self.terminate = True
raise BreakNowException("User pressed CTRL+C or IO went wrong")
finally:
self.AfterRun(result)
return result
def Cleanup(self):
return
class TestOutput(object):
def __init__(self, test, command, output, store_unexpected_output):
self.test = test
self.command = command
self.output = output
self.store_unexpected_output = store_unexpected_output
def UnexpectedOutput(self):
if self.HasCrashed():
outcome = CRASH
elif self.HasTimedOut():
outcome = TIMEOUT
elif self.HasFailed():
outcome = FAIL
else:
outcome = PASS
return not outcome in self.test.outcomes
def HasPreciousOutput(self):
return self.UnexpectedOutput() and self.store_unexpected_output
def HasCrashed(self):
if utils.IsWindows():
return 0x80000000 & self.output.exit_code and not (0x3FFFFF00 & self.output.exit_code)
else:
# Timed out tests will have exit_code -signal.SIGTERM.
if self.output.timed_out:
return False
return self.output.exit_code < 0 and \
self.output.exit_code != -signal.SIGABRT
def HasTimedOut(self):
return self.output.timed_out
def HasFailed(self):
execution_failed = self.test.DidFail(self.output)
if self.test.IsNegative():
return not execution_failed
else:
return execution_failed
def KillProcessWithID(pid):
if utils.IsWindows():
os.popen('taskkill /T /F /PID %d' % pid)
else:
os.kill(pid, signal.SIGTERM)
MAX_SLEEP_TIME = 0.1
INITIAL_SLEEP_TIME = 0.0001
SLEEP_TIME_FACTOR = 1.25
SEM_INVALID_VALUE = -1
SEM_NOGPFAULTERRORBOX = 0x0002 # Microsoft Platform SDK WinBase.h
def Win32SetErrorMode(mode):
prev_error_mode = SEM_INVALID_VALUE
try:
import ctypes
prev_error_mode = ctypes.windll.kernel32.SetErrorMode(mode)
except ImportError:
pass
return prev_error_mode
def RunProcess(context, timeout, args, **rest):
if context.verbose: print "#", " ".join(args)
popen_args = args
prev_error_mode = SEM_INVALID_VALUE
if utils.IsWindows():
popen_args = subprocess.list2cmdline(args)
if context.suppress_dialogs:
# Try to change the error mode to avoid dialogs on fatal errors. Don't
# touch any existing error mode flags by merging the existing error mode.
# See http://blogs.msdn.com/oldnewthing/archive/2004/07/27/198410.aspx.
error_mode = SEM_NOGPFAULTERRORBOX
prev_error_mode = Win32SetErrorMode(error_mode)
Win32SetErrorMode(error_mode | prev_error_mode)
process = subprocess.Popen(
shell = utils.IsWindows(),
args = popen_args,
**rest
)
if utils.IsWindows() and context.suppress_dialogs and prev_error_mode != SEM_INVALID_VALUE:
Win32SetErrorMode(prev_error_mode)
# Compute the end time - if the process crosses this limit we
# consider it timed out.
if timeout is None: end_time = None
else: end_time = time.time() + timeout
timed_out = False
# Repeatedly check the exit code from the process in a
# loop and keep track of whether or not it times out.
exit_code = None
sleep_time = INITIAL_SLEEP_TIME
while exit_code is None:
if (not end_time is None) and (time.time() >= end_time):
# Kill the process and wait for it to exit.
KillProcessWithID(process.pid)
exit_code = process.wait()
timed_out = True
else:
exit_code = process.poll()
time.sleep(sleep_time)
sleep_time = sleep_time * SLEEP_TIME_FACTOR
if sleep_time > MAX_SLEEP_TIME:
sleep_time = MAX_SLEEP_TIME
return (process, exit_code, timed_out)
def PrintError(str):
sys.stderr.write(str)
sys.stderr.write('\n')
def CheckedUnlink(name):
# On Windows, when run with -jN in parallel processes,
# OS often fails to unlink the temp file. Not sure why.
# Need to retry.
# Idea from https://bugs.webkit.org/attachment.cgi?id=75982&action=prettypatch
retry_count = 0
while retry_count < 30:
try:
os.unlink(name)
return
except OSError, e:
retry_count += 1
time.sleep(retry_count * 0.1)
PrintError("os.unlink() " + str(e))
def Execute(args, context, timeout=None):
(fd_out, outname) = tempfile.mkstemp()
(fd_err, errname) = tempfile.mkstemp()
(process, exit_code, timed_out) = RunProcess(
context,
timeout,
args = args,
stdout = fd_out,
stderr = fd_err,
)
os.close(fd_out)
os.close(fd_err)
output = file(outname).read()
errors = file(errname).read()
CheckedUnlink(outname)
CheckedUnlink(errname)
return CommandOutput(exit_code, timed_out, output, errors)
def ExecuteNoCapture(args, context, timeout=None):
(process, exit_code, timed_out) = RunProcess(
context,
timeout,
args = args,
)
return CommandOutput(exit_code, False, "", "")
def CarCdr(path):
if len(path) == 0:
return (None, [ ])
else:
return (path[0], path[1:])
# Use this to run several variants of the tests, e.g.:
# VARIANT_FLAGS = [[], ['--always_compact', '--noflush_code']]
VARIANT_FLAGS = [[],
['--stress-opt', '--always-opt'],
['--nocrankshaft']]
class TestConfiguration(object):
def __init__(self, context, root):
self.context = context
self.root = root
def Contains(self, path, file):
if len(path) > len(file):
return False
for i in xrange(len(path)):
if not path[i].match(file[i]):
return False
return True
def GetTestStatus(self, sections, defs):
pass
def VariantFlags(self):
return VARIANT_FLAGS
class TestSuite(object):
def __init__(self, name):
self.name = name
def GetName(self):
return self.name
class TestRepository(TestSuite):
def __init__(self, path):
normalized_path = abspath(path)
super(TestRepository, self).__init__(basename(normalized_path))
self.path = normalized_path
self.is_loaded = False
self.config = None
def GetConfiguration(self, context):
if self.is_loaded:
return self.config
self.is_loaded = True
file = None
try:
(file, pathname, description) = imp.find_module('testcfg', [ self.path ])
module = imp.load_module('testcfg', file, pathname, description)
self.config = module.GetConfiguration(context, self.path)
finally:
if file:
file.close()
return self.config
def GetBuildRequirements(self, path, context):
return self.GetConfiguration(context).GetBuildRequirements()
def DownloadData(self, context):
config = self.GetConfiguration(context)
if 'DownloadData' in dir(config):
config.DownloadData()
def AddTestsToList(self, result, current_path, path, context, mode):
config = self.GetConfiguration(context)
for v in config.VariantFlags():
tests = config.ListTests(current_path, path, mode, v)
for t in tests: t.variant_flags = v
result += tests
def GetTestStatus(self, context, sections, defs):
self.GetConfiguration(context).GetTestStatus(sections, defs)
class LiteralTestSuite(TestSuite):
def __init__(self, tests):
super(LiteralTestSuite, self).__init__('root')
self.tests = tests
def GetBuildRequirements(self, path, context):
(name, rest) = CarCdr(path)
result = [ ]
for test in self.tests:
if not name or name.match(test.GetName()):
result += test.GetBuildRequirements(rest, context)
return result
def DownloadData(self, path, context):
(name, rest) = CarCdr(path)
for test in self.tests:
if not name or name.match(test.GetName()):
test.DownloadData(context)
def ListTests(self, current_path, path, context, mode, variant_flags):
(name, rest) = CarCdr(path)
result = [ ]
for test in self.tests:
test_name = test.GetName()
if not name or name.match(test_name):
full_path = current_path + [test_name]
test.AddTestsToList(result, full_path, path, context, mode)
return result
def GetTestStatus(self, context, sections, defs):
for test in self.tests:
test.GetTestStatus(context, sections, defs)
SUFFIX = {
'debug' : '_g',
'release' : '' }
FLAGS = {
'debug' : ['--nobreak-on-abort', '--enable-slow-asserts', '--debug-code', '--verify-heap'],
'release' : ['--nobreak-on-abort']}
TIMEOUT_SCALEFACTOR = {
'debug' : 4,
'release' : 1 }
class Context(object):
def __init__(self, workspace, buildspace, verbose, vm, timeout, processor, suppress_dialogs, store_unexpected_output):
self.workspace = workspace
self.buildspace = buildspace
self.verbose = verbose
self.vm_root = vm
self.timeout = timeout
self.processor = processor
self.suppress_dialogs = suppress_dialogs
self.store_unexpected_output = store_unexpected_output
def GetVm(self, mode):
name = self.vm_root + SUFFIX[mode]
if utils.IsWindows() and not name.endswith('.exe'):
name = name + '.exe'
return name
def GetVmCommand(self, testcase, mode):
return [self.GetVm(mode)] + self.GetVmFlags(testcase, mode)
def GetVmFlags(self, testcase, mode):
flags = testcase.GetCustomFlags(mode)
if flags is None:
flags = FLAGS[mode]
return testcase.variant_flags + flags
def GetTimeout(self, testcase, mode):
result = self.timeout * TIMEOUT_SCALEFACTOR[mode]
if '--stress-opt' in self.GetVmFlags(testcase, mode):
return result * 4
else:
return result
def RunTestCases(cases_to_run, progress, tasks):
progress = PROGRESS_INDICATORS[progress](cases_to_run)
result = 0
try:
result = progress.Run(tasks)
except Exception, e:
print "\n", e
return result
def BuildRequirements(context, requirements, mode, scons_flags):
command_line = (['scons', '-Y', context.workspace, 'mode=' + ",".join(mode)]
+ requirements
+ scons_flags)
output = ExecuteNoCapture(command_line, context)
return output.exit_code == 0
# -------------------------------------------
# --- T e s t C o n f i g u r a t i o n ---
# -------------------------------------------
SKIP = 'skip'
FAIL = 'fail'
PASS = 'pass'
OKAY = 'okay'
TIMEOUT = 'timeout'
CRASH = 'crash'
SLOW = 'slow'
class Expression(object):
pass
class Constant(Expression):
def __init__(self, value):
self.value = value
def Evaluate(self, env, defs):
return self.value
class Variable(Expression):
def __init__(self, name):
self.name = name
def GetOutcomes(self, env, defs):
if self.name in env: return ListSet([env[self.name]])
else: return Nothing()
def Evaluate(self, env, defs):
return env[self.name]
class Outcome(Expression):
def __init__(self, name):
self.name = name
def GetOutcomes(self, env, defs):
if self.name in defs:
return defs[self.name].GetOutcomes(env, defs)
else:
return ListSet([self.name])
class Set(object):
pass
class ListSet(Set):
def __init__(self, elms):
self.elms = elms
def __str__(self):
return "ListSet%s" % str(self.elms)
def Intersect(self, that):
if not isinstance(that, ListSet):
return that.Intersect(self)
return ListSet([ x for x in self.elms if x in that.elms ])
def Union(self, that):
if not isinstance(that, ListSet):
return that.Union(self)
return ListSet(self.elms + [ x for x in that.elms if x not in self.elms ])
def IsEmpty(self):
return len(self.elms) == 0
class Everything(Set):
def Intersect(self, that):
return that
def Union(self, that):
return self
def IsEmpty(self):
return False
class Nothing(Set):
def Intersect(self, that):
return self
def Union(self, that):
return that
def IsEmpty(self):
return True
class Operation(Expression):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
def Evaluate(self, env, defs):
if self.op == '||' or self.op == ',':
return self.left.Evaluate(env, defs) or self.right.Evaluate(env, defs)
elif self.op == 'if':
return False
elif self.op == '==':
inter = self.left.GetOutcomes(env, defs).Intersect(self.right.GetOutcomes(env, defs))
return not inter.IsEmpty()
elif self.op == '!=':
inter = self.left.GetOutcomes(env, defs).Intersect(self.right.GetOutcomes(env, defs))
return inter.IsEmpty()
else:
assert self.op == '&&'
return self.left.Evaluate(env, defs) and self.right.Evaluate(env, defs)
def GetOutcomes(self, env, defs):
if self.op == '||' or self.op == ',':
return self.left.GetOutcomes(env, defs).Union(self.right.GetOutcomes(env, defs))
elif self.op == 'if':
if self.right.Evaluate(env, defs): return self.left.GetOutcomes(env, defs)
else: return Nothing()
else:
assert self.op == '&&'
return self.left.GetOutcomes(env, defs).Intersect(self.right.GetOutcomes(env, defs))
def IsAlpha(str):
for char in str:
if not (char.isalpha() or char.isdigit() or char == '_'):
return False
return True
class Tokenizer(object):
"""A simple string tokenizer that chops expressions into variables,
parens and operators"""
def __init__(self, expr):
self.index = 0
self.expr = expr
self.length = len(expr)
self.tokens = None
def Current(self, length = 1):
if not self.HasMore(length): return ""
return self.expr[self.index:self.index+length]
def HasMore(self, length = 1):
return self.index < self.length + (length - 1)
def Advance(self, count = 1):
self.index = self.index + count
def AddToken(self, token):
self.tokens.append(token)
def SkipSpaces(self):
while self.HasMore() and self.Current().isspace():
self.Advance()
def Tokenize(self):
self.tokens = [ ]
while self.HasMore():
self.SkipSpaces()
if not self.HasMore():
return None
if self.Current() == '(':
self.AddToken('(')
self.Advance()
elif self.Current() == ')':
self.AddToken(')')
self.Advance()
elif self.Current() == '$':
self.AddToken('$')
self.Advance()
elif self.Current() == ',':
self.AddToken(',')
self.Advance()
elif IsAlpha(self.Current()):
buf = ""
while self.HasMore() and IsAlpha(self.Current()):
buf += self.Current()
self.Advance()
self.AddToken(buf)
elif self.Current(2) == '&&':
self.AddToken('&&')
self.Advance(2)
elif self.Current(2) == '||':
self.AddToken('||')
self.Advance(2)
elif self.Current(2) == '==':
self.AddToken('==')
self.Advance(2)
elif self.Current(2) == '!=':
self.AddToken('!=')
self.Advance(2)
else:
return None
return self.tokens
class Scanner(object):
"""A simple scanner that can serve out tokens from a given list"""
def __init__(self, tokens):
self.tokens = tokens
self.length = len(tokens)
self.index = 0
def HasMore(self):
return self.index < self.length
def Current(self):
return self.tokens[self.index]
def Advance(self):
self.index = self.index + 1
def ParseAtomicExpression(scan):
if scan.Current() == "true":
scan.Advance()
return Constant(True)
elif scan.Current() == "false":
scan.Advance()
return Constant(False)
elif IsAlpha(scan.Current()):
name = scan.Current()
scan.Advance()
return Outcome(name.lower())
elif scan.Current() == '$':
scan.Advance()
if not IsAlpha(scan.Current()):
return None
name = scan.Current()
scan.Advance()
return Variable(name.lower())
elif scan.Current() == '(':
scan.Advance()
result = ParseLogicalExpression(scan)
if (not result) or (scan.Current() != ')'):
return None
scan.Advance()
return result
else:
return None
BINARIES = ['==', '!=']
def ParseOperatorExpression(scan):
left = ParseAtomicExpression(scan)
if not left: return None
while scan.HasMore() and (scan.Current() in BINARIES):
op = scan.Current()
scan.Advance()
right = ParseOperatorExpression(scan)
if not right:
return None
left = Operation(left, op, right)
return left
def ParseConditionalExpression(scan):
left = ParseOperatorExpression(scan)
if not left: return None
while scan.HasMore() and (scan.Current() == 'if'):
scan.Advance()
right = ParseOperatorExpression(scan)
if not right:
return None
left = Operation(left, 'if', right)
return left
LOGICALS = ["&&", "||", ","]
def ParseLogicalExpression(scan):
left = ParseConditionalExpression(scan)
if not left: return None
while scan.HasMore() and (scan.Current() in LOGICALS):
op = scan.Current()
scan.Advance()
right = ParseConditionalExpression(scan)
if not right:
return None
left = Operation(left, op, right)
return left
def ParseCondition(expr):
"""Parses a logical expression into an Expression object"""
tokens = Tokenizer(expr).Tokenize()
if not tokens:
print "Malformed expression: '%s'" % expr
return None
scan = Scanner(tokens)
ast = ParseLogicalExpression(scan)
if not ast:
print "Malformed expression: '%s'" % expr
return None
if scan.HasMore():
print "Malformed expression: '%s'" % expr
return None
return ast
class ClassifiedTest(object):
def __init__(self, case, outcomes):
self.case = case
self.outcomes = outcomes
def TestsIsolates(self):
return self.case.TestsIsolates()
class Configuration(object):
"""The parsed contents of a configuration file"""
def __init__(self, sections, defs):
self.sections = sections
self.defs = defs
def ClassifyTests(self, cases, env):
sections = [s for s in self.sections if s.condition.Evaluate(env, self.defs)]
all_rules = reduce(list.__add__, [s.rules for s in sections], [])
unused_rules = set(all_rules)
result = [ ]
all_outcomes = set([])
for case in cases:
matches = [ r for r in all_rules if r.Contains(case.path) ]
outcomes = set([])
for rule in matches:
outcomes = outcomes.union(rule.GetOutcomes(env, self.defs))
unused_rules.discard(rule)
if not outcomes:
outcomes = [PASS]
case.outcomes = outcomes
all_outcomes = all_outcomes.union(outcomes)
result.append(ClassifiedTest(case, outcomes))
return (result, list(unused_rules), all_outcomes)
class Section(object):
"""A section of the configuration file. Sections are enabled or
disabled prior to running the tests, based on their conditions"""
def __init__(self, condition):
self.condition = condition
self.rules = [ ]
def AddRule(self, rule):
self.rules.append(rule)
class Rule(object):
"""A single rule that specifies the expected outcome for a single
test."""
def __init__(self, raw_path, path, value):
self.raw_path = raw_path
self.path = path
self.value = value
def GetOutcomes(self, env, defs):
set = self.value.GetOutcomes(env, defs)
assert isinstance(set, ListSet)
return set.elms
def Contains(self, path):
if len(self.path) > len(path):
return False
for i in xrange(len(self.path)):
if not self.path[i].match(path[i]):
return False
return True
HEADER_PATTERN = re.compile(r'\[([^]]+)\]')
RULE_PATTERN = re.compile(r'\s*([^: ]*)\s*:(.*)')
DEF_PATTERN = re.compile(r'^def\s*(\w+)\s*=(.*)$')
PREFIX_PATTERN = re.compile(r'^\s*prefix\s+([\w\_\.\-\/]+)$')
def ReadConfigurationInto(path, sections, defs):
current_section = Section(Constant(True))
sections.append(current_section)
prefix = []
for line in utils.ReadLinesFrom(path):
header_match = HEADER_PATTERN.match(line)
if header_match:
condition_str = header_match.group(1).strip()
condition = ParseCondition(condition_str)
new_section = Section(condition)
sections.append(new_section)
current_section = new_section
continue
rule_match = RULE_PATTERN.match(line)
if rule_match:
path = prefix + SplitPath(rule_match.group(1).strip())
value_str = rule_match.group(2).strip()
value = ParseCondition(value_str)
if not value:
return False
current_section.AddRule(Rule(rule_match.group(1), path, value))
continue
def_match = DEF_PATTERN.match(line)
if def_match:
name = def_match.group(1).lower()
value = ParseCondition(def_match.group(2).strip())
if not value:
return False
defs[name] = value
continue
prefix_match = PREFIX_PATTERN.match(line)
if prefix_match:
prefix = SplitPath(prefix_match.group(1).strip())
continue
print "Malformed line: '%s'." % line
return False
return True
# ---------------
# --- M a i n ---
# ---------------
ARCH_GUESS = utils.GuessArchitecture()
TIMEOUT_DEFAULT = 60;
def BuildOptions():
result = optparse.OptionParser()
result.add_option("-m", "--mode", help="The test modes in which to run (comma-separated)",
default='release')
result.add_option("-v", "--verbose", help="Verbose output",
default=False, action="store_true")
result.add_option("-S", dest="scons_flags", help="Flag to pass through to scons",
default=[], action="append")
result.add_option("-p", "--progress",
help="The style of progress indicator (verbose, dots, color, mono)",
choices=PROGRESS_INDICATORS.keys(), default="mono")
result.add_option("--no-build", help="Don't build requirements",
default=False, action="store_true")
result.add_option("--build-only", help="Only build requirements, don't run the tests",
default=False, action="store_true")
result.add_option("--build-system", help="Build system in use (scons or gyp)",
default='scons')
result.add_option("--report", help="Print a summary of the tests to be run",
default=False, action="store_true")
result.add_option("--download-data", help="Download missing test suite data",
default=False, action="store_true")
result.add_option("-s", "--suite", help="A test suite",
default=[], action="append")
result.add_option("-t", "--timeout", help="Timeout in seconds",
default=-1, type="int")
result.add_option("--arch", help='The architecture to run tests for',
default='none')
result.add_option("--snapshot", help="Run the tests with snapshot turned on",
default=False, action="store_true")
result.add_option("--simulator", help="Run tests with architecture simulator",
default='none')
result.add_option("--special-command", default=None)
result.add_option("--valgrind", help="Run tests through valgrind",
default=False, action="store_true")
result.add_option("--cat", help="Print the source of the tests",
default=False, action="store_true")
result.add_option("--warn-unused", help="Report unused rules",
default=False, action="store_true")
result.add_option("-j", help="The number of parallel tasks to run",
default=1, type="int")
result.add_option("--time", help="Print timing information after running",
default=False, action="store_true")
result.add_option("--suppress-dialogs", help="Suppress Windows dialogs for crashing tests",
dest="suppress_dialogs", default=True, action="store_true")
result.add_option("--no-suppress-dialogs", help="Display Windows dialogs for crashing tests",
dest="suppress_dialogs", action="store_false")
result.add_option("--mips-arch-variant", help="mips architecture variant: mips32r1/mips32r2", default="mips32r2");
result.add_option("--shell", help="Path to V8 shell", default="d8")
result.add_option("--isolates", help="Whether to test isolates", default=False, action="store_true")
result.add_option("--store-unexpected-output",
help="Store the temporary JS files from tests that fails",
dest="store_unexpected_output", default=True, action="store_true")
result.add_option("--no-store-unexpected-output",
help="Deletes the temporary JS files from tests that fails",
dest="store_unexpected_output", action="store_false")
result.add_option("--stress-only",
help="Only run tests with --always-opt --stress-opt",
default=False, action="store_true")
result.add_option("--nostress",
help="Don't run crankshaft --always-opt --stress-op test",
default=False, action="store_true")
result.add_option("--crankshaft",
help="Run with the --crankshaft flag",
default=False, action="store_true")
result.add_option("--shard-count",
help="Split testsuites into this number of shards",
default=1, type="int")
result.add_option("--shard-run",
help="Run this shard from the split up tests.",
default=1, type="int")
result.add_option("--noprof", help="Disable profiling support",
default=False)
return result
def ProcessOptions(options):
global VERBOSE
VERBOSE = options.verbose
options.mode = options.mode.split(',')
for mode in options.mode:
if not mode in ['debug', 'release']:
print "Unknown mode %s" % mode
return False
if options.simulator != 'none':
# Simulator argument was set. Make sure arch and simulator agree.
if options.simulator != options.arch:
if options.arch == 'none':
options.arch = options.simulator
else:
print "Architecture %s does not match sim %s" %(options.arch, options.simulator)
return False
# Ensure that the simulator argument is handed down to scons.
options.scons_flags.append("simulator=" + options.simulator)
else:
# If options.arch is not set by the command line and no simulator setting
# was found, set the arch to the guess.
if options.arch == 'none':
options.arch = ARCH_GUESS
options.scons_flags.append("arch=" + options.arch)
# Simulators are slow, therefore allow a longer default timeout.
if options.timeout == -1:
if options.arch == 'arm' or options.arch == 'mips':
options.timeout = 2 * TIMEOUT_DEFAULT;
else:
options.timeout = TIMEOUT_DEFAULT;
if options.snapshot:
options.scons_flags.append("snapshot=on")
global VARIANT_FLAGS
if options.mips_arch_variant:
options.scons_flags.append("mips_arch_variant=" + options.mips_arch_variant)
if options.stress_only:
VARIANT_FLAGS = [['--stress-opt', '--always-opt']]
if options.nostress:
VARIANT_FLAGS = [[],['--nocrankshaft']]
if options.crankshaft:
if options.special_command:
options.special_command += " --crankshaft"
else:
options.special_command = "@ --crankshaft"
if options.shell.endswith("d8"):
if options.special_command:
options.special_command += " --test"
else:
options.special_command = "@ --test"
if options.noprof:
options.scons_flags.append("prof=off")
options.scons_flags.append("profilingsupport=off")
if options.build_system == 'gyp':
if options.build_only:
print "--build-only not supported for gyp, please build manually."
options.build_only = False
return True
def DoSkip(case):
return (SKIP in case.outcomes) or (SLOW in case.outcomes)
REPORT_TEMPLATE = """\
Total: %(total)i tests
* %(skipped)4d tests will be skipped
* %(timeout)4d tests are expected to timeout sometimes
* %(nocrash)4d tests are expected to be flaky but not crash
* %(pass)4d tests are expected to pass
* %(fail_ok)4d tests are expected to fail that we won't fix
* %(fail)4d tests are expected to fail that we should fix\
"""
def PrintReport(cases):
def IsFlaky(o):
return (PASS in o) and (FAIL in o) and (not CRASH in o) and (not OKAY in o)
def IsFailOk(o):
return (len(o) == 2) and (FAIL in o) and (OKAY in o)
unskipped = [c for c in cases if not DoSkip(c)]
print REPORT_TEMPLATE % {
'total': len(cases),
'skipped': len(cases) - len(unskipped),
'timeout': len([t for t in unskipped if TIMEOUT in t.outcomes]),
'nocrash': len([t for t in unskipped if IsFlaky(t.outcomes)]),
'pass': len([t for t in unskipped if list(t.outcomes) == [PASS]]),
'fail_ok': len([t for t in unskipped if IsFailOk(t.outcomes)]),
'fail': len([t for t in unskipped if list(t.outcomes) == [FAIL]])
}
class Pattern(object):
def __init__(self, pattern):
self.pattern = pattern
self.compiled = None
def match(self, str):
if not self.compiled:
pattern = "^" + self.pattern.replace('*', '.*') + "$"
self.compiled = re.compile(pattern)
return self.compiled.match(str)
def __str__(self):
return self.pattern
def SplitPath(s):
stripped = [ c.strip() for c in s.split('/') ]
return [ Pattern(s) for s in stripped if len(s) > 0 ]
def GetSpecialCommandProcessor(value):
if (not value) or (value.find('@') == -1):
def ExpandCommand(args):
return args
return ExpandCommand
else:
pos = value.find('@')
import urllib
prefix = urllib.unquote(value[:pos]).split()
suffix = urllib.unquote(value[pos+1:]).split()
def ExpandCommand(args):
return prefix + args + suffix
return ExpandCommand
BUILT_IN_TESTS = ['mjsunit', 'cctest', 'message', 'preparser']
def GetSuites(test_root):
def IsSuite(path):
return isdir(path) and exists(join(path, 'testcfg.py'))
return [ f for f in os.listdir(test_root) if IsSuite(join(test_root, f)) ]
def FormatTime(d):
millis = round(d * 1000) % 1000
return time.strftime("%M:%S.", time.gmtime(d)) + ("%03i" % millis)
def ShardTests(tests, options):
if options.shard_count < 2:
return tests
if options.shard_run < 1 or options.shard_run > options.shard_count:
print "shard-run not a valid number, should be in [1:shard-count]"
print "defaulting back to running all tests"
return tests
count = 0
shard = []
for test in tests:
if count % options.shard_count == options.shard_run - 1:
shard.append(test)
count += 1
return shard
def Main():
parser = BuildOptions()
(options, args) = parser.parse_args()
if not ProcessOptions(options):
parser.print_help()
return 1
workspace = abspath(join(dirname(sys.argv[0]), '..'))
suites = GetSuites(join(workspace, 'test'))
repositories = [TestRepository(join(workspace, 'test', name)) for name in suites]
repositories += [TestRepository(a) for a in options.suite]
root = LiteralTestSuite(repositories)
if len(args) == 0:
paths = [SplitPath(t) for t in BUILT_IN_TESTS]
else:
paths = [ ]
for arg in args:
path = SplitPath(arg)
paths.append(path)
# Check for --valgrind option. If enabled, we overwrite the special
# command flag with a command that uses the run-valgrind.py script.
if options.valgrind:
run_valgrind = join(workspace, "tools", "run-valgrind.py")
options.special_command = "python -u " + run_valgrind + " @"
if options.build_system == 'gyp':
SUFFIX['debug'] = ''
shell = abspath(options.shell)
buildspace = dirname(shell)
context = Context(workspace, buildspace, VERBOSE,
shell,
options.timeout,
GetSpecialCommandProcessor(options.special_command),
options.suppress_dialogs,
options.store_unexpected_output)
# First build the required targets
if not options.no_build:
reqs = [ ]
for path in paths:
reqs += root.GetBuildRequirements(path, context)
reqs = list(set(reqs))
if len(reqs) > 0:
if options.j != 1:
options.scons_flags += ['-j', str(options.j)]
if not BuildRequirements(context, reqs, options.mode, options.scons_flags):
return 1
# Just return if we are only building the targets for running the tests.
if options.build_only:
return 0
# Get status for tests
sections = [ ]
defs = { }
root.GetTestStatus(context, sections, defs)
config = Configuration(sections, defs)
# Download missing test suite data if requested.
if options.download_data:
for path in paths:
root.DownloadData(path, context)
# List the tests
all_cases = [ ]
all_unused = [ ]
unclassified_tests = [ ]
globally_unused_rules = None
for path in paths:
for mode in options.mode:
env = {
'mode': mode,
'system': utils.GuessOS(),
'arch': options.arch,
'simulator': options.simulator,
'crankshaft': options.crankshaft,
'isolates': options.isolates
}
test_list = root.ListTests([], path, context, mode, [])
unclassified_tests += test_list
(cases, unused_rules, all_outcomes) = config.ClassifyTests(test_list, env)
if globally_unused_rules is None:
globally_unused_rules = set(unused_rules)
else:
globally_unused_rules = globally_unused_rules.intersection(unused_rules)
all_cases += ShardTests(cases, options)
all_unused.append(unused_rules)
if options.cat:
visited = set()
for test in unclassified_tests:
key = tuple(test.path)
if key in visited:
continue
visited.add(key)
print "--- begin source: %s ---" % test.GetLabel()
source = test.GetSource().strip()
print source
print "--- end source: %s ---" % test.GetLabel()
return 0
if options.warn_unused:
for rule in globally_unused_rules:
print "Rule for '%s' was not used." % '/'.join([str(s) for s in rule.path])
if not options.isolates:
all_cases = [c for c in all_cases if not c.TestsIsolates()]
if options.report:
PrintReport(all_cases)
result = None
cases_to_run = [ c for c in all_cases if not DoSkip(c) ]
if len(cases_to_run) == 0:
print "No tests to run."
return 0
else:
try:
start = time.time()
if RunTestCases(cases_to_run, options.progress, options.j):
result = 0
else:
result = 1
duration = time.time() - start
except KeyboardInterrupt:
print "Interrupted"
return 1
if options.time:
# Write the times to stderr to make it easy to separate from the
# test output.
print
sys.stderr.write("--- Total time: %s ---\n" % FormatTime(duration))
timed_tests = [ t.case for t in cases_to_run if not t.case.duration is None ]
timed_tests.sort(lambda a, b: a.CompareTime(b))
index = 1
for entry in timed_tests[:20]:
t = FormatTime(entry.duration)
sys.stderr.write("%4i (%s) %s\n" % (index, t, entry.GetLabel()))
index += 1
return result
if __name__ == '__main__':
sys.exit(Main())
|
python
|
# -*- coding: utf-8 -*-
import tkinter
def affiche_touche_pressee():
root.event_generate("<<perso>>", rooty=-5)
def perso(evt):
print("perso", evt.y_root)
root = tkinter.Tk()
b = tkinter.Button(text="clic", command=affiche_touche_pressee)
b.pack()
root.bind("<<perso>>", perso) # on intercepte un événement personnalisé
root.mainloop ()
|
python
|
#!/usr/bin/env python
import rospy #importar ros para python
from std_msgs.msg import String, Int32 # importar mensajes de ROS tipo String y tipo Int32
from geometry_msgs.msg import Twist # importar mensajes de ROS tipo geometry / Twist
class Printer(object):
def __init__(self, args):
super(Printer, self).__init__()
self.subscriber = rospy.Subscriber("/chatter", Int32, self.callback)
def callback(self,msg):
rospy.loginfo(msg.data)
def main():
rospy.init_node('Printer') #creacion y registro del nodo!
obj = Printer('args') # Crea un objeto del tipo Template, cuya definicion se encuentra arriba
#objeto.publicar() #llama al metodo publicar del objeto obj de tipo Template
rospy.spin() #funcion de ROS que evita que el programa termine - se debe usar en Subscribers
if __name__ =='__main__':
main()
|
python
|
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 6):
print(sys.stderr, "{}: need Python 3.6 or later.".format(sys.argv[0]))
print(sys.stderr, "Your Python is {}".format(sys.version))
sys.exit(1)
ROOT_DIR = os.path.dirname(__file__)
setup(
name="py-pdf-parser",
packages=find_packages(),
exclude=["tests.*", "tests", "docs", "docs.*"],
version="0.10.1",
url="https://github.com/jstockwin/py-pdf-parser",
license="BSD",
description="A tool to help extracting information from structured PDFs.",
long_description=open(os.path.join(ROOT_DIR, "README.md")).read(),
long_description_content_type="text/markdown",
author="Jake Stockwin",
author_email="[email protected]",
include_package_data=True,
install_requires=[
"pdfminer.six==20211012",
"docopt==0.6.2",
"wand==0.6.7",
],
extras_require={
"dev": [
"matplotlib==3.4.3",
"pillow==8.4.0",
"pyvoronoi==1.0.7",
"shapely==1.7.1",
],
"test": [
"black==21.9b0",
"ddt==1.4.4",
"matplotlib==3.4.3",
"mock==4.0.3",
"mypy==0.910",
"nose==1.3.7",
"pillow==8.4.0",
"pycodestyle==2.8.0",
"pytype==2021.9.9",
"recommonmark==0.7.1",
"sphinx-autobuild==2021.3.14",
"sphinx-rtd-theme==1.0.0",
"Sphinx==4.2.0",
],
},
)
|
python
|
"""
Copyright (C) king.com Ltd 2019
https://github.com/king/s3vdc
License: MIT, https://raw.github.com/king/s3vdc/LICENSE.md
"""
import tensorflow as tf
def _session_config() -> tf.ConfigProto:
"""Constructs a session config specifying gpu memory usage.
Returns:
tf.ConfigProto -- session config.
"""
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95, allow_growth=True)
session_config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)
return session_config
def default_run_config(
model_dir: str,
save_summary_steps: int = 100,
save_checkpoints_mins: int = 5,
keep_checkpoint_max: int = 5,
) -> tf.estimator.RunConfig:
"""Constructs a tf.contrib.learn.RunConfig instance with the specified model dir and default values.
Arguments:
model_dir {str} -- The model directory to save checkpoints, summary outputs etc.
Keyword Arguments:
save_summary_steps {int} -- save summary every x steps (default: {100})
save_checkpoints_mins {int} -- save checkpoints every x steps (default: {5})
keep_checkpoint_max {int} -- keep maximum x checkpoints (default: {5})
Returns:
tf.estimator.RunConfig -- The constructed RunConfig.
"""
return tf.estimator.RunConfig(
model_dir=model_dir,
save_summary_steps=save_summary_steps,
save_checkpoints_steps=None,
save_checkpoints_secs=save_checkpoints_mins * 60, # seconds
keep_checkpoint_max=keep_checkpoint_max,
session_config=_session_config(),
)
|
python
|
"""Runtimes manager."""
import logging
from contextlib import suppress
from importlib import import_module
from types import ModuleType
from typing import Dict, Optional, Set, Type
from .runtime import Process
logger = logging.getLogger(__name__)
class RegisteredRuntimes:
"""A list of registered base python processes to be copied into executor.
The python processes is must extend the base class for
python processes :class:`resolwe.process.runtime.Process` and set the
class attribute `_abstract` to True. They must also be registered by
addind their name to the settings `FLOW_PROCESSES_RUNTIMES`.
Is such case the entire parent module of the file in which the process is
defined is copied to the executor. It is the responsibility of the
programer to make sure that the module uses only Python standard library
(and possibly other runtimes it inherits from).
"""
def __init__(self):
"""Initialization."""
self._class_module: Dict[str, ModuleType] = dict()
self._registered_classes: Dict[str, Type[Process]] = dict()
# A set of dependencies for every registered class.
self._dependencies: Dict[str, Set[ModuleType]] = dict()
self._register_runtimes()
def _register_runtimes(self):
"""Register python runtimes."""
with suppress(ImportError):
from django.conf import settings
for runtime_class_name in getattr(
settings,
"FLOW_PROCESSES_RUNTIMES",
("resolwe.process.runtime.Process",),
):
module_name, class_name = runtime_class_name.rsplit(".", 1)
self.register_runtime(getattr(import_module(module_name), class_name))
def _get_runtime_classes(self, klass: Type["Process"]) -> Set[Type["Process"]]:
"""Get all the runtime classes of a given class.
This includes all the runtime classes this class inherits from.
"""
bases = set()
if "_abstract" in klass.__dict__ and issubclass(klass, Process):
bases.add(klass)
for base_class in klass.__bases__:
bases.update(self._get_runtime_classes(base_class))
return bases
def register_runtime(self, klass: Type["Process"]):
"""Register base class for processes.
:raises AssertionError: if runtime is already registered or klass is
not a base class for python processes.
"""
class_name = klass.__name__
assert (
class_name not in self._registered_classes
), f"Class {class_name} already registered."
assert issubclass(
klass, Process
), f"Class {class_name} must be a subclass of resolwe.process.runtime.Process."
assert (
"_abstract" in klass.__dict__
), f"Class {class_name} must contain as class attribute _abstract."
module_name = klass.__module__[: klass.__module__.rindex(".")]
module = import_module(module_name)
self._registered_classes[klass.__name__] = klass
self._class_module[klass.__name__] = module
self._dependencies[klass.__name__] = {
self._class_module[runtime_class.__name__]
for runtime_class in self._get_runtime_classes(klass)
}
logger.debug(
"Registered python class %s, module %s.", klass.__name__, module.__name__
)
def necessary_modules(self, class_name: str) -> Set[ModuleType]:
"""Get a set of necessary modules for the given class_name."""
return self._dependencies[class_name]
def registered_class(self, class_name: str) -> Optional[Type["PythonProcess"]]:
"""Get registered class from name."""
return self._registered_classes.get(class_name)
def is_registered(self, class_name: str) -> bool:
"""Return if the given class name is registered as runtime class."""
return class_name in self._registered_classes
python_runtimes_manager = RegisteredRuntimes()
|
python
|
# use lists as stack, LIFO (last-in-first-out)
stack = [1, 2, 3, 4, 5]
print(stack)
print('LIFO stack')
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)
print("\n")
# use lists as FIFO (first-in-first-out)
print('FIFO stack')
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop(0))
print(stack.pop(0))
print(stack)
input("Press Enter to continue...")
|
python
|
from constance import config
from django.http import Http404
from impersonate.decorators import allowed_user_required
from impersonate.views import impersonate, stop_impersonate
from bitcaster.models import User
def queryset(request):
return User.objects.exclude(id=request.user.id).exclude(is_superuser=True).order_by('email')
@allowed_user_required
def impersonate_start(request, uid):
if not config.ENABLE_IMPERSONATE:
raise Http404
return impersonate(request, uid)
def impersonate_stop(request):
return stop_impersonate(request)
|
python
|
import numpy as np
class LogisticRegression(object):
# setting learning rate and iteration times
def __init__(self, alpha=0.0005, lamb=0.1, iters=100):
self.iters = iters
self.alpha = alpha
self.lamb = lamb
# add one line for intercept
self.theta = np.array([0.0] * (X.shape[1] + 1))
def __normalize(self, tensor):
return (tensor - np.mean(tensor, axis=0)) / np.std(tensor, axis=0)
def __addIntercept(self, tensor):
intercept = np.ones((tensor.shape[0], 1))
return np.append(intercept, tensor, axis=1)
def __preprocess(self, tensor):
# feature normalize
tensor = self.__normalize(tensor)
# add constant column to x(to accommodate the θ0 intercept term)
tensor = self.__addIntercept(tensor)
return tensor
def __sigmoid(self,tensor):
return 1/(np.exp(-tensor)+1)
def __hypothese(self,X,theta):
return self.__sigmoid(np.dot(
X,theta
))
def computeCost(self,X,y,theta):
positive = np.multiply((-y),np.log(self.__hypothese(X,theta)))
negative = np.multiply((1-y),(1-np.log(self.__hypothese(X,theta))))
penalty = self.lamb/( 2*(X.shape[0]) ) * np.dot(theta[1:],theta[1:])
return np.sum(positive-negative)/len(X)
def __gradientDescent(self,X,y,theta):
for i in range(self.iters):
# use vectorization implementation to optimize performance
# do not penalize θ0.
theta[0:1] = theta[0:1] - (self.alpha/X.shape[0])*(
np.dot(X[:,0:1].T,self.__hypothese(X[:,0:1],theta[0:1])-y)
)
# calculate others theta with regulation
theta[1:] = theta[0:1] - (self.alpha/X.shape[0])*(
np.dot(X[:,1:].T,self.__hypothese(X[:,1:],theta[1:])-y)
+ self.lamb * theta[1:])
print("the cost of iteration {} is {}".format(
i, self.computeCost(X, y, theta)))
return theta
def fit(self, X, y):
X = self.__preprocess(X)
print(X)
self.theta = self.__gradientDescent(X, y, self.theta)
def predict(self, X):
X = self.__preprocess(X)
pred = self.__hypothese(X,self.theta)
numpy.putmask(pred,pred>=0.5,1.0)
numpy.putmask(pred,pred<0.5,0.0)
return pred
if __name__ == "__main__":
pass
|
python
|
import pickle
def load( path ):
with open(path, 'rb') as ff :
model = pickle.load(ff)[0]
return model
|
python
|
#!/usr/bin/env python36
# -*- coding: utf-8 -*-
"""
Created on 2018/10/6 11:48 AM
@author: Tangrizzly
"""
from __future__ import print_function
from collections import OrderedDict
import datetime
import cPickle
import os
from public.GeoIE import GeoIE
from public.Global_Best import GlobalBest
from public.Load_Data_GeoIE import *
from public.Valuate import fun_predict_auc_recall_map_ndcg, fun_save_best_and_losses
__docformat__ = 'restructedtext en'
WHOLE = './poidata/'
PATH_f = os.path.join(WHOLE, 'Foursquare/sequence')
PATH_g = os.path.join(WHOLE, 'Gowalla/sequence')
PATH = PATH_f
def exe_time(func):
def new_func(*args, **args2):
name = func.__name__
start = datetime.datetime.now()
print("-- {%s} start: @ %ss" % (name, start))
back = func(*args, **args2)
end = datetime.datetime.now()
print("-- {%s} start: @ %ss" % (name, start))
print("-- {%s} end: @ %ss" % (name, end))
total = (end - start).total_seconds()
print("-- {%s} total: @ %.3fs = %.3fh" % (name, total, total / 3600.0))
return back
return new_func
class Params(object):
def __init__(self, p=None):
if not p:
t = 't'
assert 't' == t or 'v' == t or 's' == t # no other case
p = OrderedDict(
[
('dataset', 'Foursquare.txt'),
# ('dataset', 'Gowalla.txt'),
('mode', 'test' if 't' == t else 'valid' if 'v' == t else 's'),
('load_epoch', 0),
('save_per_epoch', 100),
('split', -2 if 'v' == t else -1),
('at_nums', [5, 10, 15, 20]),
('epochs', 101),
('latent_size', 20),
('alpha', 0.01),
('lambda', 0.001),
('mini_batch', 0), # 0:one_by_one, 1:mini_batch. 全都用逐条。
('GeoIE', 1), # 1:(ijcai18)GeoIE
('batch_size_train', 1), #
('batch_size_test', 5),
])
for i in p.items():
print(i)
[(user_num, item_num), pois_cordis, (tra_buys, tes_buys), (tra_dist, tes_dist), tra_count] = \
load_data(os.path.join(PATH, p['dataset']), p['mode'], p['split'])
tra_buys_masks, tra_dist_masks, tra_masks, tra_count = fun_data_buys_masks(tra_buys, tra_dist, [item_num], [0], tra_count)
tes_buys_masks, tes_dist_masks, tes_masks = fun_data_buys_masks(tes_buys, tes_dist, [item_num], [0])
tra_buys_neg_masks = fun_random_neg_masks_tra(item_num, tra_buys_masks)
tes_buys_neg_masks = fun_random_neg_masks_tes(item_num, tra_buys_masks, tes_buys_masks)
tra_dist_pos_masks, tra_dist_neg_masks, tra_dist_masks = fun_compute_dist_neg(tra_buys_masks, tra_masks, tra_buys_neg_masks, pois_cordis)
usrs_last_poi_to_all_intervals = fun_compute_distance(tra_buys, tra_masks, pois_cordis, p['batch_size_test'])
self.p = p
self.user_num, self.item_num = user_num, item_num
self.pois_cordis = pois_cordis
self.tra_count = tra_count
self.tra_masks, self.tes_masks = tra_masks, tes_masks
self.tra_buys_masks, self.tes_buys_masks = tra_buys_masks, tes_buys_masks
self.tra_buys_neg_masks, self.tes_buys_neg_masks = tra_buys_neg_masks, tes_buys_neg_masks
self.tra_dist_pos_masks, self.tra_dist_neg_masks, self.tra_dist_masks = tra_dist_pos_masks, tra_dist_neg_masks, tra_dist_masks
self.ulptai = usrs_last_poi_to_all_intervals
def build_model_one_by_one(self, flag=0):
"""
建立模型对象
:param flag: 参数变量、数据
:return:
"""
print('Building the model one_by_one ...')
p = self.p
size = p['latent_size']
model = GeoIE(
train=[self.tra_buys_masks, self.tra_buys_neg_masks, self.tra_count, self.tra_masks],
test=[self.tes_buys_masks, self.tes_buys_neg_masks],
alpha_lambda=[p['alpha'], p['lambda']],
n_user=self.user_num,
n_item=self.item_num,
n_in=size,
n_hidden=size,
ulptai=self.ulptai)
model_name = model.__class__.__name__
print('\t the current Class name is: {val}'.format(val=model_name))
return model, model_name
def compute_start_end(self, flag):
"""
获取mini-batch的各个start_end(np.array类型,一组连续的数值)
:param flag: 'train', 'test'
:return: 各个start_end组成的list
"""
assert flag in ['train', 'test', 'test_auc']
if 'train' == flag:
size = self.p['batch_size_train']
elif 'test' == flag:
size = self.p['batch_size_test']
else:
size = self.p['batch_size_test'] * 10
user_num = self.user_num
rest = (user_num % size) > 0
n_batches = np.minimum(user_num // size + rest, user_num)
batch_idxs = np.arange(n_batches, dtype=np.int32)
starts_ends = []
for bidx in batch_idxs:
start = bidx * size
end = np.minimum(start + size, user_num)
start_end = np.arange(start, end, dtype=np.int32)
starts_ends.append(start_end)
return batch_idxs, starts_ends
def train_valid_or_test(pas):
"""
主程序
:return:
"""
p = pas.p
model, model_name = pas.build_model_one_by_one(flag=p['GeoIE'])
best = GlobalBest(at_nums=p['at_nums'])
_, starts_ends_tes = pas.compute_start_end(flag='test')
_, starts_ends_auc = pas.compute_start_end(flag='test_auc')
user_num, item_num = pas.user_num, pas.item_num
tra_masks, tes_masks = pas.tra_masks, pas.tes_masks
tra_buys_masks, tes_buys_masks = pas.tra_buys_masks, pas.tes_buys_masks
tra_dist_pos_masks, tra_dist_neg_masks, tra_dist_masks = pas.tra_dist_pos_masks, pas.tra_dist_neg_masks, pas.tra_dist_masks
pois_cordis = pas.pois_cordis
del pas
# 主循环
losses = []
times0, times1, times2, times3 = [], [], [], []
for epoch in np.arange(0, p['epochs']):
print("Epoch {val} ==================================".format(val=epoch))
if epoch > 0:
tra_buys_neg_masks = fun_random_neg_masks_tra(item_num, tra_buys_masks)
tra_dist_pos_masks, tra_dist_neg_masks, tra_dist_masks = fun_compute_dist_neg(tra_buys_masks, tra_masks,
tra_buys_neg_masks,
pois_cordis)
# ----------------------------------------------------------------------------------------------------------
print("\tTraining ...")
t0 = time.time()
loss = 0.
ls = [0, 0]
total_ls = []
random.seed(str(123 + epoch))
user_idxs_tra = np.arange(user_num, dtype=np.int32)
random.shuffle(user_idxs_tra)
for uidx in user_idxs_tra:
print(model.a.eval(), model.b.eval())
dist_pos = tra_dist_pos_masks[uidx]
dist_neg = tra_dist_neg_masks[uidx]
msk = tra_dist_masks[uidx]
tmp = model.train(uidx, dist_pos, dist_neg, msk)
loss += tmp
print(tmp)
rnn_l2_sqr = model.l2.eval()
def cut2(x):
return '%0.2f' % x
print('\t\tsum_loss = {val} = {v1} + {v2}'.format(val=loss + rnn_l2_sqr, v1=loss, v2=rnn_l2_sqr))
losses.append('{v1}'.format(v1=int(loss + rnn_l2_sqr)))
# ls = model.loss_weight
print('\t\tloss_weight = {v1}, {v2}'.format(v1=ls[0], v2=ls[1]))
t1 = time.time()
times0.append(t1 - t0)
# ----------------------------------------------------------------------------------------------------------
print("\tPredicting ...")
model.update_trained()
t2 = time.time()
times1.append(t2 - t1)
fun_predict_auc_recall_map_ndcg(
p, model, best, epoch, starts_ends_auc, starts_ends_tes, tes_buys_masks, tes_masks)
best.fun_print_best(epoch)
t3 = time.time()
times2.append(t3-t2)
print('\tavg. time (train, user, test): %0.0fs,' % np.average(times0),
'%0.0fs,' % np.average(times1), '%0.0fs' % np.average(times2),
'| alpha, lam: {v1}'.format(v1=', '.join([str(lam) for lam in [p['alpha'], p['lambda']]])),
'| model: {v1}'.format(v1=model_name))
# ----------------------------------------------------------------------------------------------------------
if epoch == p['epochs'] - 1:
print("\tBest and losses saving ...")
path = os.path.join(os.path.split(__file__)[0], '..', 'Results_best_and_losses', PATH.split('/')[-2])
fun_save_best_and_losses(path, model_name, epoch, p, best, losses)
if 2 == p['gru']:
size = p['latent_size']
fil_name = 'size' + str(size) + 'UD' + str(p['UD']) + 'dd' + str(p['dd']) + 'loss.txt'
fil = os.path.join(path, fil_name)
np.savetxt(fil, total_ls)
if 2 == p['gru'] and epoch % p['save_per_epoch'] == 0 and epoch != 0:
m_path = './model/' + p['dataset'] + '/' + model_name + '_size' + \
str(p['latent_size']) + '_UD' + str(p['UD']) + '_dd' + str(p['dd']) + '_epoch' + str(epoch)
with open(m_path, 'wb') as file:
save_model = [model.loss_weight.get_value(), model.wd.get_value(), model.lt.get_value(), model.di.get_value(),
model.ui.get_value(), model.wh.get_value(), model.bi.get_value(), model.vs.get_value(),
model.bs.get_value()]
cPickle.dump(save_model, file, protocol=cPickle.HIGHEST_PROTOCOL)
for i in p.items():
print(i)
print('\t the current Class name is: {val}'.format(val=model_name))
@exe_time
def main():
pas = Params()
train_valid_or_test(pas)
if '__main__' == __name__:
main()
|
python
|
import abc
import rospy
import numpy as np
import matplotlib.pyplot as plt
import math
class JointTrajectoryPlanner(object):
def __init__(self, time_i = 0.0, time_step = 0.1, time_f = None,
movement_duration = None):
self._time_step = time_step
self._time_i = time_i
self._time_f = time_f
self._movement_duration = movement_duration
if movement_duration is None and time_f is None:
raise AttributeError("Either final time or movement duration " +
"shall be passed in " +
"JointTrajectoryPlanner constructor")
elif movement_duration is None:
self.movement_duration = time_f - time_i
elif time_f is None:
self._time_f = time_i + movement_duration
breakpoint_qty = int(self._movement_duration / self._time_step + 1)
self._timespan = np.linspace(self._time_i, self._time_f, breakpoint_qty)
(self._position_profile, self._velocity_profile,
self._acceleration_profile) = self.generate_profiles()
def generate_profiles(self):
return (self.generate_position_profile(),
self.generate_velocity_profile(),
self.generate_acceleration_profile())
# @abc.abstractmethod
def generate_position_profile(self):
pass
# @abc.abstractmethod
def generate_velocity_profile(self):
pass
# @abc.abstractmethod
def generate_acceleration_profile(self):
pass
def __get_info_at(self, time, vector):
if time < self._time_i:
rospy.logwarn("Requested trajectory information before its " +
"beginning")
return time[0]
elif time > self._time_f:
rospy.logwarn("Requested trajectory information after its " +
"ending")
return time[-1]
else:
return np.interp(time, self._timespan, vector)
def get_position_at(self, time):
return self.__get_info_at(time, self._position_profile)
def get_velocity_at(self, time):
return self.__get_info_at(time, self._velocity_profile)
def get_acceleration_at(self, time):
return self.__get_info_at(time, self._acceleration_profile)
def plot_position_profile(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(self._timespan, self._position_profile)
ax.set_title('Position Trajectory')
ax.set_xlabel('Time / s')
ax.set_ylabel('Position / rad')
fig.tight_layout()
fig.show()
def plot_velocity_profile(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(self._timespan, self._velocity_profile)
ax.set_title('Velocity Trajectory')
ax.set_xlabel('Time / s')
ax.set_ylabel('Velocity / rad/s')
fig.tight_layout()
fig.show()
def plot_acceleration_profile(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(self._timespan, self._acceleration_profile)
ax.set_title('Acceleration Trajectory')
ax.set_xlabel('Time / s')
ax.set_ylabel('Acceleration / rad/s\u00b2')
fig.tight_layout()
fig.show()
def normalize_angle(angle):
if angle > math.pi:
return angle - 2 * math.pi
elif angle < - math.pi:
return angle + 2 * math.pi
else:
return angle
def calculate_displacement(pos_i, pos_f):
return normalize_angle(pos_f - pos_i)
|
python
|
from pymongo import MongoClient
import datetime
def collect_validated_input(prompt, error_msg, validator):
user_input = input(prompt)
validated = validator(user_input)
while not validated:
user_input = input(error_msg)
validated = validator(user_input)
return user_input
if __name__=="__main__":
client = MongoClient()
db = client.day_entries
# prompt for the day's rating
day_validation = lambda x: x.isdigit() and int(x) <= 7 and int(x) >= 1
day_prompt = "Enter the day's rating out of 7: "
day_error_msg = "Oops, enter an integer between 1 and 7: "
day_rating = int(collect_validated_input(day_prompt, day_error_msg, day_validation))
# good & bad & ugly
bad = ""
if day_rating < 4:
bad = input("I'm sorry it wasn't a good day! What went wrong? \n")
good = input("What was one good part about the day? \n")
ugly = input("What is one thing that you learned or threw you off today? \n")
db.entries.insert_one({
"rating": day_rating,
"timestamp": datetime.datetime.now(),
"good": good,
"bad": bad,
"learned": ugly,
})
|
python
|
import json
import unittest
# from mayday.utils import query_util, ticket_util
from mayday import helpers
from mayday.objects import Query, Ticket
USER_ID = 12345678
USERNAME = 'Mayday'
class Test(unittest.TestCase):
def test_init_ticket(self):
ticket = Ticket(user_id=USER_ID, username=USERNAME).to_dict()
helper = helpers.Helper('test')
result = helper.flatten(ticket)
expect = dict(
category='',
date='',
price='',
quantity='',
section='',
row='',
seat='',
status='待交易',
remarks='',
user_id=int(USER_ID),
username=str(USERNAME),
wish_date='',
wish_price='',
wish_quantity=''
)
self.assertDictEqual(result, expect)
def test_flatten_ticket_remark(self):
ticket = Ticket(user_id=USER_ID, username=USERNAME).to_dict()
helper = helpers.Helper('test')
ticket['remarks'] = '123456ABC'
result = helper.flatten(ticket)
expect = dict(
category='',
date='',
price='',
quantity='',
section='',
row='',
seat='',
status='待交易',
remarks='123456ABC',
user_id=int(USER_ID),
username=str(USERNAME),
wish_date='',
wish_price='',
wish_quantity=''
)
self.assertDictEqual(result, expect)
def test_init_query(self):
query = Query(user_id=USER_ID, username=USERNAME).to_dict()
helper = helpers.Helper('test')
result = helper.flatten(query)
expect = dict(
category='',
date='',
price='',
quantity='',
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
self.assertDictEqual(result, expect)
def test_flatten_query_category(self):
source = dict(
category=1,
date=[],
price=[],
quantity=[],
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
helper = helpers.Helper('test')
result = helper.flatten(source)
expect = dict(
category='原價轉讓',
date='',
price='',
quantity='',
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
self.assertEqual(json.dumps(result, ensure_ascii=False, sort_keys=True),
json.dumps(expect, ensure_ascii=False, sort_keys=True))
def test_flatten_query_date_1(self):
helper = helpers.Helper('test')
source = dict(
category=1,
date=[504],
price=[],
quantity=[],
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
result = helper.flatten(source)
expect = dict(
category='原價轉讓',
date='5.4(Fri)',
price='',
quantity='',
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
self.assertEqual(json.dumps(result, ensure_ascii=False, sort_keys=True),
json.dumps(expect, ensure_ascii=False, sort_keys=True))
def test_flatten_query_date_2(self):
helper = helpers.Helper('test')
source = dict(
category=1,
date=[504, 511],
price=[],
quantity=[],
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
result = helper.flatten(source)
expect = dict(
category='原價轉讓',
date='5.4(Fri), 5.11(Fri)',
price='',
quantity='',
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
self.assertEqual(json.dumps(result, ensure_ascii=False, sort_keys=True),
json.dumps(expect, ensure_ascii=False, sort_keys=True))
def test_flatten_query_date_3(self):
helper = helpers.Helper('test')
source = dict(
category=1,
date=[504, 511, 512],
price=[],
quantity=[],
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
result = helper.flatten(source)
expect = dict(
category='原價轉讓',
date='5.4(Fri), 5.11(Fri), 5.12(Sat)',
price='',
quantity='',
status='',
user_id=int(USER_ID),
username=str(USERNAME),
)
self.assertEqual(json.dumps(result, ensure_ascii=False, sort_keys=True),
json.dumps(expect, ensure_ascii=False, sort_keys=True))
def test_generate_tickets_traits_ls_trait_len(self):
helper = helpers.Helper('test')
tickets = [
dict(
category=2,
date=511,
id=20,
price=2,
quantity=2,
remarks=None,
row="",
section="",
status=1,
update_at="2018-03-28 11:47:16",
user_id=USER_ID,
username=USERNAME,
wish_date="511,512,513",
wish_price="4,2",
wish_quantity="1,2"
)
]
expect = [[{
'category': '換飛',
'date': '5.11(Fri)',
'id': 20,
'price': '$880座位',
'quantity': '2',
'row': '',
'section': '',
"remarks": '',
'status': '待交易',
'update_at': '2018-03-28 11:47:16',
'username': USERNAME,
"wish_date": "5.11(Fri), 5.12(Sat), 5.13(Sun)",
"wish_price": "$880座位, $680企位",
"wish_quantity": "1, 2"
}]]
result = helper.generate_tickets_traits(tickets)
self.assertEqual(expect, result)
def test_generate_tickets_traits_gt_trait_len(self):
helper = helpers.Helper('test')
tickets = []
ticket = {
"category": 2,
"date": 511,
"id": 20,
"price": 2,
"quantity": 2,
"remarks": None,
"row": "",
"section": "",
"status": 1,
"update_at": "2018-03-28 11:47:16",
"user_id": USER_ID,
"username": USERNAME,
"wish_date": "511,512,513",
"wish_price": "4,2",
"wish_quantity": "1,2"
}
for i in range(0, 6):
tickets.append(ticket)
expect_ticket = {
'category': '換飛',
'date': '5.11(Fri)',
'id': 20,
'price': '$880座位',
'quantity': '2',
'row': '',
'section': '',
"remarks": '',
'status': '待交易',
'update_at': '2018-03-28 11:47:16',
'username': USERNAME,
"wish_date": "5.11(Fri), 5.12(Sat), 5.13(Sun)",
"wish_price": "$880座位, $680企位",
"wish_quantity": "1, 2"
}
expect = [[expect_ticket, expect_ticket, expect_ticket, expect_ticket, expect_ticket], [expect_ticket]]
result = helper.generate_tickets_traits(tickets)
# self.assertCountEqual(expect, result)
self.assertEqual(expect, result)
def test_error_case(self):
ticket = {
"category": 2,
"date": 504,
"price": 4,
"quantity": 2,
"section": "F2",
"row": "p",
"seat": "",
"status": 1,
"remarks": "",
"wish_date": [506],
"wish_price": [3],
"wish_quantity": [],
"user_id": USER_ID,
"username": USERNAME
}
expected = {
'category': '換飛',
'date': '5.4(Fri)',
'price': '$680企位',
'quantity': '2',
'section': 'F2',
'row': 'p',
'seat': '',
'status': '待交易',
'remarks': '',
'wish_date': '5.6(Sun)',
'wish_price': '$680座位',
'wish_quantity': '',
'user_id': USER_ID,
'username': USERNAME
}
helper = helpers.Helper('test')
result = helper.flatten(ticket)
self.assertDictEqual(expected, result)
if __name__ == '__main__':
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
python
|
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name,missing-docstring,broad-except
# Copyright 2018 IBM RESEARCH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""Non-string identifiers for circuit and record identifiers test"""
import unittest
from qiskit import (ClassicalRegister, QISKitError, QuantumCircuit,
QuantumRegister, QuantumProgram)
from .common import QiskitTestCase
class TestAnonymousIds(QiskitTestCase):
"""Circuits and records can have no name"""
def setUp(self):
self.QPS_SPECS_NONAMES = {
"circuits": [{
"quantum_registers": [{
"size": 3}],
"classical_registers": [{
"size": 3}]
}]
}
###############################################################
# Tests to initiate an build a quantum program with anonymous ids
###############################################################
def test_create_program_with_specs_nonames(self):
"""Test Quantum Object Factory creation using Specs definition
object with no names for circuit nor records.
"""
result = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
self.assertIsInstance(result, QuantumProgram)
def test_create_anonymous_classical_register(self):
"""Test create_classical_register with no name.
"""
q_program = QuantumProgram()
cr = q_program.create_classical_register(size=3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_anonymous_quantum_register(self):
"""Test create_quantum_register with no name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(size=3)
self.assertIsInstance(qr, QuantumRegister)
def test_create_classical_registers_noname(self):
"""Test create_classical_registers with no name
"""
q_program = QuantumProgram()
classical_registers = [{"size": 4},
{"size": 2}]
crs = q_program.create_classical_registers(classical_registers)
for i in crs:
self.assertIsInstance(i, ClassicalRegister)
def test_create_quantum_registers_noname(self):
"""Test create_quantum_registers with no name.
"""
q_program = QuantumProgram()
quantum_registers = [{"size": 4},
{"size": 2}]
qrs = q_program.create_quantum_registers(quantum_registers)
for i in qrs:
self.assertIsInstance(i, QuantumRegister)
def test_create_circuit_noname(self):
"""Test create_circuit with no name
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(size=3)
cr = q_program.create_classical_register(size=3)
qc = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
self.assertIsInstance(qc, QuantumCircuit)
def test_create_several_circuits_noname(self):
"""Test create_circuit with several inputs and without names.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(size=3)
cr1 = q_program.create_classical_register(size=3)
qr2 = q_program.create_quantum_register(size=3)
cr2 = q_program.create_classical_register(size=3)
qc1 = q_program.create_circuit(qregisters=[qr1], cregisters=[cr1])
qc2 = q_program.create_circuit(qregisters=[qr2], cregisters=[cr2])
qc3 = q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2])
self.assertIsInstance(qc1, QuantumCircuit)
self.assertIsInstance(qc2, QuantumCircuit)
self.assertIsInstance(qc3, QuantumCircuit)
def test_get_register_and_circuit_names_nonames(self):
"""Get the names of the circuits and registers after create them without a name
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(size=3)
cr1 = q_program.create_classical_register(size=3)
qr2 = q_program.create_quantum_register(size=3)
cr2 = q_program.create_classical_register(size=3)
q_program.create_circuit(qregisters=[qr1], cregisters=[cr1])
q_program.create_circuit(qregisters=[qr2], cregisters=[cr2])
q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2])
qrn = q_program.get_quantum_register_names()
crn = q_program.get_classical_register_names()
qcn = q_program.get_circuit_names()
self.assertEqual(len(qrn), 2)
self.assertEqual(len(crn), 2)
self.assertEqual(len(qcn), 3)
def test_get_circuit_noname(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qc = q_program.get_circuit()
self.assertIsInstance(qc, QuantumCircuit)
def test_get_quantum_register_noname(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qr = q_program.get_quantum_register()
self.assertIsInstance(qr, QuantumRegister)
def test_get_classical_register_noname(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
cr = q_program.get_classical_register()
self.assertIsInstance(cr, ClassicalRegister)
def test_get_qasm_noname(self):
"""Test the get_qasm using an specification without names.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qc = q_program.get_circuit()
qrn = list(q_program.get_quantum_register_names())
self.assertEqual(len(qrn), 1)
qr = q_program.get_quantum_register(qrn[0])
crn = list(q_program.get_classical_register_names())
self.assertEqual(len(crn), 1)
cr = q_program.get_classical_register(crn[0])
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm()
self.assertEqual(len(result), len(qrn[0]) * 9 + len(crn[0]) * 4 + 147)
def test_get_qasms_noname(self):
"""Test the get_qasms from a qprogram without names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(size=3)
cr = q_program.create_classical_register(size=3)
qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[1], qr[2])
qc1.measure(qr[0], cr[0])
qc1.measure(qr[1], cr[1])
qc1.measure(qr[2], cr[2])
qc2.h(qr)
qc2.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc2.measure(qr[2], cr[2])
results = dict(zip(q_program.get_circuit_names(), q_program.get_qasms()))
qr_name_len = len(qr.openqasm_name)
cr_name_len = len(cr.openqasm_name)
self.assertEqual(len(results[qc1.name]), qr_name_len * 9 + cr_name_len * 4 + 147)
self.assertEqual(len(results[qc2.name]), qr_name_len * 7 + cr_name_len * 4 + 137)
def test_get_qasm_all_gates(self):
"""Test the get_qasm for more gates, using an specification without names.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qc = q_program.get_circuit()
qr = q_program.get_quantum_register()
cr = q_program.get_classical_register()
qc.u1(0.3, qr[0])
qc.u2(0.2, 0.1, qr[1])
qc.u3(0.3, 0.2, 0.1, qr[2])
qc.s(qr[1])
qc.s(qr[2]).inverse()
qc.cx(qr[1], qr[2])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.x(qr[2]).c_if(cr, 0)
qc.y(qr[2]).c_if(cr, 1)
qc.z(qr[2]).c_if(cr, 2)
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm()
self.assertEqual(len(result), (len(qr.openqasm_name) * 23 +
len(cr.openqasm_name) * 7 +
385))
###############################################################
# Test for compile
###############################################################
def test_compile_program_noname(self):
"""Test compile with a no name.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qc = q_program.get_circuit()
qr = q_program.get_quantum_register()
cr = q_program.get_classical_register()
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
out = q_program.compile()
self.log.info(out)
self.assertEqual(len(out), 3)
def test_get_execution_list_noname(self):
"""Test get_execution_list for circuits without name.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qc = q_program.get_circuit()
qr = q_program.get_quantum_register()
cr = q_program.get_classical_register()
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qobj = q_program.compile()
result = q_program.get_execution_list(qobj, print_func=self.log.info)
self.assertEqual(len(result), 1)
def test_change_circuit_qobj_after_compile_noname(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_NONAMES)
qr = q_program.get_quantum_register()
cr = q_program.get_classical_register()
qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc3 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc2.h(qr[0])
qc2.cx(qr[0], qr[1])
qc2.cx(qr[0], qr[2])
qc3.h(qr)
qc2.measure(qr, cr)
qc3.measure(qr, cr)
circuits = [qc2.name, qc3.name]
shots = 1024 # the number of shots in the experiment.
backend = 'local_qasm_simulator'
config = {'seed': 10, 'shots': 1, 'xvals': [1, 2, 3, 4]}
qobj1 = q_program.compile(circuits, backend=backend, shots=shots, seed=88, config=config)
qobj1['circuits'][0]['config']['shots'] = 50
qobj1['circuits'][0]['config']['xvals'] = [1, 1, 1]
config['shots'] = 1000
config['xvals'][0] = 'only for qobj2'
qobj2 = q_program.compile(circuits, backend=backend, shots=shots, seed=88, config=config)
self.assertTrue(qobj1['circuits'][0]['config']['shots'] == 50)
self.assertTrue(qobj1['circuits'][1]['config']['shots'] == 1)
self.assertTrue(qobj1['circuits'][0]['config']['xvals'] == [1, 1, 1])
self.assertTrue(qobj1['circuits'][1]['config']['xvals'] == [1, 2, 3, 4])
self.assertTrue(qobj1['config']['shots'] == 1024)
self.assertTrue(qobj2['circuits'][0]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][1]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][0]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
self.assertTrue(qobj2['circuits'][1]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
def test_add_circuit_noname(self):
"""Test add two circuits without names. Also tests get_counts without circuit name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(size=2)
cr = q_program.create_classical_register(size=2)
qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
new_circuit = qc1 + qc2
q_program.add_circuit(quantum_circuit=new_circuit)
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment.
result = q_program.execute(backend=backend, shots=shots, seed=78)
counts = result.get_counts(new_circuit.name)
target = {'00': shots / 2, '01': shots / 2}
threshold = 0.025 * shots
self.assertDictAlmostEqual(counts, target, threshold)
self.assertRaises(QISKitError, result.get_counts)
class TestZeroIds(QiskitTestCase):
"""Circuits and records can have zero as names"""
def setUp(self):
self.QPS_SPECS_ZEROS = {
"circuits": [{
"name": 0,
"quantum_registers": [{
"name": 0,
"size": 3}],
"classical_registers": [{
"name": "",
"size": 3}]
}]
}
###############################################################
# Tests to initiate an build a quantum program with zeros ids
###############################################################
def test_create_program_with_specs(self):
"""Test Quantum Object Factory creation using Specs definition
object with zeros names for circuit nor records.
"""
result = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
self.assertIsInstance(result, QuantumProgram)
def test_create_classical_register(self):
"""Test create_classical_register with zero name
"""
q_program = QuantumProgram()
cr = q_program.create_classical_register(0, 3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_quantum_register(self):
"""Test create_quantum_register with zero name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(0, 3)
self.assertIsInstance(qr, QuantumRegister)
def test_fail_create_classical_register_name(self):
"""Test duplicated create_quantum_register with zeros as names.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register(0, 3)
self.assertIsInstance(cr1, ClassicalRegister)
self.assertRaises(QISKitError,
q_program.create_classical_register, 0, 2)
def test_create_quantum_register_same(self):
"""Test create_quantum_register of same name (a zero) and size.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(0, 3)
qr2 = q_program.create_quantum_register(0, 3)
self.assertIs(qr1, qr2)
def test_create_classical_register_same(self):
"""Test create_classical_register of same name (a zero) and size.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register(0, 3)
cr2 = q_program.create_classical_register(0, 3)
self.assertIs(cr1, cr2)
def test_create_classical_registers(self):
"""Test create_classical_registers with 0 as a name.
"""
q_program = QuantumProgram()
classical_registers = [{"name": 0, "size": 4},
{"name": "", "size": 2}]
crs = q_program.create_classical_registers(classical_registers)
for i in crs:
self.assertIsInstance(i, ClassicalRegister)
def test_create_quantum_registers(self):
"""Test create_quantum_registers with 0 as names
"""
q_program = QuantumProgram()
quantum_registers = [{"name": 0, "size": 4},
{"name": "", "size": 2}]
qrs = q_program.create_quantum_registers(quantum_registers)
for i in qrs:
self.assertIsInstance(i, QuantumRegister)
def test_destroy_classical_register(self):
"""Test destroy_classical_register with 0 as name."""
q_program = QuantumProgram()
_ = q_program.create_classical_register(0, 3)
self.assertIn(0, q_program.get_classical_register_names())
q_program.destroy_classical_register(0)
self.assertNotIn(0, q_program.get_classical_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_classical_register(0)
self.assertIn('Not present', str(context.exception))
def test_destroy_quantum_register(self):
"""Test destroy_quantum_register with 0 as name."""
q_program = QuantumProgram()
_ = q_program.create_quantum_register(0, 3)
self.assertIn(0, q_program.get_quantum_register_names())
q_program.destroy_quantum_register(0)
self.assertNotIn(0, q_program.get_quantum_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_quantum_register(0)
self.assertIn('Not present', str(context.exception))
def test_create_circuit(self):
"""Test create_circuit with 0 as a name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(0, 3)
cr = q_program.create_classical_register("", 3)
qc = q_program.create_circuit(0, [qr], [cr])
self.assertIsInstance(qc, QuantumCircuit)
def test_create_several_circuits(self):
"""Test create_circuit with several inputs with int names.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(10, 3)
cr1 = q_program.create_classical_register(20, 3)
qr2 = q_program.create_quantum_register(11, 3)
cr2 = q_program.create_classical_register(21, 3)
qc1 = q_program.create_circuit(30, [qr1], [cr1])
qc2 = q_program.create_circuit(31, [qr2], [cr2])
qc3 = q_program.create_circuit(32, [qr1, qr2], [cr1, cr2])
self.assertIsInstance(qc1, QuantumCircuit)
self.assertIsInstance(qc2, QuantumCircuit)
self.assertIsInstance(qc3, QuantumCircuit)
def test_destroy_circuit(self):
"""Test destroy_circuit with an int name."""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(2, 3)
cr = q_program.create_classical_register(1, 3)
_ = q_program.create_circuit(10, [qr], [cr])
self.assertIn(10, q_program.get_circuit_names())
q_program.destroy_circuit(10)
self.assertNotIn(10, q_program.get_circuit_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_circuit(10)
self.assertIn('Not present', str(context.exception))
def test_get_register_and_circuit_names(self):
"""Get the names of the circuits and registers when their names are ints.
"""
qr1n = 10
qr2n = 11
cr1n = 12
cr2n = 13
qc1n = 14
qc2n = 15
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(qr1n, 3)
cr1 = q_program.create_classical_register(cr1n, 3)
qr2 = q_program.create_quantum_register(qr2n, 3)
cr2 = q_program.create_classical_register(cr2n, 3)
q_program.create_circuit(qc1n, [qr1], [cr1])
q_program.create_circuit(qc2n, [qr2], [cr2])
q_program.create_circuit(qc2n, [qr1, qr2], [cr1, cr2])
qrn = q_program.get_quantum_register_names()
crn = q_program.get_classical_register_names()
qcn = q_program.get_circuit_names()
self.assertCountEqual(qrn, [qr1n, qr2n])
self.assertCountEqual(crn, [cr1n, cr2n])
self.assertCountEqual(qcn, [qc1n, qc2n])
def test_get_qasm(self):
"""Test the get_qasm with int name. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
qc = q_program.get_circuit(0)
qr = q_program.get_quantum_register(0)
cr = q_program.get_classical_register("")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm(0)
self.assertEqual(len(result), (147 +
len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4))
def test_get_qasms(self):
"""Test the get_qasms with int names. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(10, 3)
cr = q_program.create_classical_register(20, 3)
qc1 = q_program.create_circuit(101, [qr], [cr])
qc2 = q_program.create_circuit(102, [qr], [cr])
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[1], qr[2])
qc1.measure(qr[0], cr[0])
qc1.measure(qr[1], cr[1])
qc1.measure(qr[2], cr[2])
qc2.h(qr)
qc2.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc2.measure(qr[2], cr[2])
result = q_program.get_qasms([101, 102])
self.assertEqual(len(result[0]), (147 +
len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4))
self.assertEqual(len(result[1]), (137 +
len(qr.openqasm_name) * 7 +
len(cr.openqasm_name) * 4))
def test_get_qasm_all_gates(self):
"""Test the get_qasm for more gates. Names are ints.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
qc = q_program.get_circuit(0)
qr = q_program.get_quantum_register(0)
cr = q_program.get_classical_register("")
qc.u1(0.3, qr[0])
qc.u2(0.2, 0.1, qr[1])
qc.u3(0.3, 0.2, 0.1, qr[2])
qc.s(qr[1])
qc.s(qr[2]).inverse()
qc.cx(qr[1], qr[2])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.x(qr[2]).c_if(cr, 0)
qc.y(qr[2]).c_if(cr, 1)
qc.z(qr[2]).c_if(cr, 2)
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm(0)
self.assertEqual(len(result), (385 +
len(qr.openqasm_name) * 23 +
len(cr.openqasm_name) * 7))
###############################################################
# Test for compile when names are integers
###############################################################
def test_compile_program(self):
"""Test compile_program. Names are integers
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
qc = q_program.get_circuit(0)
qr = q_program.get_quantum_register(0)
cr = q_program.get_classical_register("")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
out = q_program.compile([0], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
self.log.info(out)
self.assertEqual(len(out), 3)
def test_get_execution_list(self):
"""Test get_execution_list with int names.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
qc = q_program.get_circuit(0)
qr = q_program.get_quantum_register(0)
cr = q_program.get_classical_register("")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
qobj = q_program.compile([0], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
result = q_program.get_execution_list(qobj, print_func=self.log.info)
self.log.info(result)
self.assertEqual(result, [0])
def test_change_circuit_qobj_after_compile(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_ZEROS)
qr = q_program.get_quantum_register(0)
cr = q_program.get_classical_register("")
qc2 = q_program.create_circuit(102, [qr], [cr])
qc3 = q_program.create_circuit(103, [qr], [cr])
qc2.h(qr[0])
qc2.cx(qr[0], qr[1])
qc2.cx(qr[0], qr[2])
qc3.h(qr)
qc2.measure(qr, cr)
qc3.measure(qr, cr)
circuits = [102, 103]
shots = 1024 # the number of shots in the experiment.
backend = 'local_qasm_simulator'
config = {'seed': 10, 'shots': 1, 'xvals': [1, 2, 3, 4]}
qobj1 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
qobj1['circuits'][0]['config']['shots'] = 50
qobj1['circuits'][0]['config']['xvals'] = [1, 1, 1]
config['shots'] = 1000
config['xvals'][0] = 'only for qobj2'
qobj2 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
self.assertTrue(qobj1['circuits'][0]['config']['shots'] == 50)
self.assertTrue(qobj1['circuits'][1]['config']['shots'] == 1)
self.assertTrue(qobj1['circuits'][0]['config']['xvals'] == [1, 1, 1])
self.assertTrue(qobj1['circuits'][1]['config']['xvals'] == [1, 2, 3, 4])
self.assertTrue(qobj1['config']['shots'] == 1024)
self.assertTrue(qobj2['circuits'][0]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][1]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][0]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
self.assertTrue(qobj2['circuits'][1]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
def test_add_circuit(self):
"""Test add two circuits with zero names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(0, 2)
cr = q_program.create_classical_register("", 2)
qc1 = q_program.create_circuit(0, [qr], [cr])
qc2 = q_program.create_circuit("", [qr], [cr])
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
new_circuit = qc1 + qc2
q_program.add_circuit(1001, new_circuit)
circuits = [1001]
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment.
result = q_program.execute(circuits, backend=backend, shots=shots, seed=78)
counts = result.get_counts(1001)
target = {'00': shots / 2, '01': shots / 2}
threshold = 0.025 * shots
self.assertDictAlmostEqual(counts, target, threshold)
class TestIntegerIds(QiskitTestCase):
"""Circuits and records can have integers as names"""
def setUp(self):
self.QPS_SPECS_INT = {
"circuits": [{
"name": 1,
"quantum_registers": [{
"name": 40,
"size": 3}],
"classical_registers": [{
"name": 50,
"size": 3}]
}]
}
###############################################################
# Tests to initiate an build a quantum program with integer ids
###############################################################
def test_create_program_with_specs(self):
"""Test Quantum Object Factory creation using Specs definition
object with int names for circuit nor records.
"""
result = QuantumProgram(specs=self.QPS_SPECS_INT)
self.assertIsInstance(result, QuantumProgram)
def test_create_classical_register(self):
"""Test create_classical_register with int name
"""
q_program = QuantumProgram()
cr = q_program.create_classical_register(42, 3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_quantum_register(self):
"""Test create_quantum_register with int name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(32, 3)
self.assertIsInstance(qr, QuantumRegister)
def test_fail_create_classical_register_name(self):
"""Test duplicated create_quantum_register with int as names.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register(2, 3)
self.assertIsInstance(cr1, ClassicalRegister)
self.assertRaises(QISKitError,
q_program.create_classical_register, 2, 2)
def test_create_quantum_register_same(self):
"""Test create_quantum_register of same int name and size.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(1, 3)
qr2 = q_program.create_quantum_register(1, 3)
self.assertIs(qr1, qr2)
def test_create_classical_register_same(self):
"""Test create_classical_register of same int name and size.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register(2, 3)
cr2 = q_program.create_classical_register(2, 3)
self.assertIs(cr1, cr2)
def test_create_classical_registers(self):
"""Test create_classical_registers with int name.
"""
q_program = QuantumProgram()
classical_registers = [{"name": 1, "size": 4},
{"name": 2, "size": 2}]
crs = q_program.create_classical_registers(classical_registers)
for i in crs:
self.assertIsInstance(i, ClassicalRegister)
def test_create_quantum_registers(self):
"""Test create_quantum_registers with int names
"""
q_program = QuantumProgram()
quantum_registers = [{"name": 1, "size": 4},
{"name": 2, "size": 2}]
qrs = q_program.create_quantum_registers(quantum_registers)
for i in qrs:
self.assertIsInstance(i, QuantumRegister)
def test_destroy_classical_register(self):
"""Test destroy_classical_register with int name."""
q_program = QuantumProgram()
_ = q_program.create_classical_register(1, 3)
self.assertIn(1, q_program.get_classical_register_names())
q_program.destroy_classical_register(1)
self.assertNotIn(1, q_program.get_classical_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_classical_register(1)
self.assertIn('Not present', str(context.exception))
def test_destroy_quantum_register(self):
"""Test destroy_quantum_register with int name."""
q_program = QuantumProgram()
_ = q_program.create_quantum_register(1, 3)
self.assertIn(1, q_program.get_quantum_register_names())
q_program.destroy_quantum_register(1)
self.assertNotIn(1, q_program.get_quantum_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_quantum_register(1)
self.assertIn('Not present', str(context.exception))
def test_create_circuit(self):
"""Test create_circuit with int names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(1, 3)
cr = q_program.create_classical_register(2, 3)
qc = q_program.create_circuit(3, [qr], [cr])
self.assertIsInstance(qc, QuantumCircuit)
def test_create_several_circuits(self):
"""Test create_circuit with several inputs with int names.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(10, 3)
cr1 = q_program.create_classical_register(20, 3)
qr2 = q_program.create_quantum_register(11, 3)
cr2 = q_program.create_classical_register(21, 3)
qc1 = q_program.create_circuit(30, [qr1], [cr1])
qc2 = q_program.create_circuit(31, [qr2], [cr2])
qc3 = q_program.create_circuit(32, [qr1, qr2], [cr1, cr2])
self.assertIsInstance(qc1, QuantumCircuit)
self.assertIsInstance(qc2, QuantumCircuit)
self.assertIsInstance(qc3, QuantumCircuit)
def test_destroy_circuit(self):
"""Test destroy_circuit with an int name."""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(2, 3)
cr = q_program.create_classical_register(1, 3)
_ = q_program.create_circuit(10, [qr], [cr])
self.assertIn(10, q_program.get_circuit_names())
q_program.destroy_circuit(10)
self.assertNotIn(10, q_program.get_circuit_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_circuit(10)
self.assertIn('Not present', str(context.exception))
def test_get_register_and_circuit_names(self):
"""Get the names of the circuits and registers when their names are ints.
"""
qr1n = 10
qr2n = 11
cr1n = 12
cr2n = 13
qc1n = 14
qc2n = 15
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(qr1n, 3)
cr1 = q_program.create_classical_register(cr1n, 3)
qr2 = q_program.create_quantum_register(qr2n, 3)
cr2 = q_program.create_classical_register(cr2n, 3)
q_program.create_circuit(qc1n, [qr1], [cr1])
q_program.create_circuit(qc2n, [qr2], [cr2])
q_program.create_circuit(qc2n, [qr1, qr2], [cr1, cr2])
qrn = q_program.get_quantum_register_names()
crn = q_program.get_classical_register_names()
qcn = q_program.get_circuit_names()
self.assertCountEqual(qrn, [qr1n, qr2n])
self.assertCountEqual(crn, [cr1n, cr2n])
self.assertCountEqual(qcn, [qc1n, qc2n])
def test_get_qasm(self):
"""Test the get_qasm with int name. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_INT)
qc = q_program.get_circuit(1)
qr = q_program.get_quantum_register(40)
cr = q_program.get_classical_register(50)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm(1)
self.assertEqual(len(result), (147 +
len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4))
def test_get_qasms(self):
"""Test the get_qasms with int names. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(10, 3)
cr = q_program.create_classical_register(20, 3)
qc1 = q_program.create_circuit(101, [qr], [cr])
qc2 = q_program.create_circuit(102, [qr], [cr])
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[1], qr[2])
qc1.measure(qr[0], cr[0])
qc1.measure(qr[1], cr[1])
qc1.measure(qr[2], cr[2])
qc2.h(qr)
qc2.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc2.measure(qr[2], cr[2])
result = q_program.get_qasms([101, 102])
self.assertEqual(len(result[0]), (147 +
len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4))
self.assertEqual(len(result[1]), (137 +
len(qr.openqasm_name) * 7 +
len(cr.openqasm_name) * 4))
def test_get_qasm_all_gates(self):
"""Test the get_qasm for more gates. Names are ints.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_INT)
qc = q_program.get_circuit(1)
qr = q_program.get_quantum_register(40)
cr = q_program.get_classical_register(50)
qc.u1(0.3, qr[0])
qc.u2(0.2, 0.1, qr[1])
qc.u3(0.3, 0.2, 0.1, qr[2])
qc.s(qr[1])
qc.s(qr[2]).inverse()
qc.cx(qr[1], qr[2])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.x(qr[2]).c_if(cr, 0)
qc.y(qr[2]).c_if(cr, 1)
qc.z(qr[2]).c_if(cr, 2)
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm(1)
self.assertEqual(len(result), (385 +
len(qr.openqasm_name) * 23 +
len(cr.openqasm_name) * 7))
###############################################################
# Test for compile when names are integers
###############################################################
def test_compile_program(self):
"""Test compile_program. Names are integers
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_INT)
qc = q_program.get_circuit(1)
qr = q_program.get_quantum_register(40)
cr = q_program.get_classical_register(50)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
out = q_program.compile([1], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
self.log.info(out)
self.assertEqual(len(out), 3)
def test_get_execution_list(self):
"""Test get_execution_list with int names.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_INT)
qc = q_program.get_circuit(1)
qr = q_program.get_quantum_register(40)
cr = q_program.get_classical_register(50)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
qobj = q_program.compile([1], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
result = q_program.get_execution_list(qobj, print_func=self.log.info)
self.log.info(result)
self.assertEqual(result, [1])
def test_change_circuit_qobj_after_compile(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_INT)
qr = q_program.get_quantum_register(40)
cr = q_program.get_classical_register(50)
qc2 = q_program.create_circuit(102, [qr], [cr])
qc3 = q_program.create_circuit(103, [qr], [cr])
qc2.h(qr[0])
qc2.cx(qr[0], qr[1])
qc2.cx(qr[0], qr[2])
qc3.h(qr)
qc2.measure(qr, cr)
qc3.measure(qr, cr)
circuits = [102, 103]
shots = 1024 # the number of shots in the experiment.
backend = 'local_qasm_simulator'
config = {'seed': 10, 'shots': 1, 'xvals': [1, 2, 3, 4]}
qobj1 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
qobj1['circuits'][0]['config']['shots'] = 50
qobj1['circuits'][0]['config']['xvals'] = [1, 1, 1]
config['shots'] = 1000
config['xvals'][0] = 'only for qobj2'
qobj2 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
self.assertTrue(qobj1['circuits'][0]['config']['shots'] == 50)
self.assertTrue(qobj1['circuits'][1]['config']['shots'] == 1)
self.assertTrue(qobj1['circuits'][0]['config']['xvals'] == [1, 1, 1])
self.assertTrue(qobj1['circuits'][1]['config']['xvals'] == [1, 2, 3, 4])
self.assertTrue(qobj1['config']['shots'] == 1024)
self.assertTrue(qobj2['circuits'][0]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][1]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][0]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
self.assertTrue(qobj2['circuits'][1]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
def test_add_circuit(self):
"""Test add two circuits with int names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(1, 2)
cr = q_program.create_classical_register(2, 2)
qc1 = q_program.create_circuit(10, [qr], [cr])
qc2 = q_program.create_circuit(20, [qr], [cr])
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
new_circuit = qc1 + qc2
q_program.add_circuit(1001, new_circuit)
# new_circuit.measure(qr[0], cr[0])
circuits = [1001]
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment.
result = q_program.execute(circuits, backend=backend, shots=shots,
seed=78)
counts = result.get_counts(1001)
target = {'00': shots / 2, '01': shots / 2}
threshold = 0.025 * shots
self.assertDictAlmostEqual(counts, target, threshold)
class TestTupleIds(QiskitTestCase):
"""Circuits and records can have tuples as names"""
def setUp(self):
self.QPS_SPECS_TUPLE = {
"circuits": [{
"name": (1.1, 1j),
"quantum_registers": [{
"name": (40.1, 40j),
"size": 3}],
"classical_registers": [{
"name": (50.1, 50j),
"size": 3}]
}]
}
###############################################################
# Tests to initiate an build a quantum program with tuple ids
###############################################################
def test_create_program_with_specs(self):
"""Test Quantum Object Factory creation using Specs definition
object with tuple names for circuit nor records.
"""
result = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
self.assertIsInstance(result, QuantumProgram)
def test_create_classical_register(self):
"""Test create_classical_register with tuple name
"""
q_program = QuantumProgram()
cr = q_program.create_classical_register((50.1, 50j), 3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_quantum_register(self):
"""Test create_quantum_register with tuple name.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register((32.1, 32j), 3)
self.assertIsInstance(qr, QuantumRegister)
def test_fail_create_classical_register_name(self):
"""Test duplicated create_quantum_register with int as names.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register((2.1, 2j), 3)
self.assertIsInstance(cr1, ClassicalRegister)
self.assertRaises(QISKitError,
q_program.create_classical_register, (2.1, 2j), 2)
def test_create_quantum_register_same(self):
"""Test create_quantum_register of same tuple name and size.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register((1.1, 1j), 3)
qr2 = q_program.create_quantum_register((1.1, 1j), 3)
self.assertIs(qr1, qr2)
def test_create_classical_register_same(self):
"""Test create_classical_register of same tuple name and size.
"""
q_program = QuantumProgram()
cr1 = q_program.create_classical_register((2.1, 2j), 3)
cr2 = q_program.create_classical_register((2.1, 2j), 3)
self.assertIs(cr1, cr2)
def test_create_classical_registers(self):
"""Test create_classical_registers with tuple name.
"""
q_program = QuantumProgram()
classical_registers = [{"name": (1.1, 1j), "size": 4},
{"name": (2.1, 2j), "size": 2}]
crs = q_program.create_classical_registers(classical_registers)
for i in crs:
self.assertIsInstance(i, ClassicalRegister)
def test_create_quantum_registers(self):
"""Test create_quantum_registers with tuple names
"""
q_program = QuantumProgram()
quantum_registers = [{"name": (1.1, 1j), "size": 4},
{"name": (2.1, 2j), "size": 2}]
qrs = q_program.create_quantum_registers(quantum_registers)
for i in qrs:
self.assertIsInstance(i, QuantumRegister)
def test_destroy_classical_register(self):
"""Test destroy_classical_register with tuple name."""
q_program = QuantumProgram()
_ = q_program.create_classical_register((1.1, 1j), 3)
self.assertIn((1.1, 1j), q_program.get_classical_register_names())
q_program.destroy_classical_register((1.1, 1j))
self.assertNotIn((1.1, 1j), q_program.get_classical_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_classical_register((1.1, 1j))
self.assertIn('Not present', str(context.exception))
def test_destroy_quantum_register(self):
"""Test destroy_quantum_register with tuple name."""
q_program = QuantumProgram()
_ = q_program.create_quantum_register((1.1, 1j), 3)
self.assertIn((1.1, 1j), q_program.get_quantum_register_names())
q_program.destroy_quantum_register((1.1, 1j))
self.assertNotIn((1.1, 1j), q_program.get_quantum_register_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_quantum_register((1.1, 1j))
self.assertIn('Not present', str(context.exception))
def test_create_circuit(self):
"""Test create_circuit with tuple names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register((1.1, 1j), 3)
cr = q_program.create_classical_register((2.1, 2j), 3)
qc = q_program.create_circuit((3.1, 3j), [qr], [cr])
self.assertIsInstance(qc, QuantumCircuit)
def test_create_several_circuits(self):
"""Test create_circuit with several inputs with tuple names.
"""
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register((10.1, 10j), 3)
cr1 = q_program.create_classical_register((20.1, 20j), 3)
qr2 = q_program.create_quantum_register((11.1, 11j), 3)
cr2 = q_program.create_classical_register((21.1, 21j), 3)
qc1 = q_program.create_circuit((30.1, 30j), [qr1], [cr1])
qc2 = q_program.create_circuit((31.1, 31j), [qr2], [cr2])
qc3 = q_program.create_circuit((32.1, 32j), [qr1, qr2], [cr1, cr2])
self.assertIsInstance(qc1, QuantumCircuit)
self.assertIsInstance(qc2, QuantumCircuit)
self.assertIsInstance(qc3, QuantumCircuit)
def test_destroy_circuit(self):
"""Test destroy_circuit with an tuple name."""
q_program = QuantumProgram()
qr = q_program.create_quantum_register((2.1, 2j), 3)
cr = q_program.create_classical_register((1.1, 1j), 3)
_ = q_program.create_circuit((10.1, 10j), [qr], [cr])
self.assertIn((10.1, 10j), q_program.get_circuit_names())
q_program.destroy_circuit((10.1, 10j))
self.assertNotIn((10.1, 10j), q_program.get_circuit_names())
# Destroying an invalid register should fail.
with self.assertRaises(QISKitError) as context:
q_program.destroy_circuit((10.1, 10j))
self.assertIn('Not present', str(context.exception))
def test_get_register_and_circuit_names(self):
"""Get the names of the circuits and registers when their names are ints.
"""
qr1n = (10.1, 10j)
qr2n = (11.1, 11j)
cr1n = (12.1, 12j)
cr2n = (13.1, 13j)
qc1n = (14.1, 14j)
qc2n = (15.1, 15j)
q_program = QuantumProgram()
qr1 = q_program.create_quantum_register(qr1n, 3)
cr1 = q_program.create_classical_register(cr1n, 3)
qr2 = q_program.create_quantum_register(qr2n, 3)
cr2 = q_program.create_classical_register(cr2n, 3)
q_program.create_circuit(qc1n, [qr1], [cr1])
q_program.create_circuit(qc2n, [qr2], [cr2])
q_program.create_circuit(qc2n, [qr1, qr2], [cr1, cr2])
qrn = q_program.get_quantum_register_names()
crn = q_program.get_classical_register_names()
qcn = q_program.get_circuit_names()
self.assertCountEqual(qrn, [qr1n, qr2n])
self.assertCountEqual(crn, [cr1n, cr2n])
self.assertCountEqual(qcn, [qc1n, qc2n])
def test_get_qasm(self):
"""Test the get_qasm with tuple name. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
qc = q_program.get_circuit((1.1, 1j))
qr = q_program.get_quantum_register((40.1, 40j))
cr = q_program.get_classical_register((50.1, 50j))
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm((1.1, 1j))
self.assertEqual(len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4 + 147, len(result))
def test_get_qasms(self):
"""Test the get_qasms with tuple names. They need to be coverted to OpenQASM format.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register((10.1, 10j), 3)
cr = q_program.create_classical_register((20.1, 20j), 3)
qc1 = q_program.create_circuit((101.1, 101j), [qr], [cr])
qc2 = q_program.create_circuit((102.1, 102j), [qr], [cr])
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[1], qr[2])
qc1.measure(qr[0], cr[0])
qc1.measure(qr[1], cr[1])
qc1.measure(qr[2], cr[2])
qc2.h(qr)
qc2.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc2.measure(qr[2], cr[2])
result = q_program.get_qasms([(101.1, 101j), (102.1, 102j)])
self.assertEqual(len(qr.openqasm_name) * 9 +
len(cr.openqasm_name) * 4 + 147, len(result[0]))
self.assertEqual(len(qr.openqasm_name) * 7 +
len(cr.openqasm_name) * 4 + 137, len(result[1]))
def test_get_qasm_all_gates(self):
"""Test the get_qasm for more gates. Names are tuples.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
qc = q_program.get_circuit((1.1, 1j))
qr = q_program.get_quantum_register((40.1, 40j))
cr = q_program.get_classical_register((50.1, 50j))
qc.u1(0.3, qr[0])
qc.u2(0.2, 0.1, qr[1])
qc.u3(0.3, 0.2, 0.1, qr[2])
qc.s(qr[1])
qc.s(qr[2]).inverse()
qc.cx(qr[1], qr[2])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.x(qr[2]).c_if(cr, 0)
qc.y(qr[2]).c_if(cr, 1)
qc.z(qr[2]).c_if(cr, 2)
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
result = q_program.get_qasm((1.1, 1j))
self.assertEqual(len(qr.openqasm_name) * 23 +
len(cr.openqasm_name) * 7 + 385, len(result))
###############################################################
# Test for compile when names are tuples
###############################################################
def test_compile_program(self):
"""Test compile_program. Names are tuples
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
qc = q_program.get_circuit((1.1, 1j))
qr = q_program.get_quantum_register((40.1, 40j))
cr = q_program.get_classical_register((50.1, 50j))
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
out = q_program.compile([(1.1, 1j)], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
self.log.info(out)
self.assertEqual(len(out), 3)
def test_get_execution_list(self):
"""Test get_execution_list with tuple names.
"""
q_program = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
qc = q_program.get_circuit((1.1, 1j))
qr = q_program.get_quantum_register((40.1, 40j))
cr = q_program.get_classical_register((50.1, 50j))
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
backend = 'local_qasm_simulator'
coupling_map = None
qobj = q_program.compile([(1.1, 1j)], backend=backend,
coupling_map=coupling_map, qobj_id='cooljob')
result = q_program.get_execution_list(qobj, print_func=self.log.info)
self.log.info(result)
self.assertCountEqual(result, [(1.1, 1j)])
def test_change_circuit_qobj_after_compile(self):
q_program = QuantumProgram(specs=self.QPS_SPECS_TUPLE)
qr = q_program.get_quantum_register((40.1, 40j))
cr = q_program.get_classical_register((50.1, 50j))
qc2 = q_program.create_circuit((102.1, 102j), [qr], [cr])
qc3 = q_program.create_circuit((103.1, 103j), [qr], [cr])
qc2.h(qr[0])
qc2.cx(qr[0], qr[1])
qc2.cx(qr[0], qr[2])
qc3.h(qr)
qc2.measure(qr, cr)
qc3.measure(qr, cr)
circuits = [(102.1, 102j), (103.1, 103j)]
shots = 1024 # the number of shots in the experiment.
backend = 'local_qasm_simulator'
config = {'seed': 10, 'shots': 1, 'xvals': [1, 2, 3, 4]}
qobj1 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
qobj1['circuits'][0]['config']['shots'] = 50
qobj1['circuits'][0]['config']['xvals'] = [1, 1, 1]
config['shots'] = 1000
config['xvals'][0] = 'only for qobj2'
qobj2 = q_program.compile(circuits, backend=backend, shots=shots,
seed=88, config=config)
self.assertTrue(qobj1['circuits'][0]['config']['shots'] == 50)
self.assertTrue(qobj1['circuits'][1]['config']['shots'] == 1)
self.assertTrue(qobj1['circuits'][0]['config']['xvals'] == [1, 1, 1])
self.assertTrue(qobj1['circuits'][1]['config']['xvals'] == [1, 2, 3, 4])
self.assertTrue(qobj1['config']['shots'] == 1024)
self.assertTrue(qobj2['circuits'][0]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][1]['config']['shots'] == 1000)
self.assertTrue(qobj2['circuits'][0]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
self.assertTrue(qobj2['circuits'][1]['config']['xvals'] == [
'only for qobj2', 2, 3, 4])
def test_add_circuit(self):
"""Test add two circuits with tuple names.
"""
q_program = QuantumProgram()
qr = q_program.create_quantum_register(1, 2)
cr = q_program.create_classical_register(2, 2)
qc1 = q_program.create_circuit((10.1, 10j), [qr], [cr])
qc2 = q_program.create_circuit((20.1, 20j), [qr], [cr])
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
new_circuit = qc1 + qc2
q_program.add_circuit((1001.1, 1001j), new_circuit)
circuits = [(1001.1, 1001j)]
backend = 'local_qasm_simulator' # the backend to run on
shots = 1024 # the number of shots in the experiment.
result = q_program.execute(circuits, backend=backend, shots=shots,
seed=78)
counts = result.get_counts((1001.1, 1001j))
target = {'00': shots / 2, '01': shots / 2}
threshold = 0.025 * shots
self.assertDictAlmostEqual(counts, target, threshold)
class TestAnonymousIdsNoQuantumProgram(QiskitTestCase):
"""Test the anonymous use of registers.
TODO: this needs to be expanded, ending up with the rest of the tests
in the file not using QuantumProgram when it is deprecated.
"""
def test_create_anonymous_classical_register(self):
"""Test creating a ClassicalRegister with no name.
"""
cr = ClassicalRegister(size=3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_anonymous_quantum_register(self):
"""Test creating a QuantumRegister with no name.
"""
qr = QuantumRegister(size=3)
self.assertIsInstance(qr, QuantumRegister)
def test_create_anonymous_classical_registers(self):
"""Test creating several ClassicalRegister with no name.
"""
cr1 = ClassicalRegister(size=3)
cr2 = ClassicalRegister(size=3)
self.assertNotEqual(cr1.name, cr2.name)
def test_create_anonymous_quantum_registers(self):
"""Test creating several QuantumRegister with no name.
"""
qr1 = QuantumRegister(size=3)
qr2 = QuantumRegister(size=3)
self.assertNotEqual(qr1.name, qr2.name)
def test_create_anonymous_mixed_registers(self):
"""Test creating several Registers with no name.
"""
cr0 = ClassicalRegister(size=3)
qr0 = QuantumRegister(size=3)
# Get the current index counte of the registers
cr_index = int(cr0.name[1:])
qr_index = int(qr0.name[1:])
cr1 = ClassicalRegister(size=3)
_ = QuantumRegister(size=3)
qr2 = QuantumRegister(size=3)
# Check that the counters for each kind are incremented separately.
cr_current = int(cr1.name[1:])
qr_current = int(qr2.name[1:])
self.assertEqual(cr_current, cr_index + 1)
self.assertEqual(qr_current, qr_index + 2)
def test_create_circuit_noname(self):
"""Test create_circuit with no name
"""
q_program = QuantumProgram()
qr = QuantumRegister(size=3)
cr = ClassicalRegister(size=3)
qc = q_program.create_circuit(qregisters=[qr], cregisters=[cr])
self.assertIsInstance(qc, QuantumCircuit)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
python
|
from setuptools import setup, find_packages
import byte_api
setup(
name='byte-api',
version=byte_api.__version__,
author=byte_api.__author__,
url='https://github.com/byte-api/byte-python',
download_url='https://github.com/byte-api/byte-python/archive/v{}.zip'.format(
byte_api.__version__
),
description='Byte API Wrapper',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8'
],
license='MIT',
packages=find_packages(),
install_requires=['requests']
)
|
python
|
'''Provides access to a subset of the NAM-NMM dataset.
The North American Mesoscale Forecast System (NAM) is one of the
major weather models run by the National Centers for Environmental
Prediction (NCEP) for producing weather forecasts. Dozens of weather
parameters are available from the NAM grids, from temperature and
precipitation to lightning and turbulent kinetic energy.
As of June 20, 2006, the NAM model has been running with a non-
hydrostatic version of the Weather Research and Forecasting (WRF)
model at its core. This version of the NAM is also known as the NAM
Non-hydrostatic Mesoscale Model (NAM-NMM).
The dataset lives remotely. A live feed is provided by NCEP and an 11
month archive is provided by NCDC (both are divisions of NOAA). This
module caches the data locally, allowing us to build a larger archive.
The remote dataset is provided in GRIB format, while this module uses
the netCDF format for its local storage.
This module provides access to only a subset of the NAM-NMM dataset.
The geographic region is reduced and centered around Georgia, and only
as subset of the variables are provided.
Queries return an instance of :class:`xarray.Dataset` where each variable
has exactly five dimensions: reftime, forecast, z, y, and x. The z-axis
for each variable has a different name depending on the type of index
measuring the axis, e.g. ``z_ISBL`` for isobaric pressure levels.
'''
import builtins
import contextlib
import logging
from functools import reduce
from pathlib import Path
from time import sleep
from tempfile import TemporaryDirectory
import cartopy.crs as ccrs
import numpy as np
import pandas as pd
import requests
import xarray as xr
import apollo
# Module level logger
logger = logging.getLogger(__name__)
# URLs of remote grib files.
# PROD_URL typically has the most recent 7 days.
# ARCHIVE_URL typically has the most recent 11 months, about 1 week behind.
PROD_URL = 'http://nomads.ncep.noaa.gov/pub/data/nccf/com/nam/prod/nam.{ref.year:04d}{ref.month:02d}{ref.day:02d}/nam.t{ref.hour:02d}z.awphys{forecast:02d}.tm00.grib2'
ARCHIVE_URL = 'https://nomads.ncdc.noaa.gov/data/meso-eta-hi/{ref.year:04d}{ref.month:02d}/{ref.year:04d}{ref.month:02d}{ref.day:02d}/nam_218_{ref.year:04d}{ref.month:02d}{ref.day:02d}_{ref.hour:02d}00_{forecast:03d}.grb2'
# The full forecast period of the NAM-NMM dataset: 0h to 36h by 1h and 36h to 84h by 3h
# The forecast period we work with: 0h to 36h by 1h
FULL_FORECAST_PERIOD = tuple(range(36)) + tuple(range(36, 85, 3))
FORECAST_PERIOD = FULL_FORECAST_PERIOD[:37]
#: A Lambert conformal map projection of NAM grid 218.
#:
#: NOAA numbers the differnt maps used by their their products. The specific
#: map used by NAM forecasts is number 218.
#:
#: This is a Lambert conformal conic projection over a spherical globe covering
#: the contiguous United States.
#:
#: .. seealso::
#: `Master List of NCEP Storage Grids <http://www.nco.ncep.noaa.gov/pmb/docs/on388/tableb.html#GRID218>`_
NAM218 = ccrs.LambertConformal(
central_latitude=25,
central_longitude=265,
standard_parallels=(25, 25),
# The default cartopy globe is WGS 84, but
# NAM assumes a spherical globe with radius 6,371.229 km
globe=ccrs.Globe(ellipse=None, semimajor_axis=6371229, semiminor_axis=6371229),
)
#: The latitude and longitude of a solar array in Athens, GA.
#:
#: In practice, this gets rounded to the nearest coordinate in the NAM dataset.
#: That location is ``(33.93593, -83.32683)`` and is near the intersection of
#: Gains School and Lexington.
#:
#: .. note::
#: This is was taken from Google Maps as the lat/lon of the State
#: Botanical Garden of Georgia.
ATHENS_LATLON = (33.9052058, -83.382608)
#: The planar features of the NAM dataset.
#:
#: These are the features which have only a trivial Z-axis. These include
#: features at the surface (SFC), top of atmosphere (TOA), and entire
#: atmosphere as a single layer (EATM).
PLANAR_FEATURES = (
'PRES_SFC',
'HGT_SFC',
'HGT_TOA',
'TMP_SFC',
'VIS_SFC',
'UGRD_TOA',
'VGRD_TOA',
'DSWRF_SFC',
'DLWRF_SFC',
'TCC_EATM',
)
def proj_coords(lats, lons):
'''Transform geographic coordinates into the NAM218 projection.
This function converts latitude-longitude pairs into x-y pairs, where x and
y are measured in meters relative to the NAM218 projection described by
:data:`NAM218`.
NAM218 is the name of the projection used by NAM. It is a Lambert Conformal
projection covering the contiguous United States.
The latitude and longitude arguments may be given as floats or arrays, but
must have the same shape. The returned values have the same shape as the
inputs.
Arguments:
lats (float or numpy.ndarray):
The latitudes.
lons (float or numpy.ndarray):
The longitudes.
Returns:
pair of arrays:
A pair of arrays ``(x, y)`` that give the x and y coordinates
respectivly, measured in meters.
'''
lats = np.asarray(lats)
lons = np.asarray(lons)
unproj = ccrs.PlateCarree()
coords = NAM218.transform_points(unproj, lons.flatten(), lats.flatten())
x, y = coords[...,0], coords[...,1]
x = x.reshape(lats.shape)
y = y.reshape(lats.shape)
return x, y
def slice_geo(data, center, shape):
'''Slice a dataset along geographic coordinates.
Arguments:
data (xarray.Dataset):
The dataset to slice. It should have coordinates ``x`` and ``y``
measured in meters relative to the NAM218 projection.
center (pair of float):
The center of the slice, as a latitude-longited pair.
shape (float or pair of float):
The height and width of the geographic area, measured in meters. If
a scalar, both height and width are the same size.
Returns:
Dataset:
The sliced dataset.
'''
# Convert the center from lat-lon to x-y.
lat, lon = center
x, y = proj_coords(lat, lon)
# Round x and y to the nearest index.
center_data = data.sel(x=x, y=y, method='nearest')
x = center_data.x.values
y = center_data.y.values
# Compute the slice bounds from the shape.
# The distance between grid cells (axes x and y) may not be exactly 12km.
# We add 1.5km to the deltas to ensure we select the full area.
if np.isscalar(shape): shape = (shape, shape)
x_shape, y_shape = shape
x_delta = x_shape / 2 + 1500
y_delta = y_shape / 2 + 1500
x_slice = slice(x - x_delta, x + x_delta)
y_slice = slice(y - y_delta, y + y_delta)
# Perform the selection.
return data.sel(x=x_slice, y=y_slice)
class CacheMiss(Exception):
'''A requested forecast does not exist in the local store.
'''
pass
def grib_url(reftime, forecast):
'''The URL to a GRIB for the given reference and forecast times.
This method resolves the URL from one of two sources. The production
NAM forecasts are hosted by the National Centers for Environmental
Prediction (NCEP, <https://www.ncep.noaa.gov/>). After seven days, the
forecasts are moved to an eleven month archive hosted by the National
Climatic Data Center (NCDC, <https://www.ncdc.noaa.gov/>). Older
forecasts will resolve to the NCDC URL, but they are unlikely to exist.
Arguments:
reftime (timestamp):
The reference time.
forecast (int):
The forecast hour.
Returns:
str:
A URL to a GRIB file.
'''
reftime = apollo.Timestamp(reftime).floor('6h')
now = apollo.Timestamp('now').floor('6h')
delta = now - reftime
if pd.Timedelta(7, 'd') < delta:
url_fmt = ARCHIVE_URL
else:
url_fmt = PROD_URL
return url_fmt.format(ref=reftime, forecast=forecast)
def grib_path(reftime, forecast):
'''The path to a GRIB for the given reference and forecast times.
GRIB forecasts are downloaded to this path and may be deleted once the
forecast is processed into netCDF. This file does not necessarily exist.
Arguments:
reftime (timestamp):
The reference time.
forecast (int):
The forecast hour.
Returns:
pathlib.Path:
The local path for a GRIB file, which may not exist.
'''
reftime = apollo.Timestamp(reftime).floor('6h')
prefix_fmt = 'nam.{ref.year:04d}{ref.month:02d}{ref.day:02d}'
filename_fmt = 'nam.t{ref.hour:02d}z.awphys{forecast:02d}.tm00.grib'
prefix = prefix_fmt.format(forecast=forecast, ref=reftime)
filename = filename_fmt.format(forecast=forecast, ref=reftime)
return apollo.path(f'NAM-NMM/{prefix}/{filename}')
def nc_path(reftime):
'''The path to a netCDF for the given reference time.
NetCDF files are generated after forecasts are processed from the raw
GRIB data. This file does not necessarily exist.
Arguments:
reftime (timestamp):
The reference time.
Returns:
pathlib.Path:
The local path to a netCDF file, which may not exist.
'''
reftime = reftime = apollo.Timestamp(reftime).floor('6h')
prefix = f'nam.{reftime.year:04d}{reftime.month:02d}{reftime.day:02d}'
filename = f'nam.t{reftime.hour:02d}z.awphys.tm00.nc'
return apollo.path(f'NAM-NMM/{prefix}/{filename}')
def _download_grib(reftime, forecast, max_tries=8, timeout=10, fail_fast=False):
'''Ensure that the GRIB for this reftime and forecast exists locally.
Arguments:
reftime (timestamp):
The reference time to download.
forecast (int):
The forecast hour to download
max_tries (int):
The maximum number of failed downloads for a single file
before raising an `IOError`. Exponential backoff is applied
between attempts, starting at 1 second.
timeout (int):
The network timeout in seconds. The government servers are often
slow to respond.
fail_fast (bool):
If true, the download errors are treated as fatal.
This overrides the `max_tries` argument.
Returns:
xarray.Dataset:
The downloaded dataset.
'''
if fail_fast:
max_tries = 1
url = grib_url(reftime, forecast)
path = grib_path(reftime, forecast)
path.parent.mkdir(exist_ok=True)
for i in range(max_tries):
if path.exists():
break
try:
# Perform a streaming download because the files are big.
logger.info(f'downloading {url}')
with path.open('wb') as fd:
r = requests.get(url, timeout=timeout, stream=True)
r.raise_for_status()
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
break
except IOError as err:
# IOError includes both system and HTTP errors.
# Retry with exponential backoff.
logger.warning(err)
path.unlink()
if i + 1 == max_tries:
logger.error(f'download of {path.name} failed, giving up')
raise err
else:
delay = 2**i
logger.warning(f'download of {path.name} failed, retrying in {delay}s')
sleep(delay)
continue
except (Exception, SystemExit, KeyboardInterrupt) as err:
# Partial files should be deleted
# SystemExit and KeyboardInterrupt must be caught explicitly.
path.unlink()
raise err
logger.info(f'reading {path}')
return xr.open_dataset(path, engine='pynio')
def _process_grib(ds, reftime, forecast):
'''Process a forecast loaded from GRIB.
GRIB files contain a forecast for a specific forecast hour at a specific
reftime, including all NAM data variables for the entire NAM 218 grid.
This method trims the dataset to the subset of variables and geographic
region that we are interested in, normalizes variable names and shapes
to a more consistent format, and adds additional metadata.
Arguments:
ds (xarray.Dataset):
The dataset to process.
reftime (timestamp):
The reference time associated with the dataset.
forecast (int):
The forecast hour associated with the dataset.
Returns:
xarray.Dataset:
A processed dataset.
'''
features = {
# Data variables
'DLWRF_P0_L1_GLC0': 'DLWRF_SFC', 'DSWRF_P0_L1_GLC0': 'DSWRF_SFC',
'PRES_P0_L1_GLC0': 'PRES_SFC',
'PRES_P0_L6_GLC0': 'PRES_MWSL', 'PRES_P0_L7_GLC0': 'PRES_TRO',
'TCDC_P0_L200_GLC0': 'TCC_EATM', 'TMP_P0_2L108_GLC0': 'TMP_SPDY',
'TMP_P0_L1_GLC0': 'TMP_SFC', 'TMP_P0_L100_GLC0': 'TMP_ISBL',
'TMP_P0_L103_GLC0': 'TMP_HTGL', 'TMP_P0_L7_GLC0': 'TMP_TRO',
'RH_P0_2L104_GLC0': 'RH_SIGY', 'RH_P0_2L108_GLC0': 'RH_SPDY',
'RH_P0_L100_GLC0': 'RH_ISBL',
'RH_P0_L4_GLC0': 'RH_0DEG', 'UGRD_P0_2L108_GLC0': 'UGRD_SPDY',
'UGRD_P0_L100_GLC0': 'UGRD_ISBL', 'UGRD_P0_L103_GLC0': 'UGRD_HTGL',
'UGRD_P0_L220_GLC0': 'UGRD_TOA', 'UGRD_P0_L6_GLC0': 'UGRD_MWSL',
'UGRD_P0_L7_GLC0': 'UGRD_TRO', 'VGRD_P0_2L108_GLC0': 'VGRD_SPDY',
'VGRD_P0_L100_GLC0': 'VGRD_ISBL', 'VGRD_P0_L103_GLC0': 'VGRD_HTGL',
'VGRD_P0_L220_GLC0': 'VGRD_TOA', 'VGRD_P0_L6_GLC0': 'VGRD_MWSL',
'VGRD_P0_L7_GLC0': 'VGRD_TRO', 'VIS_P0_L1_GLC0': 'VIS_SFC',
'LHTFL_P0_L1_GLC0': 'LHTFL_SFC', 'SHTFL_P0_L1_GLC0': 'SHTFL_SFC',
'REFC_P0_L200_GLC0': 'REFC_EATM', 'REFD_P0_L103_GLC0': 'REFD_HTGL',
'REFD_P0_L105_GLC0': 'REFD_HYBL', 'VVEL_P0_L100_GLC0': 'VVEL_ISBL',
'HGT_P0_L1_GLC0': 'HGT_SFC', 'HGT_P0_L100_GLC0': 'HGT_ISBL',
'HGT_P0_L2_GLC0': 'HGT_CBL', 'HGT_P0_L220_GLC0': 'HGT_TOA',
'HGT_P0_L245_GLC0': 'HGT_LLTW', 'HGT_P0_L4_GLC0': 'HGT_0DEG',
'PWAT_P0_L200_GLC0': 'PWAT_EATM', 'TKE_P0_L100_GLC0': 'TKE_ISBL',
# Coordinate variables
'lv_HTGL1': 'z_HTGL1', 'lv_HTGL3': 'z_HTGL2',
'lv_HTGL6': 'z_HTGL3', 'lv_ISBL0': 'z_ISBL',
'lv_SPDL2': 'z_SPDY',
'xgrid_0': 'x', 'ygrid_0': 'y',
'gridlat_0': 'lat', 'gridlon_0': 'lon',
}
unwanted = [k for k in ds.variables.keys() if k not in features]
ds = ds.drop(unwanted)
ds = ds.rename(features)
# Subset the geographic region to a square area centered around Macon, GA.
ds = ds.isel(y=slice(63, 223, None), x=slice(355, 515, None))
# Free memory from unused features and areas.
ds = ds.copy(deep=True)
# Compute the coordinates for x and y
x, y = proj_coords(ds.lat.data, ds.lon.data)
x, y = x[0,:], y[:,0]
ds = ds.assign_coords(x=x, y=y)
# Add a z dimension to variables that don't have one.
for v in ds.data_vars:
if ds[v].dims == ('y', 'x'):
layer = ds[v].name.split('_')[1]
ds[v] = ds[v].expand_dims(f'z_{layer}')
# Create reftime and forecast dimensions.
# Both are stored as integers with appropriate units.
# The reftime dimension is hours since the Unix epoch (1970-01-01 00:00).
# The forecast dimension is hours since the reftime.
reftime = apollo.Timestamp(reftime).floor('6h')
epoch = apollo.Timestamp('1970-01-01 00:00')
delta_seconds = int((reftime - epoch).total_seconds())
delta_hours = delta_seconds // 60 // 60
ds = ds.assign_coords(
reftime=delta_hours,
forecast=forecast,
)
for v in ds.data_vars:
ds[v] = ds[v].expand_dims(('reftime', 'forecast'))
# Fix the z_SPDY coordinate.
# The layer is defined in term of bounds above and below.
# The dataset expresses this as three coordinates: the index, lower bound, and upper bound.
# We kept the index and now replace the values to be the upper bound, in Pascals
ds['z_SPDY'] = ds['z_SPDY'].assign_attrs(
comment='The values give the upper bound of the layer, the lower bound is 3000 Pa less',
)
ds['z_SPDY'].data = np.array([3000, 6000, 9000, 12000, 15000, 18000])
# Set metadata according to CF conventions
# http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html
metadata = {
# Data Variables
# TODO: The wind directions may be backwards, should be confirmed with NCEP.
'DLWRF_SFC': {'standard_name':'downwelling_longwave_flux', 'units':'W/m^2'},
'DSWRF_SFC': {'standard_name':'downwelling_shortwave_flux', 'units':'W/m^2'},
'HGT_0DEG': {'standard_name':'geopotential_height', 'units':'gpm'},
'HGT_CBL': {'standard_name':'geopotential_height', 'units':'gpm'},
'HGT_ISBL': {'standard_name':'geopotential_height', 'units':'gpm'},
'HGT_LLTW': {'standard_name':'geopotential_height', 'units':'gpm'},
'HGT_TOA': {'standard_name':'geopotential_height', 'units':'gpm'},
'HGT_SFC': {'standard_name':'geopotential_height', 'units':'gpm'},
'PRES_MWSL': {'standard_name':'air_pressure', 'units':'Pa'},
'PRES_SFC': {'standard_name':'air_pressure', 'units':'Pa'},
'PRES_TRO': {'standard_name':'air_pressure', 'units':'Pa'},
'PWAT_EATM': {'standard_name':'atmosphere_water_vapor_content', 'units':'kg/m^2'},
'REFC_EATM': {'standard_name':'equivalent_reflectivity_factor', 'units':'dBZ'},
'REFD_HTGL': {'standard_name':'equivalent_reflectivity_factor', 'units':'dBZ'},
'REFD_HYBL': {'standard_name':'equivalent_reflectivity_factor', 'units':'dBZ'},
'RH_0DEG': {'standard_name':'relative_humidity', 'units':'%'},
'RH_ISBL': {'standard_name':'relative_humidity', 'units':'%'},
'RH_SIGY': {'standard_name':'relative_humidity', 'units':'%'},
'RH_SPDY': {'standard_name':'relative_humidity', 'units':'%'},
'LHTFL_SFC': {'standard_name':'upward_latent_heat_flux', 'units':'W/m2'},
'SHTFL_SFC': {'standard_name':'upward_sensible_heat_flux', 'units':'W/m2'},
'TCC_EATM': {'standard_name':'cloud_area_fraction', 'units':'%'},
'TKE_ISBL': {'standard_name':'atmosphere_kinetic_energy_content', 'units':'J/kg'},
'TMP_HTGL': {'standard_name':'air_temperature', 'units':'K'},
'TMP_ISBL': {'standard_name':'air_temperature', 'units':'K'},
'TMP_SFC': {'standard_name':'air_temperature', 'units':'K'},
'TMP_SPDY': {'standard_name':'air_temperature', 'units':'K'},
'TMP_TRO': {'standard_name':'air_temperature', 'units':'K'},
'UGRD_HTGL': {'standard_name':'eastward_wind', 'units':'m/s'},
'UGRD_ISBL': {'standard_name':'eastward_wind', 'units':'m/s'},
'UGRD_MWSL': {'standard_name':'eastward_wind', 'units':'m/s'},
'UGRD_TOA': {'standard_name':'eastward_wind', 'units':'m/s'},
'UGRD_SPDY': {'standard_name':'eastward_wind', 'units':'m/s'},
'UGRD_TRO': {'standard_name':'eastward_wind', 'units':'m/s'},
'VGRD_HTGL': {'standard_name':'northward_wind', 'units':'m/s'},
'VGRD_ISBL': {'standard_name':'northward_wind', 'units':'m/s'},
'VGRD_MWSL': {'standard_name':'northward_wind', 'units':'m/s'},
'VGRD_TOA': {'standard_name':'northward_wind', 'units':'m/s'},
'VGRD_SPDY': {'standard_name':'northward_wind', 'units':'m/s'},
'VGRD_TRO': {'standard_name':'northward_wind', 'units':'m/s'},
'VIS_SFC': {'standard_name':'visibility', 'units':'m'},
'VVEL_ISBL': {'standard_name':'vertical_air_velocity_expressed_as_tendency_of_pressure',
'units':'Pa/s'},
# Coordinates
# I couldn't find standard names for all of the layers...
# I'm not sure if both forecast and reftime should be marked as axis T...
'x': {'axis':'X', 'standard_name':'projection_x_coordinate', 'units':'m'},
'y': {'axis':'Y', 'standard_name':'projection_y_coordinate', 'units':'m'},
'z_CBL': {'axis':'Z', 'standard_name':'cloud_base'},
'z_HYBL': {'axis':'Z', 'standard_name':'atmosphere_hybrid_sigma_pressure_coordinate'},
'z_TOA': {'axis':'Z', 'standard_name':'toa'},
'z_SFC': {'axis':'Z', 'standard_name':'surface'},
'z_SIGY': {'axis':'Z', 'standard_name':'atmosphere_sigma_coordinate'},
'z_TRO': {'axis':'Z', 'standard_name':'tropopause'},
'z_SPDY': {'axis':'Z', 'long_name':'specified pressure difference', 'units':'Pa'},
'z_HTGL1': {'axis':'Z', 'long_name':'fixed_height_above_ground', 'units':'m'},
'z_HTGL2': {'axis':'Z', 'long_name':'fixed_height_above_ground', 'units':'m'},
'z_HTGL3': {'axis':'Z', 'long_name':'fixed_height_above_ground', 'units':'m'},
'z_ISBL': {'axis':'Z', 'long_name':'isobaric_level', 'units':'Pa'},
'z_0DEG': {'axis':'Z', 'long_name':'0_degree_C_isotherm'},
'z_EATM': {'axis':'Z', 'long_name':'entire_atmosphere'},
'z_LLTW': {'axis':'Z', 'long_name':'lowest_level_of_the_wet_bulb_zero'},
'z_MWSL': {'axis':'Z', 'long_name':'max_wind_surface_layer'},
'forecast': {'axis':'T', 'standard_name':'forecast_period', 'units':'hours'},
'reftime': {'axis':'T', 'standard_name':'forecast_reference_time', 'units':'hours since 1970-01-01T00:00'},
'lat': {'standard_name':'latitude', 'units':'degree_north'},
'lon': {'standard_name':'longitude', 'units':'degree_east'},
}
for v in metadata:
ds[v] = ds[v].assign_attrs(metadata[v])
now = apollo.Timestamp('now')
ds.attrs['title'] = 'NAM-UGA, a subset of NAM-NMM for solar forecasting research in Georgia'
ds.attrs['history'] = f'{now.isoformat()} Initial conversion from GRIB files released by NCEP\n'
ds = xr.decode_cf(ds)
return ds
def _open_dataset(paths):
'''Open one or more netCDF files as a single dataset.
This is a wrapper around :func:`xarray.open_mfdataset` providing defaults
relevant to Apollo's filesystem layout.
Arguments:
paths (str or pathlib.Path or list):
One or more paths to the datasets.
Returns:
xarray.Dataset:
The combined dataset.
'''
if isinstance(paths, (str, Path)):
paths = [paths]
# Xarray and libnetcdf sometimes send trash to stdout or stderr.
# We completly silence both streams temporarily.
with builtins.open('/dev/null', 'w') as dev_null:
with contextlib.redirect_stdout(dev_null):
with contextlib.redirect_stderr(dev_null):
return xr.open_mfdataset(paths, combine='by_coords')
def download(reftime='now', save_nc=True, keep_gribs=False, force=False, **kwargs):
'''Download a forecast.
The download is skipped for GRIB files in the cache.
Arguments:
reftime (timestamp):
The reference time to open.
save_nc (bool or None):
Whether to save the processed forecast in the cache as a netCDF.
keep_gribs (bool or None):
Whether to save the raw forecast in the cache as a set of GRIBs.
force (bool):
If true, download even if the dataset already exists locally.
max_tries (int):
The maximum number of failed downloads for a single file
before raising an `IOError`. Exponential backoff is applied
between attempts, starting at 1 second.
timeout (int):
The network timeout in seconds. The government servers are often
slow to respond.
fail_fast (bool):
If true, the download errors are treated as fatal.
This overrides the `max_tries` argument.
Returns:
xarray.Dataset:
A dataset for the forecast at this reftime.
'''
# No need to download if we already have the dataset.
if not force and nc_path(reftime).exists():
logger.info(f'skipping downlod, file exists: {nc_path(reftime)}')
return open(reftime, on_miss='raise')
# We save each GRIB as a netCDF in a temp directory, then reopen all
# as a single dataset, which we finally persist in the datastore.
# It is important to persist the intermediate datasets for performance
# and memory usage.
with TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
paths = []
for forecast in FORECAST_PERIOD:
path = tmpdir / f'{forecast}.nc'
ds = _download_grib(reftime, forecast)
ds = _process_grib(ds, reftime, forecast)
ds.to_netcdf(path)
paths.append(path)
ds = _open_dataset(paths)
if save_nc:
path = nc_path(reftime)
logger.info(f'writing {path}')
ds.to_netcdf(path)
ds = _open_dataset([path])
if not keep_gribs:
for forecast in FORECAST_PERIOD:
path = grib_path(reftime, forecast)
logger.info(f'deleting {path}')
path.unlink()
return ds
def open(reftimes='now', on_miss='raise', **kwargs):
'''Open a forecast for one or more reference times.
Arguments:
reftimes (timestamp or sequence):
The reference time(s) to open. The default is to load the most
recent forecast.
on_miss ('raise' or 'download' or 'skip'):
Determines the behavior on a cache miss:
- ``'raise'``: Raise a :class:`CacheMiss` exception.
- ``'download'``: Attempt to download the missing forecast.
- ``'skip'``: Skip missing forecasts. This mode will raise a
:class:`CacheMiss` exception only if the resulting dataset
would be empty.
**kwargs:
Additional keyword arguments are forwarded to :func:`download`.
Returns:
xarray.Dataset:
A single dataset containing all forecasts at the given reference
times.
'''
if not on_miss in ('raise', 'download', 'skip'):
raise ValueError(f"Unknown cache miss strategy: {repr(on_miss)}")
try:
reftimes = [
apollo.Timestamp(reftimes).floor('6h')
]
except TypeError:
reftimes = [
apollo.Timestamp(r).floor('6h')
for r in reftimes
]
paths = []
for reftime in reftimes:
path = nc_path(reftime)
if path.exists():
paths.append(path)
elif on_miss == 'download':
download(reftime)
paths.append(path)
elif on_miss == 'skip':
continue
else:
raise CacheMiss(f'Missing forecast for reftime {reftime}')
if len(paths) == 0:
raise CacheMiss('No applicable forecasts were found')
ds = _open_dataset(paths)
# Reconstruct `time` dimension by combining `reftime` and `forecast`.
# - `reftime` is the time the forecast was made.
# - `forecast` is the offset of the data relative to the reftime.
# - `time` is the time being forecasted.
time = ds.reftime + ds.forecast
ds = ds.assign_coords(time=time)
return ds
def open_range(start, stop='now', on_miss='skip', **kwargs):
'''Open a forecast for a range of reference times.
Arguments:
start (timestamp):
The first time in the range.
stop (timestamp):
The last time in the range.
on_miss (str):
Determines the behavior on a cache miss:
- ``'raise'``: Raise a :class:`CacheMiss` exception.
- ``'download'``: Attempt to download the forecast.
- ``'skip'``: Skip missing forecasts.
**kwargs:
Additional keyword arguments are forwarded to :func:`download`.
Returns:
xarray.Dataset:
A single dataset containing all forecasts at the given reference
times.
'''
start = apollo.Timestamp(start).floor('6h')
stop = apollo.Timestamp(stop).floor('6h')
reftimes = pd.date_range(start, stop, freq='6h')
return open(reftimes, on_miss=on_miss, **kwargs)
def iter_available_forecasts():
'''Iterate over the reftimes of available forecasts.
Yields:
pandas.Timestamp:
The forecast's reference time, with UTC timezone.
'''
for day_dir in sorted(apollo.path('NAM-NMM').glob('nam.*')):
name = day_dir.name # Formatted like "nam.20180528".
year = int(name[4:8])
month = int(name[8:10])
day = int(name[10:12])
for path in sorted(day_dir.glob('nam.*')):
name = path.name # Formatted like "nam.t18z.awphys.tm00.nc".
if not name.endswith('.nc'): continue
hour = int(name[5:7])
yield apollo.Timestamp(f'{year:04}-{month:02}-{day:02}T{hour:02}Z')
def times_to_reftimes(times):
'''Compute the reference times for forecasts containing the given times.
On the edge case, this may select one extra forecast per time.
Arguments:
times (numpy.ndarray like):
A series of forecast times.
Returns:
apollo.DatetimeIndex:
The set of reftimes for forecasts containing the given times.
'''
reftimes = apollo.DatetimeIndex(times, name='reftime').unique()
a = reftimes.floor('6h').unique()
b = a - pd.Timedelta('6h')
c = a - pd.Timedelta('12h')
d = a - pd.Timedelta('18h')
e = a - pd.Timedelta('24h')
f = a - pd.Timedelta('30h')
g = a - pd.Timedelta('36h')
return a.union(b).union(c).union(d).union(e).union(f).union(g)
|
python
|
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.conf import settings
from operator import itemgetter
from datetime import datetime, timedelta
import json
import urllib2
import re
# Get API user and token from settings
user = settings.REITTIOPAS_USER
token = settings.REITTIOPAS_TOKEN
stops = settings.REITTIOPAS_STOPS
def index(request):
all_departures = []
for stop in stops:
try:
response = urllib2.urlopen("http://api.reittiopas.fi/hsl/prod/?user=%s&pass=%s&request=stop&code=%s"%(user,token,stop))
except:
return HttpResponse("Unable to access reittiopas API.", status=500)
try:
stop_departures = json.load(response)[0]
except ValueError as e:
return HttpResponse("Error parsing json from reittiopas", status=500)
# Parse line destinations from codes
lines_dict = {}
for item in stop_departures['lines']:
parts = item.split(':')
lines_dict[parts[0]] = parts[1]
# Parse departures
departures = []
for departure in stop_departures['departures']:
# Convert code to actual line number
departure['line'] = re.sub(r'^\d0*(\d?\w*) .*', r'\1',departure['code'])
departure['stop'] = stop_departures['name_fi']
# Add destination name to departure item
departure['dest'] = lines_dict[departure['code']]
# Create datetime object to sort departures by
if departure['time'] >= 2400:
departure['time'] = departure['time']-2400
dt = datetime.strptime('%d%d'%(departure['date'], departure['time']), "%Y%m%d%H%M")
departure['datetime'] = dt + timedelta(days=1)
else:
departure['datetime'] = datetime.strptime('%d%d'%(departure['date'], departure['time']), "%Y%m%d%H%M")
departures.append(departure)
all_departures = all_departures + departures
sorted_departures = sorted(all_departures, key=itemgetter('datetime'))[:10]
return render_to_response('reittiopas/index.html', {"departures": sorted_departures}, context_instance=RequestContext(request))
|
python
|
# ここから表面データの処理
import numpy as np
# import matplotlib.pyplot as plt
import pandas as pd
# import os
# import itertools
# from scipy import signal
# import time
class Analysis_surface():
def __init__(self,k0) -> None:
self.sampling_num_surface = int(1023) # 表面粗さや2DFFTを計算したりする点数
if k0 == 1:
self.resolution = 5.85829e-3 # 表面の測定間隔1, 2DFFTで使用
self.display_range = 100
else:
self.resolution = 0.415229e-3 # 表面の測定間隔2, 2DFFTで使用
self.display_range = 25
# self.center = int((self.sampling_num_surface-1)/2) # 表面の中心
self.k0 = k0
self.freq_resolution = 1 / (self.resolution*self.sampling_num_surface)
self.list_i = [1]+list(range(3,22))
# self.list_k1 = [1,2,3] # ワークの測定場所
# self.list_k2 = [1,2] # 各場所から何個とるか
def _read_surface_data(self,i2,k1): # 加工条件i2, 測定場所k1のデータ読み取り(粗い方,1)
df = pd.read_csv('data/surface_data/'+str(i2)+'-'+str(self.k0)+'-'+str(k1)+'.csv',usecols=range(1023),skipfooter=1,names=list(range(1023)),dtype=float,engine="python") # 生データ
df2 = df.replace(0,np.nan) # 0を欠損値扱いに
df3 = df2.interpolate(limit_direction="both") # 欠損値を両側から平均で補完
z_raw = df3.to_numpy()
# ここから最小二乗法
N = self.sampling_num_surface
x = np.arange(N)*self.resolution
self.Y,self.X = np.meshgrid(x,x) # 3次元形状でx,y軸を作るときはこれでよい
X = self.X.reshape(-1,1)
Y = self.Y.reshape(-1,1)
z_raw = z_raw.reshape(-1,1)
ones = np.ones(X.shape)
Mat = np.hstack([X,Y,ones]) # この行列が最小二乗法の元となる
# 以下, Ax = b の連立方程式をxについて解く
A = np.dot(Mat.T,Mat)
b = np.dot(Mat.T,z_raw)
x = np.linalg.solve(A,b)
z_new = z_raw - x[0]*X-x[1]*Y-x[2]
z_new =z_new.reshape(N,N)
# z_new = np.mean(df3.to_numpy())
# df4 = pd.DataFrame(df3.to_numpy() - mean_df3) # 平均面を引いた高さ Sa = np.mean
# Sa = np.mean(np.abs(df4.to_numpy()))
self.surface_data = z_new
def _caluculate_Sq_Sku(self,surface_data):
A = ((len(surface_data)-1)*self.resolution)**2
dA = self.resolution**2
Sq_2 = np.sum(surface_data**2*dA)/A
Sq = np.sqrt(Sq_2)
Sku = np.sum(surface_data**4*dA)/(A*Sq**4)
return Sq,Sku
def _do_2DFFT(self):
n1 = self.display_range
FFT = np.fft.fft2(self.surface_data) # 変換
FFT = np.fft.fftshift(FFT) #周波数シフト
FFT[508:515,508:515] = 1e-3 # 中心に近い低周波成分(±3)を1に
spec = np.abs(FFT)/(self.sampling_num_surface/2)**2 # パワースペクトル
spec = spec[511:511+n1,511-n1+1:511+n1] # スペクトルの領域を狭める
fx = np.arange(n1)*self.freq_resolution
fy = np.arange(-n1+1,n1)*self.freq_resolution
FY,FX = np.meshgrid(fy,fx)
amp = round(np.max(spec),2) # スペクトルの最大値
idx = np.array(np.unravel_index(np.argmax(spec), spec.shape)) - np.array([0,n1]) #最大値の座標
print("最大スペクトルの点 : {}".format(idx))
sp_freq = round(np.sqrt(idx[0]**2+idx[1]**2)*self.freq_resolution,2) # 最大値の空間周波数(距離に比例)
fx = round(abs(idx[0])*self.freq_resolution,3)
fy = round(abs(idx[1])*self.freq_resolution,3)
angle = round(np.degrees(np.arctan2(fy,fx))) # 最大座標の角度
return FX,FY,spec,amp,fx,fy,angle
def _adjust_ax_surface_imshow(self,ax,i2,k1): # 形状データの軸周り
ax.tick_params(axis = 'x',labelsize =15)
ax.tick_params(axis = 'y',labelsize =15)
ax.set_xlabel("X [mm]",size=20,labelpad=5)
ax.set_ylabel("Y [mm]",size=20,labelpad=5)
title = "Surface "+str(i2)+"-"+str(self.k0)+"-"+str(k1)
ax.set_title(title,size=25,y=-0.28)
def _adjust_ax_2DFFT_imshow(self,ax,i2,k1): # 2DFFTの軸周り
ax.tick_params(axis = 'x',labelsize =15)
ax.tick_params(axis = 'y',labelsize =15)
ax.set_xlabel("FX [1/mm]",size=20,labelpad=5)
ax.set_ylabel("FY [1/mm]",size=20,labelpad=5)
# ax.yaxis.set_ticks(np.arange(-8,8))
title = "2D-FFT "+str(i2)+"-"+str(self.k0)+"-"+str(k1)
ax.set_title(title,size=25,y=-0.23)
|
python
|
"""
An unofficial native Python wrapper for the LivePerson Messaging Operations API.
Documentation:
https://developers.liveperson.com/data-messaging-operations-overview.html
The Messaging Operations API extracts data according to the search query. The API allows agent managers to extract
information about their call center on the account, skill, and agent level. The data includes closed conversations
and their associated attributes, such as customer satisfaction, average conversation length, resolved status and so on.
Usage Example:
1. Choose User Service Login or OAuth1 Authentication.
# For User Service Login
> from lp_api_wrapper import UserLogin
> auth = UserLogin(account_id='1234', username='YOURUSERNAME', password='YOURPASSWORD')
# For OAuth1 Authentication
> from lp_api_wrapper import OAuthLogin
> auth = OAuthLogin(account_id='1234', app_key='K', app_secret='S', access_token='T', access_token_secret='TS')
2. Import MessagingOperations and get data from connection
> from lp_api_wrapper import MessagingOperations
> mo_conn = MessagingOperations(auth=auth)
> data = mo_conn.messaging_conversation(time_frame=1440, skill_ids='1,2' agent_ids='3,4', interval=1440)
"""
import requests
from ..util import (LoginService, UserLogin, OAuthLogin)
from typing import Optional, Union
class MessagingOperations(LoginService):
def __init__(self, auth: Union[UserLogin, OAuthLogin]) -> None:
super().__init__(auth=auth)
self.am_domain = self.get_domain(service_name='leDataReporting')
def messaging_conversation(self, time_frame: int, version: int = 1, skill_ids: Optional[str] = None,
agent_ids: Optional[str] = None, interval: Optional[int] = None) -> dict:
"""
Documentation:
https://developers.liveperson.com/data-messaging-operations-messaging-conversation.html
Retrieves messaging conversation related metrics at the site, skill or agent level.
:param time_frame: The time range (in minutes) by which the data can be filtered. Where: end time is the current
time and the start time = end time - timeframe. The maximum timeframe value is 1440 minutes (24 hours).
:param version: version of API e.g. v=1
:param skill_ids: When provided, metrics on the response will be grouped by the requested skill/s' id/s.
For each skill the metrics will be grouped per agent and also in total for all the skills specified.
When neither skill nor agent ID are provided, metrics on the response will be calculated at the account level.
If there is no data for the specified skill/s an object will be returned with an empty value for key:
"metricsPerSkill" and "metricsTotal" key with a map including all metrics valued zero. You can provide one or
more skill IDs.
Example: skill_ids='4,15,3'. To retrieve all skills active for the time period use skill_ids='all'
:param agent_ids: When provided, metrics on the response will be grouped by the requested agent/s' ID/s.
The metrics will also be grouped in total for all specified agent/s' id/s. When neither skill nor agent ID
are provided, metrics on the response will be calculated at the account level. If there is no data for the
specified agent/s an object will be returned with an empty value for key: "metricsPerAgent" and "metricsTotal"
key with a map including all metrics valued at zero. You can provide one or more skill IDs.
Example: agent_ids='4,15,3'. To retrieve all skills active for the time period use agent_ids='all'
:param interval: Interval size in minutes. When provided, the returned data will be aggregated by intervals of
the requested size. The interval has to be smaller or equal to the time frame and also a divisor of the time
frame. Example:
time_frame=60 interval=30 (correct),
time_frame=60 interval=61 (bad request),
time_frame=60 interval=31 (bad request)
:return: Dictionary with same structure as the JSON data from the API.
"""
# Establish Authorization
auth_args = self.authorize(headers={'content-type': 'application/json'})
# Messaging Conversation URL
url = 'https://{}/operations/api/account/{}/msgconversation'
# Generate request
r = requests.post(
url=url.format(self.am_domain, self.account_id),
json={'timeframe': time_frame, 'v': version, 'skillIds': skill_ids, 'agentIds': agent_ids,
'interval': interval},
**auth_args
)
# Check request status
if r.status_code == requests.codes.ok:
return r.json()
else:
print('Error: {}'.format(r.json()))
r.raise_for_status()
def messaging_current_queue_health(self, version: int = 1, skill_ids: Optional[str] = None):
"""
Documentation:
https://developers.liveperson.com/data-messaging-operations-messaging-current-queue-health.html
Retrieves the information about the current messaging queue state (and all its related metrics) in the account
and skill level
:param version: Version of API e.g. v=1
:param skill_ids: When provided, metrics on the response will be grouped by the requested skills. When not
provided, defaults to 'all' skills. You can provide one or more skillIDs.
Example: skillIds=4,153. To retrieve all skills active for the time period,
use skillIds=all or do not specify this parameter at all.
:return:
"""
# Establish Authorization
auth_args = self.authorize(headers={'content-type': 'application/json'})
# Messaging Current Queue Health URL
url = 'https://{}/operations/api/account/{}/msgqueuehealth/current/'
# Generate request
r = requests.get(
url=url.format(self.am_domain, self.account_id),
params={'v': version, 'skillIds': skill_ids},
**auth_args
)
# Check request status
if r.status_code == requests.codes.ok:
return r.json()
else:
print('Error: {}'.format(r.json()))
r.raise_for_status()
def messaging_queue_health(self, time_frame: int, version: int = 1, skill_ids: Optional[str] = None,
interval: Optional[int] = None):
"""
Documentation:
https://developers.liveperson.com/data-messaging-operations-messaging-queue-health.html
Retrieves information about the state of the queue (with all related metrics) for up to the last 24 hours at
the account or skill level.
:param time_frame: The time range (in minutes) in which the data can be filtered. Where end time = current time,
and start time = end time - timeframe. The maximum timeframe value is 1440 minutes (24 hours).
:param version: Version of API, for example, v=1.
:param skill_ids: When provided, metrics on the response will be grouped by the requested skills.
When not provided, metrics on the response will be calculated for all skills. You can provide one or more
skillIDs.
Example: skillIds=4,153. To retrieve all skills active for the time period, use skillIds=all, or do not
specify this parameter at all.
:param interval: Interval size in minutes (the minimum value is five minutes). When provided,
the returned data will be aggregated by intervals of the requested size. The interval has to be smaller or
equal to the time frame and also a divisor of the time frame.
Example:
time_frame=60, interval=30 (correct)
time_frame=60, interval=61 (bad request)
time_frame=60, interval=31 (bad request)
:return:
"""
# Establish Authorization
auth_args = self.authorize(headers={'content-type': 'application/json'})
# Messaging Queue Health URL
url = 'https://{}/operations/api/account/{}/msgqueuehealth'
# Generate request
r = requests.get(
url=url.format(self.am_domain, self.account_id),
params={'timeframe': time_frame, 'v': version, 'skillIds': skill_ids, 'interval': interval},
**auth_args
)
# Check request status
if r.status_code == requests.codes.ok:
return r.json()
else:
print('Error: {}'.format(r.json()))
r.raise_for_status()
def messaging_csat_distribution(self, time_frame: int, version: int = 1, skill_ids: Optional[str] = None,
agent_ids: Optional[str] = None) -> dict:
"""
Documentation:
https://developers.liveperson.com/data-messaging-operations-messaging-csat-distribution.html
Retrieves messaging CSAT (Customer Satisfaction) distribution related metrics at the site, skill or agent level.
:param time_frame: The time range (in minutes) by which the data can be filtered. Where: end time is the current
time and the start time is the end time - timeframe. The maximum timeframe value is 1440 minutes (24 hours).
:param version: Version of API e.g. v=1
:param skill_ids: When provided, metrics on the response will be grouped by the requested skill/s' id/s.
For each skill the metrics will be grouped per agent and also in total for all the skills specified.
When neither skill nor agent ID are provided, metrics on the response will be calculated at the account level.
If there is no data for the specified skill/s an object will be returned with an empty value for key:
"metricsPerSkill" and "metricsTotal" key with a map including all metrics valued zero.
You can provide one or more skill IDs.
Example: skill_ids='4,15,3'. To retrieve all skills active for the time period use skill_ids='all'
:param agent_ids: When provided, metrics on the response will be grouped by the requested agent/s' ID/s.
The metrics will also be grouped in total for all specified agent/s' id/s. When neither skill nor agent ID are
provided, metrics on the response will be calculated at the account level. If there is no data for the
specified agent/s an object will be returned with an empty value for key: "metricsPerAgent" and "metricsTotal"
key with a map including all metrics valued at zero. You can provide one or more skill IDs.
Example: agent_ids='4,15,3'. To retrieve all skills active for the time period use agent_ids='all'
:return: Dictionary with same structure as the JSON data from the API.
"""
# Establish Authorization
auth_args = self.authorize(headers={'content-type': 'application/json'})
# Messaging CSAT Distribution URL
url = 'https://{}/operations/api/account/{}/msgcsatdistribution'
# Generate request
r = requests.get(
url=url.format(self.am_domain, self.account_id),
params={'timeframe': time_frame, 'v': version, 'skillIds': skill_ids, 'agentIds': agent_ids},
**auth_args
)
# Check request status
if r.status_code == requests.codes.ok:
return r.json()
else:
print('Error: {}'.format(r.json()))
r.raise_for_status()
|
python
|
# Generated by Django 2.2.1 on 2019-05-28 11:15
import jsonfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('internet_nl_dashboard', '0030_auto_20190515_1209'),
]
operations = [
migrations.AddField(
model_name='account',
name='report_settings',
field=jsonfield.fields.JSONField(
default={}, help_text='This stores reporting preferences: what fields are shown in the UI and so on (if any other).This field can be edited on the report page.'),
preserve_default=False,
),
]
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zerlous
# @File : index.py
# @Time : 2019-08-26 18:20
# @Desc :
print "aaaaa"
print ('你好')
flag = False
if flag:
print 'true'
else:
print 'false'
|
python
|
# coding: utf-8
# CarND-Behavioral-Cloning-P3
# In[3]:
#Importing Dependencies when required
import os
import csv
samples=[]
with open('./data/driving_log.csv') as csvfile:
has_header = csv.Sniffer().has_header(csvfile.read(1024))
csvfile.seek(0) # Rewind.
reader=csv.reader(csvfile)
if has_header:
next(reader) # Skip header row.
for line in reader:
samples.append(line)
from sklearn.model_selection import train_test_split
train_samples, validation_samples = train_test_split(samples, test_size=0.21)
#Quick Visualization of what we did above
print("Length of Training Data: ",len(train_samples))
print("Random datapoint - ",train_samples[9])
print("Length of Validation Data: ",len(validation_samples))
print("Random datapoint - ",validation_samples[9])
# In[4]:
#Using the example Generator from Classroom
import cv2
import numpy as np
from sklearn.utils import shuffle
from matplotlib import pyplot as plt
from scipy.misc import toimage
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout, ELU, MaxPooling2D
from keras.layers.convolutional import Convolution2D
from keras.regularizers import l2
from keras.optimizers import Adam
def generator(samples, batch_size=33):
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset+(batch_size)]
images = []
angles = []
for batch_sample in batch_samples:
name = './data/IMG/'+batch_sample[0].split('/')[-1]
center_image = cv2.imread(name)
center_angle = float(batch_sample[3])
name = './data/IMG/'+batch_sample[1].split('/')[-1]
left_image = cv2.imread(name)
left_angle = float(batch_sample[3])+0.25
name = './data/IMG/'+batch_sample[2].split('/')[-1]
right_image = cv2.imread(name)
right_angle = float(batch_sample[3])-0.25
images.append(center_image)
angles.append(center_angle)
images.append(left_image)
angles.append(left_angle)
images.append(right_image)
angles.append(right_angle)
#Augment Data by flipping
augmented_images, augmented_measurements = [] , []
for image,measurement in zip(images, angles):
augmented_images.append(image)
augmented_measurements.append(measurement)
augmented_images.append(cv2.flip(image,1))
augmented_measurements.append(measurement*-1.0)
X_train = np.array(augmented_images)
y_train = np.array(augmented_measurements)
yield shuffle(X_train, y_train)
# compile and train the model using the generator function
train_generator = generator(train_samples, batch_size=33)
validation_generator = generator(validation_samples, batch_size=33)
#ch, row, col = 3, 160, 320 # Trimmed image format
model = Sequential()
# Preprocess incoming data, centered around zero with small standard deviation
#model.add(Lambda(lambda x: x/127.5 - 1.))
#model.add(... finish defining the rest of your model architecture here ...)
model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160,320,3), output_shape=(160,320,3)))
model.add(Cropping2D(cropping=((70,25),(0,0))))
model.add(Convolution2D(24,5,5,subsample=(2,2),activation="relu",W_regularizer=l2(0.001)))
model.add(Convolution2D(36,5,5,subsample=(2,2),activation="relu",W_regularizer=l2(0.001)))
model.add(Convolution2D(48,5,5,subsample=(2,2),activation="relu",W_regularizer=l2(0.001)))
model.add(Convolution2D(64,3,3,activation="relu",W_regularizer=l2(0.001)))
#model.add(MaxPooling2D((1,1)))
model.add(Convolution2D(64,3,3,activation="relu",W_regularizer=l2(0.001)))
model.add(Flatten())
model.add(Dense(100,W_regularizer=l2(0.001)))
#model.add(Dropout(.6))
#model.add(ELU())
model.add(Dense(50,W_regularizer=l2(0.001)))
model.add(Dense(10,W_regularizer=l2(0.001)))
model.add(Dense(1))
#Adam(lr=1e-4)
model.compile(loss='mse', optimizer='adam')
history_object=model.fit_generator(train_generator, samples_per_epoch= len(train_samples)*6, validation_data=validation_generator, nb_val_samples=len(validation_samples), nb_epoch=5)
model.save('model.h5')
### print the keys contained in the history object
print(history_object.history.keys())
### plot the training and validation loss for each epoch
plt.plot(history_object.history['loss'])
plt.plot(history_object.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.show()
|
python
|
import sys
sys.path.insert(1, '../')
from selenium.webdriver.common.keys import Keys
import random
from random import randint
from functions import fetchLists, wait, chanceOccured, cleanNumber, updateLists
from bot import Bot
class ProcessAccountsBot(Bot):
def __init__(self, account: str = None):
super().__init__()
if (account is not None):
self.initialUsers, self.notFollowed, self.followed, self.privateRequested = fetchLists(account)
self.initialAccount = account
def alreadyStored(self, user: str):
if (user in self.notFollowed or user in self.followed or user in self.privateRequested):
return True
else:
return False
#gotta wait til ban to find out the english word haha
def isBan(self):
try:
if (self.browser.find_element_by_tag_name('h2').text == 'Fehler'):
print('BAN')
return True
return False
except:
return False
def isHashtag(self):
try:
if (self.browser.find_element_by_class_name('_7UhW9.fKFbl.yUEEX.KV-D4.uL8Hv').text[0]=='#'):
print('HASHTAG')
return True
return False
except:
return False
def isLocation(self):
try:
self.browser.find_element_by_class_name('leaflet-tile.leaflet-tile-loaded')
print('LOCATION')
return True
except:
return False
def isPrivate(self):
try:
self.browser.find_element_by_class_name('rkEop') # privat
return True
except:
return False
def isUnexisting(self):
try:
if (self.browser.find_element_by_class_name('VnYfv').text == "Sorry, this page isn't available."):
return True
return False
except:
return False
def getCurrentUserData(self, user: str):
posts = int(cleanNumber(self.browser.find_elements_by_class_name('g47SY')[0].text))
isFollowedBy = int(cleanNumber(self.browser.find_elements_by_class_name('g47SY')[1].text))
isFollowing = int(cleanNumber(self.browser.find_elements_by_class_name('g47SY')[2].text))
return user, posts, isFollowedBy, isFollowing
def isCandidateForFollow(self, userStats: (int, int, int)):
#0.85 represents follower -> following - threshold to which a user is a candidate
if (userStats[1] >= 12 and userStats[2] in range(300, 5000) and (userStats[2] <= 0.85 * userStats[3])):
return True
else:
return False
def isCandidateForProcessing(self, userStats: (int, int, int)):
if (not self.isPrivate() and userStats[1] >= 25 and userStats[2] > 1500):
return True
else:
return False
def processAccount(self, user, commentChance):
randomIndeces = []
while (len(randomIndeces) < 3):
y = randint(0,2)
if (y not in randomIndeces):
randomIndeces.append(y)
commentControl = random.choice(randomIndeces)
for index in randomIndeces:
self.browser.find_elements_by_class_name('eLAPa')[index].click()
wait(8,10)
self.likePost()
wait(6,8)
if (commentControl == index):
if(chanceOccured(commentChance)):
try:
self.insertComment(user)
except Exception as e:
print('Blocked Commenting')
print(e)
self.actions.send_keys(Keys.ESCAPE).perform()
wait(5,8)
self.actions.reset_actions()
self.actions.key_down(Keys.SHIFT) # Before following, go to the top of the page by simulating shift and space
self.actions.send_keys(' ')
for i in range(2):
self.actions.perform()
wait(3,5)
self.actions.reset_actions()
def processAccountList(self):
notFollowedUsers = []
followedUsers = []
privateUsers = []
# gets increased by 2 for each processing and by 1 for each following
banControl = 0
try:
for user in self.initialUsers:
if (self.alreadyStored(user)):
print('continuamous: User already stored')
continue
print(banControl)
# threshold can be met by (18 + 2; 19 + 1; 19 + 2); Bot NEEDS to take a 10-15 min break
if (banControl not in (0,1) and (banControl % 20 in (0,1))):
print('WAITING!')
banControl = 0
wait(600,900)
if (not self.searchUser(user)):
print('continuamous: Something went wrong in the search')
continue
if (self.isUnexisting() or self.isBan() or self.isHashtag() or self.isLocation()):
print('continuamous: not a user; BAN; Hashtag; Location')
continue
userData = self.getCurrentUserData(user)
print(userData)
if (self.isCandidateForFollow(userData)):
if (self.isPrivate()):
self.tryFollow()
print('private requested')
privateUsers.append(userData)
banControl = banControl + 1
else:
self.processAccount(user, 33)
self.tryFollow()
print('public followed')
followedUsers.append(userData)
banControl = banControl + 2
else:
if (self.isCandidateForProcessing(userData)):
self.processAccount(user, 88)
print('just processed, not followed')
notFollowedUsers.append(userData)
banControl = banControl + 2
wait(5,10)
else:
print('not followed')
notFollowedUsers.append(userData)
wait(5,10)
continue
except Exception as e:
print(e)
updateLists(self.initialAccount, notFollowedUsers, followedUsers, privateUsers)
|
python
|
from flask import g
def transform(ugc):
if not g.netanyahu:
return ugc
new_ugc = []
for u in ugc:
new_u = {
'censored': u.get('censored', False),
'ugcdocid': u['ugcdocid'],
'pages': u['pages'],
'summary': u.get('summary', '').strip(),
'date': u.get('date', '').strip(),
'title': u.get('title2', u.get('title', '')).strip(),
'who': u.get('who', '').strip()
}
if new_u['summary'] and new_u['summary'][-1] != '.':
new_u['summary'] = '%s%s' % (new_u['summary'], '.')
new_ugc.append(new_u)
def sort_by_date_key(u):
if u:
return tuple(u['date'].split('/')[::-1])
else:
return ('0000', '00', '00')
new_ugc.sort(key=sort_by_date_key)
return new_ugc
|
python
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from erpnext import get_company_currency, get_default_company
from erpnext.accounts.report.utils import get_currency, convert_to_presentation_currency
from frappe.utils import getdate, cstr, flt, fmt_money
from frappe import _, _dict
from erpnext.accounts.utils import get_account_currency
tempColoumn = []
def execute(filters=None):
account_details = {}
if filters and filters.get('print_in_account_currency') and \
not filters.get('account'):
frappe.throw(_("Select an account to print in account currency"))
for acc in frappe.db.sql("""select name, is_group from tabAccount""", as_dict=1):
account_details.setdefault(acc.name, acc)
validate_filters(filters, account_details)
filters = set_account_currency(filters)
res, tempColoumn = get_result(filters, account_details)
columns = get_columns(filters, tempColoumn)
return columns, res
def validate_filters(filters, account_details):
if not filters.get('company'):
frappe.throw(_('{0} is mandatory').format(_('Company')))
if filters.get("account") and not account_details.get(filters.account):
frappe.throw(_("Account {0} does not exists").format(filters.account))
if filters.get("account") and filters.get("group_by_account") \
and account_details[filters.account].is_group == 0:
frappe.throw(_("Can not filter based on Account, if grouped by Account"))
if filters.get("voucher_no") and filters.get("group_by_voucher"):
frappe.throw(_("Can not filter based on Voucher No, if grouped by Voucher"))
if filters.from_date > filters.to_date:
frappe.throw(_("From Date must be before To Date"))
def validate_party(filters):
party_type, party = filters.get("party_type"), filters.get("party")
if party:
if not party_type:
frappe.throw(_("To filter based on Party, select Party Type first"))
elif not frappe.db.exists(party_type, party):
frappe.throw(_("Invalid {0}: {1}").format(party_type, party))
def set_account_currency(filters):
if not (filters.get("account") or filters.get("party")):
return filters
else:
filters["company_currency"] = frappe.db.get_value("Company", filters.company, "default_currency")
account_currency = None
if filters.get("account"):
account_currency = get_account_currency(filters.account)
elif filters.get("party"):
gle_currency = frappe.db.get_value(
"GL Entry", {
"party_type": filters.party_type, "party": filters.party, "company": filters.company
},
"account_currency"
)
if gle_currency:
account_currency = gle_currency
else:
account_currency = None if filters.party_type in ["Employee", "Student", "Shareholder"] else \
frappe.db.get_value(filters.party_type, filters.party, "default_currency")
filters["account_currency"] = account_currency or filters.company_currency
if filters.account_currency != filters.company_currency:
filters["show_in_account_currency"] = 1
return filters
def get_result(filters, account_details):
gl_entries, mydata = get_gl_entries(filters)
# data = get_data_with_opening_closing(filters, account_details, gl_entries)
data = gl_entries
result = get_result_as_list(data, filters)
return result, mydata
def get_gl_entries(filters):
if filters.get("presentation_currency"):
currency = filters["presentation_currency"]
else:
if filters.get("company"):
currency = get_company_currency(filters["company"])
else:
company = get_default_company()
currency = get_company_currency(company)
currency_map = get_currency(filters)
tempDict = []
tempVar = ""
oldVar= ""
temp = 1
temp1 = False
columns = []
tempColoumn = []
totalGross = 0.0
setParticulars = []
myVar = 0
select_fields = """, (B.debit_in_account_currency) as debit_in_account_currency, (B.credit_in_account_currency) as credit_in_account_currency""" \
group_by_condition = " B.account, B.cost_center" \
if filters.get("group_by_voucher") else "group by E.name"
mydata = """select E.posting_date, E.is_opening as is_opening, B.is_advance as is_advance, E.title, E.bill_no as bill_no, E.company as company, E.voucher_type as voucher_type, E.voucher_type as voucher_type_link, E.owner as created_by_whom, E.modified_by as modified_by_whom, B.party_type as party_type, E.bill_date as bill_date, B.parent as voucher_no, B.account, B.party as party_name,(E.total_debit) as debit, B.name as childId, B.credit as account_credit, B.debit as account_debit, (E.total_credit) as credit, B.cost_center, B.project,account_currency,E.remark, E.is_opening {select_fields} from `tabJournal Entry` E LEFT JOIN `tabJournal Entry Account` B ON B.parent = E.name where E.docstatus ='1' AND {conditions} order by E.posting_date, B.account """.format(select_fields=select_fields, conditions=get_conditions(filters))
gl_entries = frappe.db.sql(mydata,filters, as_dict=1)
if gl_entries:
for j in gl_entries:
j['voucher_type_link'] = 'Journal Entry'
mykey = ''
setPriority = ''
totalGross = 0.0
if(temp == 1):
temp = 2
myVar = myVar +1
j['particulars'] = ''
setPriority, totalGross, isDuplicate = setPriorityOfAccount(j.voucher_no, setParticulars, tempColoumn)
if setPriority and isDuplicate:
setParticulars.append(setPriority)
if setPriority:
mykey = 'gross'
j['particulars'] = str(setPriority)
j['gross'] = str(totalGross)
if(str(j['account']) != str(setPriority)):
j['credit'] = float("-"+str(j['credit']))
mykey = str(j['account'])
j[mykey] = str(j['account_debit'])
if(str(j['account_credit']) != '0.0'):
j[mykey] = '-'+str(j['account_credit'])
j['bill_no'] = j['bill_no']
tempDict.append(j)
columnsObj = {}
if (mykey != 'gross' and mykey !=''):
columnsObj['label'] = ""+mykey+""
columnsObj['fieldname'] = ""+mykey+""
columnsObj['fieldtype'] = "Float"
columnsObj['width'] = 90
if columnsObj:
if(checkDuplicate(columnsObj['fieldname'],tempColoumn)):
tempColoumn.append(columnsObj)
else:
if tempDict:
temp1 = True
for m in tempDict:
if(m['voucher_no'] == j['voucher_no']):
mykey = ''
alredyExist = True
if m.has_key(str(j['account'])):
alredyExist = False
if(str(j['account_credit']) !='0.0'):
m[str(j['account'])] = float(m[str(j['account'])]) - float(j['account_credit'])
else:
m[str(j['account'])] = float(m[str(j['account'])]) + float(j['account_debit'])
if alredyExist:
if(str(m['particulars']) != str(j['account'])):
mykey = str(j['account'])
if (str(j['account_debit']) !='0.0'):
m[mykey] = float(j['account_debit'])
else:
m[mykey] = '-'+str(float(j['account_credit']))
columnsObj = {}
if (mykey != 'gross' and mykey !=''):
columnsObj['label'] = ""+mykey+""
columnsObj['fieldname'] = ""+mykey+""
columnsObj['fieldtype'] = "Float"
columnsObj['width'] = 90
if columnsObj:
if(checkDuplicate(columnsObj['fieldname'],tempColoumn)):
tempColoumn.append(columnsObj)
temp1 = False
if temp1:
setPriority = ''
myVar = myVar +1
j['particulars'] = ''
setPriority, totalGross, isDuplicate = setPriorityOfAccount(j.voucher_no, setParticulars, tempColoumn)
if setPriority != None and str(setPriority) != '' and isDuplicate == True:
setParticulars.append(setPriority)
if setPriority:
mykey = 'gross'
j['particulars'] = str(setPriority)
j['gross'] = str(totalGross)
if(str(j['account']) != str(setPriority)):
if float(j['credit']) > 0.0:
j['credit'] = float("-"+str(j['credit']))
mykey = str(j['account'])
j[mykey] = str(j['account_debit'])
if(str(j['account_credit']) != '0.0'):
j[mykey] = '-'+str(j['account_credit'])
j['bill_no'] = j['bill_no']
tempDict.append(j)
columnsObj = {}
if (mykey != 'gross' and mykey !=''):
columnsObj['label'] = ""+mykey+""
columnsObj['fieldname'] = ""+mykey+""
columnsObj['fieldtype'] = "Float"
columnsObj['width'] = 90
if columnsObj:
if(checkDuplicate(columnsObj['fieldname'],tempColoumn)):
tempColoumn.append(columnsObj)
gl_entries = tempDict
if filters.get('presentation_currency'):
return convert_to_presentation_currency(gl_entries, currency_map)
else:
return gl_entries, tempColoumn
def checkDuplicate(fieldName = '', tempColoumn=[]):
tempData = True
if tempColoumn:
for i in tempColoumn:
if (str(i['fieldname']) == str(fieldName)):
tempData = False
return False
if tempData:
return True
def get_conditions(filters):
conditions = []
if filters.get("account"):
lft, rgt = frappe.db.get_value("Account", filters["account"], ["lft", "rgt"])
conditions.append("""account in (select name from tabAccount
where lft>=%s and rgt<=%s and docstatus<2)""" % (lft, rgt))
if filters.get("voucher_no"):
conditions.append("E.name=%(voucher_no)s")
if filters.get("party_type"):
conditions.append("B.party_type=%(party_type)s")
if filters.get("party"):
conditions.append("B.party=%(party)s")
if not (filters.get("account") or filters.get("party") or filters.get("group_by_account")):
conditions.append("E.posting_date >= %(from_date)s")
conditions.append("E.posting_date <= %(to_date)s")
if filters.get("project"):
conditions.append("B.project=%(company)s")
if filters.get("company"):
conditions.append("E.company=%(company)s")
return " {}".format(" and ".join(conditions)) if conditions else ""
def get_data_with_opening_closing(filters, account_details, gl_entries):
data = []
gle_map = initialize_gle_map(gl_entries)
totals, entries = get_accountwise_gle(filters, gl_entries, gle_map)
# Opening for filtered account
data.append(totals.opening)
if filters.get("group_by_account"):
for acc, acc_dict in gle_map.items():
if acc_dict.entries:
# opening
data.append({})
data.append(acc_dict.totals.opening)
data += acc_dict.entries
# totals
data.append(acc_dict.totals.total)
# closing
data.append(acc_dict.totals.closing)
data.append({})
else:
data += entries
# totals
data.append(totals.total)
# closing
data.append(totals.closing)
return data
def get_totals_dict():
def _get_debit_credit_dict(label):
return _dict(
account="'{0}'".format(label),
debit=0.0,
credit=0.0,
debit_in_account_currency=0.0,
credit_in_account_currency=0.0
)
return _dict(
opening = _get_debit_credit_dict(_('Opening')),
total = _get_debit_credit_dict(_('Total')),
closing = _get_debit_credit_dict(_('Closing (Opening + Total)'))
)
def initialize_gle_map(gl_entries):
gle_map = frappe._dict()
for gle in gl_entries:
gle_map.setdefault(gle.account, _dict(totals=get_totals_dict(), entries=[]))
return gle_map
def get_accountwise_gle(filters, gl_entries, gle_map):
totals = get_totals_dict()
entries = []
def update_value_in_dict(data, key, gle):
data[key].debit += flt(gle.debit)
data[key].credit += flt(gle.credit)
data[key].debit_in_account_currency += flt(gle.debit_in_account_currency)
data[key].credit_in_account_currency += flt(gle.credit_in_account_currency)
from_date, to_date = getdate(filters.from_date), getdate(filters.to_date)
for gle in gl_entries:
if gle.posting_date < from_date or cstr(gle.is_opening) == "Yes":
update_value_in_dict(gle_map[gle.account].totals, 'opening', gle)
update_value_in_dict(totals, 'opening', gle)
update_value_in_dict(gle_map[gle.account].totals, 'closing', gle)
update_value_in_dict(totals, 'closing', gle)
elif gle.posting_date <= to_date:
update_value_in_dict(gle_map[gle.account].totals, 'total', gle)
update_value_in_dict(totals, 'total', gle)
if filters.get("group_by_account"):
gle_map[gle.account].entries.append(gle)
else:
entries.append(gle)
update_value_in_dict(gle_map[gle.account].totals, 'closing', gle)
update_value_in_dict(totals, 'closing', gle)
return totals, entries
def get_result_as_list(data, filters):
balance, balance_in_account_currency = 0, 0
inv_details = get_supplier_invoice_details()
for d in data:
if not d.get('posting_date'):
balance, balance_in_account_currency = 0, 0
balance = get_balance(d, balance, 'debit', 'credit')
d['balance'] = balance
if filters.get("show_in_account_currency"):
balance_in_account_currency = get_balance(d, balance_in_account_currency,
'debit_in_account_currency', 'credit_in_account_currency')
d['balance_in_account_currency'] = balance_in_account_currency
else:
d['debit_in_account_currency'] = d.get('debit', 0)
d['credit_in_account_currency'] = d.get('credit', 0)
d['balance_in_account_currency'] = d.get('balance')
d['account_currency'] = filters.account_currency
# d['bill_no'] = inv_details.get(d.get('against_voucher'), '')
return data
def get_supplier_invoice_details():
inv_details = {}
for d in frappe.db.sql(""" select name, bill_no from `tabPurchase Invoice`
where docstatus = 1 and bill_no is not null and bill_no != '' """, as_dict=1):
inv_details[d.name] = d.bill_no
return inv_details
def get_balance(row, balance, debit_field, credit_field):
balance += (row.get(debit_field, 0) - row.get(credit_field, 0))
return balance
def getAccountType():
accountData = []
mysql = "SELECT * FROM `tabAccount` where docstatus='0'"
getAccountDetails = frappe.db.sql(mysql,as_dict=True)
if getAccountDetails:
for i in getAccountDetails:
accountData.append({"name":i.name,
"account_name":i.account_name,
"parent":i.parent})
return accountData
def setPriorityOfAccount(parentId= '', setParticulars = [], tempDict = []):
account_exist = True
isDuplicate = True
ifParticulars = True
isCoulmn = False
accountArray = []
accountArrayType = []
my_sql = "SELECT * FROM `tabJournal Entry Account` WHERE parent = '"+str(parentId)+"' group by account"
getAccountDetails = frappe.db.sql(my_sql, as_dict= True)
if getAccountDetails:
for o in getAccountDetails:
# my_sql = "SELECT * FROM `tabAccount` WHERE name = %s and report_type ='Balance Sheet'"
# getAccountReport = frappe.db.sql(my_sql, (o.account), as_dict=True)
# if getAccountReport:
accountArray.append({"account": str(o.account), "type": str(o.account_type)})
accountName, accountType = check_account(accountArray, parentId)
if(accountName):
if tempDict:
for l in tempDict:
if( str(accountName) != str(l['fieldname'])):
isCoulmn = True
else:
isCoulmn = True
if isCoulmn:
if setParticulars:
for n in setParticulars:
if (str(n) == str(accountName)):
account_exist = False
returnTotal = 0.0
isDuplicate = False
ifParticulars = False
my_sql = "SELECT * FROM `tabJournal Entry Account` WHERE parent = '"+str(parentId)+"' and account = '"+str(accountName)+"'"
getAccountWise = frappe.db.sql(my_sql, as_dict=True)
if getAccountWise:
for k in getAccountWise:
if (k['debit'] !='' and k['debit'] !=None):
returnTotal = returnTotal + float(k['debit'])
if (k['credit'] !='' and k['credit'] !=None):
returnTotal = returnTotal + float(k['credit'])
return str(n),returnTotal, isDuplicate
if ifParticulars:
account_exist = False
returnTotal = 0.0
my_sql = "SELECT * FROM `tabJournal Entry Account` WHERE parent = '"+str(parentId)+"' and account = '"+str(accountName)+"'"
getAccountWise = frappe.db.sql(my_sql, as_dict=True)
if getAccountWise:
for j in getAccountWise:
if (j['debit'] !='' and j['debit'] !=None):
returnTotal = returnTotal + float(j['debit'])
if (j['credit'] !='' and j['credit'] !=None):
returnTotal = returnTotal + float(j['credit'])
return str(accountName),returnTotal, isDuplicate
if(account_exist):
return str(''),'', isDuplicate
def check_account(account = [], parentId=''):
tempCount = 0
account_type_list = ['Payable', 'Bank', 'Expense Account', 'Cash', 'Receivable']
account_type = ['Creditors for Service - SLPL', 'Petty Cash - SLPL']
if account:
for n in account:
accountType = '-'
if(str(n['account']) == str(account_type[0])):
if str(n['type']) =='' or str(n['type']) ==None:
accountType = '-'
return str(n['account']), str(accountType)
for i in account_type_list:
tempCount = tempCount +1
for j in account:
if (str(j['type']) !='' and str(j['type']) !=None):
if str(i) == str(j['type']):
return str(j['account']), str(j['type'])
if (tempCount ==5):
for k in account_type:
for l in account:
accountType = '-'
if str(k)== str(l['account']):
if str(j['type']) =='' or str(j['type']) ==None:
accountType = '-'
return str(l['account']), str(accountType)
return '', ''
def get_columns(filters, tempColoumn):
columns = []
# tempColoumn = []
frappe.msgprint(len(tempColoumn))
if filters.get("presentation_currency"):
currency = filters["presentation_currency"]
else:
if filters.get("company"):
currency = get_company_currency(filters["company"])
else:
company = get_default_company()
currency = get_company_currency(company)
columns = [
{
"label": _("Jv Ref"),
"fieldname": "voucher_no",
"fieldtype": "Dynamic Link",
"options": "voucher_type_link",
"width": 180
},
{
"label": _("Posting Date"),
"fieldname": "posting_date",
"fieldtype": "Date",
"width": 90
},
{
"label": _("Particulars"),
"fieldname": "particulars",
"width": 120
},
{
"label": _("Party Name"),
"fieldname": "party_name",
"width": 100
},
{
"label": _("Party"),
"fieldname": "party_type",
"width": 100
},
{
"label": _("Company"),
"fieldname": "company",
"width": 180
},
{
"label": _("Voucher Type"),
"fieldname": "voucher_type",
"width": 120
},
{
"label": _("Bill No"),
"fieldname": "bill_no",
"width": 100
},
{
"label": _("Bill Date"),
"fieldname": "bill_date",
"fieldtype": "Date",
"width": 90
},
{
"label": _("Address"),
"fieldname": "address",
"width": 100
},
{
"label": _("Pan Card"),
"fieldname": "pan_card",
"width": 100
},
{
"label": _("GST NO."),
"fieldname": "gst_no",
"width": 100
},
{
"label": _("Remarks"),
"fieldname": "remark",
"width": 400
},
{
"label": _("Ref No."),
"fieldname": "bill_no",
"width": 100
},
{
"label": _("Ref Date"),
"fieldname": "bill_date",
"fieldtype": "Date",
"width": 90
},
{
"label": _("Is Advance"),
"fieldname": "is_advance",
"width": 90
},
{
"label": _("Is Opening"),
"fieldname": "is_opening",
"width": 90
},
{
"label": _("Created by whom"),
"fieldname": "created_by_whom",
"width": 90
},
{
"label": _("Modified by whom"),
"fieldname": "modified_by_whom",
"width": 90
},
{
"label": _("Gross ({0})".format(currency)),
"fieldname": "gross",
"fieldtype": "Float",
"width": 100
}
]
if tempColoumn:
for i in tempColoumn:
columns.append(i)
return columns
|
python
|
from string import ascii_lowercase
def destroyer(input_sets):
"""
takes in a tuple with 1 or more sets of characters and replaces the alphabet with letters that are in the sets
First gets the candidates of the alphabets and gets the letters to knock out into a list
:param input_sets:
:return: string of letters with the letters in the input sets having been replaced with _
:rtype: str
"""
letters_to_knock = []
candidates = " ".join([let for let in ascii_lowercase])
result = ""
for sets in input_sets:
for char in sets:
letters_to_knock.append(char)
for let in candidates:
if let in letters_to_knock:
result += "_"
else:
result += let
return result
# alternative
def destroyer_2(input_sets):
from string import ascii_lowercase as alphabet
return " ".join(c if c not in set.union(*input_sets) else "_" for c in alphabet)
|
python
|
import mysql.connector
from contextlib import closing
with closing(mysql.connector.connect(
host="localhost",
port=3306,
user="root",
password="sql!DB123!",
database="app"
)) as db:
with closing(db.cursor(dictionary=True)) as cur:
sql = "select closing_date, currency_symbol, " \
"exchange_rate from rate where id = %s"
params = (1,) # create tuple with one element
cur.execute(sql, params)
row = cur.fetchone()
print(row['exchange_rate'])
|
python
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tensor summaries for exporting information about a model.
See the @{$python/summary} guide.
@@FileWriter
@@FileWriterCache
@@tensor_summary
@@scalar
@@histogram
@@audio
@@image
@@merge
@@merge_all
@@get_summary_description
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re as _re
from google.protobuf import json_format as _json_format
# exports Summary, SummaryDescription, Event, TaggedRunMetadata, SessionLog
# pylint: disable=unused-import
from tensorflow.core.framework.summary_pb2 import Summary
from tensorflow.core.framework.summary_pb2 import SummaryDescription
from tensorflow.core.util.event_pb2 import Event
from tensorflow.core.util.event_pb2 import SessionLog
from tensorflow.core.util.event_pb2 import TaggedRunMetadata
# pylint: enable=unused-import
from tensorflow.python.framework import dtypes as _dtypes
from tensorflow.python.framework import ops as _ops
from tensorflow.python.ops import gen_logging_ops as _gen_logging_ops
# exports tensor_summary
# pylint: disable=unused-import
from tensorflow.python.ops.summary_ops import tensor_summary
# pylint: enable=unused-import
from tensorflow.python.platform import tf_logging as _logging
# exports FileWriter, FileWriterCache
# pylint: disable=unused-import
from tensorflow.python.summary.writer.writer import FileWriter
from tensorflow.python.summary.writer.writer_cache import FileWriterCache
# pylint: enable=unused-import
from tensorflow.python.util import compat as _compat
from tensorflow.python.util.all_util import remove_undocumented
def _collect(val, collections, default_collections):
if collections is None:
collections = default_collections
for key in collections:
_ops.add_to_collection(key, val)
_INVALID_TAG_CHARACTERS = _re.compile(r'[^-/\w\.]')
def _clean_tag(name):
# In the past, the first argument to summary ops was a tag, which allowed
# arbitrary characters. Now we are changing the first argument to be the node
# name. This has a number of advantages (users of summary ops now can
# take advantage of the tf name scope system) but risks breaking existing
# usage, because a much smaller set of characters are allowed in node names.
# This function replaces all illegal characters with _s, and logs a warning.
# It also strips leading slashes from the name.
if name is not None:
new_name = _INVALID_TAG_CHARACTERS.sub('_', name)
new_name = new_name.lstrip('/') # Remove leading slashes
if new_name != name:
_logging.info(
'Summary name %s is illegal; using %s instead.' %
(name, new_name))
name = new_name
return name
def scalar(name, tensor, collections=None):
"""Outputs a `Summary` protocol buffer containing a single scalar value.
The generated Summary has a Tensor.proto containing the input Tensor.
Args:
name: A name for the generated node. Will also serve as the series name in
TensorBoard.
tensor: A real numeric Tensor containing a single value.
collections: Optional list of graph collections keys. The new summary op is
added to these collections. Defaults to `[GraphKeys.SUMMARIES]`.
Returns:
A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf.
Raises:
ValueError: If tensor has the wrong shape or type.
"""
name = _clean_tag(name)
with _ops.name_scope(name, None, [tensor]) as scope:
# pylint: disable=protected-access
val = _gen_logging_ops._scalar_summary(
tags=scope.rstrip('/'), values=tensor, name=scope)
_collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
def image(name, tensor, max_outputs=3, collections=None):
"""Outputs a `Summary` protocol buffer with images.
The summary has up to `max_outputs` summary values containing images. The
images are built from `tensor` which must be 4-D with shape `[batch_size,
height, width, channels]` and where `channels` can be:
* 1: `tensor` is interpreted as Grayscale.
* 3: `tensor` is interpreted as RGB.
* 4: `tensor` is interpreted as RGBA.
The images have the same number of channels as the input tensor. For float
input, the values are normalized one image at a time to fit in the range
`[0, 255]`. `uint8` values are unchanged. The op uses two different
normalization algorithms:
* If the input values are all positive, they are rescaled so the largest one
is 255.
* If any input value is negative, the values are shifted so input value 0.0
is at 127. They are then rescaled so that either the smallest value is 0,
or the largest one is 255.
The `tag` in the outputted Summary.Value protobufs is generated based on the
name, with a suffix depending on the max_outputs setting:
* If `max_outputs` is 1, the summary value tag is '*name*/image'.
* If `max_outputs` is greater than 1, the summary value tags are
generated sequentially as '*name*/image/0', '*name*/image/1', etc.
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: A 4-D `uint8` or `float32` `Tensor` of shape `[batch_size, height,
width, channels]` where `channels` is 1, 3, or 4.
max_outputs: Max number of batch elements to generate images for.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A scalar `Tensor` of type `string`. The serialized `Summary` protocol
buffer.
"""
name = _clean_tag(name)
with _ops.name_scope(name, None, [tensor]) as scope:
# pylint: disable=protected-access
val = _gen_logging_ops._image_summary(
tag=scope.rstrip('/'),
tensor=tensor,
max_images=max_outputs,
name=scope)
_collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
def histogram(name, values, collections=None):
# pylint: disable=line-too-long
"""Outputs a `Summary` protocol buffer with a histogram.
The generated
[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
has one summary value containing a histogram for `values`.
This op reports an `InvalidArgument` error if any value is not finite.
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
values: A real numeric `Tensor`. Any shape. Values to use to
build the histogram.
collections: Optional list of graph collections keys. The new summary op is
added to these collections. Defaults to `[GraphKeys.SUMMARIES]`.
Returns:
A scalar `Tensor` of type `string`. The serialized `Summary` protocol
buffer.
"""
# pylint: enable=line-too-long
name = _clean_tag(name)
with _ops.name_scope(name, 'HistogramSummary', [values]) as scope:
# pylint: disable=protected-access
val = _gen_logging_ops._histogram_summary(
tag=scope.rstrip('/'), values=values, name=scope)
_collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
def audio(name, tensor, sample_rate, max_outputs=3, collections=None):
# pylint: disable=line-too-long
"""Outputs a `Summary` protocol buffer with audio.
The summary has up to `max_outputs` summary values containing audio. The
audio is built from `tensor` which must be 3-D with shape `[batch_size,
frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are
assumed to be in the range of `[-1.0, 1.0]` with a sample rate of
`sample_rate`.
The `tag` in the outputted Summary.Value protobufs is generated based on the
name, with a suffix depending on the max_outputs setting:
* If `max_outputs` is 1, the summary value tag is '*name*/audio'.
* If `max_outputs` is greater than 1, the summary value tags are
generated sequentially as '*name*/audio/0', '*name*/audio/1', etc
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: A 3-D `float32` `Tensor` of shape `[batch_size, frames, channels]`
or a 2-D `float32` `Tensor` of shape `[batch_size, frames]`.
sample_rate: A Scalar `float32` `Tensor` indicating the sample rate of the
signal in hertz.
max_outputs: Max number of batch elements to generate audio for.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A scalar `Tensor` of type `string`. The serialized `Summary` protocol
buffer.
"""
# pylint: enable=line-too-long
name = _clean_tag(name)
with _ops.name_scope(name, None, [tensor]) as scope:
# pylint: disable=protected-access
sample_rate = _ops.convert_to_tensor(
sample_rate, dtype=_dtypes.float32, name='sample_rate')
val = _gen_logging_ops._audio_summary_v2(
tag=scope.rstrip('/'),
tensor=tensor,
max_outputs=max_outputs,
sample_rate=sample_rate,
name=scope)
_collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
def merge(inputs, collections=None, name=None):
# pylint: disable=line-too-long
"""Merges summaries.
This op creates a
[`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
protocol buffer that contains the union of all the values in the input
summaries.
When the Op is run, it reports an `InvalidArgument` error if multiple values
in the summaries to merge use the same tag.
Args:
inputs: A list of `string` `Tensor` objects containing serialized `Summary`
protocol buffers.
collections: Optional list of graph collections keys. The new summary op is
added to these collections. Defaults to `[]`.
name: A name for the operation (optional).
Returns:
A scalar `Tensor` of type `string`. The serialized `Summary` protocol
buffer resulting from the merging.
"""
# pylint: enable=line-too-long
name = _clean_tag(name)
with _ops.name_scope(name, 'Merge', inputs):
# pylint: disable=protected-access
val = _gen_logging_ops._merge_summary(inputs=inputs, name=name)
_collect(val, collections, [])
return val
def merge_all(key=_ops.GraphKeys.SUMMARIES):
"""Merges all summaries collected in the default graph.
Args:
key: `GraphKey` used to collect the summaries. Defaults to
`GraphKeys.SUMMARIES`.
Returns:
If no summaries were collected, returns None. Otherwise returns a scalar
`Tensor` of type `string` containing the serialized `Summary` protocol
buffer resulting from the merging.
"""
summary_ops = _ops.get_collection(key)
if not summary_ops:
return None
else:
return merge(summary_ops)
def get_summary_description(node_def):
"""Given a TensorSummary node_def, retrieve its SummaryDescription.
When a Summary op is instantiated, a SummaryDescription of associated
metadata is stored in its NodeDef. This method retrieves the description.
Args:
node_def: the node_def_pb2.NodeDef of a TensorSummary op
Returns:
a summary_pb2.SummaryDescription
Raises:
ValueError: if the node is not a summary op.
"""
if node_def.op != 'TensorSummary':
raise ValueError("Can't get_summary_description on %s" % node_def.op)
description_str = _compat.as_str_any(node_def.attr['description'].s)
summary_description = SummaryDescription()
_json_format.Parse(description_str, summary_description)
return summary_description
_allowed_symbols = [
'Summary', 'SummaryDescription', 'Event', 'TaggedRunMetadata', 'SessionLog'
]
remove_undocumented(__name__, _allowed_symbols)
|
python
|
from pathlib import Path
import torch
import torch.nn as nn
from torch.autograd import Variable
from mnist_efficientnet import io
from mnist_efficientnet.network import Network, extract_result
root = Path("../input/digit-recognizer")
train_x, train_y = io.load_train_data(root)
test = io.load_test_data(root)
net = Network()
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 10
batch_size = 50
loss_log = []
for e in range(epochs):
loss = None
for i in range(0, train_x.shape[0], batch_size):
x_mini = train_x[i : i + batch_size]
y_mini = train_y[i : i + batch_size]
optimizer.zero_grad()
net_out = net(Variable(x_mini))
loss = loss_func(net_out, Variable(y_mini))
loss.backward()
optimizer.step()
if loss is not None:
print(f"Epoch: {e+1} - Loss: {loss.item():.6f}")
with torch.no_grad():
net_out = net(test)
result = extract_result(net_out)
io.save_result(result)
|
python
|
"""
Tests for the pynagios package.
"""
class TestPyNagios(object):
pass
|
python
|
import pwndbg.color.theme as theme
import pwndbg.config as config
from pwndbg.color import generateColorFunction
config_prefix = theme.Parameter('backtrace-prefix', '►', 'prefix for current backtrace label')
config_prefix_color = theme.ColoredParameter('backtrace-prefix-color', 'none', 'color for prefix of current backtrace label')
config_address_color = theme.ColoredParameter('backtrace-address-color', 'none', 'color for backtrace (address)')
config_symbol_color = theme.ColoredParameter('backtrace-symbol-color', 'none', 'color for backtrace (symbol)')
config_label_color = theme.ColoredParameter('backtrace-frame-label-color', 'none', 'color for backtrace (frame label)')
def prefix(x):
return generateColorFunction(config.backtrace_prefix_color)(x)
def address(x):
return generateColorFunction(config.backtrace_address_color)(x)
def symbol(x):
return generateColorFunction(config.backtrace_symbol_color)(x)
def frame_label(x):
return generateColorFunction(config.backtrace_frame_label_color)(x)
|
python
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class network1(nn.Module):
def __init__(self):
super().__init__()
self.cnn1 = nn.Sequential(
nn.ReflectionPad2d(1),
nn.Conv2d(1, 4, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(4),
nn.ReflectionPad2d(1),
nn.Conv2d(4, 8, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(8),
nn.ReflectionPad2d(1),
nn.Conv2d(8, 8, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(8),
)
self.fc1 = nn.Sequential(
nn.Linear(8*100*100, 500),
nn.ReLU(inplace=True),
nn.Linear(500, 500),
nn.ReLU(inplace=True),
nn.Linear(500, 36))
def forward_once(self, x):
output = self.cnn1(x)
output = output.view(output.size()[0], -1)
output = self.fc1(output)
return output
class SiameseNetwork(network1):
def __init__(self):
super().__init__()
def forward(self, input1, input2):
output1 = self.forward_once(input1)
output2 = self.forward_once(input2)
return output1, output2
class CNN(network1):
def __init__(self):
super().__init__()
def forward(self,input1):
return self.forward_once(input1)
|
python
|
#!/usr/bin/python
#
# Chrome - Profile Launcher for Chrome
# @see http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
# https://pygobject.readthedocs.io/en/latest/getting_started.html
# https://lazka.github.io/pgi-docs/
# http://www.programcreek.com/python/example/9059/gtk.IconView
import os
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib
from gi.repository.GdkPixbuf import Pixbuf
import glob
import find_browser
import find_profile
import browser_chrome
import browser_firefox
import browser_links
NAME="Browser Launcher"
#ICON="google-chrome"
ICON="applications-internet"
# @see http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
#if __name__ == '__main__':
# import signal
# signal.signal(signal.SIGINT, signal.SIG_DFL)
# your_application_main()
#
# My Window Class
class Fabula_Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title=NAME)
self.set_border_width(1)
self.set_default_size(640, 480)
self.set_size_request(640, 480)
self.set_decorated(True)
self.set_double_buffered(True)
self.set_hide_titlebar_when_maximized(True)
self.set_icon( Gtk.IconTheme.get_default().load_icon(ICON, 64, 0) )
self.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
self.set_resizable(True)
# CTRL+Q to Quit
ag = Gtk.AccelGroup()
ag.connect(Gdk.keyval_from_name('Q'), Gdk.ModifierType.CONTROL_MASK, 0, Gtk.main_quit)
self.add_accel_group(ag)
self.add_head()
self.vbox = Gtk.VBox(False, 0)
self.add(self.vbox)
self.add_profile_list()
# self.add_options()
self.add_buttons()
if (len(sys.argv) >= 2):
sb = Gtk.Statusbar()
sb.set_size_request(200, 25)
#sb.set_has_resize_grip(True)
sbc = sb.get_context_id("url")
sb.push(sbc, "URL: " + sys.argv[1])
self.vbox.pack_end(sb, False, False, 0)
#end-if
#
# Add our Magic Headerbar
def add_head(self):
hb = Gtk.HeaderBar()
hb.set_title(NAME)
hb.set_subtitle("Select Binary and Profile")
hb.set_decoration_layout("icon,menu:minimize,maximize,close")
hb.set_show_close_button(True)
self.set_titlebar(hb)
#end-def
#
# Profile
def add_profile_list(self):
liststore = Gtk.ListStore(str, Pixbuf, object)
iconview = Gtk.IconView.new()
iconview.set_model(liststore)
iconview.set_columns(3)
iconview.set_item_padding(0)
iconview.set_item_width((640 - 16) / 6)
iconview.set_margin(0)
iconview.set_pixbuf_column(1)
iconview.set_row_spacing(0)
iconview.set_spacing(0)
iconview.set_text_column(0)
prof_list = find_profile.load_browser_profiles()
for prof in prof_list:
#print(prof)
liststore.append([ prof['name'], prof['icon'], prof ])
# end-for
#
#
wrapview = Gtk.ScrolledWindow()
#wrapview.set_shadow_type(Gtk.ShadowType.NONE)
wrapview.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
wrapview.add(iconview)
iconview.connect("item-activated", self.profile_launch)
iconview.connect("selection-changed", self.profile_selected)
self.vbox.pack_start(wrapview, True, True, 0)
#self.add(iconview)
#end-def
def add_buttons(self):
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=50)
b0 = Gtk.Button(label="Launch")
b0.connect("clicked", self.launch_browser)
hbox.pack_start(b0, True, True, 0)
b1 = Gtk.Button(label="Incognito")
b1.connect("clicked", self.launch_browser_incognito)
hbox.pack_start(b1, True, True, 0)
b2 = Gtk.Button(label="Cancel")
b2.connect("clicked", Gtk.main_quit)
hbox.pack_start(b2, True, True, 0)
self.vbox.pack_start(hbox, False, False, 0)
#end-def
def profile_selected(self, view):
print("profile_selected")
#print(view)
data = view.get_model()
path = view.get_selected_items()
#print(listdata)
#sel_list = listdata.get_selected_items()
#print(sel_list)
self._prof = data[path][2]
#print(self._prof)
#end-def
def profile_launch(self, view, path):
print("profile_launch")
#print(self._prof)
self.launch_browser(False)
#end-def
#
#
def launch_browser(self, x):
print("launch_browser")
#print(self)
#print(view)
#print(path)
#listdata = view.get_model()
#print(listdata)
#prof = listdata[path][2]
print(self._prof)
args = {}
args['link'] = None
args['private'] = False
if (len(sys.argv) >= 2):
args['link'] = sys.argv[1]
#end-if
if "chrome" == self._prof['type']:
browser_chrome.launch(self._prof, args)
elif "firefox" == self._prof['type']:
browser_firefox.launch(self._prof, args)
elif "links" == self._prof['type']:
browser_links.launch(self._prof, args)
#end-if
#self.hide()
Gtk.main_quit()
#end-def
#
#
def launch_browser_incognito(self, x):
print("launch_browser_incognito")
args = {}
args['link'] = None
args['private'] = True
if (len(sys.argv) >= 2):
args['link'] = sys.argv[1]
#end-if
if "chrome" == self._prof['type']:
browser_chrome.launch(self._prof, args)
elif "firefox" == self._prof['type']:
browser_firefox.launch(self._prof, args)
elif "links" == self._prof['type']:
browser_links.launch(self._prof, args)
#end-if
#self.hide()
Gtk.main_quit()
#end-def
#end-class
#
# main()
win = Fabula_Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
#print(dir(win.props))
#print(dir(Gtk.Window))
Gtk.main()
#GLib.MainLoop().run()
|
python
|
import unittest
import os.path
import os
import sys
sys.path.append(".")
#from pywinauto.timings import Timings
#Timings.Fast()
excludes = ['test_sendkeys']
def run_tests():
testfolder = os.path.abspath(os.path.split(__file__)[0])
sys.path.append(testfolder)
for root, dirs, files in os.walk(testfolder):
test_modules = [
file.replace('.py', '') for file in files if
file.startswith('test_') and
file.endswith('.py')]
test_modules = [mod for mod in test_modules if mod.lower() not in excludes]
for mod in test_modules:
#globals().update(__import__(mod, globals(), locals()).__dict__)
# import it
imported_mod = __import__(mod, globals(), locals())
#print imported_mod.__dict__
globals().update(imported_mod.__dict__)
#runner = unittest.TextTestRunner(verbosity = 2)
unittest.main()#testRunner = runner)
if __name__ == '__main__':
run_tests()
|
python
|
import torch
from torch import nn
from torch.utils.data import DataLoader
import os
from abc import ABC
from ssl_eval import Evaluator
from typing import Tuple
from .. import pkbar
from ..logger import Logger, EmptyLogger
from ..utils import AllReduce, after_init_world_size_n_rank
from ..scheduler import Scheduler
class GeneralTrainer(ABC):
"""GeneralTrainer
A trainer class responsible for training N epochs.
This is an abstract class, both SSL and LinearEval methods will
be inherited from this class.
Parameters
----------
model : nn.Module
The model we desire to train.
optimizer : torch.optim.Optimizer
The optimizer to use for training.
data_loaders : Tuple[DataLoader, DataLoader]
Train and validation data loaders
save_params : dict, optional
Parameters used for saving the network.
These parameters can be the name of the method and the name
of the dataset which together define the model architecture
the code built up. It must also contain a save_dir key
which tells to which folder the model should be saved. If
save_dir is None, the trainer will not save anything.
By default {"save_dir": None}
evaluator : KNNEvaluator, optional
An evaluator for the model which calculates the KNN accuracies.
If None, this step is skipped.
By default None.
"""
def __init__(self,
model: nn.Module,
scheduler: Scheduler,
data_loaders: Tuple[DataLoader, DataLoader],
save_params: dict = {"save_dir": None},
evaluator: Evaluator = None,
logger: Logger = EmptyLogger()):
self.model = model
self.optimizer = scheduler.optimizer
self.train_loader, self.val_loader = data_loaders
self.save_dir = save_params.pop('save_dir')
self.save_dict = save_params
self.evaluator = evaluator
self.scheduler = scheduler
self.scaler = torch.cuda.amp.GradScaler()
self.world_size, self.rank = after_init_world_size_n_rank()
if not (self.rank is None or self.rank == 0):
self.logger = EmptyLogger()
else:
self.logger = logger
self.start_epoch = 0
# Progress bar with running average metrics
self.pbar = ProgressBar([self.train_loader], self.rank)
# Checkpoints in which we save the model
self.save_checkpoints = []
@property
def device(self):
return next(self.model.parameters()).device
def _need_save(self, epoch: int) -> bool:
"""_need_save
Determines if the model should be saved in this
particular epoch.
"""
save_dir_given = self.save_dir is not None
in_saving_epoch = (epoch + 1) in self.save_checkpoints
is_saving_core = self.rank is None or self.rank == 0
return save_dir_given and in_saving_epoch and is_saving_core
def _ckp_name(self, epoch: int):
"""_ckp_name
Checkpoint filename. It has an own unique class, because
each trainer might define different filenames.
"""
return f'checkpoint_{epoch+1:04d}.pth.tar'
def _save(self, epoch: int):
"""_save [summary]
Save the current checkpoint to a file.
"""
save_dict = {
'epoch': epoch + 1,
'state_dict': self.model.state_dict(),
'optimizer': self.optimizer.state_dict(),
'amp': self.scaler.state_dict(),
}
save_dict.update(self.save_dict)
filename = self._ckp_name(epoch)
os.makedirs(self.save_dir, exist_ok=True)
filepath = os.path.join(self.save_dir, filename)
torch.save(save_dict, filepath)
def load(self, path):
save_dict = torch.load(path, map_location=self.device)
self.model.load_state_dict(save_dict['state_dict'])
self.optimizer.load_state_dict(save_dict['optimizer'])
self.scaler.load_state_dict(save_dict['amp'])
self.start_epoch = save_dict['epoch']
torch.distributed.barrier()
def train(self, n_epochs: int):
"""train
Train n epochs.
Parameters
----------
n_epochs : int
Number of epochs to train.
ref_lr : float, optional
Base learning rate to cosine scheduler, by default 0.1
n_warmup_epochs : int, optional
Number of warmup epochs, by default 10
"""
self.scheduler.set_epoch(self.start_epoch)
for epoch in range(self.start_epoch, n_epochs):
# Reset progress bar to the start of the line
self.pbar.reset(epoch, n_epochs)
self.logger.add_scalar("stats/epoch", epoch, force=True)
# Set epoch in sampler
if self.world_size > 1:
self.train_loader.sampler.set_epoch(epoch)
for i, lr in enumerate(torch.unique(torch.tensor(self.scheduler.current_lrs))):
self.logger.add_scalar(f"stats/learning_rate_{i}", lr, force=True)
# Train
self.train_an_epoch()
# Validate
if (epoch + 1) % 5 == 0 or epoch == 0:
self.run_validation()
# Save network
if self._need_save(epoch):
self._save(epoch)
def train_an_epoch(self):
for data_batch in self.train_loader:
metrics = self.train_step(data_batch)
self.model.step(progress=self.scheduler.progress)
self.scheduler.step()
self.logger.step()
for i, lr in enumerate(torch.unique(torch.tensor(self.scheduler.current_unfixed_lrs))):
metrics[f'lr{i}'] = lr
self.pbar.update(metrics)
for k, v in metrics.items():
self.logger.add_scalar(f"train/{k}", v)
def run_validation(self):
self.evaluator.generate_embeddings()
batch_size = 4096 // self.world_size
init_lr = 1.6
accuracy = self.evaluator.linear_eval(batch_size=batch_size, lr=init_lr)
self.logger.add_scalar("test/lineval_acc", accuracy, force=True)
def train_step(self, batch: torch.Tensor):
raise NotImplementedError
def val_step(self, batch: torch.Tensor):
raise NotImplementedError
def _accuracy(self, y_hat: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""_accuracy
Accuracy of the model
"""
pred = torch.max(y_hat.data, 1)[1]
acc = (pred == y).sum() / len(y)
return AllReduce.apply(acc)
class ProgressBar:
def __init__(self, data_loaders, rank):
self.n_iter = sum([len(x) for x in data_loaders])
self.kbar = None
self.is_active = rank is None or rank == 0
def reset(self, epoch_i, n_epochs):
if self.is_active:
self.kbar = pkbar.Kbar(target=self.n_iter,
epoch=epoch_i,
num_epochs=n_epochs,
width=8,
always_stateful=False,
stateful_metrics=['lr'])
def update(self, value_dict):
if self.is_active:
values = [(k, v) for (k, v) in value_dict.items()]
self.kbar.add(1, values=values)
|
python
|
"""Domain classes for fulltext extraction service."""
from typing import NamedTuple, Optional, Any
from datetime import datetime
from pytz import UTC
from backports.datetime_fromisoformat import MonkeyPatch
from enum import Enum
MonkeyPatch.patch_fromisoformat()
class Extraction(NamedTuple): # arch: domain
"""Metadata about an extraction."""
class Status(Enum): # type: ignore
"""Task Status."""
IN_PROGRESS = 'in_progress'
SUCCEEDED = 'succeeded'
FAILED = 'failed'
identifier: str
"""Identifier of the document from which the extraction was generated."""
version: str
"""The version of the extractor that generated the product."""
bucket: str = 'arxiv'
"""The bucket or collection to which the extraction belongs."""
started: Optional[datetime] = None
"""The datetime when the extraction was created."""
ended: Optional[datetime] = None
"""The datetime when the extraction was completed."""
owner: Optional[str] = None
"""Owner of the resource."""
exception: Optional[str] = None
"""An exception raised during a failed task."""
task_id: Optional[str] = None
"""The identifier of the running task."""
status: 'Extraction.Status' = Status.IN_PROGRESS
"""Status of the extraction task."""
content: Optional[str] = None
"""Extraction content."""
def to_dict(self) -> dict:
"""Generate a dict representation of this placeholder."""
return {
'identifier': self.identifier,
'version': self.version,
'started': self.started.isoformat() if self.started else None,
'ended': self.ended.isoformat() if self.ended else None,
'owner': self.owner,
'task_id': self.task_id,
'exception': self.exception,
'status': self.status.value,
'content': self.content,
'bucket': self.bucket
}
def copy(self, **kwargs: Any) -> 'Extraction':
"""Create a new :class:`.Extraction` with updated values."""
data = self.to_dict()
data.update(kwargs)
# mypy does not know about fromisoformat yet, apparently.
if isinstance(data['status'], str):
data['status'] = Extraction.Status(data['status'])
if isinstance(data['started'], str):
data['started'] = datetime.fromisoformat(data['started']) # type: ignore
if isinstance(data['ended'], str):
data['ended'] = datetime.fromisoformat(data['ended']) # type: ignore
return Extraction(**data)
@property
def completed(self) -> bool:
"""Determine whether the task is in a completed states."""
return self.status in [self.Status.SUCCEEDED, self.Status.FAILED]
class _SupportedFormats:
"""Defines the text output formats supported by this service."""
PLAIN = 'plain'
PSV = 'psv'
def __contains__(self, value: str) -> bool:
return value in [self.PLAIN, self.PSV]
class _SupportedBuckets:
"""Defines the supported buckets for extracted plain text."""
ARXIV = 'arxiv'
SUBMISSION = 'submission'
def __contains__(self, value: str) -> bool:
return value in [self.ARXIV, self.SUBMISSION]
SupportedFormats = _SupportedFormats() # arch: domain
SupportedBuckets = _SupportedBuckets() # arch: domain
SupportedFormats.PLAIN
|
python
|
import bmesh as bm
import bpy
from bpy_extras import object_utils
from mathutils import Matrix
import numpy as np
from smorgasbord.common.io import get_scalars
from smorgasbord.common.mat_manip import make_transf_mat
from smorgasbord.common.transf import transf_pts
def combine_meshes(obs):
"""
Returns the meshes of all passed objects combined.
Parameters
----------
obs : Iterable[bpy_types.Object]
Objects to combine. Fails if non-mesh object is passed.
Returns
-------
verts : numpy.ndarray
Nx3 float array of XYZ vertex coordinates in world space
indcs : numpy.ndarray
Nx3 int array of triangle indices
info : list[tuple]
Holds a tuple for each passed object. The first entry stores
the index of the first element in 'verts' belonging to the
corresponding object, the second entry the same for 'indcs'.
"""
vtotlen = 0
itotlen = 0
info = []
# Accumulate vertex and triangle counts of all passed objects to
# later allocate the right amount of memory
for o in obs:
mesh = o.data
mesh.calc_loop_triangles()
vtotlen += len(mesh.vertices)
itotlen += len(mesh.loop_triangles)
info.append((vtotlen, itotlen))
# Initialize joined lists
verts = np.empty(vtotlen * 3, dtype=np.float32)
indcs = np.empty(itotlen * 3, dtype=np.int32)
vstart = 0
istart = 0
for o in obs:
# Calculate current object's slice in combined list
mesh = o.data
vend = vstart + len(mesh.vertices) * 3
iend = istart + len(mesh.loop_triangles) * 3
vslice = verts[vstart:vend]
islice = indcs[istart:iend]
# Get vertex coordinates of current object
mesh.vertices.foreach_get('co', vslice)
# Transform vertices to world space
verts[vstart:vend] = transf_pts(
o.matrix_world,
vslice.reshape(-1, 3),
).ravel()
# Get triangle indices of current object
mesh.loop_triangles.foreach_get('vertices', islice)
# Offset each new index by the vertex count already in the
# joined list so that the indices still point to the correct
# vertex coordinates.
islice += int(vstart / 3)
vstart = vend
istart = iend
verts.shape = (-1, 3)
indcs.shape = (-1, 3)
return verts, indcs, info
def get_unit_cube():
"""
Returns vertex coordinates and face indices for a unit cube.
Returns
-------
verts : numpy.ndarray
3x8 float array of XYZ vertex coordinates.
quads : numpy.ndarray
4x6 array of vertex indices for each quad face. Each 4-value tuple
holds the indices of the vertices in the verts array the
corresponding quad is connected to.
"""
verts = np.array([
(+0.5, +0.5, -0.5),
(+0.5, -0.5, -0.5),
(-0.5, -0.5, -0.5),
(-0.5, +0.5, -0.5),
(+0.5, +0.5, +0.5),
(+0.5, -0.5, +0.5),
(-0.5, -0.5, +0.5),
(-0.5, +0.5, +0.5),
])
quads = np.array([
(0, 1, 2, 3),
(4, 7, 6, 5),
(0, 4, 5, 1),
(1, 5, 6, 2),
(2, 6, 7, 3),
(4, 0, 3, 7),
])
return verts, quads
def add_geom_to_bmesh(bob, verts, faces, select=True):
"""
Add geometry to a bmesh object.
Parameters
----------
bob : bmesh.BMesh
The object to add the geometry to
verts : numpy.ndarray
3xN array of XYZ coordinates for N vertices to add.
quads : numpy.ndarray
Array of vertex indices for each face. Each entry holds the
indices of the vertices in the verts array the corresponding face
gets connected to.
select : Bool = True
Should the newly added vertices be selected? If yes, any other
vertex gets deselected
"""
bverts = bob.verts
bfaces = bob.faces
bverts_new = []
# Vertex indices need to be offset by the number of verts already
# present in the mesh before anything is done.
for i, v in enumerate(verts, start=len(bverts)):
# Add new vert and select it
bv = bverts.new(v)
bv.index = i
bv.select = select
bverts_new.append(bv)
bverts.ensure_lookup_table()
for f in faces:
# Push list of BVert objects to bfaces that make up face f
bfaces.new([bverts_new[v_idx] for v_idx in f])
if select:
bob.select_flush(True)
def add_box_to_scene(
context,
location=np.zeros(3),
rotation=np.zeros(3),
size=np.ones(3),
name='Box'):
"""
Add a box mesh to a given context.
Parameters
----------
context : bpy.context
Blender context to add the box to
location : numpy.ndarray = (0, 0, 0)
World location of the box
rotation : numpy.ndarray = (0, 0, 0)
World rotation of the box in Euler angles
size : numpy.ndarray = (1, 1, 1)
Length, height, and depth of the box, respectively
name : String
Name of the box
"""
bob = bm.new()
verts, faces = get_unit_cube()
add_geom_to_bmesh(bob, verts, faces)
mesh = bpy.data.meshes.new(name)
bob.to_mesh(mesh)
mesh.update()
# Add the mesh as an object into the scene
ob = object_utils.object_data_add(context, mesh)
mat = make_transf_mat(location, rotation, size)
ob.matrix_world = Matrix(mat)
def add_box_to_obj(
ob,
location=np.zeros(3),
rotation=np.zeros(3),
size=np.ones(3),
select=True,
deselect=True):
"""
Add a box mesh to a given Blender object.
Parameters
----------
ob : bpy.object
Blender object to add the box to
location : numpy.ndarray = (0, 0, 0)
World location of the box
rotation : numpy.ndarray = (0, 0, 0)
World rotation of the box in Euler angles
size : numpy.ndarray = (1, 1, 1)
Length, height, and depth of the box, respectively
select_new : Bool = True
Should the newly added vertices be selected?
deselect : Bool = True
Should already existing vertices be deselected?
"""
bob = bm.from_edit_mesh(ob.data)
# If box should be selected, deselect everything else
if deselect:
for v in bob.verts:
v.select = False
bob.select_flush(False)
verts, faces = get_unit_cube()
# First apply given box transform, then transform it from world to
# local space
mat = np.array(ob.matrix_world.inverted()) @ \
make_transf_mat(location, rotation, size)
verts = transf_pts(mat, verts)
add_geom_to_bmesh(bob, verts, faces, select)
bm.update_edit_mesh(ob.data)
def remove_selection(data, type='VERTS'):
"""
Delete selected geometry from an object
Parameters
----------
data : bpy.object.data
Blender object data to add the box to
type : String = 'VERTS'
Which geometry to delete: 'VERTS', 'EDGES', or 'FACES'?
"""
bob = bm.from_edit_mesh(data)
if type == 'EDGES':
geom = data.edges
bgeom = bob.edges
elif type == 'FACES':
geom = data.polygons
bgeom = bob.faces
else:
geom = data.vertices
bgeom = bob.verts
flags = get_scalars(geom)
to_del = np.array(bgeom)[flags]
bm.ops.delete(bob, geom=to_del, context=type)
bm.update_edit_mesh(data)
|
python
|
import time
time.perf_counter()
from game_mechanics import Player, Simulator
from strategies import make_turn_strat
import numpy as np
import matplotlib.pyplot as plt
# A bot plays Incan Gold in single-player mode.
# The bot leaves when the turn reaches the Turn Threshold value.
# The game is simulated many times for a range of Turn Threshold values.
# Plots the average score achieved by the bot for each Turn Threshold value.
# Set the number of simulations per Turn Threshold value.
games = 1000
# Set the lower and upper values (and step size) for the Turn Threshold range.
lower = 1
upper = 21
step = 1
# Set whether to print and plot data.
print_data = True
print_best = True
plot_data = True
# Set random seed if desired.
seed = None
# No need to modify below here.
turn_range = list(range(lower, upper, step))
score_max = []
score_ave = []
score_std = []
score_min = []
for turn_threshold in turn_range:
turn_strat = make_turn_strat(turn_threshold)
bot = Player("Bot", turn_strat)
players = [bot]
incan = Simulator(verbosity=0, manual=False, seed=seed)
incan.sim(games, players)
score_ave.append(sum(bot.log) / len(bot.log))
score_std.append(np.std(bot.log, ddof=1))
score_min.append(min(bot.log))
score_max.append(max(bot.log))
if print_data:
for index, turn in enumerate(turn_range):
print(f"Turns {turn}: Ave = {round(score_ave[index], 1)} +/- {round(score_std[index])}")
if print_best:
score_ave_sorted = sorted(zip(score_ave, turn_range), reverse=True)
print("\nHighest scoring Turn Threshold values:")
print(f"1st - Turns {score_ave_sorted[0][1]}: Ave = {round(score_ave_sorted[0][0], 1)}")
print(f"2nd - Turns {score_ave_sorted[1][1]}: Ave = {round(score_ave_sorted[1][0], 1)}")
print(f"3rd - Turns {score_ave_sorted[2][1]}: Ave = {round(score_ave_sorted[2][0], 1)}")
if plot_data:
plt.errorbar(turn_range, score_max, fmt="go-", label="max")
plt.errorbar(turn_range, score_ave, fmt="bo-", label="average +/- std")
plt.errorbar(turn_range, score_ave, yerr=score_std, fmt="bo")
plt.errorbar(turn_range, score_min, fmt="ro-", label="min")
plt.legend()
plt.xticks(turn_range)
plt.xlabel("Turn Threshold")
plt.ylabel("Score")
plt.title("Single-player score when waiting for Turn Threshold")
print("Program run time (seconds):", time.perf_counter())
if plot_data:
plt.show()
|
python
|
import logging
_logger = logging.getLogger(__name__)
import sys
#import random
import numpy as np
from .agent import Agent
from .ataristatebuffer import AtariStateBuffer
class AtariAgent(Agent):
""" This class is an implementation of an Atari agent.
The agent interacts with the given environment, organizes the trainig of the
network and sends information to the statistics.
Attributes:
buf (AtariStateBuffer): Simple buffer of sequence_length to concatenate frames to form the current state.
n_avail_actions (int): Number of available actions for the agent to select for a specific environment.
avail_actions (tuple[int]): The IDs of the availabe actions.
train_all (bool): Indicates if the network uses all possible actions as output or only the available ones.
random_starts (int): Perform max this number of dummy actions at beginning of an episode to produce more random game dynamics.
sequence_length (int): Determines how many frames form a state.
epsilon_start (float): Start value of the exploration rate (epsilon).
epsilon_end (float): Final value of the exploration rate (epsilon).
epsilon_decay_steps (int): Number of steps from epsilon_start to epsilon_end.
epsilon_test (float): Exploration rate (epsilon) during the test phase.
train_frequency (int): Perform training after this many game steps.
train_repeat (int): Number of times to sample minibatch during training.
Note:
More attributes of this class are defined in the base class Agent.
"""
def __init__(self, env, mem, net, args, rng, name = "AtariAgent"):
""" Initializes an agent for the Atari environment.
Args:
env (AtariEnv): The envirnoment in which the agent actuates.
mem (ReplayMemory): The replay memory to save the experiences.
net (Learner): Object of one of the Learner modules.
args (argparse.Namespace): All settings either with a default value or set via command line arguments.
rng (mtrand.RandomState): initialized Mersenne Twister pseudo-random number generator.
name (str): The name of the network object.
Note:
This function should always call the base class first to initialize
the common values for the networks.
"""
_logger.info("Initializing new object of type " + str(type(self).__name__))
super(AtariAgent, self).__init__(env, mem, net, args, rng, name)
self.buf = AtariStateBuffer(args)
self.n_avail_actions = self.env.n_avail_actions
self.avail_actions = self.env.avail_actions
self.train_all = args.train_all
self.random_starts = args.random_starts
self.sequence_length = args.sequence_length
self.epsilon_start = args.epsilon_start
self.epsilon_end = args.epsilon_end
self.epsilon_decay_steps = args.epsilon_decay_steps
self.epsilon_test = args.epsilon_test
self.train_frequency = args.train_frequency
self.train_repeat = args.train_repeat
_logger.debug("%s" % self)
def _do_dummy_steps(self):
""" Do some dummy steps at the beginning of each new episode for better randomization. """
_logger.debug("Restarting environment with a number of dummy actions")
self.env.reset_env()
for i in xrange(self.rng.randint(self.sequence_length, self.random_starts) + 1):
reward = self.env.step(0)
frame = self.env.get_current_frame()
terminal = self.env.is_state_terminal()
assert not terminal, "terminal state occurred during random initialization"
# add dummy states to buffer
self.buf.add(frame)
def _update_epsilon(self):
""" Update the exploration rate (epsilon) with regard to the decay rate
Returns:
epsilon (float): Upated epsilon value.
"""
_logger.debug("Updating exploration rate")
if self.n_steps_total < self.epsilon_decay_steps:
return self.epsilon_start - self.n_steps_total * (self.epsilon_start - self.epsilon_end) / self.epsilon_decay_steps
else:
return self.epsilon_end
def step(self, epsilon):
""" Perform one step in the environment, send the results to the buffer and update the stats.
Args:
epsilon (float): The current epsilon value.
"""
_logger.debug("Epsilon %f " % epsilon)
if self.rng.random_sample() < epsilon:
how = "random"
action = self.rng.choice(self.avail_actions)
else:
# if not random choose action with highest Q-value
how = "predicted"
state = self.buf.get_current_state()
qvalues = self.net.get_Q(state)
_logger.debug("qvalues shape = %s, type = %s" % (str(qvalues.shape),str(type(qvalues))))
assert len(qvalues.shape) == 1, "Qvalues not as expected -> " + qvalues.shape
if self.train_all:
qvalues = qvalues[np.array(self.avail_actions)]
action = self.avail_actions[np.argmax(qvalues)]
#_logger.debug("action %s <-- Qvalues: %s" % (str(action),str(qvalues)))
# perform the action
reward = self.env.step(action)
frame = self.env.get_current_frame()
self.buf.add(frame)
terminal = self.env.is_state_terminal()
_logger.debug("Observation: action=%s (%s), reward=%s, frame_dims=%s, just_lost_live=%s, terminal=%s" % (str(action), str(how), str(reward), str(frame.shape), str(self.env.just_lost_live), str(terminal) ))
# TODO: check if lost live to end episode
#if self.has_just_lost_live:
# restart the game if over
if terminal:
#_logger.debug("GAME OVER: reached terminal state --> restarting")
self._do_dummy_steps()
# call callback to record statistics
if self.callback:
self.callback.from_agent(reward, terminal, epsilon)
return action, reward, frame, terminal
def populate_mem(self, size):
""" Play a given number of steps to prefill the replay memory
Args:
size (int): The desired size of the memory initialization.
"""
_logger.debug("Playing without exploitation for %d steps " % size)
for i in xrange(size):
action, reward, frame, terminal = self.step(1)
self.mem.add(action, reward, frame, terminal)
def train(self, steps, epoch):
""" Performs a complete training epoch, filling the replay memory and calling the network train function.
Args:
steps (int): The number of steps.
epoch (int): The current epoch.
"""
_logger.debug("Training epoch %d for %d steps" % ((epoch + 1), steps))
for i in xrange(steps):
# perform game step
action, reward, frame, terminal = self.step(self._update_epsilon())
self.mem.add(action, reward, frame, terminal)
# train after every train_frequency steps
if self.mem.count > self.mem.batch_size and i % self.train_frequency == 0:
for j in xrange(self.train_repeat):
states, actions, rewards, followup_states, terminals = self.mem.get_minibatch()
if not self.train_all:
actions = np.asarray(
[np.where(self.avail_actions == action)[0][0] for action in actions],
dtype = np.uint8)
# train the network
minibatch = states, actions, rewards, followup_states, terminals
self.net.train(minibatch, epoch)
# increase number of training steps for epsilon decay
self.n_steps_total += 1
def test(self, steps, epoch):
""" Performs a complete testing epoch.
Args:
steps (int): The number of steps.
epoch (int): The current epoch.
"""
# just make sure there is sequence_length frames to form a state
_logger.debug("Testing epoch %d for %d steps" % ((epoch + 1), steps))
self._do_dummy_steps()
for i in xrange(steps):
self.step(self.epsilon_test)
def play(self, num_games):
""" Plays the game for a num_games times.
Args:
num_games (int): The number of games to play until stop.
"""
_logger.debug("Playing without exploration for %d games " % num_games)
self._do_dummy_steps()
for i in xrange(num_games):
terminal = False
while not terminal:
action, reward, frame, terminal = self.step(self.epsilon_test)
|
python
|
r"""
Optimizing noisy circuits with Cirq
===================================
.. meta::
:property="og:description": Learn how noise can affect the optimization and training of quantum computations.
:property="og:image": https://pennylane.ai/qml/_images/noisy_circuit_optimization_thumbnail.png
.. figure:: ../demonstrations/noisy_circuit_optimization/noisy_qubit.png
:align: center
:width: 90%
.. related::
pytorch_noise PyTorch and noisy devices
Until we have fault-tolerant quantum computers,
we will have to learn to live with noise. There are lots of exciting
ideas and algorithms in quantum computing and quantum machine learning,
but how well do they survive the reality of today's noisy devices?
Background
----------
Quantum pure-state simulators are great and readily available in
a number of quantum software packages.
They allow us to experiment, prototype, test, and validate algorithms
and research ideas---up to a certain number of qubits, at least.
But present-day hardware is not ideal. We're forced to confront
decoherence, bit flips, amplitude damping, and so on. Does the
presence of noise in near-term devices impact their use in,
for example,
:doc:`variational quantum algorithms </glossary/variational_circuit>`?
Won't our models, trained so carefully in simulators, fall apart
when we run on noisy devices?
In fact, there is some optimism that variational algorithms may be
the best type of algorithms on near-term devices, and could
have an in-built adaptability to noise that more rigid
textbook algorithms do not possess.
Variational algorithms are somewhat robust against the fact
that the device they are run on may not be ideal. Being variational
in nature, they can be tuned to "work around" noise to some extent.
Quantum machine learning leverages a lot of tools from its
classical counterpart. Fortunately, there is great evidence that
machine learning algorithms can not only be robust to noise, but
can even benefit from it!
Examples include the use of
`reduced-precision arithmetic in deep learning <https://dl.acm.org/doi/abs/10.5555/3045118.3045303>`_,
the strong performance of
`stochastic gradient descent <https://en.wikipedia.org/wiki/Stochastic_gradient_descent>`_,
and the use of "dropout" noise to
`prevent overfitting <https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf>`_.
With this evidence to motivate us, we can still hope to find,
extract, and work with the underlying quantum "signal"
that is influenced by a device's inherent noise.
Noisy circuits: creating a Bell state
-------------------------------------
Let's consider a simple quantum circuit which performs a standard
quantum information task: the creation of an entangled
state and the measurement of a
`Bell inequality <https://en.wikipedia.org/wiki/Bell%27s_theorem>`_
(also known as the
`CHSH inequality <https://en.wikipedia.org/wiki/CHSH_inequality>`_).
Since we'll be dealing with noise, we'll need to use a simulator
that supports noise and density-state representations of quantum
states (in contrast to many simulators, which use a pure-state
representation).
Fortunately, `Cirq <https://cirq.readthedocs.io>`_ provides mixed-state
simulators and noisy operations natively, so we can use the
`PennyLane-Cirq plugin <https://pennylane-cirq.readthedocs.io>`_
to carry out our noisy simulations.
"""
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
dev = qml.device("cirq.mixedsimulator", wires=2)
# CHSH observables
A1 = qml.PauliZ(0)
A2 = qml.PauliX(0)
B1 = qml.Hermitian(np.array([[1, 1], [1, -1]]) / np.sqrt(2), wires=1)
B2 = qml.Hermitian(np.array([[1, -1], [-1, -1]]) / np.sqrt(2), wires=1)
CHSH_observables = [A1 @ B1, A1 @ B2, A2 @ B1, A2 @ B2]
# subcircuit for creating an entangled pair of qubits
def bell_pair():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
# circuits for measuring each distinct observable
@qml.qnode(dev)
def measure_A1B1():
bell_pair()
return qml.expval(A1 @ B1)
@qml.qnode(dev)
def measure_A1B2():
bell_pair()
return qml.expval(A1 @ B2)
@qml.qnode(dev)
def measure_A2B1():
bell_pair()
return qml.expval(A2 @ B1)
@qml.qnode(dev)
def measure_A2B2():
bell_pair()
return qml.expval(A2 @ B2)
circuits = qml.QNodeCollection([measure_A1B1,
measure_A1B2,
measure_A2B1,
measure_A2B2])
# now we measure each circuit and construct the CHSH inequality
expvals = circuits()
# The CHSH operator is A1 @ B1 + A1 @ B2 + A2 @ B1 - A2 @ B2
CHSH_expval = np.sum(expvals[:3]) - expvals[3]
print(CHSH_expval)
##############################################################################
# The output here is :math:`2\sqrt{2}`, which is the maximal value of the
# CHSH inequality. States which have a value
# :math:`\langle CHSH \rangle \geq 2` can safely be considered
# "quantum".
#
# .. note:: In this situation "quantum" means that there is
# no `local hidden variable theory <https://en.wikipedia.org/wiki/Local_hidden-variable_theory>`_
# which could produce these measurement outcomes. It does not strictly
# mean the presence of entanglement.
#
# Now let's turn up the noise! 📢 📢 📢
#
# Cirq provides a number of noisy channels that are not part of
# PennyLane core. This is no issue, as the
# `PennyLane-Cirq <https://pennylane-cirq.readthedocs.io>`_
# plugin provides these and allows them to be used directly in PennyLane
# circuit declarations.
from pennylane_cirq import ops as cirq_ops
# Note that the 'Operation' op is a generic base class
# from PennyLane core.
# All other ops are provided by Cirq.
available_ops = [op for op in dir(cirq_ops) if not op.startswith('_')]
print("\n".join(available_ops))
##############################################################################
# PennyLane operations and external framework-specific operations can be
# interwoven freely in circuits that use that plugin's device
# for execution.
# In this case, the Cirq-provided channels can be used with
# Cirq's mixed-state simulator.
#
# We'll use the ``BitFlip`` channel, which has the effect of
# randomly flipping the qubits in the computational basis.
noise_vals = np.linspace(0, 1, 25)
CHSH_vals = []
noisy_expvals = []
for p in noise_vals:
# we overwrite the bell_pair() subcircuit to add
# extra noisy channels after the entangled state is created
def bell_pair():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
cirq_ops.BitFlip(p, wires=0)
cirq_ops.BitFlip(p, wires=1)
# measuring the circuits will now use the new noisy bell_pair() function
expvals = circuits()
noisy_expvals.append(expvals)
noisy_expvals = np.array(noisy_expvals)
CHSH_expvals = np.sum(noisy_expvals[:,:3], axis=1) - noisy_expvals[:,3]
# Plot the individual observables
plt.plot(noise_vals, noisy_expvals[:, 0], 'D',
label = r"$\hat{A1}\otimes \hat{B1}$", markersize=5)
plt.plot(noise_vals, noisy_expvals[:, 1], 'x',
label = r"$\hat{A1}\otimes \hat{B2}$", markersize=12)
plt.plot(noise_vals, noisy_expvals[:, 2], '+',
label = r"$\hat{A2}\otimes \hat{B1}$", markersize=10)
plt.plot(noise_vals, noisy_expvals[:, 3], 'v',
label = r"$\hat{A2}\otimes \hat{B2}$", markersize=10)
plt.xlabel('Noise parameter')
plt.ylabel(r'Expectation value $\langle \hat{A}_i\otimes\hat{B}_j\rangle$')
plt.legend()
plt.show()
##############################################################################
# By adding the bit-flip noise, we have degraded the value of the
# CHSH observable. The first two observables
# :math:`\hat{A}_1\otimes \hat{B}_1`
# and :math:`\hat{A}_1\otimes \hat{B}_2` are sensitive to this
# noise parameter. Their value is weakened when the noise parameter is not
# 0 or 1 (note that the the CHSH operator is symmetric with
# respect to bit flips).
#
# The latter two observables, on the other hand, are seemingly
# unaffected by the noise at all.
#
# We can see that even when noise is present, there may still be subspaces
# or observables which are minimally affected or unaffected.
# This gives us some hope that variational algorithms can learn
# to find and exploit such noise-free substructures on otherwise
# noisy devices.
#
# We can also plot the CHSH observable in the noisy case. Remember,
# values greater than 2 can safely be considered "quantum".
plt.plot(noise_vals, CHSH_expvals, label="CHSH")
plt.plot(noise_vals, 2 * np.ones_like(noise_vals),
label="Quantum-classical boundary")
plt.xlabel('Noise parameter')
plt.ylabel('CHSH Expectation value')
plt.legend()
plt.show()
##############################################################################
# Too much noise (around 0.2 in this example), and we lose the
# quantumness we created in our circuit. But if we only have a little
# noise, the quantumness undeniably remains. So there is still hope
# that quantum algorithms can do something useful, even on noisy
# near-term devices, so long as the noise is not high.
#
# .. note::
#
# In Google's quantum supremacy paper [#arute2019]_,
# they were able to show that some
# small signature of quantumness remained in their computations,
# even after a deep many-qubit noisy circuit was executed.
##############################################################################
# Optimizing noisy circuits
# -------------------------
#
# Now, how does noise affect the ability to optimize or train a
# variational circuit?
#
# Let's consider an analog of the basic
# :doc:`qubit rotation tutorial </demos/tutorial_qubit_rotation>`,
# but where we add an extra noise channel after the gates.
#
# .. note:: We model the noise process as the application of ideal noise-free
# gates, followed by the action of a noisy channel. This is a common
# technique for modelling noise, but may not be appropriate for all
# situations.
@qml.qnode(dev)
def circuit(gate_params, noise_param=0.0):
qml.RX(gate_params[0], wires=0)
qml.RY(gate_params[1], wires=0)
cirq_ops.Depolarize(noise_param, wires=0)
return qml.expval(qml.PauliZ(0))
gate_pars = [0.54, 0.12]
print("Expectation value:", circuit(gate_pars))
##############################################################################
# In this case, the depolarizing channel degrades
# the qubit's density matrix :math:`\rho` towards the state
#
# .. math::
#
# \rho' = \tfrac{1}{3}\left[X\rho X + Y\rho Y + Z\rho Z\right]
#
# (at the value :math:`p=\frac{3}{4}`, it passes through the
# maximally mixed state).
# We can see this in our circuit by looking at how the final
# :class:`~pennylane.ops.PauliZ` expectation value changes as
# a function of the noise strength.
noise_vals = np.linspace(0., 1., 20)
expvals = [circuit(gate_pars, noise_param=p) for p in noise_vals]
plt.plot(noise_vals, expvals, label="Expectation value")
plt.plot(noise_vals, np.ones_like(noise_vals), '--', label="Highest possible")
plt.plot(noise_vals, -np.ones_like(noise_vals), '--', label="Lowest possible")
plt.ylabel(r"Expectation value $\langle \hat{Z} \rangle$")
plt.xlabel(r"Noise strength $p$")
plt.legend()
plt.show()
##############################################################################
# Let's fix the noise parameter and see how the noise affects the
# optimization of our circuit. The goal is the same as the
# :doc:`qubit rotation tutorial </demos/tutorial_qubit_rotation>`,
# i.e., to tune the qubit state until it has a ``PauliZ`` expectation value
# of :math:`-1` (the lowest possible).
# declare the cost functions to be optimized
def cost(x):
return circuit(x, noise_param=0.0)
def noisy_cost(x):
return circuit(x, noise_param=0.3)
# initialize the optimizer
opt = qml.GradientDescentOptimizer(stepsize=0.4)
# set the number of steps
steps = 100
# set the initial parameter values
init_params = np.array([0.011, 0.012])
noisy_circuit_params = init_params
params = init_params
for i in range(steps):
# update the circuit parameters
# we can optimize both in the same training loop
params = opt.step(cost, params)
noisy_circuit_params = opt.step(noisy_cost, noisy_circuit_params)
if (i + 1) % 5 == 0:
print("Step {:5d}. Cost: {: .7f}; Noisy Cost: {: .7f}"
.format(i + 1,
cost(params),
noisy_cost(noisy_circuit_params)))
print("\nOptimized rotation angles (noise-free case):")
print("({: .7f}, {: .7f})".format(*params))
print("Optimized rotation angles (noisy case):")
print("({: .7f}, {: .7f})".format(*noisy_circuit_params))
##############################################################################
# There are a couple interesting observations here:
#
# i) The noisy circuit isn't able to achieve the same final
# cost function value as the ideal circuit. This is because
# the noise causes the state to become irreversibly mixed.
# Mixed states can't achieve the same extremal expectation values
# as pure states.
#
# ii) However, both circuits still converge to
# the *same parameter values* :math:`(0,\pi)`, despite having
# different final states.
#
# It could have been the case that noisy devices irreparably
# damage the optimization of variational circuits, steering us
# towards parameter values which are not at all useful.
# Luckily, at least for the simple example above, this is not the case.
# *Optimizations on noisy devices can still lead to similar parameter
# values as when we run on ideal devices.*
##############################################################################
# Understanding the effect of noisy channels
# ------------------------------------------
#
# Let's dig a bit into the underlying quantum information theory
# to understand better what's happening [#meyer2020]_.
# Expectation values of :doc:`variational circuits </glossary/variational_circuit>`,
# like the one we are measuring, are composed of three pieces:
#
# i) an initial quantum state :math:`\rho` (usually the zero state);
# ii) a parameterized unitary transformation :math:`U(\theta)`); and
# iii) measurement of a final observable :math:`\hat{B}`.
#
# The equation for the expectation value is given by the
# `Born rule <https://en.wikipedia.org/wiki/Born_rule>`_:
#
# .. math::
#
# \langle \hat{B} \rangle (\theta) =
# \mathrm{Tr}(\hat{B}U(\theta)\rho U^\dagger(\theta)).
#
# When optimizing, we can compute gradients of many common gates
# using the :doc:`parameter-shift rule </glossary/parameter_shift>`:
#
# .. math::
#
# \nabla_\theta\langle \hat{B} \rangle(\theta)
# = \frac{1}{2}
# \left[
# \langle \hat{B} \rangle\left(\theta + \frac{\pi}{2}\right)
# - \langle \hat{B} \rangle\left(\theta - \frac{\pi}{2}\right)
# \right].
#
# In our example, the parametrized unitary :math:`U(\theta)` is split into two gates,
# :math:`U = U_2 U_1`,
# where :math:`U_1=R_X` and :math:`U_1=R_Y`, and each takes an independent
# parameter :math:`\theta_i`.
#
# What happens when we apply a
# noisy channel :math:`\Lambda` after the gates? In this case,
# the expectation value is now taken with
# respect to the noisy circuit:
#
# .. math::
#
# \langle \hat{B} \rangle (\theta) =
# \mathrm{Tr}\left(\hat{B}\Lambda\left[
# U(\theta)\rho U^\dagger(\theta)
# \right]\right).
#
# Thus, we can treat it as the expectation value of the same
# observable, but with respect to a different state
# :math:`\rho' = \Lambda\left[U(\theta)\rho U^\dagger(\theta)\right]`.
#
# Alternatively, using the Heisenberg picture, we can transfer the channel
# :math:`\Lambda` acting on the state :math:`U(\theta)\rho U^\dagger(\theta)`
# into the *adjoint channel* :math:`\Lambda^\dagger` acting on the
# observable :math:`\hat{B}`, transforming it to a new observable
# :math:`\hat{B} = \Lambda^\dagger[\hat{B}]=\hat{B}'`.
#
# With the channel present, the expectation value can be interpreted
# as if we had the same variational state, but measured a different
# observable:
#
# .. math::
#
# \langle \hat{B} \rangle (\theta) =
# \mathrm{Tr}(\hat{B}'U(\theta)\rho U^\dagger(\theta)) =
# \langle \hat{B}' \rangle (\theta).
#
# This has immediate consequences for the parameter-shift rule. With
# the channel present, we have simply
#
# .. math::
#
# \nabla_\theta\langle \hat{B} \rangle(\theta)
# = \frac{1}{2}
# \left[
# \langle \hat{B}' \rangle\left(\theta + \frac{\pi}{2}\right)
# - \langle \hat{B}' \rangle\left(\theta - \frac{\pi}{2}\right)
# \right].
#
# In other words, the parameter-shift rule continues to hold for all
# gates, even when we have additional noise!
#
# .. note:: In the above derivation, we implicitly assumed that the channel
# does not depend on the variational circuit's parameters. If the
# channel depended on the particular state, or if it depended
# on the parameters :math:`\theta`, we would need to be more careful.
#
#
# Let's confirm the above derivation with an example.
angles = np.linspace(0, 2 * np.pi, 50)
theta2 = np.pi / 4
def param_shift(theta1):
return 0.5 * (noisy_cost([theta1 + np.pi / 2, theta2]) - \
noisy_cost([theta1 - np.pi / 2, theta2]))
noisy_expvals = [noisy_cost([theta1, theta2]) for theta1 in angles]
noisy_param_shift = [param_shift(theta1) for theta1 in angles]
plt.plot(angles, noisy_expvals,
label="Expectation value") # looks like 0.4 * cos(phi)
plt.plot(angles, noisy_param_shift,
label="Parameter-shift value") # looks like -0.4 * sin(phi)
plt.ylabel(r"Expectation value $\langle \hat{Z} \rangle$")
plt.xlabel(r"Angle $\theta_1$")
plt.legend()
plt.show()
##############################################################################
# By inspecting the two curves, we can see that the parameter-shift rule
# gives the correct gradient of the expectation value, even with the presence
# of the noisy channel!
#
# In this example, the influence of the channel is to
# attenuate the maximal amplitude that the qubit state can achieve
# (:math:`\approx 0.4`). But even though the qubit's amplitude is attenuated,
# the gradient computed by the parameter-shift rule still "points in the
# right direction".
#
# This backs up the observation we made earlier that
# the result of the optimization gave the correct values for the angle
# parameters, but the value of the final cost function was lower than
# the noise-free case.
#
##############################################################################
# Interpreting noisy circuit optimizations
# ----------------------------------------
#
# Despite the observations that we can compute gradients for
# noisy channels, and that optimization may lead to the same parameter
# values for both noise-free and noisy circuits, we must still remain
# cautious in how we interpret the results.
#
# We can evaluate the correct gradient for the expectation value
#
# .. math::
#
# \langle \hat{B} \rangle =
# \mathrm{Tr}\left(\hat{B}\Lambda\left[
# U(\theta)\rho U^\dagger(\theta)
# \right]\right),
#
# but, because the noisy channel is present, *this expectation value may not
# reflect the actual expectation value we wanted to compute*. This is
# important to keep in mind for certain algorithms that have a physical
# interpretation for the variational circuit.
#
# For example, in the
# :doc:`variational quantum eigensolver </demos/tutorial_vqe>`, we
# want to find the ground-state energy of a physical system.
# If there is an appreciable amount of noise present,
# the state we are optimizing will necessarily become mixed, and
# we should be careful interpreting the optimum value as the exact
# ground-state energy.
##############################################################################
# References
# ----------
#
# .. [#arute2019]
#
# Frank Arute et al. "Quantum supremacy using a programmable
# superconducting processor."
# Nature, 574(7779), 505-510.
#
# .. [#meyer2020]
#
# Johannes Jakob Meyer, Johannes Borregaard, and Jens Eisert.
# "A variational toolbox for quantum multi-parameter estimation."
# `arXiv:2006.06303
# <https://arxiv.org/abs/2006.06303>`__, 2020.
#
|
python
|
#!/usr/bin/env python
# coding=utf-8
import argparse
import os
import re
#功能:输入一个只包含tree文件的目录,不加“/”,以及输入一个label map关系表,原来的标签必须非冗余,即不能一对多映射。然后在当前目录输出所有relabel后的tree文件。
#获取树目录下所有文件名
parser=argparse.ArgumentParser(description = "功能:批量修改nwk文件的label注释。输入一个包含tree文件的目录,和一个tree中老label和要替换的label的对应两列表。在当前目录输出relabel后的各个tree文件")
parser.add_argument("-d","--dir",metavar="<str>",
required=True,action="store",dest="input_dir",
help="一个只包含要修改的tree文件的目录,必须是绝对路径,最后面没有“/”")
parser.add_argument("-t","--table",metavar="<file>",
required=True,action="store",dest="map_dir",
help="一个两列表,第一列是树文件中原始的label名称,第二列是想修改为的label名称,中间用tab隔开。前后一一对应,且第一列不能一对多,可以直接由excel复制过来")
args = parser.parse_args()
input_dir = args.input_dir
map_dir = args.map_dir
#input_dir = "/hwfssz5/ST_INFECTION/Salmonella/liqiwen/bianshengzhe/liliqiang/bianshengzhe/VP1pipeexam/10.41K_analyse/s4.orthofinder_result_analyse/s1.over_group_gene_tree_change_label/Recon_Gene_Trees"
tree_file_list = os.listdir(input_dir)
#读入raw_label和new_label映射表为map文件
#map_dir = "/hwfssz5/ST_INFECTION/Salmonella/liqiwen/bianshengzhe/liliqiang/bianshengzhe/VP1pipeexam/10.41K_analyse/s4.orthofinder_result_analyse/s1.over_group_gene_tree_change_label/raw_treelabel_new.txt"
with open(map_dir,"r") as map_dir_f:
map_dict = {line.strip().split("%")[0]:line.strip().split("%")[1] for line in map_dir_f}
print map_dict
#ralabel算法核心:1.粗暴法,直接str.replace方法,先搜寻是否有一样的label名字,如果有匹配,就替换为对应的新name。
def relabel_tree(file_dir):
with open(file_dir,"r") as raw_tree_f:#可以正确读取原来树文件。
raw_tree_str = raw_tree_f.read()
new_tree_str=raw_tree_str
for label in map_dict.keys():
new_tree_str=new_tree_str.replace(label,map_dict[label])
print new_tree_str
out_file_name= file_dir.split("/") [-1].split(".")[0]+"_relabel.txt"
with open(out_file_name,"w") as f:
print >> f,new_tree_str
for i in tree_file_list:
file_dir = input_dir+"/"+i
relabel_tree(file_dir)
|
python
|
from os import path
from sys import modules
from fabric.api import sudo
from fabric.contrib.files import upload_template
from pkg_resources import resource_filename
def restart_systemd(service_name):
sudo("systemctl daemon-reload")
if sudo(
"systemctl status -q {service_name} --no-pager --full".format(
service_name=service_name
),
warn_only=True,
).failed:
sudo(
"systemctl start -q {service_name} --no-pager --full".format(
service_name=service_name
)
)
else:
sudo(
"systemctl stop -q {service_name} --no-pager --full".format(
service_name=service_name
)
)
sudo(
"systemctl start -q {service_name} --no-pager --full".format(
service_name=service_name
)
)
return sudo(
"systemctl status {service_name} --no-pager --full".format(
service_name=service_name
)
)
def install_upgrade_service(service_name, context, conf_local_filepath=None):
conf_local_filepath = conf_local_filepath or resource_filename(
modules[__name__].__name__.rpartition(".")[0].rpartition(".")[0],
path.join("configs", "systemd.conf"),
)
conf_remote_filename = "/lib/systemd/system/{service_name}.service".format(
service_name=service_name
)
upload_template(
conf_local_filepath,
conf_remote_filename,
context={
"ExecStart": context["ExecStart"],
"Environments": context["Environments"],
"WorkingDirectory": context["WorkingDirectory"],
"User": context["User"],
"Group": context["Group"],
"service_name": service_name,
},
use_sudo=True,
backup=False,
)
return restart_systemd(service_name)
def disable_service(service):
if sudo(
"systemctl is-active --quiet {service}".format(service=service), warn_only=True
).succeeded:
sudo("systemctl stop {service}".format(service=service))
sudo("sudo systemctl disable {service}".format(service=service))
|
python
|
from machine import Pin
import utime
from ssd1306 import SSD1306_I2C
#I/O Configuration
led = Pin(28, Pin.OUT)
onboard_led = Pin(25, Pin.OUT)
button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
#Set Initial Conditions
led.low()
onboard_led.high()
fast_blink = False
# attach the interrupt to the buttonPin
def alert(pin):
global fast_blink
#avoid rebounds
utime.sleep(0.25)
if button.value() == 1:
if fast_blink:
fast_blink = False
else:
fast_blink = True
print("Se ha pulsado el botón")
button.irq(trigger = Pin.IRQ_RISING , handler = alert)
# Main Loop
while True:
led.toggle()
onboard_led.toggle()
if fast_blink:
utime.sleep(0.25)
else:
utime.sleep(1)
|
python
|
import os
from setuptools import find_packages, setup
with open(os.path.join('.', 'VERSION')) as version_file:
version = version_file.read().strip()
setup(
name='mavelp',
version=version,
long_description=open('README.md').read(),
package_dir={'': 'src'},
packages=find_packages(where='src'),
)
|
python
|
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime,
QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase,
QIcon, QKeySequence, QLinearGradient, QPalette, QPainter, QPixmap, QRadialGradient)
from PySide2.QtWidgets import *
from selenium import webdriver
import sys
import login
from functions import resource_path
# Login Screen
from Ui_LoginScreen import Ui_LoginScreen
from main_screen import MainScreen
class Main(QMainWindow):
# To know if showPassword is on or off. 0 = off | 1 = on
passwordStatus = 0
def __init__(self):
QMainWindow.__init__(self)
self.ui = Ui_LoginScreen()
self.ui.setupUi(self)
# Remove title bar
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
# Drop shadow effect
self.shadow = QGraphicsDropShadowEffect(self)
self.shadow.setBlurRadius(30)
self.shadow.setXOffset(0)
self.shadow.setYOffset(0)
self.shadow.setColor(QColor(70, 50, 30, 80))
self.ui.dropShadowFrame.setGraphicsEffect(self.shadow)
# adding functions to GUI objects
self.ui.minimizeBtn.clicked.connect(lambda: self.showMinimized())
self.ui.closeBtn.clicked.connect(lambda: self.close())
self.ui.loginBtn.clicked.connect(lambda: self.checkLogin())
self.ui.showPass.clicked.connect(self.showPassword)
def moveWindow(e):
# Detect if the window is normal size
if not self.isMaximized(): # Not maximized
# Move window only when window is normal size
# if left mouse button is clicked (Only accept left mouse button clicks)
if e.buttons() == Qt.LeftButton:
# Move window
self.move(self.pos() + e.globalPos() - self.clickPosition)
self.clickPosition = e.globalPos()
e.accept()
self.ui.dropShadowFrame.mouseMoveEvent = moveWindow
def mousePressEvent(self, event):
self.clickPosition = event.globalPos()
def showPassword(self):
icon = QIcon()
if self.passwordStatus == 0:
self.ui.passwordTxt.setEchoMode(QLineEdit.Normal)
icon.addFile(resource_path("assets/hide_pass.png"),
QSize(), QIcon.Normal, QIcon.On)
self.passwordStatus = 1
else:
self.ui.passwordTxt.setEchoMode(QLineEdit.Password)
icon.addFile(resource_path('assets/show_pass.png'),
QSize(), QIcon.Normal, QIcon.On)
self.passwordStatus = 0
self.ui.showPass.setIcon(icon)
def checkLogin(self):
username = self.ui.usernameTxt.text()
password = self.ui.passwordTxt.text()
if len(username.strip()) == 0 or len(password.strip()) == 0:
QMessageBox.information(self, 'Advice',
"You forgot to write your account info",
QMessageBox.Ok)
self.ui.usernameTxt.setFocus()
else:
self.signin()
def signin(self):
username = self.ui.usernameTxt.text()
password = self.ui.passwordTxt.text()
try:
driver = webdriver.Chrome(resource_path('chromedriver.exe'))
l = login.Login(driver, username, password)
l.signIn()
# * we show the Main Screen and close the Login Screen
self.mainScreen = MainScreen(username, driver)
self.mainScreen.show()
self.close()
except Exception as e:
print(e)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Main()
window.show()
app.installEventFilter(window)
sys.exit(app.exec_())
|
python
|
__author__ = 'Thomas Kountis'
|
python
|
# -*- coding: utf-8 -*-
"""
* Created by PyCharm.
* Project: catalog
* Author name: Iraquitan Cordeiro Filho
* Author login: pma007
* File: api
* Date: 2/26/16
* Time: 11:26
* To change this template use File | Settings | File Templates.
"""
from flask import Blueprint, jsonify
from catalog.models import Category, Item
# Define api Blueprint for JSON endpoints
api = Blueprint('api', __name__)
@api.route('/catalog.json')
def catalog_api():
categories = Category.query.all()
all_result = []
for category in categories:
items = Item.query.filter_by(category_id=category.id).all()
result = category.serialize
result['Item'] = [i.serialize for i in items]
all_result.append(result)
return jsonify(Category=all_result)
@api.route('/category/<string:category_slug>.json')
def category_api(category_slug):
category = Category.query.filter_by(slugfield=category_slug).first_or_404()
return jsonify(category=category.serialize)
@api.route('/category/<string:category_slug>/items.json')
def category_items_api(category_slug):
category = Category.query.filter_by(slugfield=category_slug).first_or_404()
items = Item.query.filter_by(category_id=category.id).all()
result = category.serialize
result['item'] = [i.serialize for i in items]
return jsonify(category=result)
@api.route('/item/<string:item_slug>.json')
def item_api(item_slug):
item = Item.query.filter_by(slugfield=item_slug).first_or_404()
return jsonify(item=item.serialize)
|
python
|
#
# copied from
#
# https://scikit-learn.org/stable/auto_examples/covariance/plot_lw_vs_oas.html#sphx-glr-auto-examples-covariance-plot-lw-vs-oas-py
#
#
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, cholesky
from sklearn.covariance import LedoitWolf, OAS
np.random.seed(0)
n_features = 100
# simulation covariance matrix (AR(1) process)
r = 0.1
real_cov = toeplitz(r ** np.arange(n_features))
coloring_matrix = cholesky(real_cov)
n_samples_range = np.arange(6, 31, 1)
repeat = 100
lw_mse = np.zeros((n_samples_range.size, repeat))
oa_mse = np.zeros((n_samples_range.size, repeat))
lw_shrinkage = np.zeros((n_samples_range.size, repeat))
oa_shrinkage = np.zeros((n_samples_range.size, repeat))
for i, n_samples in enumerate(n_samples_range):
for j in range(repeat):
X = np.dot(
np.random.normal(size=(n_samples, n_features)), coloring_matrix.T)
lw = LedoitWolf(store_precision=False, assume_centered=True)
lw.fit(X)
lw_mse[i, j] = lw.error_norm(real_cov, scaling=False)
lw_shrinkage[i, j] = lw.shrinkage_
oa = OAS(store_precision=False, assume_centered=True)
oa.fit(X)
oa_mse[i, j] = oa.error_norm(real_cov, scaling=False)
oa_shrinkage[i, j] = oa.shrinkage_
# plot MSE
plt.subplot(2, 1, 1)
plt.errorbar(n_samples_range, lw_mse.mean(1), yerr=lw_mse.std(1),
label='Ledoit-Wolf', color='navy', lw=2)
plt.errorbar(n_samples_range, oa_mse.mean(1), yerr=oa_mse.std(1),
label='OAS', color='darkorange', lw=2)
plt.ylabel("Squared error")
plt.legend(loc="upper right")
plt.title("Comparison of covariance estimators")
plt.xlim(5, 31)
# plot shrinkage coefficient
plt.subplot(2, 1, 2)
plt.errorbar(n_samples_range, lw_shrinkage.mean(1), yerr=lw_shrinkage.std(1),
label='Ledoit-Wolf', color='navy', lw=2)
plt.errorbar(n_samples_range, oa_shrinkage.mean(1), yerr=oa_shrinkage.std(1),
label='OAS', color='darkorange', lw=2)
plt.xlabel("n_samples")
plt.ylabel("Shrinkage")
plt.legend(loc="lower right")
plt.ylim(plt.ylim()[0], 1. + (plt.ylim()[1] - plt.ylim()[0]) / 10.)
plt.xlim(5, 31)
plt.show()
resp = input('Did you see an image? ')
print('Please close the image')
if not resp.lower().startswith('y'):
raise Exception('scikit-learn tests failed.')
|
python
|
import json
import logging
import time
import datetime as dt
from bitbot import services, strategy
import pandas as pd
class Bot:
"""
A trading bot that executes a certain strategy
Attributes:
config (dict[str, any]): the loaded configuration
next_action (services.OrderDirection): the next action; wether to sell or to buy
history (pandas.DataFrame): a history of all transactions the bot has made
Args:
config (str or dict[str,any]): the configuration that the bot should use
"""
def __init__(self,name: str, config: str or dict[str, any]):
if isinstance(config, str):
with open(config, encoding="utf8") as f:
self.config = json.load(f)
else:
self.config = config
self.name = name
# initialize service class from imports
self.service : services.ServiceInterface = getattr(services, self.config["service"])()
# initialze strategy class from imports
self.strat : strategy.TradingStrategyInterface = getattr(strategy, self.config["strat"]["name"])(self.service, self.config["strat"], self.config["market"])
self.history = pd.DataFrame()
def apply_tas(self, candles: pd.DataFrame) -> pd.DataFrame:
"""
Method to apply technical indicators specified in the template
Args:
candles (pd.DataFrame): the candles to apply the technical indicators to
Returns:
pd.DataFrame
"""
if "ta_params" not in self.config["strat"]:
return candles
cfg = self.config["strat"]["ta_params"]
if "macd" in cfg:
candles = self.strat.calc_macd(candles, **cfg["macd"])
if "rsi" in cfg:
candles = self.strat.calc_rsi(candles, **cfg["rsi"])
if "roc" in cfg:
candles = self.strat.calc_roc(candles, **cfg["roc"])
return candles
def log(self, msg: str):
logging.info(f"* {self.name}: {msg}")
def warn(self, msg: str):
logging.warning(f"* {self.name}: {msg}")
def err(self, msg: str):
logging.error(f"* {self.name}: {msg}")
def run(self):
"""
Method to start the Bot. Runs in an endless loop and alternates between buying and selling, based on the signal
generated by the strategy used. Always executes market orders. Sleeps for the ``update_interval`` Seconds at the end of
every loop iteration.
Saves buying time, buying proceeds and order direction in an attribute called ``history``
"""
while True:
last_price = self.service.get_market_ticker(self.config["market"])["lastTradeRate"]
self.log(f"## {self.config['market']} ## Last Price: {last_price}")
available_balance = self.service.get_available_balance(self.config["market"].split("-")[0])
candles = self.service.get_candles(self.config["market"],
self.service.determine_candle_interval(dt.timedelta(minutes=self.config["lookback"])))
candles = candles.rename(columns={"startsAt": "time"})
candles["rsi"] = self.strat.calc_rsi(candles)
candles = self.strat.calc_macd(candles)
signal = self.strat.generate_signal(candles, self.log)
if signal != services.OrderDirection.NONE:
order = services.Order(self.config["market"], signal, services.OrderType.MARKET,
services.TimeInForce.IMMEDIATE_OR_CANCEL,
self.config["quantity"] if self.config["quantity"] <= available_balance else available_balance)
try:
res = self.service.place_order(order)
except Exception as e:
logging.error(f"{e.__class__.__name__}: {str(e)}")
time.sleep(self.config["update_interval"])
continue
if res["status"] != "CLOSED":
self.warn(f'Could not place Order: Status: {res["status"]}')
else:
self.log(f'Placed Order: {res}')
self.history = self.history.append({"time": dt.datetime.utcnow(), "value": res["proceeds"], "direction": self.next_action}, ignore_index=True)
self.next_action = services.OrderDirection.SELL if self.next_action == services.OrderDirection.BUY else services.OrderDirection.BUY
time.sleep(self.config["update_interval"])
|
python
|
import rospy
import sys
import tf
import tf2_ros
import geometry_msgs.msg
if __name__ == '__main__':
if len(sys.argv) < 8:
rospy.logerr('Invalid number of parameters\nusage: '
'./static_turtle_tf2_broadcaster.py '
'child_frame_name x y z roll pitch yaw')
sys.exit(0);
else:
if sys.argv[1] == 'world':
rospy.logerr('Your static turtle name cannot be "world"')
sys.exit(0);
rospy.init_node('my_static_tf2_broadcaster')
broadcaster = tf2_ros.StaticTransformBroadcaster()
static_transformStamped = geometry_msgs.msg.TransformStamped()
static_transformStamped.header.stamp = rospy.Time.now()
static_transformStamped.header.frame_id = "world"
static_transformStamped.child_frame_id = sys.argv[1]
static_transformStamped.transform.translation.x = float(sys.argv[2])
static_transformStamped.transform.translation.y = float(sys.argv[3])
static_transformStamped.transform.translation.z = float(sys.argv[4])
quat = tf.transformations.quaternion_from_euler(float(sys.argv[5]), float(sys.argv[6]), float(sys.argv[7]))
static_transformStamped.transform.rotation.x = quat[0]
static_transformStamped.transform.rotation.y = quat[1]
static_transformStamped.transform.rotation.z = quat[2]
static_transformStamped.transform.rotation.w = quat[3]
broadcaster.sendTransform(static_transformStamped)
rospy.spin()
|
python
|
# Generated by Django 3.2.12 on 2022-03-27 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20220328_0004'),
]
operations = [
migrations.RenameField(
model_name='predication',
old_name='avg_vocal_fundamental_frequency',
new_name='mdvp_jitter',
),
migrations.RenameField(
model_name='predication',
old_name='jitter',
new_name='mdvp_shimmer',
),
migrations.RemoveField(
model_name='predication',
name='max_vocal_fundamental_frequency',
),
migrations.RemoveField(
model_name='predication',
name='min_vocal_fundamental_frequency',
),
migrations.RemoveField(
model_name='predication',
name='pitch',
),
migrations.RemoveField(
model_name='predication',
name='shimmer',
),
migrations.AddField(
model_name='predication',
name='mdvp_fhi',
field=models.IntegerField(default=0, help_text='Minimum Vocal Fundamental Frequency'),
),
migrations.AddField(
model_name='predication',
name='mdvp_flo',
field=models.IntegerField(default=0, help_text='Maximum Vocal Fundamental Frequency'),
),
migrations.AddField(
model_name='predication',
name='mdvp_fo',
field=models.IntegerField(default=0, help_text='Average Vocal Fundamental Frequency'),
),
]
|
python
|
""" Module for time series classification using Bayesian Hidden Markov Model
-----------------
Version : 0.2
Date : December, 11th 2019
Authors : Mehdi Bennaceur
Phase : Development
Contact : _
Github : https://github.com/DatenBiene/Bayesian_Time_Series_Classification
"""
__version__ = "0.2"
__date__ = "December, 11th 2019"
__author__ = 'Mehdi Bennaceur'
__github__ = "https://github.com/DatenBiene/Bayesian_Time_Series_Classification"
from Bayesian_hmm.bayes_hmm import bayesian_hmm
from Bayesian_hmm.simulate_data import generate_markov_seq, generate_transtion_matrix, generate_series, generate_samples
from Bayesian_hmm.utils import assign_classes, build_hmm_models
__all__ = ["bayesian_hmm", "generate_markov_seq", "generate_transtion_matrix", "generate_series", "generate_samples",
"assign_classes", "build_hmm_models"]
|
python
|
# Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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.
from netforce.model import Model, fields
class TaxComponent(Model):
_name = "account.tax.component"
_fields = {
"tax_rate_id": fields.Many2One("account.tax.rate", "Tax Rate", required=True, on_delete="cascade"),
"name": fields.Char("Name", required=True),
"compound": fields.Boolean("Compound"),
"rate": fields.Decimal("Rate", required=True),
"account_id": fields.Many2One("account.account", "Account", multi_company=True),
"type": fields.Selection([["vat", "VAT"], ["vat_exempt", "VAT Exempt"], ["vat_defer", "Deferred VAT"], ["wht", "Withholding Tax"]], "Tax Type"),
"trans_type": fields.Selection([["out", "Sale"], ["in", "Purchase"]], "Transaction Type"),
"description": fields.Text("Description"),
}
_defaults = {
"rate": 0,
}
def name_get(self, ids, context={}):
vals = []
for obj in self.browse(ids):
name = "%s - %s" % (obj.tax_rate_id.name, obj.name)
vals.append((obj.id, name))
return vals
TaxComponent.register()
|
python
|
import re
from num2words import num2words
from word2number.w2n import word_to_num
from pycorenlp import StanfordCoreNLP
class PostProcess:
month_map = {
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
}
country_map = {
'India': 'Indian',
'North Korea': 'North Korean',
'Germany': 'German',
'Greece':'Greek',
'Croatia':'Croatian',
'Asia':'Asian',
'Britain':'British',
'Italy':'Italian',
'Estonia': 'Estonian',
'Russia':'Russian',
'Afghanistan':'Afghan',
'France':'French',
'Europe':'European',
'Iran':'Iranian',
'Sweden':'Swedish',
'Brazil':'Brazilian',
'Mexico':'Mexican',
'Taiwan':'Taiwanese',
'Nigeria':'Nigerian',
'Africa':'African',
'China':'Chinese',
'Japan':'japanese',
'America':'American',
'Netherlands':'Dutch',
'Norway':'Norwegian',
'Israel':'Israeli',
'Ukraine':'Ukrainian'
}
def __init__ (self, retokenize=False, span=True, compound_map_file=None):
"""
the defualt settings are for development only
for testing, span must be set to False
"""
if retokenize:
nlp = StanfordCoreNLP('http://localhost:9000')
nlp_properties = {
'annotators': "tokenize,ssplit",
"tokenize.options": "splitHyphenated=true,normalizeParentheses=false",
"tokenize.whitespace": False,
'ssplit.isOneSentence': True,
'outputFormat': 'json'
}
self.stanford_tokenize = lambda text : [x['word'] for x in nlp.annotate(text, nlp_properties)['sentences'][0]['tokens']]
self.retokenize = retokenize
self.span = span
self.compound_map = self.load_compound_map(compound_map_file)
@staticmethod
def load_compound_map(file_path):
compound_map = dict()
if file_path is None:
return compound_map
for line in open(file_path).readlines():
compound = line.strip().split()
compound_map['-'.join(compound)] = ' '.join(compound)
return compound_map
def _find_node(self, abstract, graph):
ret = []
for name in graph.name2concept:
value = graph.name2concept[name]
if abstract == value:
ret.append(name)
#assert len(ret) == 1, (ret)
if not ret:
return None
return ret[0]
def _check(self, x, abstract, graph):
"""some speical cases where we map abstract symbols to strings,
will return None if not in any case
"""
#China => Chinese
if x.startswith('NATIONALITY') or x.startswith('COUNTRY'):
node = self._find_node(x, graph)
if not node:
return None
node1 = None
for nxt in graph.graph[node]:
if graph.graph[node][nxt]['label'] == "name_reverse_":
node1 = nxt
break
if not node1:
return None
if graph.name2concept[node1] == 'country':
do_transform = False
for nxt in graph.graph[node1]:
if graph.graph[node1][nxt]['label'] == "domain":
#or graph.graph[node1][nxt]['label'] == "ARG1_reverse_":
do_transform = True
if do_transform:
v = self.country_map.get(abstract['ops'], None)
if v is not None:
return [v]
return None
#100 => hundred
if re.search(r'^\d+$', x):
node = self._find_node(x, graph)
if node is None:
return None
for nxt in graph.graph[node]:
if graph.graph[node][nxt]['label'] == "li_reverse_":
return [str(abstract['value'])]
value = abstract['value']
if value == 100000:
return ['hundreds of thousands']
if int(value) == value:
if value >= 1000000000 and value % 1000 == 0:
v = value / 1000000000
if int(v) == v:
v = int(v)
return [str(v) + ' billion']
if value >= 1000000 and value % 1000 == 0:
v = value / 1000000
if int(v) == v:
v = int(v)
return [str(v) + ' million']
return None
# 7 => July
if x.startswith('DATE_ATTRS'):
assert 'attrs' in abstract or 'edges' in abstract
if len(abstract['attrs']) > 0:
xmap = abstract['attrs']
year = xmap.get('year', None)
month = xmap.get('month', None)
day = xmap.get('day', None)
decade = xmap.get('decade', None)
century = xmap.get('century', None)
time = xmap.get('time', None)
if year and month and day:
#30 July 2019
return [str(day), self.month_map[month], str(year)]
if day and month:
#April 18th
return [self.month_map[month], num2words(day, to='ordinal_num')]
if year and month:
#October 2008
return [ self.month_map[month], str(year)]
if year:
#2020
return [str(year)]
if month:
#October
return [self.month_map[month]]
if day:
#21st
return [num2words(day, to='ordinal_num')]
if decade:
#1980s
return [str(decade) + 's']
if century:
# 21st
return [num2words(century, to='ordinal_num')]
if time:
#return as it is
return [time.strip('"')]
else:
xmap = abstract['edges']
weekday = xmap.get('weekday', None)
dayperiod = xmap.get('dayperiod', None)
if weekday and dayperiod:
return [weekday, dayperiod]
if weekday:
return [weekday]
if dayperiod:
return [dayperiod]
assert False
return None
# 3 2 => 3:2
if x.startswith('SCORE_ENTITY'):
assert len(abstract['ops']) == 2
return [str(abstract['ops'][0]), ':', str(abstract['ops'][1])]
# 3 => 3rd
if x.startswith('ORDINAL_ENTITY'):
assert len(abstract['ops']) == 1
return [num2words(int(abstract['ops'][0]), to='ordinal_num')]
def check(self, abstract, graph):
"""Get the abstract-to-string map"""
ret = dict()
for x in abstract:
y = self._check(x, abstract[x], graph)
if y is not None:
ret[x] = y
continue
xmap = abstract[x]
if 'ops' in xmap:
assert 'value' not in xmap
assert isinstance(xmap['ops'], str) or isinstance(xmap['ops'], list)
if isinstance(xmap['ops'], list):
assert len(xmap['ops'])==1
ret[x] = [str(xmap['ops'][0])]
else:
ret[x] = [xmap['ops']]
elif 'value' in xmap:
assert 'ops' not in xmap
assert isinstance(xmap['value'], float) or \
isinstance(xmap['value'], int) or \
isinstance(xmap['value'], str)
ret[x] = [str(xmap['value'])]
return ret
def post_process(self, sent, abstract, graph):
"""
span is for development only
"""
if self.span:
_abstract = {}
for x in abstract:
_abstract[x] = [abstract[x]['span']]
abstract = _abstract
else:
abstract = self.check(abstract, graph)
ret = []
for tok in sent:
if tok in abstract:
ret.extend(abstract[tok])
else:
tok = self.compound_map.get(tok, tok)
ret.append(tok)
ret = ' '.join(ret)
if self.retokenize:
ret = ' '.join(self.stanford_tokenize(ret)).lower()
else:
ret = ret.lower()
return ret
def parse_config():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--golden_file', type=str, default='../data/AMR/amr_2.0/test.txt.features')
parser.add_argument('--pred_file', type=str, default='./epoch718_batch137999_test_out')
parser.add_argument('--retokenize', type=bool, default=True)
parser.add_argument('--span', type=bool, default=False)
parser.add_argument('--compound_map_file', type=str, default='../data/AMR/amr_2.0_utils/joints.txt')
parser.add_argument('--output', action='store_true')
return parser.parse_args()
if __name__ == '__main__':
import json
from extract import read_file
import sacrebleu
args = parse_config()
pp = PostProcess(retokenize=args.retokenize, span=args.span, compound_map_file=args.compound_map_file)
ref_stream = []
for line in open(args.golden_file):
if line.startswith('# ::original '):
o = json.loads(line[len('# ::original '):].strip())
ref_stream.append(' '.join(o).lower())
# gold model output
graph, gold_sys_stream, _, abstract = read_file(args.golden_file+'.preproc')
ref_streams = [ref_stream]
pred_sys_stream = []
for line in open(args.pred_file):
if line.startswith('#model output:'):
ans = line[len('#model output:'):].strip().split()
pred_sys_stream.append(ans)
prev = [ ' '.join(o) for o in pred_sys_stream]
# choose one (gold or pred) and postprocess
sys_stream = pred_sys_stream
sys_stream = [ pp.post_process(o, abstract[i], graph[i]) for i, o in enumerate(sys_stream)]
bleu = sacrebleu.corpus_bleu(sys_stream, ref_streams,
force=True, lowercase=True,
tokenize='none')
chrf = sacrebleu.corpus_chrf(sys_stream, ref_streams)
all_sent_chrf = [sacrebleu.sentence_chrf(x, y).score for x, y in zip(sys_stream, ref_stream)]
avg_sent_chrf = sum(all_sent_chrf) / len(all_sent_chrf)
if args.output:
with open(args.pred_file+'.final', 'w') as fo:
for x in sys_stream:
fo.write(x+'\n')
with open(args.pred_file+'.ref', 'w') as fo:
for x in ref_stream:
fo.write(x+'\n')
print (avg_sent_chrf)
print (bleu.score, chrf.score)
print ('BLEU bp: {}'.format(bleu.bp))
|
python
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
##################################################################################
# File: c:\Projects\KENYA ONE PROJECT\CORE\engines\values.py #
# Project: c:\Projects\KENYA ONE PROJECT\CORE\engines #
# Created Date: Thursday, January 9th 2020, 8:56:55 pm #
# Author: Geoffrey Nyaga Kinyua ( <[email protected]> ) #
# ----- #
# Last Modified: Thursday January 9th 2020 8:56:55 pm #
# Modified By: Geoffrey Nyaga Kinyua ( <[email protected]> ) #
# ----- #
# MIT License #
# #
# Copyright (c) 2020 KENYA ONE PROJECT #
# #
# 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. #
# ----- #
# Copyright (c) 2020 KENYA ONE PROJECT #
##################################################################################
prerequisites = {"crew": 2.0, "pax": 4.0, "propEff": 0.8, "Range": 1200.0, "AR": 7.8}
prerequisites = {"Range": 1200.0}
prerequisites = {"Range": 1200.0, "propEff": 0.8}
prerequisites = {"Range": 1200.0, "propEff": 0.8, "AR": 7.8}
prerequisites = {"pax": 4.0, "Range": 1200.0, "propEff": 0.8, "AR": 7.8}
prerequisites = {"pax": 4.0, "crew": 2.0, "Range": 1200.0, "propEff": 0.8, "AR": 7.8}
TESTING_MAIN = {"cdo": 0.025}
TESTING_MAIN = {"ldMax": 14.14244503933519, "cdo": 0.025}
TESTING_MAIN = {
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"cdo": 0.025,
}
TESTING_MAIN = {
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAIN = {
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAIN = {
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"altitude": 10000,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"altitude": 10000,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"altitudeDensity": 0.0017560745944146475,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"altitude": 10000,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"S": 23.935236948468031,
"ldMax": 14.14244503933519,
"altitudeDensity": 0.0017560745944146475,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"altitude": 10000,
"P": 618.43333333297289,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"S": 23.935236948468031,
"ldMax": 14.14244503933519,
"altitudeDensity": 0.0017560745944146475,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"altitude": 10000,
"P": 618.43333333297289,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"S": 23.935236948468031,
"ldMax": 14.14244503933519,
"altitudeDensity": 0.0017560745944146475,
"cli": 0.41785873007517732,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
}
TESTING_MAIN = {
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"cli": 0.41785873007517732,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
"altitude": 10000,
"netclmax": 1.468088436705147,
"P": 618.43333333297289,
"altitudeDensity": 0.0017560745944146475,
"S": 23.935236948468031,
"finalMTOW": 5351.6620693350997,
}
TESTING_MAIN = {
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"cli": 0.41785873007517732,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
"altitude": 10000,
"netclmax": 1.468088436705147,
"P": 618.43333333297289,
"altitudeDensity": 0.0017560745944146475,
"S": 23.935236948468031,
"finalMTOW": 5351.6620693350997,
"stallSpeed": 60.06364972501056,
}
TESTING_MAIN = {
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"cli": 0.41785873007517732,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
"altitude": 10000,
"netclmax": 1.468088436705147,
"P": 618.43333333297289,
"maxSpeed": 178.81621246839975,
"altitudeDensity": 0.0017560745944146475,
"S": 23.935236948468031,
"finalMTOW": 5351.6620693350997,
"stallSpeed": 60.06364972501056,
}
TESTING_MAIN = {
"takeOffRun": 1233.759185305546,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"cli": 0.41785873007517732,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
"altitude": 10000,
"netclmax": 1.468088436705147,
"P": 618.43333333297289,
"maxSpeed": 178.81621246839975,
"altitudeDensity": 0.0017560745944146475,
"S": 23.935236948468031,
"finalMTOW": 5351.6620693350997,
"stallSpeed": 60.06364972501056,
}
TESTING_MAIN = {
"takeOffRun": 1233.759185305546,
"cdo": 0.025,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"cli": 0.41785873007517732,
"initialWeight": 5146.7647675738235,
"rhoSL": 0.002378,
"altitude": 10000,
"netclmax": 1.468088436705147,
"P": 618.43333333297289,
"maxSpeed": 178.81621246839975,
"altitudeDensity": 0.0017560745944146475,
"S": 23.935236948468031,
"finalMTOW": 5351.6620693350997,
"rateOfClimb": 9.9790621408063167,
"stallSpeed": 60.06364972501056,
}
wing = {"cdMin": 0.02541}
wing = {"cdMin": 0.02541, "taper": 0.8}
wing = {"cdMin": 0.02541, "taper": 0.8, "cbhp": 0.4586}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cbhp": 0.4586,
"altitude": 10000,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"altitude": 10000,
"chordAtY": 5.519485342101509,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"chordAtY": 5.519485342101509,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"chordAtY": 5.519485342101509,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"chordAtY": 5.519485342101509,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"averageChord": 5.4245609920969535,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"sweepHalfChord": 4,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"sweepQuarterChord": 4.0,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"sweepHalfChord": 4,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"sweepQuarterChord": 4.0,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"sweepHalfChord": 4,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"sweepLeadingEdge": 0,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"sweepTmax": 4.5,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"sweepQuarterChord": 4.0,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"sweepHalfChord": 4,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"sweepLeadingEdge": 0,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
wing = {
"cdMin": 0.02541,
"CLalfa": 4.8683198214956898,
"sweepTmax": 4.5,
"poweredSailplaneAR": 8.380031622714846,
"taper": 0.8,
"yMGC": 11.429704392564705,
"altitude": 10000,
"AOA": 5,
"cbhp": 0.4586,
"meanGeometricChord": 5.446884288360727,
"enduranceAR": 5.09578158636221,
"reducedCL": 0.8245015274022384,
"ct": 4.314242163194872e-05,
"sweepQuarterChord": 4.0,
"clmaxTip": 1.4,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"cma": -0.01,
"chordAtY": 5.519485342101509,
"tipChord": 4.821831992975071,
"reducedOswaldEff": 0.95627962746204309,
"altitudeDensity": 0.0017560745944146475,
"clmaxRoot": 1.561,
"sweepHalfChord": 4,
"oswaldEff": 0.7652715565217351,
"rootChord": 6.027289991218837,
"cruiseCL": 0.9902004995599598,
"reducedCDi": 0.021057271992274751,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"clmax": 1.56,
"alfazero": -3.757377049180328,
"clo": 0.4,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"sweepLeadingEdge": 0,
"reducedMaxSpeed": 153.25476601854305,
"fuselageWidth": 4.167,
}
airfoil = {"finalCLalfa": 4.962603674858106}
airfoil = {"CLo": 0.32541663441692503, "finalCLalfa": 4.962603674858106}
airfoil = {
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"Cma": -0.008135415860423127,
}
airfoil = {
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"Cma": -0.008135415860423127,
"cruiseCL": 0.9902004995599597,
}
airfoil = {
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"finalCLmax": 1.3666798663286048,
"Cma": -0.008135415860423127,
"cruiseCL": 0.9902004995599597,
}
valuetest = {"": 2}
valuetest = {"": 3}
wing = {"cdMin": 0.02541}
wing = {"cdMin": 0.02541, "taper": 0.8}
wing = {"cdMin": 0.02541, "cbhp": 0.4586, "taper": 0.8}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"altitude": 10000,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cruiseCL": 0.9902004995599598,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"altitude": 10000,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"altitude": 10000,
"cdMin": 0.02541,
"enduranceAR": 5.09578158636221,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"cdMin": 0.02541,
"enduranceAR": 5.09578158636221,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"cruiseCL": 0.9902004995599598,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"rootChord": 6.027289991218837,
"clalfa": 6.1,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"sweepHalfChord": 4,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"sweepHalfChord": 4,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"sweepQuarterChord": 4.0,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"sweepLeadingEdge": 0,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"sweepHalfChord": 4,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"sweepQuarterChord": 4.0,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"sweepTmax": 4.5,
"wingSpan": 47.477233630653394,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"sweepLeadingEdge": 0,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"sweepHalfChord": 4,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"sweepQuarterChord": 4.0,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {
"altitudeDensity": 0.0017560745944146475,
"tipChord": 4.821831992975071,
"reducedCL": 0.8245015274022384,
"altitude": 10000,
"clmax": 1.56,
"rootChord": 6.027289991218837,
"alfazero": -3.757377049180328,
"clalfa": 6.1,
"clmaxRoot": 1.561,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"sweepTmax": 4.5,
"wingSpan": 47.477233630653394,
"oswaldEff": 0.7652715565217351,
"clmaxTip": 1.4,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"clo": 0.4,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"reducedCDi": 0.021057271992274751,
"ct": 4.314242163194872e-05,
"fuselageWidth": 4.167,
"sweepLeadingEdge": 0,
"cdMin": 0.02541,
"chordAtY": 5.519485342101509,
"reducedOswaldEff": 0.95627962746204309,
"averageChord": 5.4245609920969535,
"rangeAR": 8.752272064010896,
"reducedMaxSpeed": 153.25476601854305,
"sweepHalfChord": 4,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"CLalfa": 4.8683198214956898,
"sweepQuarterChord": 4.0,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"taper": 0.8,
}
wing = {"cdMin": 0.02541}
wing = {"cdMin": 0.02541, "taper": 0.8}
wing = {"cbhp": 0.4586, "cdMin": 0.02541, "taper": 0.8}
wing = {
"cbhp": 0.4586,
"cdMin": 0.02541,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cbhp": 0.4586,
"cdMin": 0.02541,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"cbhp": 0.4586,
"altitudeDensity": 0.0017560745944146475,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"unPoweredSailplaneAR": 8.839144664989483,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"cruiseSpeed": 149.01351039033312,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"poweredSailplaneAR": 8.380031622714846,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"AOA": 5,
"poweredSailplaneAR": 8.380031622714846,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"altitude": 10000,
"wingSpan": 47.477233630653394,
"AOA": 5,
"poweredSailplaneAR": 8.380031622714846,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"clalfa": 6.1,
"tipChord": 4.821831992975071,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"enduranceAR": 5.09578158636221,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cruiseSpeed": 149.01351039033312,
"rootChord": 6.027289991218837,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"clmaxTip": 1.4,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"clmaxTip": 1.4,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"fuselageWidth": 4.167,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"sweepQuarterChord": 4.0,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"sweepLeadingEdge": 0,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"sweepQuarterChord": 4.0,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"sweepLeadingEdge": 0,
"sweepTmax": 4.5,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"sweepQuarterChord": 4.0,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {
"reducedMaxSpeed": 153.25476601854305,
"enduranceAR": 5.09578158636221,
"chordAtY": 5.519485342101509,
"unPoweredSailplaneAR": 8.839144664989483,
"CLalfa": 4.8683198214956898,
"AOA": 5,
"clalfa": 6.1,
"cma": -0.01,
"averageChord": 5.4245609920969535,
"cdMin": 0.02541,
"clmaxRoot": 1.561,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"reducedCDi": 0.021057271992274751,
"clmax": 1.56,
"altitude": 10000,
"wingSpan": 47.477233630653394,
"sweepLeadingEdge": 0,
"sweepTmax": 4.5,
"oswaldEff": 0.7652715565217351,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"reducedOswaldEff": 0.95627962746204309,
"clmaxTip": 1.4,
"reducedCL": 0.8245015274022384,
"fuselageWidth": 4.167,
"sweepQuarterChord": 4.0,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"rootChord": 6.027289991218837,
"tipChord": 4.821831992975071,
"alfazero": -3.757377049180328,
"meanGeometricChord": 5.446884288360727,
}
wing = {"cdMin": 0.02541}
wing = {"cdMin": 0.02541, "taper": 0.8}
wing = {"cdMin": 0.02541, "cbhp": 0.4586, "taper": 0.8}
wing = {
"cdMin": 0.02541,
"cbhp": 0.4586,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cbhp": 0.4586,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"altitude": 10000,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cbhp": 0.4586,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"cbhp": 0.4586,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"rangeAR": 8.752272064010896,
"enduranceAR": 5.09578158636221,
"cbhp": 0.4586,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"ct": 4.314242163194872e-05,
"rangeAR": 8.752272064010896,
"enduranceAR": 5.09578158636221,
"cbhp": 0.4586,
"altitude": 10000,
"cruiseCL": 0.9902004995599598,
"altitudeDensity": 0.0017560745944146475,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"poweredSailplaneAR": 8.380031622714846,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"poweredSailplaneAR": 8.380031622714846,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"poweredSailplaneAR": 8.380031622714846,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"poweredSailplaneAR": 8.380031622714846,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"meanGeometricChord": 5.446884288360727,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"meanGeometricChord": 5.446884288360727,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"meanGeometricChord": 5.446884288360727,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"wingSpan": 47.477233630653394,
"rangeAR": 8.752272064010896,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"meanGeometricChord": 5.446884288360727,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"averageChord": 5.4245609920969535,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"clalfa": 6.1,
"rootChord": 6.027289991218837,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"yMGC": 11.429704392564705,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"yMGC": 11.429704392564705,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"clmax": 1.56,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"clmaxRoot": 1.561,
"clmax": 1.56,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"clmaxRoot": 1.561,
"clmax": 1.56,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"sweepHalfChord": 4,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"sweepQuarterChord": 4.0,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"sweepHalfChord": 4,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"sweepLeadingEdge": 0,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"sweepQuarterChord": 4.0,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"sweepHalfChord": 4,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"sweepLeadingEdge": 0,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"sweepQuarterChord": 4.0,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"sweepTmax": 4.5,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"sweepHalfChord": 4,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
wing = {
"fuselageWidth": 4.167,
"cruiseSpeed": 149.01351039033312,
"taper": 0.8,
"CLalfa": 4.8683198214956898,
"reducedCL": 0.8245015274022384,
"clmaxRoot": 1.561,
"clmax": 1.56,
"reducedCDi": 0.021057271992274751,
"averageChord": 5.4245609920969535,
"chordAtY": 5.519485342101509,
"cdMin": 0.02541,
"sweepLeadingEdge": 0,
"meanGeometricChord": 5.446884288360727,
"cma": -0.01,
"yMGC": 11.429704392564705,
"clmaxTip": 1.4,
"reducedOswaldEff": 0.95627962746204309,
"clo": 0.4,
"clalfa": 6.1,
"oswaldEff": 0.7652715565217351,
"rangeAR": 8.752272064010896,
"wingSpan": 47.477233630653394,
"cbhp": 0.4586,
"altitude": 10000,
"ct": 4.314242163194872e-05,
"tipChord": 4.821831992975071,
"sweepQuarterChord": 4.0,
"poweredSailplaneAR": 8.380031622714846,
"unPoweredSailplaneAR": 8.839144664989483,
"sweepTmax": 4.5,
"reducedMaxSpeed": 153.25476601854305,
"altitudeDensity": 0.0017560745944146475,
"alfazero": -3.757377049180328,
"sweepHalfChord": 4,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"rootChord": 6.027289991218837,
"AOA": 5,
}
airfoil = {"finalCLalfa": 4.962603674858106}
airfoil = {"CLo": 0.32541663441692503, "finalCLalfa": 4.962603674858106}
airfoil = {
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"Cma": -0.008135415860423127,
}
airfoil = {
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"Cma": -0.008135415860423127,
"cruiseCL": 0.9902004995599597,
}
airfoil = {
"finalCLmax": 1.3666798663286048,
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
"Cma": -0.008135415860423127,
"cruiseCL": 0.9902004995599597,
}
airfoil = {"finalCLalfa": 4.962603674858106}
airfoil = {"CLo": 0.32541663441692503, "finalCLalfa": 4.962603674858106}
airfoil = {
"CLo": 0.32541663441692503,
"Cma": -0.008135415860423127,
"finalCLalfa": 4.962603674858106,
}
airfoil = {
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"Cma": -0.008135415860423127,
"finalCLalfa": 4.962603674858106,
}
airfoil = {
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"Cma": -0.008135415860423127,
"finalCLmax": 1.3666798663286048,
"finalCLalfa": 4.962603674858106,
}
wing = {"cdMin": 0.02541}
wing = {"cdMin": 0.02541, "taper": 0.8}
wing = {"cdMin": 0.02541, "cbhp": 0.4586, "taper": 0.8}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"cbhp": 0.4586,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"taper": 0.8,
}
wing = {
"rangeAR": 8.752272064010896,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"taper": 0.8,
}
wing = {
"rangeAR": 8.752272064010896,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"taper": 0.8,
}
wing = {
"rangeAR": 8.752272064010896,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"cbhp": 0.4586,
"enduranceAR": 5.09578158636221,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"taper": 0.8,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"chordAtY": 5.519485342101509,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
"AOA": 5,
}
wing = {
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"wingSpan": 47.477233630653394,
"averageChord": 5.4245609920969535,
"altitude": 10000,
"altitudeDensity": 0.0017560745944146475,
"poweredSailplaneAR": 8.380031622714846,
"cruiseCL": 0.9902004995599598,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"enduranceAR": 5.09578158636221,
"tipChord": 4.821831992975071,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"rootChord": 6.027289991218837,
"meanGeometricChord": 5.446884288360727,
"cbhp": 0.4586,
"unPoweredSailplaneAR": 8.839144664989483,
"clalfa": 6.1,
"AOA": 5,
}
wing = {
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
}
wing = {
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"sweepHalfChord": 4,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"wingSpan": 47.477233630653394,
"cma": -0.01,
"sweepHalfChord": 4,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"sweepQuarterChord": 4.0,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"sweepLeadingEdge": 0,
"wingSpan": 47.477233630653394,
"cma": -0.01,
"sweepHalfChord": 4,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"sweepQuarterChord": 4.0,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"sweepTmax": 4.5,
"sweepLeadingEdge": 0,
"wingSpan": 47.477233630653394,
"cma": -0.01,
"sweepHalfChord": 4,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"sweepQuarterChord": 4.0,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
wing = {
"sweepTmax": 4.5,
"sweepLeadingEdge": 0,
"wingSpan": 47.477233630653394,
"cma": -0.01,
"sweepHalfChord": 4,
"altitudeDensity": 0.0017560745944146475,
"reducedOswaldEff": 0.95627962746204309,
"chordAtY": 5.519485342101509,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"enduranceAR": 5.09578158636221,
"unPoweredSailplaneAR": 8.839144664989483,
"clmax": 1.56,
"poweredSailplaneAR": 8.380031622714846,
"clo": 0.4,
"rootChord": 6.027289991218837,
"cbhp": 0.4586,
"reducedCDi": 0.021057271992274751,
"cruiseCL": 0.9902004995599598,
"AOA": 5,
"sweepQuarterChord": 4.0,
"cdMin": 0.02541,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"averageChord": 5.4245609920969535,
"oswaldEff": 0.7652715565217351,
"meanGeometricChord": 5.446884288360727,
"reducedCL": 0.8245015274022384,
"clmaxTip": 1.4,
"clmaxRoot": 1.561,
"taper": 0.8,
"rangeAR": 8.752272064010896,
"CLalfa": 4.8683198214956898,
"ct": 4.314242163194872e-05,
"reducedMaxSpeed": 153.25476601854305,
"clalfa": 6.1,
"alfazero": -3.757377049180328,
"fuselageWidth": 4.167,
}
airfoilEngine = {"finalCLalfa": 4.962603674858106}
airfoilEngine = {"finalCLalfa": 4.962603674858106, "CLo": 0.32541663441692503}
airfoilEngine = {
"Cma": -0.008135415860423127,
"finalCLalfa": 4.962603674858106,
"CLo": 0.32541663441692503,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"finalCLalfa": 4.962603674858106,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"finalCLalfa": 4.962603674858106,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"finalCLmax": 1.3666798663286048,
}
airfoilEngine = {"finalCLalfa": 2.312126518254976}
airfoilEngine = {"finalCLalfa": 2.312126518254976, "CLo": 0.151614853656064}
airfoilEngine = {
"finalCLalfa": 2.312126518254976,
"CLo": 0.151614853656064,
"Cma": -0.023121265182549765,
}
airfoilEngine = {
"finalCLalfa": 2.312126518254976,
"CLo": 0.151614853656064,
"cruiseCL": 0.9902004995599598,
"Cma": -0.023121265182549765,
}
airfoilEngine = {
"finalCLmax": 1.3666798663286048,
"finalCLalfa": 2.312126518254976,
"CLo": 0.151614853656064,
"cruiseCL": 0.9902004995599598,
"Cma": -0.023121265182549765,
}
airfoilEngine = {"finalCLalfa": 4.962603674858106}
airfoilEngine = {"CLo": 0.32541663441692503, "finalCLalfa": 4.962603674858106}
airfoilEngine = {
"Cma": -0.008135415860423127,
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"finalCLalfa": 4.962603674858106,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"finalCLmax": 1.3666798663286048,
"finalCLalfa": 4.962603674858106,
}
airfoilEngine = {"finalCLalfa": 4.962603674858106}
airfoilEngine = {"CLo": 0.32541663441692503, "finalCLalfa": 4.962603674858106}
airfoilEngine = {
"Cma": -0.008135415860423127,
"CLo": 0.32541663441692503,
"finalCLalfa": 4.962603674858106,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"finalCLalfa": 4.962603674858106,
}
airfoilEngine = {
"Cma": -0.008135415860423127,
"finalCLmax": 1.3666798663286048,
"CLo": 0.32541663441692503,
"cruiseCL": 0.9902004995599597,
"finalCLalfa": 4.962603674858106,
}
TESTING_MAINENGINE = {"cdo": 0.025}
TESTING_MAINENGINE = {"ldMax": 14.14244503933519, "cdo": 0.025}
TESTING_MAINENGINE = {
"finalMTOW": 5351.6620693350997,
"ldMax": 14.14244503933519,
"cdo": 0.025,
}
TESTING_MAINENGINE = {
"finalMTOW": 5351.6620693350997,
"ldMax": 14.14244503933519,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAINENGINE = {
"finalMTOW": 5351.6620693350997,
"finalWeight": 4797.379010844259,
"ldMax": 14.14244503933519,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAINENGINE = {"cdo": 0.025}
TESTING_MAINENGINE = {"ldMax": 14.14244503933519, "cdo": 0.025}
TESTING_MAINENGINE = {
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"cdo": 0.025,
}
TESTING_MAINENGINE = {
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAINENGINE = {
"ldMax": 14.14244503933519,
"finalMTOW": 5351.6620693350997,
"finalWeight": 4797.379010844259,
"initialWeight": 5146.7647675738235,
"cdo": 0.025,
}
TESTING_MAINENGINE = {"finalMTOW": 5351.6620693350997}
TESTING_MAINENGINE = {
"finalMTOW": 5351.6620693350997,
"initialWeight": 5146.7647675738235,
}
TESTING_MAINENGINE = {
"finalMTOW": 5351.6620693350997,
"finalWeight": 4797.379010844259,
"initialWeight": 5146.7647675738235,
}
TESTING_MAINENGINE = {"rhoSL": 0.002378}
TESTING_MAINENGINE = {"altitude": 10000, "rhoSL": 0.002378}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"rhoSL": 0.002378,
}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"rhoSL": 0.002378,
"S": 47.870473896936062,
}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"altitude": 10000,
"rhoSL": 0.002378,
"P": 278.29499999983784,
"S": 47.870473896936062,
}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
"netclmax": 1.4680884367051465,
}
TESTING_MAINENGINE = {
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
"stallSpeed": 42.47141402336848,
"netclmax": 1.4680884367051465,
}
TESTING_MAINENGINE = {
"maxSpeed": 103.45719382955168,
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
"stallSpeed": 42.47141402336848,
"netclmax": 1.4680884367051465,
}
TESTING_MAINENGINE = {
"maxSpeed": 103.45719382955168,
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
"stallSpeed": 42.47141402336848,
"netclmax": 1.4680884367051465,
"takeOffRun": 1912.2502012007176,
}
TESTING_MAINENGINE = {
"maxSpeed": 103.45719382955168,
"altitudeDensity": 0.0017560745944146475,
"cli": 0.62415417386819338,
"rateOfClimb": 3.703932892015096,
"S": 47.870473896936062,
"P": 278.29499999983784,
"altitude": 10000,
"rhoSL": 0.002378,
"stallSpeed": 42.47141402336848,
"netclmax": 1.4680884367051465,
"takeOffRun": 1912.2502012007176,
}
TESTING_MAINENGINE = {"cli": 0.031384808036009924}
TESTING_MAINENGINE = {"netclmax": 1.4680884367051457, "cli": 0.031384808036009924}
TESTING_MAINENGINE = {
"stallSpeed": 12.808575945459246,
"netclmax": 1.4680884367051457,
"cli": 0.031384808036009924,
}
TESTING_MAINENGINE = {
"stallSpeed": 12.808575945459246,
"netclmax": 1.4680884367051457,
"cli": 0.031384808036009924,
"maxSpeed": 139.10750237369678,
}
TESTING_MAINENGINE = {
"takeOffRun": 0.082471190783628343,
"stallSpeed": 12.808575945459246,
"netclmax": 1.4680884367051457,
"cli": 0.031384808036009924,
"maxSpeed": 139.10750237369678,
}
TESTING_MAINENGINE = {
"cli": 0.031384808036009924,
"stallSpeed": 12.808575945459246,
"takeOffRun": 0.082471190783628343,
"maxSpeed": 139.10750237369678,
"rateOfClimb": 116.6955392002988,
"netclmax": 1.4680884367051457,
}
TESTING_MAINENGINE = {"cli": 0.45778518093303916}
TESTING_MAINENGINE = {"netclmax": 1.4680884367051457, "cli": 0.45778518093303916}
TESTING_MAINENGINE = {
"netclmax": 1.4680884367051457,
"stallSpeed": 60.43150743716637,
"cli": 0.45778518093303916,
}
TESTING_MAINENGINE = {
"netclmax": 1.4680884367051457,
"stallSpeed": 60.43150743716637,
"cli": 0.45778518093303916,
"maxSpeed": 171.84702039880491,
}
TESTING_MAINENGINE = {
"netclmax": 1.4680884367051457,
"stallSpeed": 60.43150743716637,
"takeOffRun": 1426.1855757082296,
"cli": 0.45778518093303916,
"maxSpeed": 171.84702039880491,
}
TESTING_MAINENGINE = {
"netclmax": 1.4680884367051457,
"cli": 0.45778518093303916,
"stallSpeed": 60.43150743716637,
"takeOffRun": 1426.1855757082296,
"maxSpeed": 171.84702039880491,
"rateOfClimb": 8.6564570337328934,
}
TESTING_MAINENGINE = {"stallSpeed": 61.01239813973099}
TESTING_MAINENGINE = {"stallSpeed": 61.01239813973099, "maxSpeed": 172.80308311080324}
TESTING_MAINENGINE = {
"stallSpeed": 61.01239813973099,
"takeOffRun": 1453.7354318427551,
"maxSpeed": 172.80308311080324,
}
TESTING_MAINENGINE = {
"stallSpeed": 61.01239813973099,
"rateOfClimb": 8.6268668268318152,
"takeOffRun": 1453.7354318427551,
"maxSpeed": 172.80308311080324,
}
wingEngine = {"cdMin": 0.02541}
wingEngine = {"cdMin": 0.02541, "taper": 0.8}
wingEngine = {"cdMin": 0.02541, "taper": 0.8, "cbhp": 0.4586}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
}
wingEngine = {
"altitude": 10000,
"cdMin": 0.02541,
"taper": 0.8,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"altitudeDensity": 0.0017560745944146475,
"cruiseSpeed": 149.01351039033312,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"altitudeDensity": 0.0017560745944146475,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"altitudeDensity": 0.0017560745944146475,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"altitudeDensity": 0.0017560745944146475,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"taper": 0.8,
"unPoweredSailplaneAR": 8.839144664989483,
"altitudeDensity": 0.0017560745944146475,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"ct": 4.314242163194872e-05,
"cruiseSpeed": 149.01351039033312,
"cruiseCL": 0.9902004995599598,
"altitude": 10000,
"cbhp": 0.4586,
}
wingEngine = {
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"AOA": 5,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clalfa": 6.1,
"wingSpan": 47.477233630653394,
"rootChord": 6.027289991218837,
"altitudeDensity": 0.0017560745944146475,
"cruiseCL": 0.9902004995599598,
"yMGC": 11.429704392564705,
"tipChord": 4.821831992975071,
"ct": 4.314242163194872e-05,
"cbhp": 0.4586,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"averageChord": 5.4245609920969535,
"poweredSailplaneAR": 8.380031622714846,
"rangeAR": 8.752272064010896,
"cruiseSpeed": 149.01351039033312,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"AOA": 5,
"enduranceAR": 5.09578158636221,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"tipChord": 4.821831992975071,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"tipChord": 4.821831992975071,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"tipChord": 4.821831992975071,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"tipChord": 4.821831992975071,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"tipChord": 4.821831992975071,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"sweepQuarterChord": 4.0,
"enduranceAR": 5.09578158636221,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"sweepQuarterChord": 4.0,
"enduranceAR": 5.09578158636221,
"sweepLeadingEdge": 0,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"clo": 0.4,
"sweepQuarterChord": 4.0,
"enduranceAR": 5.09578158636221,
"sweepLeadingEdge": 0,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"sweepTmax": 4.5,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
wingEngine = {
"clalfa": 6.1,
"averageChord": 5.4245609920969535,
"rootChord": 6.027289991218837,
"AOA": 5,
"cma": -0.01,
"reducedCDi": 0.021057271992274751,
"tipChord": 4.821831992975071,
"clmaxTip": 1.4,
"wingSpan": 47.477233630653394,
"oswaldEff": 0.7652715565217351,
"clo": 0.4,
"sweepQuarterChord": 4.0,
"enduranceAR": 5.09578158636221,
"sweepLeadingEdge": 0,
"rangeAR": 8.752272064010896,
"unPoweredSailplaneAR": 8.839144664989483,
"alfazero": -3.757377049180328,
"altitude": 10000,
"reducedMaxSpeed": 153.25476601854302,
"yMGC": 11.429704392564705,
"meanGeometricChord": 5.446884288360727,
"cdMin": 0.02541,
"clmax": 1.56,
"altitudeDensity": 0.0017560745944146475,
"CLalfa": 4.8683198214956906,
"reducedCL": 0.8245015274022386,
"ct": 4.314242163194872e-05,
"reducedOswaldEff": 0.95627962746204331,
"chordAtY": 5.519485342101509,
"sweepTmax": 4.5,
"fuselageWidth": 4.167,
"taper": 0.8,
"poweredSailplaneAR": 8.380031622714846,
"sweepHalfChord": 4,
"cruiseSpeed": 149.01351039033312,
"cbhp": 0.4586,
"clmaxRoot": 1.561,
"cruiseCL": 0.9902004995599598,
}
|
python
|
from .jxa_loader import *
|
python
|
import math
import numpy as np
import torch
from torch import nn
class MultiheadAttention(nn.Module):
"""General purpose multihead attention implementation."""
def __init__(self, input_dim, proj_dim, n_heads=1, dropout=0.0,
attn_type='cross', initializer='xavier_uniform'):
assert proj_dim % n_heads == 0, "proj_dim not divisible by n_heads."
super().__init__()
self.input_dim = input_dim
self.proj_dim = proj_dim
self.n_heads = n_heads
self.head_dim = self.proj_dim // self.n_heads
self.scale = math.sqrt(self.head_dim)
self.minus_inf = float('-inf')
self.attn_type = attn_type
self.initializer = initializer
self.p_dropout = dropout
self._apply_projections_and_reshape = getattr(
self, f'_apply_projections_and_reshape_{self.attn_type}')
# dropout over attention probability
self.dropout = nn.Dropout(dropout) if dropout > 0.0 else lambda x: x
self._create_layers()
self._reset_parameters(getattr(nn.init, f'{initializer}_'))
def __repr__(self):
s = f"MultiheadAttention({self.input_dim} -> {self.proj_dim}, {self.n_heads} heads, "
s += f"type={self.attn_type!r}, dropout={self.p_dropout})"
return s
def view_as_headed(self, x):
"""Returns a view of shape `[bsz, n_heads, seq_len, head_dim]`
from `[bsz, seq_len, head_dim * n_heads]`."""
return x.view(x.size(0), x.size(1), self.n_heads, -1).transpose(1, 2)
@staticmethod
def view_as_concat(x):
"""Returns a view of shape `[bsz, seq_len, head_dim * n_heads]`
from `[bsz, n_heads, seq_len, head_dim]`."""
return x.transpose(1, 2).contiguous().view(x.size(0), x.size(2), -1)
def _reset_parameters(self, init_fn):
"""Reinitializes layer weights."""
for param in self.parameters():
init_fn(param)
def _create_layers(self):
"""Create projection layer weights."""
self.lin_o = nn.Parameter(torch.Tensor(self.proj_dim, self.proj_dim))
if self.attn_type != 'self':
self.lin_k = nn.Parameter(torch.Tensor(self.input_dim, self.proj_dim))
self.lin_q = nn.Parameter(torch.Tensor(self.input_dim, self.proj_dim))
self.lin_v = nn.Parameter(torch.Tensor(self.input_dim, self.proj_dim))
else:
self.lin_k = nn.Parameter(torch.Tensor(self.input_dim, 3 * self.proj_dim))
def _apply_projections_and_reshape_self(self, k, v=None, q=None):
"""Projects key, value and queries and returns multi-head view
for self-attention variant.
Args:
k: Tensor of shape `[batch_size, v_len, dim]`.
v: `None` for self-attention. This is not used.
q: `None` for self-attention. This is not used.
Returns:
A tuple of 3 tensors for k,v,q projections, each with shape
`[batch_size, n_heads, v_len, head_dim]`.
"""
return (
self.view_as_headed(t) for t in k.matmul(self.lin_k).chunk(3, dim=-1))
def _apply_projections_and_reshape_cross(self, k, v, q):
"""Projects key, value and queries and returns multi-head view
for cross-attention variant.
Args:
k: Tensor of shape `[batch_size, v_len, dim]`.
v: Tensor of shape `[batch_size, v_len, dim]`.
q: Tensor of shape `[batch_size, q_len, dim]`.
Returns:
A tuple of 3 tensors for k,v,q projections, each with shape
`[batch_size, n_heads, (v|q)_len, head_dim]`.
"""
return (self.view_as_headed(k.matmul(self.lin_k)),
self.view_as_headed(v.matmul(self.lin_v)),
self.view_as_headed(q.matmul(self.lin_q)))
def _compute_scores(self, query, key, k_mask=None):
"""Computes normalized scaled dot-product scores between query and key.
Args:
query: Tensor of shape `[batch_size, n_heads, q_len, dim]`.
key: Tensor of shape `[batch_size, n_heads, v_len, dim]`.
k_mask: Tensor of shape `[batch_size, v_len]`.
Returns:
Tensor of shape `[batch_size, n_heads, q_len, v_len]` with
normalized attention weights.
"""
scores = torch.matmul(query.div(self.scale), key.transpose(-2, -1))
if k_mask is not None:
# mask <pad>'ded positions
scores.masked_fill_(k_mask[:, None, None, :], self.minus_inf)
return self.dropout(scores.softmax(dim=-1))
def _apply_scores(self, p, value, q_mask=None):
"""Applies normalized attention weights on `value`. `q_mask`
is used to zero padded positions afterwards.
Args:
p: Tensor of shape `[batch_size, n_heads, q_len, v_len]`.
value: Tensor of shape `[batch_size, n_heads, v_len, dim]`.
q_mask: Tensor of shape `[batch_size, q_len]`.
Returns:
Tensor of shape `[batch_size, n_heads, v_len, dim]`.
"""
ctx = torch.matmul(p, value)
if q_mask is not None:
# zero out <pad>'ded positions
ctx.mul_(q_mask[:, None, :, None].logical_not())
return ctx
def forward(self, k, v=None, q=None, k_mask=None, q_mask=None):
kp, vp, qp = self._apply_projections_and_reshape(k, v, q)
# Get normalized scores
alpha = self._compute_scores(qp, kp, k_mask)
# Get weighted contexts for each head -> concat -> project
return self.view_as_concat(
self._apply_scores(alpha, vp, q_mask)).matmul(self.lin_o)
def get_upstream_impl(dim, n_heads):
mha = nn.MultiheadAttention(dim, n_heads, bias=False)
nn.init.eye_(mha.out_proj.weight.data)
list(map(lambda i: nn.init.eye_(i), mha.in_proj_weight.data.chunk(3, dim=0)))
nn.init.eye_(mha.in_proj_weight.data[:dim])
nn.init.eye_(mha.in_proj_weight.data[dim:2*dim])
nn.init.eye_(mha.in_proj_weight.data[-dim:])
return mha
def get_own_self_impl(i_dim, p_dim, n_heads):
self_att = MultiheadAttention(input_dim=i_dim, proj_dim=p_dim, n_heads=n_heads, attn_type='self')
print(self_att)
nn.init.eye_(self_att.lin_o.data)
list(map(lambda x: nn.init.eye_(x), self_att.lin_k.data.chunk(3, dim=-1)))
return self_att
def get_own_cross_impl(i_dim, p_dim, n_heads):
cross_att = MultiheadAttention(input_dim=i_dim, proj_dim=p_dim, n_heads=n_heads)
print(cross_att)
nn.init.eye_(cross_att.lin_o.data)
nn.init.eye_(cross_att.lin_k.data)
nn.init.eye_(cross_att.lin_q.data)
nn.init.eye_(cross_att.lin_v.data)
return cross_att
def main():
np.random.seed(2)
torch.manual_seed(3)
torch.cuda.manual_seed(4)
input_dim = 512
batch_size = 100
vocab_size = 1000
# Create the embeddings
embs = nn.Embedding(vocab_size, embedding_dim=input_dim, padding_idx=0)
# Sample sequence lengths
src_seq_lens = np.random.normal(6, 1, size=(batch_size,)).astype('int')
trg_seq_lens = np.random.normal(6, 1, size=(batch_size,)).astype('int')
# Sample random vocab IDs
src_idxs = torch.randint(
low=1, high=vocab_size, size=(batch_size, src_seq_lens.max()))
trg_idxs = torch.randint(
low=1, high=vocab_size, size=(batch_size, trg_seq_lens.max()))
# pad short sequences
for seq, seqlen in enumerate(src_seq_lens):
src_idxs[seq, seqlen:].fill_(0)
for seq, seqlen in enumerate(trg_seq_lens):
trg_idxs[seq, seqlen:].fill_(0)
# masks with `True` for padded positions
src_padding_mask = src_idxs.eq(0)
trg_padding_mask = trg_idxs.eq(0)
# Verify lengths
assert np.allclose(src_seq_lens, src_idxs.ne(0).sum(1))
assert np.allclose(trg_seq_lens, trg_idxs.ne(0).sum(1))
# get embeddings
x = embs(src_idxs)
y = embs(trg_idxs)
# Verify lengths using embeddings
assert np.allclose(src_seq_lens, x.sum(-1).ne(0.0).sum(1))
assert np.allclose(trg_seq_lens, y.sum(-1).ne(0.0).sum(1))
mha = get_upstream_impl(input_dim, 1)
xp = x.transpose(0, 1)
yp = y.transpose(0, 1)
h_mha_self, p_mha_self = mha(
query=xp, key=xp, value=xp, key_padding_mask=src_padding_mask)
h_mha_cross, p_mha_cross = mha(
query=yp, key=xp, value=xp, key_padding_mask=src_padding_mask)
h_mha_self.transpose_(0, 1)
h_mha_cross.transpose_(0, 1)
# self attention
# q_mask: src
self_att = get_own_self_impl(input_dim, input_dim, n_heads=1)
h_self = self_att(k=x, v=x, q=x, k_mask=src_padding_mask, q_mask=None)
assert torch.allclose(h_self, h_mha_self, atol=1e-1)
# self attention with identity projections should produce the query itself
assert torch.allclose(
self_att(x, x, x, src_padding_mask, src_padding_mask), x, atol=1e-1)
# cross attention
# q_mask: trg
cross_att = get_own_cross_impl(input_dim, input_dim, n_heads=1)
h_cross = cross_att(k=x, v=x, q=y, k_mask=src_padding_mask, q_mask=trg_padding_mask)
assert torch.allclose(
cross_att(x, x, y, src_padding_mask, None), h_mha_cross, atol=1e-1)
#################
# multi-head test
#################
for nh in (1, 2, 4, 8, 16, 32):
print(f'# heads: {nh}')
self_att = get_own_self_impl(input_dim, input_dim, n_heads=nh)
cross_att = get_own_cross_impl(input_dim, input_dim, n_heads=nh)
torc_att = get_upstream_impl(input_dim, nh)
h_torc, p_torc = torc_att(xp, xp, xp, key_padding_mask=src_padding_mask)
h_torc.transpose_(0, 1)
h_self = self_att(k=x, k_mask=src_padding_mask, q_mask=None)
h_cross = cross_att(x, x, x, k_mask=src_padding_mask, q_mask=None)
assert torch.allclose(h_self, h_torc, atol=1e-1)
assert torch.allclose(h_cross, h_torc, atol=1e-1)
self_att = get_own_self_impl(input_dim, 256, n_heads=2)
cross_att = get_own_cross_impl(input_dim, 256, n_heads=2)
h_self = self_att(k=x, k_mask=src_padding_mask, q_mask=None)
h_cross = cross_att(x, x, x, k_mask=src_padding_mask, q_mask=None)
if __name__ == '__main__':
main()
|
python
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import mock
import logging
from airflow.models import (TaskInstance, DagRun)
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.decorators import apply_defaults
from airflow.utils.db import provide_session
from airflow.utils.dates import days_ago
from airflow.utils import timezone
from airflow.utils.state import State
from marquez_client.models import JobType, DatasetType
from marquez_airflow.dag import _EXTRACTORS as _DAG_EXTRACTORS
from marquez_airflow import DAG
from marquez_airflow.extractors import (
BaseExtractor, StepMetadata, Source, Dataset
)
from marquez_airflow.models import (
DbTableName,
DbTableSchema,
DbColumn
)
from marquez_airflow.utils import get_location, get_job_name
from uuid import UUID
log = logging.getLogger(__name__)
NO_INPUTS = []
NO_OUTPUTS = []
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
DAG_ID = 'test_dag'
DAG_RUN_ID = 'test_run_id_for_task_completed_and_failed'
DAG_RUN_ARGS = {'external_trigger': False}
# TODO: check with a different namespace and owner
DAG_NAMESPACE = 'default'
DAG_OWNER = 'anonymous'
DAG_DESCRIPTION = \
'A simple DAG to test the marquez.DAG metadata extraction flow.'
DAG_DEFAULT_ARGS = {
'owner': DAG_OWNER,
'depends_on_past': False,
'start_date': days_ago(1),
'email_on_failure': False,
'email_on_retry': False,
'email': ['[email protected]']
}
TASK_ID_COMPLETED = 'test_task_completed'
TASK_ID_FAILED = 'test_task_failed'
@pytest.fixture
@provide_session
def clear_db_airflow_dags(session=None):
session.query(DagRun).delete()
session.query(TaskInstance).delete()
@provide_session
def test_new_run_id(clear_db_airflow_dags, session=None):
dag = DAG(
DAG_ID,
schedule_interval='@daily',
default_args=DAG_DEFAULT_ARGS,
description=DAG_DESCRIPTION
)
run_id = dag.new_run_id()
assert UUID(run_id).version == 4
# tests a simple workflow with default extraction mechanism
@mock.patch('marquez_airflow.DAG.new_run_id')
@mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client')
@provide_session
def test_marquez_dag(mock_get_or_create_marquez_client, mock_uuid,
clear_db_airflow_dags, session=None):
dag = DAG(
DAG_ID,
schedule_interval='@daily',
default_args=DAG_DEFAULT_ARGS,
description=DAG_DESCRIPTION
)
# (1) Mock the marquez client method calls
mock_marquez_client = mock.Mock()
mock_get_or_create_marquez_client.return_value = mock_marquez_client
run_id_completed = "my-test_marquez_dag-uuid-completed"
run_id_failed = "my-test_marquez_dag-uuid-failed"
mock_uuid.side_effect = [run_id_completed, run_id_failed]
# (2) Add task that will be marked as completed
task_will_complete = DummyOperator(
task_id=TASK_ID_COMPLETED,
dag=dag
)
completed_task_location = get_location(task_will_complete.dag.fileloc)
# (3) Add task that will be marked as failed
task_will_fail = DummyOperator(
task_id=TASK_ID_FAILED,
dag=dag
)
failed_task_location = get_location(task_will_complete.dag.fileloc)
# (4) Create DAG run and mark as running
dagrun = dag.create_dagrun(
run_id=DAG_RUN_ID,
execution_date=DEFAULT_DATE,
state=State.RUNNING)
# Assert namespace meta call
mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE,
DAG_OWNER)
# Assert source and dataset meta calls
mock_marquez_client.create_source.assert_not_called()
mock_marquez_client.create_dataset.assert_not_called()
# Assert job meta calls
create_job_calls = [
mock.call(
job_name=f"{DAG_ID}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=None,
output_dataset=None,
context=mock.ANY,
description=DAG_DESCRIPTION,
namespace_name=DAG_NAMESPACE,
run_id=None
),
mock.call(
job_name=f"{DAG_ID}.{TASK_ID_FAILED}",
job_type=JobType.BATCH,
location=failed_task_location,
input_dataset=None,
output_dataset=None,
context=mock.ANY,
description=DAG_DESCRIPTION,
namespace_name=DAG_NAMESPACE,
run_id=None
)
]
log.info(
f"{ [name for name, args, kwargs in mock_marquez_client.mock_calls]}")
mock_marquez_client.create_job.assert_has_calls(create_job_calls)
# Assert job run meta calls
create_job_run_calls = [
mock.call(
job_name=f"{DAG_ID}.{TASK_ID_COMPLETED}",
run_id=mock.ANY,
run_args=DAG_RUN_ARGS,
nominal_start_time=mock.ANY,
nominal_end_time=mock.ANY,
namespace_name=DAG_NAMESPACE
),
mock.call(
job_name=f"{DAG_ID}.{TASK_ID_FAILED}",
run_id=mock.ANY,
run_args=DAG_RUN_ARGS,
nominal_start_time=mock.ANY,
nominal_end_time=mock.ANY,
namespace_name=DAG_NAMESPACE
)
]
mock_marquez_client.create_job_run.assert_has_calls(create_job_run_calls)
# (5) Start task that will be marked as completed
task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
# (6) Start task that will be marked as failed
ti1 = TaskInstance(task=task_will_fail, execution_date=DEFAULT_DATE)
ti1.state = State.FAILED
session.add(ti1)
session.commit()
dag.handle_callback(dagrun, success=True, session=session)
# Assert start run meta calls
start_job_run_calls = [
mock.call(run_id_completed, mock.ANY),
mock.call(run_id_failed, mock.ANY)
]
mock_marquez_client.mark_job_run_as_started.assert_has_calls(
start_job_run_calls
)
mock_marquez_client.mark_job_run_as_completed.assert_called_once_with(
run_id=run_id_completed,
at=mock.ANY
)
# When a task run completes, the task outputs are also updated in order
# to link a job version (=task version) to a dataset version.
# Using a DummyOperator, no outputs exists, so assert that the create
# dataset call is not invoked.
mock_marquez_client.create_dataset.assert_not_called()
dag.handle_callback(dagrun, success=False, session=session)
mock_marquez_client.mark_job_run_as_failed.assert_called_once_with(
run_id=run_id_failed,
at=mock.ANY
)
# Assert an attempt to version the outputs of a task is not made when
# a task fails
mock_marquez_client.create_dataset.assert_not_called()
class TestFixtureDummyOperator(DummyOperator):
@apply_defaults
def __init__(self, *args, **kwargs):
super(TestFixtureDummyOperator, self).__init__(*args, **kwargs)
class TestFixtureDummyExtractor(BaseExtractor):
operator_class = TestFixtureDummyOperator
source = Source(
type="DummySource",
name="dummy_source_name",
connection_url="http://dummy/source/url")
def __init__(self, operator):
super().__init__(operator)
def extract(self) -> [StepMetadata]:
inputs = [
Dataset.from_table(self.source, "extract_input1")
]
outputs = [
Dataset.from_table(self.source, "extract_output1")
]
return [StepMetadata(
name=get_job_name(task=self.operator),
inputs=inputs,
outputs=outputs,
context={
"extract": "extract"
}
)]
def extract_on_complete(self, task_instance) -> [StepMetadata]:
return []
class TestFixtureDummyExtractorOnComplete(BaseExtractor):
operator_class = TestFixtureDummyOperator
source = Source(
type="DummySource",
name="dummy_source_name",
connection_url="http://dummy/source/url")
def __init__(self, operator):
super().__init__(operator)
def extract(self) -> [StepMetadata]:
return []
def extract_on_complete(self, task_instance) -> [StepMetadata]:
inputs = [
Dataset.from_table_schema(self.source, DbTableSchema(
schema_name='schema',
table_name=DbTableName('extract_on_complete_input1'),
columns=[DbColumn(
name='field1',
type='text',
description='',
ordinal_position=1
),
DbColumn(
name='field2',
type='text',
description='',
ordinal_position=2
)]
))
]
outputs = [
Dataset.from_table(self.source, "extract_on_complete_output1")
]
return [StepMetadata(
name=get_job_name(task=self.operator),
inputs=inputs,
outputs=outputs,
context={
"extract_on_complete": "extract_on_complete"
}
)]
# test the lifecycle including with extractors
@mock.patch('marquez_airflow.DAG.new_run_id')
@mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client')
@provide_session
def test_marquez_dag_with_extractor(mock_get_or_create_marquez_client,
mock_uuid,
clear_db_airflow_dags,
session=None):
# --- test setup
dag_id = 'test_marquez_dag_with_extractor'
dag = DAG(
dag_id,
schedule_interval='@daily',
default_args=DAG_DEFAULT_ARGS,
description=DAG_DESCRIPTION
)
run_id = "my-test-uuid"
mock_uuid.side_effect = [run_id]
# Mock the marquez client method calls
mock_marquez_client = mock.Mock()
mock_get_or_create_marquez_client.return_value = mock_marquez_client
# Add task that will be marked as completed
task_will_complete = TestFixtureDummyOperator(
task_id=TASK_ID_COMPLETED,
dag=dag
)
completed_task_location = get_location(task_will_complete.dag.fileloc)
# Add the dummy extractor to the list for the task above
_DAG_EXTRACTORS[task_will_complete.__class__] = TestFixtureDummyExtractor
# --- pretend run the DAG
# Create DAG run and mark as running
dagrun = dag.create_dagrun(
run_id='test_marquez_dag_with_extractor_run_id',
execution_date=DEFAULT_DATE,
state=State.RUNNING)
# --- Asserts that the job starting triggers metadata updates
# Namespace created
mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE,
DAG_OWNER)
# Datasets are updated
mock_marquez_client.create_source.assert_called_with(
'dummy_source_name',
'DummySource',
'http://dummy/source/url'
)
mock_marquez_client.create_dataset.assert_has_calls([
mock.call(
dataset_name='extract_input1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_input1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=None
),
mock.call(
dataset_name='extract_output1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_output1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=None
)
])
# job is updated
mock_marquez_client.create_job.assert_called_once_with(
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=[{'namespace': 'default', 'name': 'extract_input1'}],
output_dataset=[{'namespace': 'default', 'name': 'extract_output1'}],
context=mock.ANY,
description=DAG_DESCRIPTION,
namespace_name=DAG_NAMESPACE,
run_id=None
)
assert mock_marquez_client.create_job.mock_calls[0].\
kwargs['context'].get('extract') == 'extract'
# run is created
mock_marquez_client.create_job_run.assert_called_once_with(
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
run_id=run_id,
run_args=DAG_RUN_ARGS,
nominal_start_time=mock.ANY,
nominal_end_time=mock.ANY,
namespace_name=DAG_NAMESPACE
)
log.info("Marquez client calls when starting:")
for call in mock_marquez_client.mock_calls:
log.info(call)
assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [
'create_namespace',
'create_source',
'create_dataset',
'create_source',
'create_dataset',
'create_job',
'create_job_run'
]
mock_marquez_client.reset_mock()
# --- Pretend complete the task
task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
dag.handle_callback(dagrun, success=True, session=session)
# run is started
mock_marquez_client.mark_job_run_as_started.assert_called_once_with(
run_id, mock.ANY
)
# --- Assert that the right marquez calls are done
# job is updated before completion
mock_marquez_client.create_job.assert_has_calls([
mock.call(
namespace_name=DAG_NAMESPACE,
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=[
{'namespace': 'default', 'name': 'extract_input1'}
],
output_dataset=[
{'namespace': 'default', 'name': 'extract_output1'}
],
context=mock.ANY,
description=DAG_DESCRIPTION,
run_id=run_id
)
])
assert mock_marquez_client.create_job.mock_calls[0].\
kwargs['context'].get('extract') == 'extract'
mock_marquez_client.mark_job_run_as_completed.assert_called_once_with(
run_id=run_id,
at=mock.ANY
)
# When a task run completes, the task outputs are also updated in order
# to link a job version (=task version) to a dataset version.
mock_marquez_client.create_dataset.assert_has_calls([
mock.call(
dataset_name='extract_input1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_input1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=None
),
mock.call(
dataset_name='extract_output1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_output1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=run_id
)
])
log.info("Marquez client calls when completing:")
for call in mock_marquez_client.mock_calls:
log.info(call)
assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [
'create_namespace',
'create_source',
'create_dataset',
'create_source',
'create_dataset',
'create_job',
'mark_job_run_as_started',
'mark_job_run_as_completed'
]
@mock.patch('marquez_airflow.DAG.new_run_id')
@mock.patch('marquez_airflow.marquez.Marquez.get_or_create_marquez_client')
@provide_session
def test_marquez_dag_with_extract_on_complete(
mock_get_or_create_marquez_client,
mock_uuid,
clear_db_airflow_dags,
session=None):
# --- test setup
dag_id = 'test_marquez_dag_with_extractor'
dag = DAG(
dag_id,
schedule_interval='@daily',
default_args=DAG_DEFAULT_ARGS,
description=DAG_DESCRIPTION
)
run_id = "my-test-uuid"
mock_uuid.side_effect = [run_id]
# Mock the marquez client method calls
mock_marquez_client = mock.Mock()
mock_get_or_create_marquez_client.return_value = mock_marquez_client
# Add task that will be marked as completed
task_will_complete = TestFixtureDummyOperator(
task_id=TASK_ID_COMPLETED,
dag=dag
)
completed_task_location = get_location(task_will_complete.dag.fileloc)
# Add the dummy extractor to the list for the task above
_DAG_EXTRACTORS[task_will_complete.__class__] = \
TestFixtureDummyExtractorOnComplete
# Create DAG run and mark as running
dagrun = dag.create_dagrun(
run_id='test_marquez_dag_with_extractor_run_id',
execution_date=DEFAULT_DATE,
state=State.RUNNING)
# Namespace created
mock_marquez_client.create_namespace.assert_called_once_with(DAG_NAMESPACE,
DAG_OWNER)
log.info("Marquez client calls when starting:")
for call in mock_marquez_client.mock_calls:
log.info(call)
assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [
'create_namespace'
]
mock_marquez_client.reset_mock()
# --- Pretend complete the task
task_will_complete.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
dag.handle_callback(dagrun, success=True, session=session)
# Datasets are updated
mock_marquez_client.create_source.assert_called_with(
'dummy_source_name',
'DummySource',
'http://dummy/source/url'
)
# Datasets get called twice, once to reenact the _begin_run_flow
# and then again at _end_run_flow w/ the run id appended for
# the output dataset
mock_marquez_client.create_dataset.assert_has_calls([
mock.call(
dataset_name='schema.extract_on_complete_input1',
dataset_type=DatasetType.DB_TABLE,
physical_name='schema.extract_on_complete_input1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=mock.ANY,
run_id=None
),
mock.call(
dataset_name='extract_on_complete_output1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_on_complete_output1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=None
),
mock.call(
dataset_name='schema.extract_on_complete_input1',
dataset_type=DatasetType.DB_TABLE,
physical_name='schema.extract_on_complete_input1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=mock.ANY,
run_id=None
),
mock.call(
dataset_name='extract_on_complete_output1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_on_complete_output1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id='my-test-uuid'
)
])
# job is updated
mock_marquez_client.create_job.assert_has_calls([
mock.call(
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=[{'namespace': 'default',
'name': 'schema.extract_on_complete_input1'}],
output_dataset=[{'namespace': 'default',
'name': 'extract_on_complete_output1'}],
context=mock.ANY,
description=DAG_DESCRIPTION,
namespace_name=DAG_NAMESPACE,
run_id=None
),
mock.call(
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=[{'namespace': 'default',
'name': 'schema.extract_on_complete_input1'}],
output_dataset=[{'namespace': 'default',
'name': 'extract_on_complete_output1'}],
context=mock.ANY,
description=DAG_DESCRIPTION,
namespace_name=DAG_NAMESPACE,
run_id='my-test-uuid'
)
])
assert mock_marquez_client.create_job.mock_calls[0].\
kwargs['context'].get('extract_on_complete') == 'extract_on_complete'
# run is created
mock_marquez_client.create_job_run.assert_called_once_with(
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
run_id=run_id,
run_args=DAG_RUN_ARGS,
nominal_start_time=mock.ANY,
nominal_end_time=mock.ANY,
namespace_name=DAG_NAMESPACE
)
# run is started
mock_marquez_client.mark_job_run_as_started.assert_called_once_with(
run_id, mock.ANY
)
# --- Assert that the right marquez calls are done
# job is updated before completion
mock_marquez_client.create_job.assert_has_calls([
mock.call(
namespace_name=DAG_NAMESPACE,
job_name=f"{dag_id}.{TASK_ID_COMPLETED}",
job_type=JobType.BATCH,
location=completed_task_location,
input_dataset=[
{'namespace': 'default',
'name': 'schema.extract_on_complete_input1'}
],
output_dataset=[
{'namespace': 'default', 'name': 'extract_on_complete_output1'}
],
context=mock.ANY,
description=DAG_DESCRIPTION,
run_id=run_id
)
])
assert mock_marquez_client.create_job.mock_calls[0].\
kwargs['context'].get('extract_on_complete') == 'extract_on_complete'
mock_marquez_client.mark_job_run_as_completed.assert_called_once_with(
run_id=run_id,
at=mock.ANY
)
# When a task run completes, the task outputs are also updated in order
# to link a job version (=task version) to a dataset version.
mock_marquez_client.create_dataset.assert_has_calls([
mock.call(
dataset_name='schema.extract_on_complete_input1',
dataset_type=DatasetType.DB_TABLE,
physical_name='schema.extract_on_complete_input1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=mock.ANY,
run_id=None
),
mock.call(
dataset_name='extract_on_complete_output1',
dataset_type=DatasetType.DB_TABLE,
physical_name='extract_on_complete_output1',
source_name='dummy_source_name',
namespace_name=DAG_NAMESPACE,
fields=[],
run_id=run_id
)
])
log.info("Marquez client calls when completing:")
for call in mock_marquez_client.mock_calls:
log.info(call)
assert [name for name, args, kwargs in mock_marquez_client.mock_calls] == [
'create_namespace',
'create_source',
'create_dataset',
'create_source',
'create_dataset',
'create_job',
'create_job_run',
'create_source',
'create_dataset',
'create_source',
'create_dataset',
'create_job',
'mark_job_run_as_started',
'mark_job_run_as_completed'
]
|
python
|
# Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for synthetic_data_generator.py."""
from absl.testing import absltest
import numpy as np
from tempfile import TemporaryDirectory
from unittest.mock import patch
from wfa_planning_evaluation_framework.data_generators.synthetic_data_design_generator import (
SyntheticDataDesignGenerator,
)
from wfa_planning_evaluation_framework.data_generators.data_design import DataDesign
from wfa_planning_evaluation_framework.data_generators.data_set_parameters import (
GeneratorParameters,
)
from wfa_planning_evaluation_framework.data_generators.independent_overlap_data_set import (
IndependentOverlapDataSet,
)
from wfa_planning_evaluation_framework.data_generators import lhs_data_design_example
from wfa_planning_evaluation_framework.data_generators import m3_data_design
from wfa_planning_evaluation_framework.data_generators import (
analysis_example_data_design,
)
from wfa_planning_evaluation_framework.data_generators import simple_data_design_example
from wfa_planning_evaluation_framework.data_generators import single_publisher_design
TEST_LEVELS = {
"largest_publisher_size": [8, 16],
"overlap_generator_params": [
GeneratorParameters(
"Independent",
IndependentOverlapDataSet,
{"largest_pub_to_universe_ratio": 0.5, "random_generator": 1},
),
],
}
class SyntheticDataDesignGeneratorTest(absltest.TestCase):
def test_simple_design(self):
simple_design = simple_data_design_example.generate_data_design_config(
np.random.default_rng(seed=1)
)
self.assertLen(list(simple_design), 27)
def test_lhs_design(self):
lhs_design = lhs_data_design_example.generate_data_design_config(
np.random.default_rng(seed=1)
)
self.assertLen(list(lhs_design), 10)
def test_m3_design_size(self):
m3_design = m3_data_design.generate_data_design_config(
np.random.default_rng(seed=1)
)
self.assertLen(list(m3_design), 100)
def test_analysis_example_design_size(self):
analysis_example_design = (
analysis_example_data_design.generate_data_design_config(
np.random.default_rng(seed=1)
)
)
self.assertLen(list(analysis_example_design), 72)
@patch(
"wfa_planning_evaluation_framework.data_generators.m3_data_design.LEVELS",
new=TEST_LEVELS,
)
@patch(
"wfa_planning_evaluation_framework.data_generators.m3_data_design.NUM_SAMPLES_FOR_LHS",
new=2,
)
def test_m3_design_generate_universe_size(self):
test_design = m3_data_design.generate_data_design_config(
np.random.default_rng(seed=1)
)
x = next(test_design).overlap_generator_params.params["universe_size"]
y = next(test_design).overlap_generator_params.params["universe_size"]
self.assertCountEqual([x, y], [16, 32])
def test_single_publisher_design(self):
sp_design = single_publisher_design.generate_data_design_config(
np.random.default_rng(seed=1)
)
self.assertLen(
list(sp_design),
128,
"Expected single pub design to have {} datasets but it had {}".format(
128, len(list(sp_design))
),
)
def test_synthetic_data_generator_simple_design(self):
with TemporaryDirectory() as d:
data_design_generator = SyntheticDataDesignGenerator(
d, simple_data_design_example.__file__, 1, False
)
data_design_generator()
dd = DataDesign(d)
self.assertEqual(dd.count, 27)
def test_synthetic_data_generator_lhs_design(self):
with TemporaryDirectory() as d:
data_design_generator = SyntheticDataDesignGenerator(
d, lhs_data_design_example.__file__, 1, False
)
data_design_generator()
dd = DataDesign(d)
self.assertEqual(dd.count, 10)
if __name__ == "__main__":
absltest.main()
|
python
|
"""
Shutterstock CLI
"""
import click
from .images import images
from .videos import videos
from .audio import audio
from .editorial import editorial
from .cv import cv
from .ai_audio import ai_audio
from .editor import editor
from .contributors import contributors
from .user import user
from .test import test
@click.group()
def cli():
"""
For reference information about the endpoints that this CLI calls, see the API reference.
http://api-reference.shutterstock.com/
"""
cli.add_command(images)
cli.add_command(videos)
cli.add_command(audio)
cli.add_command(editorial)
cli.add_command(cv)
cli.add_command(ai_audio)
cli.add_command(editor)
cli.add_command(contributors)
cli.add_command(user)
cli.add_command(test)
if __name__ == "__main__":
cli()
|
python
|
try:
from SmartFramework.serialize.tools import serializejson_, authorized_classes
from SmartFramework.serialize import serialize_parameters
except:
from serializejson import serialize_parameters
from serializejson.tools import serializejson_, authorized_classes
import array
def serializejson_array(inst):
typecode = inst.typecode
max_size = serialize_parameters.array_readable_max_size
if typecode == "u":
return inst.__class__, (typecode, inst.tounicode()), None
if isinstance(max_size, dict):
if typecode in max_size:
max_size = max_size[typecode]
else:
max_size = 0
if max_size is None or len(inst) <= max_size:
return inst.__class__, (typecode, inst.tolist()), None
else:
return inst.__class__, (typecode, inst.tobytes()), None
serializejson_[array.array] = serializejson_array
authorized_classes.update({"array.array", "array._array_reconstructor"})
|
python
|
import collections
import copy
import json
import os
import sys
import unittest
from ethereum import utils
from ethereum import config
from ethereum.tools import tester as t
from ethereum.utils import mk_contract_address, checksum_encode
import rlp
import trie
import trie.utils.nibbles
from test_utils import rec_hex, rec_bin, deploy_solidity_contract
sys.path.append(os.path.join(os.path.dirname(__file__), '../../offchain'))
import proveth
class TestVerifier(unittest.TestCase):
def null_address(self):
return '0x' + '0' * 40
def assertEqualAddr(self, *args, **kwargs):
return self.assertEqual(checksum_encode(args[0]), checksum_encode(args[1]), *args[2:], **kwargs)
def setUp(self):
config.config_metropolis['BLOCK_GAS_LIMIT'] = 2**60
self.chain = t.Chain(env=config.Env(config=config.config_metropolis))
self.chain.mine()
contract_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
self.verifier_contract = deploy_solidity_contract(
self.chain,
{'ProvethVerifier.sol': {'urls': [os.path.join(contract_dir, 'ProvethVerifier.sol')]},
'Solidity-RLP/contracts/RLPReader.sol': {'urls': [os.path.join(contract_dir, 'Solidity-RLP/contracts/RLPReader.sol')]},
'ProvethVerifierTestHelper.sol': {'urls': [os.path.join(contract_dir, 'ProvethVerifierTestHelper.sol')]},
},
contract_dir,
'ProvethVerifierTestHelper.sol',
'ProvethVerifierTestHelper',
10**7,
)
self.rpc_cache = {}
def test_decodeUnsignedTx(self):
tx = collections.OrderedDict([
('nonce', 3),
('gasprice', 0x06fc23ac00),
('startgas', 0x0494e5),
('to', rec_bin('0xb13f6f423781bd1934fc8599782f5e161ce7c816')),
('value', 0x2386f26fc10000),
('data', rec_bin('0xf435f5a7000000000000000000000000c198eccab3fe1f35e9160b48eb18af7934a13262')),
])
rlp_tx = rlp.encode(list(tx.values()))
print(rec_hex(utils.sha3(rlp_tx)))
(nonce, gasprice, startgas, to, value, data, is_contract_creation) = \
self.verifier_contract.exposedDecodeUnsignedTx(
rlp_tx
)
self.assertEqual(nonce, tx['nonce'])
self.assertEqual(gasprice, tx['gasprice'])
self.assertEqual(startgas, tx['startgas'])
self.assertEqualAddr(to, tx['to'])
self.assertEqual(value, tx['value'])
self.assertEqual(data, tx['data'])
self.assertFalse(is_contract_creation)
def test_decodeSignedTx(self):
tx = collections.OrderedDict([
('nonce', 3),
('gasprice', 0x06fc23ac00),
('startgas', 0x0494e5),
('to', rec_bin('0xb13f6f423781bd1934fc8599782f5e161ce7c816')),
('value', 0x2386f26fc10000),
('data', rec_bin('0xf435f5a7000000000000000000000000c198eccab3fe1f35e9160b48eb18af7934a13262')),
('v', 28),
('r', 115792089237316195423570985008687907852837564279074904382605163141518161494337 - 1),
('s', 17),
])
rlp_tx = rlp.encode(list(tx.values()))
print(rec_hex(utils.sha3(rlp_tx)))
(nonce, gasprice, startgas, to, value, data, v, r, s, is_contract_creation) = \
self.verifier_contract.exposedDecodeSignedTx(
rlp_tx
)
self.assertEqual(nonce, tx['nonce'])
self.assertEqual(gasprice, tx['gasprice'])
self.assertEqual(startgas, tx['startgas'])
self.assertEqualAddr(to, tx['to'])
self.assertEqual(value, tx['value'])
self.assertEqual(data, tx['data'])
self.assertEqual(v, tx['v'])
self.assertEqual(r, tx['r'])
self.assertEqual(s, tx['s'])
self.assertFalse(is_contract_creation)
def test_sharedPrefixLength(self):
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(0, b'', b'a'),
0)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(0, b'b', b'a'),
0)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(0, b'b', b''),
0)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(0, b'a', b'a'),
1)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(0, b'aaac', b'aaab'),
3)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(1, b'aaac', b'aaab'),
2)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(3, b'aaac', b'aaab'),
0)
self.assertEqual(
self.verifier_contract.exposedSharedPrefixLength(4, b'aaaa', b'aaaa'),
0)
def test_merklePatriciaCompactDecode(self):
self.assertEqual(
[False, utils.decode_hex('')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('00')))
self.assertEqual(
[False, utils.decode_hex('00')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('10')))
self.assertEqual(
[False, utils.decode_hex('0102030405')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('112345')))
self.assertEqual(
[False, utils.decode_hex('000102030405')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('00012345')))
self.assertEqual(
[True, utils.decode_hex('000f010c0b08')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('200f1cb8')))
self.assertEqual(
[True, utils.decode_hex('0f010c0b08')],
self.verifier_contract.exposedMerklePatriciaCompactDecode(utils.decode_hex('3f1cb8')))
def test_validateMPTProof(self):
def assert_at_mpt_key(mpt, mpt_key, value):
mpt_key = bytes(mpt_key)
stack = proveth.generate_proof(mpt, mpt_key)
self.assertEqual(
self.verifier_contract.exposedValidateMPTProof(
mpt.root_hash,
bytes(mpt_key),
rlp.encode(stack),
),
value)
mpt = trie.HexaryTrie(db={})
# empty trie
assert_at_mpt_key(mpt, [], b'')
assert_at_mpt_key(mpt, [1], b'')
assert_at_mpt_key(mpt, [1, 2], b'')
assert_at_mpt_key(mpt, [1, 2, 3], b'')
assert_at_mpt_key(mpt, [1, 2, 3, 4], b'')
# trie with one element
key = bytes([127])
mpt_key = list(trie.utils.nibbles.bytes_to_nibbles(rlp.encode(key)))
value = b'hello'
mpt.set(key, value)
self.assertEqual(mpt_key, [7, 15])
assert_at_mpt_key(mpt, mpt_key, b'hello')
assert_at_mpt_key(mpt, [], b'')
assert_at_mpt_key(mpt, [6], b'')
assert_at_mpt_key(mpt, [7], b'')
assert_at_mpt_key(mpt, [7, 14], b'')
assert_at_mpt_key(mpt, [7, 15, 0], b'')
# trie with two elements
key = bytes([126])
mpt_key = list(trie.utils.nibbles.bytes_to_nibbles(rlp.encode(key)))
value = b'bonjour'
mpt.set(key, value)
self.assertEqual(mpt_key, [7, 14])
assert_at_mpt_key(mpt, mpt_key, b'bonjour')
assert_at_mpt_key(mpt, [7, 15], b'hello')
assert_at_mpt_key(mpt, [], b'')
assert_at_mpt_key(mpt, [6], b'')
assert_at_mpt_key(mpt, [7], b'')
assert_at_mpt_key(mpt, [7, 14, 0], b'')
def test_manual1(self):
# from block 1322230 on ropsten
decoded_proof_blob = [
'01',
[
'5b5782c32df715c083da95b805959d4718ec698915a4b0288e325aa346436be1',
'1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
'fee3a49dc4243fa92019fc4331228043b3c5e825',
'13a50145091c1b5bae07abe10da88c54c5111c3fbb74fc91074ad2ffec311f6b',
'0c673fc4822ba97cc737cfa7a839d6f6f755deedb1506490911f710bfa9315bf',
'0c1fcb2441331ab1abc2e174a7293acce160d0b04f35a4b791bf89e9fd452b10',
'00000000000000200000000000000000000000000010002000000000000000000040000000000000000000000010000000000000000000000040000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000100',
'0c0b580c',
'142cf6',
'47e7c4',
'0428a1',
'596e599f',
'd883010606846765746887676f312e382e338664617277696e',
'6ebda3617b113ba6550d08cb34119f940ddb96b509c62b7d0a8420722329d5b4',
'61ebb9e58c93ac26',
],
'01',
[
['da42945ae3c75118e89abff39ad566fd0a30b574e5df8ae70ce59d4cc5f19cb1', '', '', '', '', '', '', '', 'ca85a0d0ed219e8583feadf2dce0a73aa05e7d6a790c32efcc1dd6c901195f16', '', '', '', '', '', '', '', ''],
['', 'e61bb422a77353192ae2b4b29c3773b018da71d1425b2a48cca04d7da9917fab', '6b46aad90e0a9eeede8f2ad992401e52b3e52ce7d5bf723a48922401d5af95cc', '997f63912b72cdf8a907025644e1df51c313015c4e9e51500fa6ffa52241eef4', '5ad4d0c46a043da4e1da601955a1d29d5bd3b6c5b2dfc2776c8a898f998af498', '457048648440cf69193e770035a2df6f42ab5a6b8bc4d789a92074dc2beb2091', '', '', '', '', '', '', '', '', '', '', ''],
['20', 'f88b820beb8506fc23ac00832dd5d8943d04303126cd6e75324825455685b028401e0ec280a4e733ca974e6964610000000000000000000000000000000000000000000000000000000029a0f5405ffd54b78fc27dc56c49364ec22ba94c471f4639f052cfe324e3fc05d1d3a041291d64a8cdf499c386fde5bc04a1ca743aa81f65dc59198d29f8d66ee588a5'],
],
]
block_hash = utils.decode_hex('51c92d45e39db17e43f0f7333de44c592b504bb8ac24dc3c39135d46655bae4f')
result, index, nonce, gas_price, gas, to, value, data, v, r, s, contract_creation = self.verifier_contract.txProof(
block_hash,
rlp.encode(rec_bin(decoded_proof_blob)),
startgas=10**6)
self.assertEqual(result, self.verifier_contract.TX_PROOF_RESULT_PRESENT())
self.assertEqual(index, 1)
def assert_failed_call(modified_decoded_proof_blob, block_hash=block_hash):
with self.assertRaises(t.TransactionFailed):
_ = self.verifier_contract.txProof(
block_hash,
rlp.encode(rec_bin(modified_decoded_proof_blob)),
startgas=10**6)
assert_failed_call(decoded_proof_blob, block_hash=utils.decode_hex('51c92d45e39db17e43f0f7333de44c592b504bb8ac24dc3c39135d46655bae40'))
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[0] = 'ab'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[1][0] = '5b5782c32df715c083da95b805959d4718ec698915a4b0288e325aa346436be2'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[2] = '02'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[3][0][0] = 'da42945ae3c75118e89abff39ad566fd0a30b574e5df8ae70ce59d4cc5f19cb2'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[3][1][1] = 'e61bb422a77353192ae2b4b29c3773b018da71d1425b2a48cca04d7da9917fac'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[3][2][0] = '21'
assert_failed_call(modified_decoded_proof_blob)
modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob)
modified_decoded_proof_blob[3][2][1] = modified_decoded_proof_blob[3][2][1].replace(
'e733ca974e69646100000000000000000000000000000000000000000000000000000000',
'f733ca974e69646100000000000000000000000000000000000000000000000000000000')
assert_failed_call(modified_decoded_proof_blob)
def test_manual2(self):
proof_blob = utils.decode_hex('f904bb01f90203a0e7c29816452c474e261b1d02d3bab489df00069892863bc654ddd609b7f7fc4ba01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794b2930b35844a230f00e51431acae96fe543a0347a00272d32e39cf493242e079965942776e1a6492e74532eb25d5ed8f56aab40331a01b0134ed566a1bf54f29bd55929b75139de4450d8bf43d33b02a1b26b4873af6a0b9b5d8d9f58ad6b835be1b1bde2461e809905257c2610329fe94de5109c2cfadb9010003424803034030147969000005008084532a1c8a0020000400000424302c0578310012204d0883204010ca0000401800020448800000909104008110e02b006000060142000000994112c20924a0200002820020002402000801001020004412203000281600200000c1802940080a1c0010a029080410408a0020150400681c32020104600800004400100900032840000285000800209440420209010500800606200010420003050010100064884080000c23a02080c130028054a401080040086402088c0252005c00000000e82000406005824800412011200c2020a0010810000901120010020c08c4a000828440040008a004608950810200c208008887090e046147907c834c4d6b837a11d38379ca58845a709667827331a0915aa3cd5dea74d24e39ffd6acc5da3b2b692d4b3fcc6cc26222b9205fd64b46880eb2c4f807cb14248182f902aff90131a08e61195faa58f0c8467b7f62a15ec6122d7f9484021eaf7b9fe372fffde310b8a05b9674e1d977f6a30fc12a9ac35aeecbbe0d49dcc0d8952e5d833539504ca649a05262513c779d4d62f559300126b4a34435923dceadd291ec3e1d4da6d284b8fca0672d7beb02403cbf570f2aa2956d3d6a8be5b928a425ee263e744db509958d06a0cb1005949f6f4f14beeaf39c9ee07fc2cf68fcb804aaecc4168828bb265f3f1ca0d89a971d2813936524ef4e38ee2dd300cf02764bec57845b8c0064118246ab97a014d80d349c773c690ef2711a7c4c916cec6a333594d378d2b6cebf2bff1c9ce2a0a932d14ab39608d22c0ba8a0e2fafa8a9359968f29b34827cff06e3cc5d0fdeea059d69a507142ffd21a40f829f094f283758e8a32b077c8373a6215cc0e0d61328080808080808080f851a0af2178a9930004f22ee1e2eb87f1035e559971de937dc9ae6f6ba7b6640df2a7a0d92a714520fe45d10652c6b429ca037104644bae3fe13edb8e52b2efb645e16a808080808080808080808080808080e218a01bf683031aaa6ef9c75509021a8ba5f4c9eb6f134413d57b2d3ae92699f58d95f891a06b621312dca8604610878ecf0384c9855dd6e388a0d587441be1dedfe2c73804a0530e3712b1763a989ef0b80b5a90619e7b0452069f1cf4ba3be0a7459a8654cca05f174cd7f8bd7be186b9f8127e181be52bb94cc662f36a8ec1fa3c6083db0ec7a0d94d6ab7f87669a948645e2191b193672be0720018f15115e71720140a027f3e80808080808080808080808080f87020b86df86b821935843b9aca00825208944ce3adf23418a3c3f4a61cde1c7057677befd9bf86719a2d5d6e008025a0121772bdbd0945dcfea42152186b9f7ae6d0271fdd6d1777fcadf5383a88336ca021196e93025480173f429c9e9a27c1921dd6c10b3705c30125424285250bd5a5')
block_hash = utils.decode_hex('23d2df699671ac564b382f5b046e0cf533ebc44ab8e36426cef9d60486c3a220')
result, index, nonce, gas_price, gas, to, value, data, v, r, s, contract_creation = self.verifier_contract.txProof(
block_hash,
proof_blob,
startgas=10**6)
self.assertEqual(result, self.verifier_contract.TX_PROOF_RESULT_PRESENT())
self.assertEqual(index, 130)
def help_test_entire_block(self, path_to_jsonrpc_response):
PRESENT = self.verifier_contract.TX_PROOF_RESULT_PRESENT()
ABSENT = self.verifier_contract.TX_PROOF_RESULT_ABSENT()
with open(path_to_jsonrpc_response, 'r') as f:
jsonrpc = json.load(f)
block_dict = jsonrpc['result']
for i in range(len(block_dict['transactions']) + 20):
proof_blob = proveth.generate_proof_blob_from_jsonrpc_response(jsonrpc, i)
result, index, nonce, gas_price, gas, to, value, data, v, r, s, contract_creation = self.verifier_contract.txProof(
utils.decode_hex(block_dict['hash']),
proof_blob,
startgas=10**7)
print(i)
present = i < len(block_dict['transactions'])
self.assertEqual(result, PRESENT if present else ABSENT)
self.assertEqual(index, i)
if present:
self.assertEqual(nonce, utils.parse_as_int(block_dict['transactions'][i]['nonce']))
self.assertEqual(gas_price, utils.parse_as_int(block_dict['transactions'][i]['gasPrice']))
self.assertEqual(gas, utils.parse_as_int(block_dict['transactions'][i]['gas']))
# contract creation corner case
if utils.normalize_address(block_dict['transactions'][i]['to'] or '', allow_blank=True) == b'':
self.assertEqual(utils.normalize_address(to), utils.normalize_address("0x0000000000000000000000000000000000000000"))
self.assertEqual(utils.parse_as_int(contract_creation), 1)
else:
self.assertEqual(utils.normalize_address(to), utils.normalize_address(block_dict['transactions'][i]['to']))
self.assertEqual(utils.parse_as_int(contract_creation), 0)
self.assertEqual(value, utils.parse_as_int(block_dict['transactions'][i]['value']))
self.assertEqual(data, utils.decode_hex(block_dict['transactions'][i]['input']))
self.assertEqual(v, utils.parse_as_int(block_dict['transactions'][i]['v']))
self.assertEqual(r, utils.parse_as_int(block_dict['transactions'][i]['r']))
self.assertEqual(s, utils.parse_as_int(block_dict['transactions'][i]['s']))
if i > 0 and i % 100 == 0:
self.chain.mine()
def test_mainnet_blocks(self):
blocks = [
'0x0b963d785005ee2d25cb078daba5dd5cae1b376707ac53533d8ad638f9cb9659.json',
'0x23d2df699671ac564b382f5b046e0cf533ebc44ab8e36426cef9d60486c3a220.json',
'0x2471ea6da13bb9926a988580fae95056ef1610291d3628aca0ef7f91456c9ef4.json',
'0x829bb7e1211b1f6f85b9944c2ba1a1614a7d7dedebe9e6bd530ca93dae126a16.json',
]
for block in blocks:
with self.subTest(block=block):
print(block)
self.help_test_entire_block(os.path.join('resources', block))
def test_single_short_transaction(self):
self.help_test_entire_block('resources/block_with_single_short_transaction.json')
def test_big_block_with_short_transaction(self):
self.help_test_entire_block('resources/big_block_with_short_transaction.json')
def test_txValidate(self):
block_hash = '0x51c92d45e39db17e43f0f7333de44c592b504bb8ac24dc3c39135d46655bae4f'
print("Testing Tx validation for tx 0 in (ropsten) block {}"
.format(block_hash))
block_header = [
"0x5b5782c32df715c083da95b805959d4718ec698915a4b0288e325aa346436be1",
"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"0xfee3a49dc4243fa92019fc4331228043b3c5e825",
"0x13a50145091c1b5bae07abe10da88c54c5111c3fbb74fc91074ad2ffec311f6b",
"0x0c673fc4822ba97cc737cfa7a839d6f6f755deedb1506490911f710bfa9315bf",
"0x0c1fcb2441331ab1abc2e174a7293acce160d0b04f35a4b791bf89e9fd452b10",
"0x00000000000000200000000000000000000000000010002000000000000000000040000000000000000000000010000000000000000000000040000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000100",
202070028,
1322230,
4712388,
272545,
1500404127,
"0xd883010606846765746887676f312e382e338664617277696e",
"0x6ebda3617b113ba6550d08cb34119f940ddb96b509c62b7d0a8420722329d5b4",
"0x61ebb9e58c93ac26",
]
self.assertEqual(utils.sha3(rlp.encode(rec_bin(block_header))), rec_bin(block_hash))
tx = collections.OrderedDict([
('nonce', 3),
('gasprice', 0x06fc23ac00),
('startgas', 0x0494e5),
('to', rec_bin('0xb13f6f423781bd1934fc8599782f5e161ce7c816')),
('value', 0x2386f26fc10000),
('data', rec_bin('0xf435f5a7000000000000000000000000c198eccab3fe1f35e9160b48eb18af7934a13262')),
('v', 0x29),
('r', 0x4602fcb7ef369fbe1e6d7d1658934a18bcc3b373454fc33dedb53cd9dd0226d2),
('s', 0x3a94a58becc2493007a6411b73a2b5c5a58b17b7a79bbb103568cc62b8945961),
])
proof_type = 1
tx_index = 0
stack = [
['da42945ae3c75118e89abff39ad566fd0a30b574e5df8ae70ce59d4cc5f19cb1', '', '', '', '', '', '', '', 'ca85a0d0ed219e8583feadf2dce0a73aa05e7d6a790c32efcc1dd6c901195f16', '', '', '', '', '', '', '', ''],
['30', rec_hex(rlp.encode(list(tx.values())))],
]
proof_blob = rlp.encode(rec_bin([
proof_type,
block_header,
tx_index,
stack,
]))
(result, index, nonce, gasprice, startgas, to, value, data, v, r, s, contract_creation) = \
self.verifier_contract.txProof(
rec_bin(block_hash),
proof_blob,
startgas=10**6,
)
self.assertEqual(result, self.verifier_contract.TX_PROOF_RESULT_PRESENT())
self.assertEqual(index, 0)
self.assertEqual(nonce, tx['nonce'])
self.assertEqual(gasprice, tx['gasprice'])
self.assertEqual(startgas, tx['startgas'])
self.assertEqualAddr(to, tx['to'])
self.assertEqual(value, tx['value'])
self.assertEqual(data, tx['data'])
self.assertEqual(v, tx['v'])
self.assertEqual(r, tx['r'])
self.assertEqual(s, tx['s'])
self.assertEqual(contract_creation, False)
if __name__ == '__main__':
unittest.main()
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 09:26:03 2022
@author: thejorabek
"""
'''son=10
print(son,type(son))
son=3.14
print(son,type(son))
son='Salom Foundationchilar'
print(son,type(son))
son=True
print(son,type(son))
son=int()
print(son,type(son))
print("Assalom",123,3.14,True,sep='salom')
print(1,2,3,4,5,6,7,8,9,10,sep='+',end='')
print(' =',1+2+3+4+5+6+7+8+9+10)
print(float(son))
print(str(son))
print(bool(son))
son=1
print(bool(son))'''
'''a=int(input('a='))
b=int(input('b='))
c=a
a=b
b=c
print("a =",a)
print("b =",b)'''
'''a=int(input('a='))
b=int(input('b='))
c=int(input('c='))
d=b
b=a
a=c
c=d
print('a=',a)
print('b=',b)
print('c=',c)'''
'''a=int(input('a='))
b=int(input('b='))
c=int(input('c='))
d=a
a=b
b=c
c=d
print('a=',a)
print('b=',b)
print('c=',c)'''
'''son=int(input("Sonni kiriting: "))
son+=1
print("son=",son,type(son))
fson=float(input("Haqiqiy sonni kiriting: "))
print("fson=",fson,type(fson))
bson=bool(input())
print("bson=",bson)
text=input("Textni kiriting: ")
print(text,type(text))
text='Salom bolalar'
print(text)
text="Salom o'rdak"
print(text)
text="""Salom "Salom BRO" bolalar
'O'rdak' Hello Foundation
Ch\tao \nBRO"""
print(text)'''
'''text="Salom"
print(len(text))
print(text[0],text[1],text[2],text[3],text[4])
print(text[-1],text[-2],text[-3],text[-4],text[-5],sep="")
print(*text)
text="Salom bolalar"
print(*text[0:len(text):2],sep=',') # 0-indeksdan oxirigacha 2 ta qadamda sakrash
print(*text[::-1]) # stringni teskari chiqarish
print(text[:5]) # boshidan 5-indeksgacha chiqarish
print(text[6:]) # 6-indeksdan oxirigacha chiqarish
# [start : end : step]
# start - boshlanish indeksi, end - tugash indeksi, step - oshirish yoki kamayish qadami'''
|
python
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: 17.py
@time: 2019/5/29 22:07
@desc:
'''
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) < 1:
return []
string = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = list(string[digits[0]])
for i in digits[1:]:
temp = []
for j in res:
for k in string[i]:
temp.append(j + k)
res = temp
return res
string = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = []
def recursion(self, comb, digits):
if not digits:
res.append(comb)
for i in string[digits[0]]:
self.recursion(comb+i, digits[1:])
self.recursion([], digits)
|
python
|
# Copyright (C) 2014-2017 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Author: Maciek Fijalkowski
from features.softwaresupport.core import *
def prepare_default_command():
"""
This function stores a command that is used to run a dhclient on DUT.
It specifies a lease file and a config file.
"""
build_leases_path()
build_config_path()
world.clntCfg["log_file"] = world.f_cfg.software_install_path + "dhclient.log"
world.clntCfg["command"] = world.f_cfg.software_install_path + 'sbin/dhclient -6 -v ' \
+ world.f_cfg.iface + " -lf " + world.clntCfg["leases"] + \
" -cf " + world.clntCfg["confpath"] + " &> " + \
world.clntCfg["log_file"]
def build_leases_path():
"""
This small function stores in variable a path for leases file.
"""
world.clntCfg["leases"] = world.f_cfg.software_install_path + "dhclient.leases"
def build_config_path():
"""
This small function stores in variable a path for config file.
"""
world.clntCfg["confpath"] = world.f_cfg.software_install_path + "dhclient.conf"
def clean_leases():
"""
Function that executes command on DUT, which removes the old lease
file and creates an empty, new one.
"""
fabric_run_command('echo y | rm ' + world.clntCfg['leases'])
fabric_run_command('touch ' + world.clntCfg['leases'])
def create_clnt_cfg():
"""
Function that stores in variable a template for config file
that is being generated.
"""
world.clntCfg["config"] = "# Config file for ISC-DHCPv6 client\n"
openBracket = "{"
closeBracket = "}"
eth = world.f_cfg.iface
world.clntCfg["config"] += """interface "{eth}" {openBracket} \n\trequest;""".format(**locals())
def write_clnt_cfg_to_file():
"""
Function creates a config file from previously specified template.
It checks whether there are equal count of open/closing brackets.
"""
openCount = world.clntCfg["config"].count("{")
closeCount = world.clntCfg["config"].count("}")
if openCount == closeCount + 1:
world.clntCfg["config"] += "\n}\n"
# write generated config to a file
world.clntCfg["Filename"] = "temp"
cfgFile = open(world.clntCfg["Filename"], "w")
cfgFile.write(world.clntCfg["config"])
cfgFile.close()
def restart_clnt(step):
"""
This function shut downs and later starts dhclient on DUT.
@step("Restart client.")
"""
stop_clnt()
# clean_leases() ## ?
fabric_sudo_command('(rm nohup.out; nohup ' + \
world.clntCfg["command"] + ' & ); sleep 1;')
def stop_clnt():
"""
This function destroys every running instance of dhclient on DUT.
"""
fabric_run_command("sudo killall dhclient &>/dev/null")
def kill_clnt():
"""
Same as stop_clnt().
"""
stop_clnt()
def release_command():
"""
Function that executes a previously generated command with "-r"
option, which results in sending by dhclient RELEASE repeatedly, until
REPLY is received. There's no need to execute it with delay like in
dibbler-client's case, since message will being retransmitted.
"""
fabric_sudo_command('(rm nohup.out; nohup ' + \
world.clntCfg["command"] + ' -r & ); sleep 1;')
def client_option_req(step, another1, opt):
"""
@step("Client is configured to include (another )?(\S+) option.")
Lettuce step for adding particular option to dhclient's config file.
Currently only supported options are IA_PD and rapid_commit.
"""
if opt == "IA_PD":
if "command" not in world.clntCfg.keys():
prepare_default_command()
idx = world.clntCfg["command"].find("&")
world.clntCfg["command"] = world.clntCfg["command"][:idx] + "-P " + \
world.clntCfg["command"][idx:]
elif opt == "rapid_commit":
world.clntCfg["config"] += "\n send dhcp6.rapid-commit;"
def client_setup(step):
"""
@step("Setting up test.")
This function provides a lettuce step for initializing clients' config.
"""
prepare_default_command()
create_clnt_cfg()
def make_script():
"""
Function creates a script file that will execute a previously created
command with delay. Execution will take place on DUT. It is important
to sniff first SOLICIT message sent by client, hence the delay.
See also more detailed description of it in dibbler_client/functions.py.
"""
world.clntCfg["content"] = "!#/bin/sh\nsleep 10;\n"
world.clntCfg["content"] += world.clntCfg["command"] + " &\n"
world.clntCfg["script"] = "temp1"
script = open(world.clntCfg["script"], "w")
script.write(world.clntCfg["content"])
script.close()
def client_parse_config(step, contain):
"""
@step("Client MUST (NOT )?use prefix with values given by server.")
Step firstly downloads a lease file from DUT. Then, the needed parts
are further parsed and specific lease structure is created.
"""
world.clntCfg["lease_file"] = world.cfg["dir_name"] + "/dhclient.leases"
fabric_download_file(world.clntCfg["leases"], world.clntCfg["lease_file"])
file_ = open(world.clntCfg["lease_file"],"r").readlines()
count = 0
# remove things that we do not want
for line in list(file_):
if "lease6" not in line:
del(file_[count])
count += 1
else:
break
count = 0
for line in list(file_):
if "option" in line:
del(file_[count])
else:
count += 1
# add required quotes and semicolons to file;
# it needs to have a dhcpd.conf syntax in order
# to got accepted by ParseISCString function;
copied = []
for line in file_:
line = line.lstrip().rstrip("\n")
line = line.split(" ")
if len(line) > 1:
if line[1][0].isdigit():
if line[1][-1] is ";":
line[1] = '''"''' + line[1][:len(line[1])-1] + '''"''' + line[1][-1]
else:
line[1] = '''"''' + line[1] + '''"'''
elif line[0] == "}":
line[0] += ";"
copied.append(line)
copied = [" ".join(line) + "\n" for line in copied]
result = " ".join(copied)
parsed = ParseISCString(result)
if 'lease6' in parsed:
del(parsed['lease6']['interface'])
for entry in parsed['lease6'].keys():
if entry.startswith("ia-pd"):
del(parsed['lease6'][entry]['starts'])
for key in parsed['lease6'][entry].keys():
if key.startswith('iaprefix'):
del(parsed['lease6'][entry][key]['starts'])
world.clntCfg["real_lease"] = parsed
"""
print "\n\n\n"
print world.clntCfg["real_lease"]
print "\n\n\n"
print world.clntCfg['scapy_lease']
print "\n\n\n"
"""
if contain:
assert world.clntCfg["real_lease"] == world.clntCfg['scapy_lease'], \
"leases are different."
else:
assert world.clntCfg["real_lease"] != world.clntCfg['scapy_lease'], \
"leases are the same, but they should not be."
def start_clnt(step):
"""
@step("Client is started.")
Lettuce step for writing config to file, sending it and starting client.
"""
write_clnt_cfg_to_file()
make_script()
get_common_logger().debug("Start dhclient6 with generated config:")
clean_leases()
world.clntCfg["keep_lease"] = False
fabric_send_file(world.clntCfg["Filename"], world.f_cfg.software_install_path + "dhclient.conf")
fabric_send_file(world.clntCfg["script"], world.f_cfg.software_install_path + "comm.sh")
fabric_remove_file_command(world.clntCfg["Filename"])
fabric_remove_file_command(world.clntCfg["log_file"])
fabric_sudo_command('(rm nohup.out; nohup bash ' + \
world.f_cfg.software_install_path + 'comm.sh &); sleep 1;')
def save_leases():
world.clntCfg["keep_lease"] = True
def save_logs():
fabric_download_file(world.clntCfg["log_file"], world.cfg["dir_name"] + \
"/dhclient.log")
def clear_all():
fabric_remove_file_command(world.f_cfg.software_install_path + 'comm.sh')
fabric_remove_file_command(world.f_cfg.software_install_path + 'dhclient.conf')
fabric_remove_file_command(world.f_cfg.software_install_path + 'dhclient.leases')
remove_local_file(world.clntCfg["Filename"])
remove_local_file(world.clntCfg["script"])
if not world.clntCfg["keep_lease"] and world.clntCfg['lease_file'] is not "":
remove_local_file(world.clntCfg['lease_file'])
|
python
|
from os import stat
from re import VERBOSE
from request_api.services.commentservice import commentservice
from request_api.services.notificationservice import notificationservice
from request_api.models.FOIRawRequests import FOIRawRequest
from request_api.models.FOIMinistryRequests import FOIMinistryRequest
from request_api.models.FOIRequestStatus import FOIRequestStatus
import json
from request_api.models.default_method_result import DefaultMethodResult
class assignmentevent:
""" FOI Event management service
"""
def createassignmentevent(self, requestid, requesttype, userid, isministryuser):
ischanged = self.__haschanged(requestid, requesttype)
if ischanged == True:
notificationresponse = self.__createnotification(requestid, requesttype, userid, isministryuser)
if notificationresponse.success == True:
return DefaultMethodResult(True,'Notification posted',requestid)
else:
return DefaultMethodResult(False,'unable to post notification',requestid)
return DefaultMethodResult(True,'No change',requestid)
def __createnotification(self, requestid, requesttype, userid, isministryuser):
notification = self.__preparenotification()
return notificationservice().createnotification(notification, requestid, requesttype, self.__assignmenttype(isministryuser), userid)
def __preparenotification(self):
return self.__notificationmessage()
def __haschanged(self, requestid, requesttype):
assignments = self.__getassignments(requestid, requesttype)
if len(assignments) ==1 and self.__isnoneorblank(assignments[0]) == False:
return True
if len(assignments) == 2 and \
((assignments[0]['assignedto'] != assignments[1]['assignedto'] and self.__isnoneorblank(assignments[0]['assignedto']) == False) \
or (requesttype == "ministryrequest" and \
assignments[0]['assignedministryperson'] != assignments[1]['assignedministryperson'] \
and self.__isnoneorblank(assignments[0]['assignedministryperson']) == False)):
return True
return False
def __isnoneorblank(self, value):
if value is not None and value != '':
return False
return True
def __getassignments(self, requestid, requesttype):
if requesttype == "ministryrequest":
return FOIMinistryRequest.getassignmenttransition(requestid)
else:
return FOIRawRequest.getassignmenttransition(requestid)
def __notificationmessage(self):
return 'New Request Assigned to You.'
def __assignmenttype(self, isministryuser):
return 'Ministry Assignment' if isministryuser == True else 'IAO Assignment'
|
python
|
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""
Helper functions --- :mod:`MDAnalysis.lib.util`
====================================================
Small helper functions that don't fit anywhere else.
.. versionchanged:: 0.11.0
Moved mathematical functions into lib.mdamath
Files and directories
---------------------
.. autofunction:: filename
.. autofunction:: openany
.. autofunction:: anyopen
.. autofunction:: greedy_splitext
.. autofunction:: which
.. autofunction:: realpath
.. autofunction:: get_ext
.. autofunction:: check_compressed_format
.. autofunction:: format_from_filename_extension
.. autofunction:: guess_format
Streams
-------
Many of the readers are not restricted to just reading files. They can
also use gzip-compressed or bzip2-compressed files (through the
internal use of :func:`openany`). It is also possible to provide more
general streams as inputs, such as a :func:`cStringIO.StringIO`
instances (essentially, a memory buffer) by wrapping these instances
into a :class:`NamedStream`. This :class:`NamedStream` can then be
used in place of an ordinary file name (typically, with a
class:`~MDAnalysis.core.universe.Universe` but it is also possible to
*write* to such a stream using :func:`MDAnalysis.Writer`).
.. rubric: Examples
In the following example, we use a PDB stored as a string ``pdb_s``::
import MDAnalysis
from MDAnalysis.lib.util import NamedStream
import cStringIO
pdb_s = "TITLE Lonely Ion\\nATOM 1 NA NA+ 1 81.260 64.982 10.926 1.00 0.00\\n"
u = MDAnalysis.Universe(NamedStream(cStringIO.StringIO(pdb_s), "ion.pdb"))
print(u)
# <Universe with 1 atoms>
print(u.atoms.positions)
# [[ 81.26000214 64.98200226 10.92599964]]
It is important to provide a proper pseudo file name with the correct extension
(".pdb") to :class:`NamedStream` because the file type recognition uses the
extension of the file name to determine the file format or alternatively
provide the ``format="pdb"`` keyword argument to the
:class:`~MDAnalysis.core.universe.Universe`.
The use of streams becomes more interesting when MDAnalysis is used as glue
between different analysis packages and when one can arrange things so that
intermediate frames (typically in the PDB format) are not written to disk but
remain in memory via e.g. :mod:`cStringIO` buffers.
.. The following does *not* work because most readers need to
.. reopen files, which is not possible with http streams. Might
.. need to implement a buffer.
..
.. Read a test LAMMPS data file from the MDAnalysis repository::
..
.. import MDAnalysis
.. from MDAnalysis.lib.util import NamedStream
.. import urllib2
.. URI = "https://mdanalysis.googlecode.com/git-history/develop/testsuite/MDAnalysisTests/data/mini.data"
.. urldata = NamedStream(urllib2.urlopen(URI), "mini.data")
.. u = MDAnalysis.Universe(urldata)
.. Note:: A remote connection created by :func:`urllib2.urlopen` is not seekable
and therefore will often not work as an input. But try it...
.. autoclass:: NamedStream
:members:
.. autofunction:: isstream
Containers and lists
--------------------
.. autofunction:: iterable
.. autofunction:: asiterable
.. autofunction:: hasmethod
.. autoclass:: Namespace
Arrays
------
.. autofunction:: unique_int_1d(values)
.. autofunction:: unique_rows
.. autofunction:: blocks_of
File parsing
------------
.. autoclass:: FORTRANReader
:members:
.. autodata:: FORTRAN_format_regex
Data manipulation and handling
------------------------------
.. autofunction:: fixedwidth_bins
.. autofunction:: get_weights
.. autofunction:: ltruncate_int
.. autofunction:: flatten_dict
Strings
-------
.. autofunction:: convert_aa_code
.. autofunction:: parse_residue
.. autofunction:: conv_float
Class decorators
----------------
.. autofunction:: cached
Function decorators
-------------------
.. autofunction:: static_variables
.. autofunction:: warn_if_not_unique
.. autofunction:: check_coords
Code management
---------------
.. autofunction:: deprecate
.. autoclass:: _Deprecate
.. autofunction:: dedent_docstring
Data format checks
------------------
.. autofunction:: check_box
.. Rubric:: Footnotes
.. [#NamedStreamClose] The reason why :meth:`NamedStream.close` does
not close a stream by default (but just rewinds it to the
beginning) is so that one can use the class :class:`NamedStream` as
a drop-in replacement for file names, which are often re-opened
(e.g. when the same file is used as a topology and coordinate file
or when repeatedly iterating through a trajectory in some
implementations). The ``close=True`` keyword can be supplied in
order to make :meth:`NamedStream.close` actually close the
underlying stream and ``NamedStream.close(force=True)`` will also
close it.
"""
from __future__ import division, absolute_import
import six
from six.moves import range, map
import sys
__docformat__ = "restructuredtext en"
import os
import os.path
import errno
from contextlib import contextmanager
import bz2
import gzip
import re
import io
import warnings
import functools
from functools import wraps
import textwrap
import mmtf
import numpy as np
from numpy.testing import assert_equal
import inspect
from ..exceptions import StreamWarning, DuplicateWarning
try:
from ._cutil import unique_int_1d
except ImportError:
raise ImportError("MDAnalysis not installed properly. "
"This can happen if your C extensions "
"have not been built.")
# Python 3.0, 3.1 do not have the builtin callable()
try:
callable(list)
except NameError:
# http://bugs.python.org/issue10518
import collections
def callable(obj):
return isinstance(obj, collections.Callable)
try:
from os import PathLike
except ImportError:
class PathLike(object):
pass
def filename(name, ext=None, keep=False):
"""Return a new name that has suffix attached; replaces other extensions.
Parameters
----------
name : str or NamedStream
filename; extension is replaced unless ``keep=True``;
`name` can also be a :class:`NamedStream` (and its
:attr:`NamedStream.name` will be changed accordingly)
ext : None or str
extension to use in the new filename
keep : bool
- ``False``: replace existing extension with `ext`;
- ``True``: keep old extension if one existed
.. versionchanged:: 0.9.0
Also permits :class:`NamedStream` to pass through.
"""
if ext is not None:
ext = ext.lower()
if not ext.startswith(os.path.extsep):
ext = os.path.extsep + ext
root, origext = os.path.splitext(name)
if not keep or len(origext) == 0:
newname = root + ext
if isstream(name):
name.name = newname
else:
name = newname
return name if isstream(name) else str(name)
@contextmanager
def openany(datasource, mode='rt', reset=True):
"""Context manager for :func:`anyopen`.
Open the `datasource` and close it when the context of the :keyword:`with`
statement exits.
`datasource` can be a filename or a stream (see :func:`isstream`). A stream
is reset to its start if possible (via :meth:`~io.IOBase.seek` or
:meth:`~cString.StringIO.reset`).
The advantage of this function is that very different input sources
("streams") can be used for a "file", ranging from files on disk (including
compressed files) to open file objects to sockets and strings---as long as
they have a file-like interface.
Parameters
----------
datasource : a file or a stream
mode : {'r', 'w'} (optional)
open in r(ead) or w(rite) mode
reset : bool (optional)
try to read (`mode` 'r') the stream from the start [``True``]
Examples
--------
Open a gzipped file and process it line by line::
with openany("input.pdb.gz") as pdb:
for line in pdb:
if line.startswith('ATOM'):
print(line)
Open a URL and read it::
import urllib2
with openany(urllib2.urlopen("https://www.mdanalysis.org/")) as html:
print(html.read())
See Also
--------
:func:`anyopen`
"""
stream = anyopen(datasource, mode=mode, reset=reset)
try:
yield stream
finally:
stream.close()
# On python 3, we want to use bz2.open to open and uncompress bz2 files. That
# function allows to specify the type of the uncompressed file (bytes ot text).
# The function does not exist in python 2, thus we must use bz2.BZFile to
# which we cannot tell if the uncompressed file contains bytes or text.
# Therefore, on python 2 we use a proxy function that removes the type of the
# uncompressed file from the `mode` argument.
try:
bz2.open
except AttributeError:
# We are on python 2 and bz2.open is not available
def bz2_open(filename, mode):
"""Open and uncompress a BZ2 file"""
mode = mode.replace('t', '').replace('b', '')
return bz2.BZ2File(filename, mode)
else:
# We are on python 3 so we can use bz2.open
bz2_open = bz2.open
def anyopen(datasource, mode='rt', reset=True):
"""Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.reset`).
If possible, the attribute ``stream.name`` is set to the filename or
"<stream>" if no filename could be associated with the *datasource*.
Parameters
----------
datasource
a file (from :class:`file` or :func:`open`) or a stream (e.g. from
:func:`urllib2.urlopen` or :class:`cStringIO.StringIO`)
mode: {'r', 'w', 'a'} (optional)
Open in r(ead), w(rite) or a(ppen) mode. More complicated
modes ('r+', 'w+', ...) are not supported; only the first letter of
`mode` is used and thus any additional modifiers are silently ignored.
reset: bool (optional)
try to read (`mode` 'r') the stream from the start
Returns
-------
file-like object
See Also
--------
:func:`openany`
to be used with the :keyword:`with` statement.
.. versionchanged:: 0.9.0
Only returns the ``stream`` and tries to set ``stream.name = filename`` instead of the previous
behavior to return a tuple ``(stream, filename)``.
"""
handlers = {'bz2': bz2_open, 'gz': gzip.open, '': open}
if mode.startswith('r'):
if isstream(datasource):
stream = datasource
try:
filename = str(stream.name) # maybe that does not always work?
except AttributeError:
filename = "<stream>"
if reset:
try:
stream.reset()
except (AttributeError, IOError):
try:
stream.seek(0)
except (AttributeError, IOError):
warnings.warn("Stream {0}: not guaranteed to be at the beginning."
"".format(filename),
category=StreamWarning)
else:
stream = None
filename = datasource
for ext in ('bz2', 'gz', ''): # file == '' should be last
openfunc = handlers[ext]
stream = _get_stream(datasource, openfunc, mode=mode)
if stream is not None:
break
if stream is None:
raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename))
elif mode.startswith('w') or mode.startswith('a'): # append 'a' not tested...
if isstream(datasource):
stream = datasource
try:
filename = str(stream.name) # maybe that does not always work?
except AttributeError:
filename = "<stream>"
else:
stream = None
filename = datasource
name, ext = os.path.splitext(filename)
if ext.startswith('.'):
ext = ext[1:]
if not ext in ('bz2', 'gz'):
ext = '' # anything else but bz2 or gz is just a normal file
openfunc = handlers[ext]
stream = openfunc(datasource, mode=mode)
if stream is None:
raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename))
else:
raise NotImplementedError("Sorry, mode={mode!r} is not implemented for {datasource!r}".format(**vars()))
try:
stream.name = filename
except (AttributeError, TypeError):
pass # can't set name (e.g. cStringIO.StringIO)
return stream
def _get_stream(filename, openfunction=open, mode='r'):
"""Return open stream if *filename* can be opened with *openfunction* or else ``None``."""
try:
stream = openfunction(filename, mode=mode)
except (IOError, OSError) as err:
# An exception might be raised due to two reasons, first the openfunction is unable to open the file, in this
# case we have to ignore the error and return None. Second is when openfunction can't open the file because
# either the file isn't there or the permissions don't allow access.
if errno.errorcode[err.errno] in ['ENOENT', 'EACCES']:
six.reraise(*sys.exc_info())
return None
if mode.startswith('r'):
# additional check for reading (eg can we uncompress) --- is this needed?
try:
stream.readline()
except IOError:
stream.close()
stream = None
except:
stream.close()
raise
else:
stream.close()
stream = openfunction(filename, mode=mode)
return stream
def greedy_splitext(p):
"""Split extension in path *p* at the left-most separator.
Extensions are taken to be separated from the filename with the
separator :data:`os.extsep` (as used by :func:`os.path.splitext`).
Arguments
---------
p : str
path
Returns
-------
(root, extension) : tuple
where ``root`` is the full path and filename with all
extensions removed whereas ``extension`` is the string of
all extensions.
Example
-------
>>> greedy_splitext("/home/joe/protein.pdb.bz2")
('/home/joe/protein', '.pdb.bz2')
"""
path, root = os.path.split(p)
extension = ''
while True:
root, ext = os.path.splitext(root)
extension = ext + extension
if not ext:
break
return os.path.join(path, root), extension
def hasmethod(obj, m):
"""Return ``True`` if object *obj* contains the method *m*."""
return hasattr(obj, m) and callable(getattr(obj, m))
def isstream(obj):
"""Detect if `obj` is a stream.
We consider anything a stream that has the methods
- ``close()``
and either set of the following
- ``read()``, ``readline()``, ``readlines()``
- ``write()``, ``writeline()``, ``writelines()``
Parameters
----------
obj : stream or str
Returns
-------
bool
``True`` if `obj` is a stream, ``False`` otherwise
See Also
--------
:mod:`io`
.. versionadded:: 0.9.0
"""
signature_methods = ("close",)
alternative_methods = (
("read", "readline", "readlines"),
("write", "writeline", "writelines"))
# Must have ALL the signature methods
for m in signature_methods:
if not hasmethod(obj, m):
return False
# Must have at least one complete set of alternative_methods
alternative_results = [
np.all([hasmethod(obj, m) for m in alternatives])
for alternatives in alternative_methods]
return np.any(alternative_results)
def which(program):
"""Determine full path of executable `program` on :envvar:`PATH`.
(Jay at http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python)
Parameters
----------
programe : str
name of the executable
Returns
-------
path : str or None
absolute path to the executable if it can be found, else ``None``
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
real_program = realpath(program)
if is_exe(real_program):
return real_program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
@functools.total_ordering
class NamedStream(io.IOBase, PathLike):
"""Stream that also provides a (fake) name.
By wrapping a stream `stream` in this class, it can be passed to
code that uses inspection of the filename to make decisions. For
instance. :func:`os.path.split` will work correctly on a
:class:`NamedStream`.
The class can be used as a context manager.
:class:`NamedStream` is derived from :class:`io.IOBase` (to indicate that
it is a stream). Many operations that normally expect a string will also
work with a :class:`NamedStream`; for instance, most of the functions in
:mod:`os.path` will work with the exception of :func:`os.path.expandvars`
and :func:`os.path.expanduser`, which will return the :class:`NamedStream`
itself instead of a string if no substitutions were made.
Example
-------
Wrap a :func:`cStringIO.StringIO` instance to write to::
import cStringIO
import os.path
stream = cStringIO.StringIO()
f = NamedStream(stream, "output.pdb")
print(os.path.splitext(f))
Wrap a :class:`file` instance to read from::
stream = open("input.pdb")
f = NamedStream(stream, stream.name)
Use as a context manager (closes stream automatically when the
:keyword:`with` block is left)::
with NamedStream(open("input.pdb"), "input.pdb") as f:
# use f
print f.closed # --> False
# ...
print f.closed # --> True
Note
----
This class uses its own :meth:`__getitem__` method so if `stream`
implements :meth:`stream.__getitem__` then that will be masked and
this class should not be used.
Warning
-------
By default, :meth:`NamedStream.close` will **not close the
stream** but instead :meth:`~NamedStream.reset` it to the
beginning. [#NamedStreamClose]_ Provide the ``force=True`` keyword
to :meth:`NamedStream.close` to always close the stream.
"""
def __init__(self, stream, filename, reset=True, close=False):
"""Initialize the :class:`NamedStream` from a `stream` and give it a `name`.
The constructor attempts to rewind the stream to the beginning unless
the keyword `reset` is set to ``False``. If rewinding fails, a
:class:`MDAnalysis.StreamWarning` is issued.
Parameters
----------
stream : stream
an open stream (e.g. :class:`file` or :func:`cStringIO.StringIO`)
filename : str
the filename that should be associated with the stream
reset : bool (optional)
start the stream from the beginning (either :meth:`reset` or :meth:`seek`)
when the class instance is constructed
close : bool (optional)
close the stream when a :keyword:`with` block exits or when
:meth:`close` is called; note that the default is **not to close
the stream**
Notes
-----
By default, this stream will *not* be closed by :keyword:`with` and
:meth:`close` (see there) unless the `close` keyword is set to
``True``.
.. versionadded:: 0.9.0
"""
# constructing the class from an instance of itself has weird behavior
# on __del__ and super on python 3. Let's warn the user and ensure the
# class works normally.
if isinstance(stream, NamedStream):
warnings.warn("Constructed NamedStream from a NamedStream",
RuntimeWarning)
stream = stream.stream
self.stream = stream
self.name = filename
self.close_stream = close
if reset:
self.reset()
def reset(self):
"""Move to the beginning of the stream"""
# try to rewind
try:
self.stream.reset() # e.g. StreamIO
except (AttributeError, IOError):
try:
self.stream.seek(0) # typical file objects
except (AttributeError, IOError):
warnings.warn("NamedStream {0}: not guaranteed to be at the beginning."
"".format(self.name),
category=StreamWarning)
# access the stream
def __getattr__(self, x):
try:
return getattr(self.stream, x)
except AttributeError:
return getattr(self.name, x)
def __iter__(self):
return iter(self.stream)
def __next__(self):
return self.stream.__next__()
def __enter__(self):
# do not call the stream's __enter__ because the stream is already open
return self
def __exit__(self, *args):
# NOTE: By default (close=False) we only reset the stream and NOT close it; this makes
# it easier to use it as a drop-in replacement for a filename that might
# be opened repeatedly (at least in MDAnalysis)
#try:
# return self.stream.__exit__(*args)
#except AttributeError:
# super(NamedStream, self).__exit__(*args)
self.close()
def __fspath__(self):
return self.name
# override more IOBase methods, as these are provided by IOBase and are not
# caught with __getattr__ (ugly...)
def close(self, force=False):
"""Reset or close the stream.
If :attr:`NamedStream.close_stream` is set to ``False`` (the default)
then this method will *not close the stream* and only :meth:`reset` it.
If the *force* = ``True`` keyword is provided, the stream will be
closed.
.. Note:: This ``close()`` method is non-standard. ``del NamedStream``
always closes the underlying stream.
"""
if self.close_stream or force:
try:
return self.stream.close()
except AttributeError:
return super(NamedStream, self).close()
else:
self.flush()
self.reset()
def __del__(self):
"""Always closes the stream."""
self.close(force=True)
@property
def closed(self):
"""``True`` if stream is closed."""
try:
return self.stream.closed
except AttributeError:
return super(NamedStream, self).closed
def seek(self, offset, whence=os.SEEK_SET):
"""Change the stream position to the given byte `offset` .
Parameters
----------
offset : int
`offset` is interpreted relative to the position
indicated by `whence`.
whence : {0, 1, 2} (optional)
Values for `whence` are:
- :data:`io.SEEK_SET` or 0 – start of the stream (the default); `offset`
should be zero or positive
- :data:`io.SEEK_CUR` or 1 – current stream position; `offset` may be
negative
- :data:`io.SEEK_END` or 2 – end of the stream; `offset` is usually
negative
Returns
-------
int
the new absolute position in bytes.
"""
try:
return self.stream.seek(offset, whence) # file.seek: no kw
except AttributeError:
return super(NamedStream, self).seek(offset, whence)
def tell(self):
"""Return the current stream position."""
try:
return self.stream.tell()
except AttributeError:
return super(NamedStream, self).tell()
def truncate(self, *size):
"""Truncate the stream's size to `size`.
Parameters
----------
size : int (optional)
The `size` defaults to the current position (if no `size` argument
is supplied). The current file position is not changed.
"""
try:
return self.stream.truncate(*size)
except AttributeError:
return super(NamedStream, self).truncate(*size)
def seekable(self):
"""Return ``True`` if the stream supports random access.
If ``False``, :meth:`seek`, :meth:`tell` and :meth:`truncate` will
raise :exc:`IOError`.
"""
try:
return self.stream.seekable()
except AttributeError:
return super(NamedStream, self).seekable()
def readable(self):
"""Return ``True`` if the stream can be read from.
If ``False``, :meth:`read` will raise :exc:`IOError`.
"""
try:
return self.stream.readable()
except AttributeError:
return super(NamedStream, self).readable()
def writable(self):
"""Return ``True`` if the stream can be written to.
If ``False``, :meth:`write` will raise :exc:`IOError`.
"""
try:
return self.stream.writable()
except AttributeError:
return super(NamedStream, self).writable()
def flush(self):
"""Flush the write buffers of the stream if applicable.
This does nothing for read-only and non-blocking streams. For file
objects one also needs to call :func:`os.fsync` to write contents to
disk.
"""
try:
return self.stream.flush()
except AttributeError:
return super(NamedStream, self).flush()
def fileno(self):
"""Return the underlying file descriptor (an integer) of the stream if it exists.
An :exc:`IOError` is raised if the IO object does not use a file descriptor.
"""
try:
return self.stream.fileno()
except AttributeError:
# IOBase.fileno does not raise IOError as advertised so we do this here
six.raise_from(
IOError("This NamedStream does not use a file descriptor."),
None)
def readline(self):
try:
return self.stream.readline()
except AttributeError:
return super(NamedStream, self).readline()
# fake the important parts of the string API
# (other methods such as rfind() are automatically dealt with via __getattr__)
def __getitem__(self, x):
return self.name[x]
def __eq__(self, x):
return self.name == x
def __ne__(self, x):
return not self == x
def __lt__(self, x):
return self.name < x
def __len__(self):
return len(self.name)
def __add__(self, x):
return self.name + x
def __radd__(self, x):
return x + self.name
def __mul__(self, x):
return self.name * x
__rmul__ = __mul__
def __format__(self, format_spec):
return self.name.format(format_spec)
def __str__(self):
return self.name
def __repr__(self):
return "<NamedStream({0}, {1})>".format(self.stream, self.name)
def realpath(*args):
"""Join all args and return the real path, rooted at ``/``.
Expands '~', '~user', and environment variables such as :envvar:`$HOME`.
Returns ``None`` if any of the args is ``None``.
"""
if None in args:
return None
return os.path.realpath(os.path.expanduser(os.path.expandvars(os.path.join(*args))))
def get_ext(filename):
"""Return the lower-cased extension of `filename` without a leading dot.
Parameters
----------
filename : str
Returns
-------
root : str
ext : str
"""
root, ext = os.path.splitext(filename)
if ext.startswith(os.extsep):
ext = ext[1:]
return root, ext.lower()
def check_compressed_format(root, ext):
"""Check if this is a supported gzipped/bzip2ed file format and return UPPERCASE format.
Parameters
----------
root : str
path of a file, without extension `ext`
ext : str
extension (currently only "bz2" and "gz" are recognized as compressed formats)
Returns
-------
format : str
upper case format extension *if* the compression can be handled by
:func:`openany`
See Also
--------
openany : function that is used to open and decompress formats on the fly; only
compression formats implemented in :func:`openany` are recognized
"""
# XYZReader&others are setup to handle both plain and compressed (bzip2, gz) files
# ..so if the first file extension is bzip2 or gz, look at the one to the left of it
if ext.lower() in ("bz2", "gz"):
try:
root, ext = get_ext(root)
except Exception:
six.raise_from(
TypeError("Cannot determine coordinate format for '{0}.{1}'"
"".format(root, ext)),
None)
return ext.upper()
def format_from_filename_extension(filename):
"""Guess file format from the file extension.
Parameters
----------
filename : str
Returns
-------
format : str
Raises
------
TypeError
if the file format cannot be determined
"""
try:
root, ext = get_ext(filename)
except Exception:
six.raise_from(TypeError(
"Cannot determine file format for file '{0}'.\n"
" You can set the format explicitly with "
"'Universe(..., format=FORMAT)'.".format(filename)),
None)
format = check_compressed_format(root, ext)
return format
def guess_format(filename):
"""Return the format of `filename`
The current heuristic simply looks at the filename extension and can work
around compressed format extensions.
Parameters
----------
filename : str or stream
path to the file or a stream, in which case ``filename.name`` is looked
at for a hint to the format
Returns
-------
format : str
format specifier (upper case)
Raises
------
ValueError
if the heuristics are insufficient to guess a supported format
.. versionadded:: 0.11.0
Moved into lib.util
"""
if isstream(filename):
# perhaps StringIO or open stream
try:
format = format_from_filename_extension(filename.name)
except AttributeError:
# format is None so we need to complain:
six.raise_from(
ValueError("guess_format requires an explicit format specifier "
"for stream {0}".format(filename)),
None)
else:
# iterator, list, filename: simple extension checking... something more
# complicated is left for the ambitious.
# Note: at the moment the upper-case extension *is* the format specifier
# and list of filenames is handled by ChainReader
format = (format_from_filename_extension(filename)
if not iterable(filename) else 'CHAIN')
return format.upper()
def iterable(obj):
"""Returns ``True`` if `obj` can be iterated over and is *not* a string
nor a :class:`NamedStream`"""
if isinstance(obj, (six.string_types, NamedStream)):
return False # avoid iterating over characters of a string
if hasattr(obj, 'next'):
return True # any iterator will do
try:
len(obj) # anything else that might work
except (TypeError, AttributeError):
return False
return True
def asiterable(obj):
"""Returns `obj` so that it can be iterated over.
A string is *not* detected as and iterable and is wrapped into a :class:`list`
with a single element.
See Also
--------
iterable
"""
if not iterable(obj):
obj = [obj]
return obj
#: Regular expresssion (see :mod:`re`) to parse a simple `FORTRAN edit descriptor`_.
#: ``(?P<repeat>\d?)(?P<format>[IFELAX])(?P<numfmt>(?P<length>\d+)(\.(?P<decimals>\d+))?)?``
#:
#: .. _FORTRAN edit descriptor: http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html
FORTRAN_format_regex = "(?P<repeat>\d+?)(?P<format>[IFEAX])(?P<numfmt>(?P<length>\d+)(\.(?P<decimals>\d+))?)?"
_FORTRAN_format_pattern = re.compile(FORTRAN_format_regex)
def strip(s):
"""Convert `s` to a string and return it white-space stripped."""
return str(s).strip()
class FixedcolumnEntry(object):
"""Represent an entry at specific fixed columns.
Reads from line[start:stop] and converts according to
typespecifier.
"""
convertors = {'I': int, 'F': float, 'E': float, 'A': strip}
def __init__(self, start, stop, typespecifier):
"""
Parameters
----------
start : int
first column
stop : int
last column + 1
typespecifier : str
'I': int, 'F': float, 'E': float, 'A': stripped string
The start/stop arguments follow standard Python convention in that
they are 0-based and that the *stop* argument is not included.
"""
self.start = start
self.stop = stop
self.typespecifier = typespecifier
self.convertor = self.convertors[typespecifier]
def read(self, line):
"""Read the entry from `line` and convert to appropriate type."""
try:
return self.convertor(line[self.start:self.stop])
except ValueError:
six.raise_from(
ValueError(
"{0!r}: Failed to read&convert {1!r}".format(
self, line[self.start:self.stop])),
None)
def __len__(self):
"""Length of the field in columns (stop - start)"""
return self.stop - self.start
def __repr__(self):
return "FixedcolumnEntry({0:d},{1:d},{2!r})".format(self.start, self.stop, self.typespecifier)
class FORTRANReader(object):
"""FORTRANReader provides a method to parse FORTRAN formatted lines in a file.
The contents of lines in a file can be parsed according to FORTRAN format
edit descriptors (see `Fortran Formats`_ for the syntax).
Only simple one-character specifiers supported here: *I F E A X* (see
:data:`FORTRAN_format_regex`).
Strings are stripped of leading and trailing white space.
.. _`Fortran Formats`: http://www.webcitation.org/5xbaWMV2x
.. _`Fortran Formats (URL)`:
http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html
"""
def __init__(self, fmt):
"""Set up the reader with the FORTRAN format string.
The string `fmt` should look like '2I10,2X,A8,2X,A8,3F20.10,2X,A8,2X,A8,F20.10'.
Parameters
----------
fmt : str
FORTRAN format edit descriptor for a line as described in `Fortran
Formats`_
Example
-------
Parsing of a standard CRD file::
atomformat = FORTRANReader('2I10,2X,A8,2X,A8,3F20.10,2X,A8,2X,A8,F20.10')
for line in open('coordinates.crd'):
serial,TotRes,resName,name,x,y,z,chainID,resSeq,tempFactor = atomformat.read(line)
"""
self.fmt = fmt.split(',')
descriptors = [self.parse_FORTRAN_format(descriptor) for descriptor in self.fmt]
start = 0
self.entries = []
for d in descriptors:
if d['format'] != 'X':
for x in range(d['repeat']):
stop = start + d['length']
self.entries.append(FixedcolumnEntry(start, stop, d['format']))
start = stop
else:
start += d['totallength']
def read(self, line):
"""Parse `line` according to the format string and return list of values.
Values are converted to Python types according to the format specifier.
Parameters
----------
line : str
Returns
-------
list
list of entries with appropriate types
Raises
------
ValueError
Any of the conversions cannot be made (e.g. space for an int)
See Also
--------
:meth:`FORTRANReader.number_of_matches`
"""
return [e.read(line) for e in self.entries]
def number_of_matches(self, line):
"""Return how many format entries could be populated with legal values."""
# not optimal, I suppose...
matches = 0
for e in self.entries:
try:
e.read(line)
matches += 1
except ValueError:
pass
return matches
def parse_FORTRAN_format(self, edit_descriptor):
"""Parse the descriptor.
Parameters
----------
edit_descriptor : str
FORTRAN format edit descriptor
Returns
-------
dict
dict with totallength (in chars), repeat, length, format, decimals
Raises
------
ValueError
The `edit_descriptor` is not recognized and cannot be parsed
Note
----
Specifiers: *L ES EN T TL TR / r S SP SS BN BZ* are *not* supported,
and neither are the scientific notation *Ew.dEe* forms.
"""
m = _FORTRAN_format_pattern.match(edit_descriptor.upper())
if m is None:
try:
m = _FORTRAN_format_pattern.match("1" + edit_descriptor.upper())
if m is None:
raise ValueError # really no idea what the descriptor is supposed to mean
except:
raise ValueError("unrecognized FORTRAN format {0!r}".format(edit_descriptor))
d = m.groupdict()
if d['repeat'] == '':
d['repeat'] = 1
if d['format'] == 'X':
d['length'] = 1
for k in ('repeat', 'length', 'decimals'):
try:
d[k] = int(d[k])
except ValueError: # catches ''
d[k] = 0
except TypeError: # keep None
pass
d['totallength'] = d['repeat'] * d['length']
return d
def __len__(self):
"""Returns number of entries."""
return len(self.entries)
def __repr__(self):
return self.__class__.__name__ + "(" + ",".join(self.fmt) + ")"
def fixedwidth_bins(delta, xmin, xmax):
"""Return bins of width `delta` that cover `xmin`, `xmax` (or a larger range).
The bin parameters are computed such that the bin size `delta` is
guaranteed. In order to achieve this, the range `[xmin, xmax]` can be
increased.
Bins can be calculated for 1D data (then all parameters are simple floats)
or nD data (then parameters are supplied as arrays, with each entry
correpsonding to one dimension).
Parameters
----------
delta : float or array_like
desired spacing of the bins
xmin : float or array_like
lower bound (left boundary of first bin)
xmax : float or array_like
upper bound (right boundary of last bin)
Returns
-------
dict
The dict contains 'Nbins', 'delta', 'min', and 'max'; these are either
floats or arrays, depending on the input.
Example
-------
Use with :func:`numpy.histogram`::
B = fixedwidth_bins(delta, xmin, xmax)
h, e = np.histogram(data, bins=B['Nbins'], range=(B['min'], B['max']))
"""
if not np.all(xmin < xmax):
raise ValueError('Boundaries are not sane: should be xmin < xmax.')
_delta = np.asarray(delta, dtype=np.float_)
_xmin = np.asarray(xmin, dtype=np.float_)
_xmax = np.asarray(xmax, dtype=np.float_)
_length = _xmax - _xmin
N = np.ceil(_length / _delta).astype(np.int_) # number of bins
dx = 0.5 * (N * _delta - _length) # add half of the excess to each end
return {'Nbins': N, 'delta': _delta, 'min': _xmin - dx, 'max': _xmax + dx}
def get_weights(atoms, weights):
"""Check that a `weights` argument is compatible with `atoms`.
Parameters
----------
atoms : AtomGroup or array_like
The atoms that the `weights` should be applied to. Typically this
is a :class:`AtomGroup` but because only the length is compared,
any sequence for which ``len(atoms)`` is defined is acceptable.
weights : {"mass", None} or array_like
All MDAnalysis functions or classes understand "mass" and will then
use ``atoms.masses``. ``None`` indicates equal weights for all atoms.
Using an ``array_like`` assigns a custom weight to each element of
`atoms`.
Returns
-------
weights : array_like or None
If "mass" was selected, ``atoms.masses`` is returned, otherwise the
value of `weights` (which can be ``None``).
Raises
------
TypeError
If `weights` is not one of the allowed values or if "mass" is
selected but ``atoms.masses`` is not available.
ValueError
If `weights` is not a 1D array with the same length as
`atoms`, then the exception is raised. :exc:`TypeError` is
also raised if ``atoms.masses`` is not defined.
"""
if not iterable(weights) and weights == "mass":
try:
weights = atoms.masses
except AttributeError:
six.raise_from(
TypeError("weights='mass' selected but atoms.masses is missing"),
None)
if iterable(weights):
if len(np.asarray(weights).shape) != 1:
raise ValueError("weights must be a 1D array, not with shape "
"{0}".format(np.asarray(weights).shape))
elif len(weights) != len(atoms):
raise ValueError("weights (length {0}) must be of same length as "
"the atoms ({1})".format(
len(weights), len(atoms)))
elif weights is not None:
raise ValueError("weights must be {'mass', None} or an iterable of the "
"same size as the atomgroup.")
return weights
# String functions
# ----------------
#: translation table for 3-letter codes --> 1-letter codes
#: .. SeeAlso:: :data:`alternative_inverse_aa_codes`
canonical_inverse_aa_codes = {
'ALA': 'A', 'CYS': 'C', 'ASP': 'D', 'GLU': 'E',
'PHE': 'F', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I',
'LYS': 'K', 'LEU': 'L', 'MET': 'M', 'ASN': 'N',
'PRO': 'P', 'GLN': 'Q', 'ARG': 'R', 'SER': 'S',
'THR': 'T', 'VAL': 'V', 'TRP': 'W', 'TYR': 'Y'}
#: translation table for 1-letter codes --> *canonical* 3-letter codes.
#: The table is used for :func:`convert_aa_code`.
amino_acid_codes = {one: three for three, one in canonical_inverse_aa_codes.items()}
#: non-default charge state amino acids or special charge state descriptions
#: (Not fully synchronized with :class:`MDAnalysis.core.selection.ProteinSelection`.)
alternative_inverse_aa_codes = {
'HISA': 'H', 'HISB': 'H', 'HSE': 'H', 'HSD': 'H', 'HID': 'H', 'HIE': 'H', 'HIS1': 'H',
'HIS2': 'H',
'ASPH': 'D', 'ASH': 'D',
'GLUH': 'E', 'GLH': 'E',
'LYSH': 'K', 'LYN': 'K',
'ARGN': 'R',
'CYSH': 'C', 'CYS1': 'C', 'CYS2': 'C'}
#: lookup table from 3/4 letter resnames to 1-letter codes. Note that non-standard residue names
#: for tautomers or different protonation states such as HSE are converted to canonical 1-letter codes ("H").
#: The table is used for :func:`convert_aa_code`.
#: .. SeeAlso:: :data:`canonical_inverse_aa_codes` and :data:`alternative_inverse_aa_codes`
inverse_aa_codes = {}
inverse_aa_codes.update(canonical_inverse_aa_codes)
inverse_aa_codes.update(alternative_inverse_aa_codes)
def convert_aa_code(x):
"""Converts between 3-letter and 1-letter amino acid codes.
Parameters
----------
x : str
1-letter or 3-letter amino acid code
Returns
-------
str
3-letter or 1-letter amino acid code
Raises
------
ValueError
No conversion can be made; the amino acid code is not defined.
Note
----
Data are defined in :data:`amino_acid_codes` and :data:`inverse_aa_codes`.
"""
if len(x) == 1:
d = amino_acid_codes
else:
d = inverse_aa_codes
try:
return d[x.upper()]
except KeyError:
six.raise_from(
ValueError(
"No conversion for {0} found (1 letter -> 3 letter or 3/4 letter -> 1 letter)".format(x)
),
None)
#: Regular expression to match and parse a residue-atom selection; will match
#: "LYS300:HZ1" or "K300:HZ1" or "K300" or "4GB300:H6O" or "4GB300" or "YaA300".
RESIDUE = re.compile("""
(?P<aa>([ACDEFGHIKLMNPQRSTVWY]) # 1-letter amino acid
| # or
([0-9A-Z][a-zA-Z][A-Z][A-Z]?) # 3-letter or 4-letter residue name
)
\s* # white space allowed
(?P<resid>\d+) # resid
\s*
(: # separator ':'
\s*
(?P<atom>\w+) # atom name
)? # possibly one
""", re.VERBOSE | re.IGNORECASE)
# from GromacsWrapper cbook.IndexBuilder
def parse_residue(residue):
"""Process residue string.
Parameters
----------
residue: str
The *residue* must contain a 1-letter or 3-letter or
4-letter residue string, a number (the resid) and
optionally an atom identifier, which must be separate
from the residue with a colon (":"). White space is
allowed in between.
Returns
-------
tuple
`(3-letter aa string, resid, atomname)`; known 1-letter
aa codes are converted to 3-letter codes
Examples
--------
- "LYS300:HZ1" --> ("LYS", 300, "HZ1")
- "K300:HZ1" --> ("LYS", 300, "HZ1")
- "K300" --> ("LYS", 300, None)
- "4GB300:H6O" --> ("4GB", 300, "H6O")
- "4GB300" --> ("4GB", 300, None)
"""
# XXX: use _translate_residue() ....
m = RESIDUE.match(residue)
if not m:
raise ValueError("Selection {residue!r} is not valid (only 1/3/4 letter resnames, resid required).".format(**vars()))
resid = int(m.group('resid'))
residue = m.group('aa')
if len(residue) == 1:
resname = convert_aa_code(residue) # only works for AA
else:
resname = residue # use 3-letter for any resname
atomname = m.group('atom')
return (resname, resid, atomname)
def conv_float(s):
"""Convert an object `s` to float if possible.
Function to be passed into :func:`map` or a list comprehension. If
the argument can be interpreted as a float it is converted,
otherwise the original object is passed back.
"""
try:
return float(s)
except ValueError:
return s
def cached(key):
"""Cache a property within a class.
Requires the Class to have a cache dict called ``_cache``.
Example
-------
How to add a cache for a variable to a class by using the `@cached`
decorator::
class A(object):
def__init__(self):
self._cache = dict()
@property
@cached('keyname')
def size(self):
# This code gets ran only if the lookup of keyname fails
# After this code has been ran once, the result is stored in
# _cache with the key: 'keyname'
size = 10.0
.. versionadded:: 0.9.0
"""
def cached_lookup(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
return self._cache[key]
except KeyError:
self._cache[key] = ret = func(self, *args, **kwargs)
return ret
return wrapper
return cached_lookup
def unique_rows(arr, return_index=False):
"""Return the unique rows of an array.
Arguments
---------
arr : numpy.ndarray
Array of shape ``(n1, m)``.
return_index : bool, optional
If ``True``, returns indices of array that formed answer (see
:func:`numpy.unique`)
Returns
-------
unique_rows : numpy.ndarray
Array of shape ``(n2, m)`` containing only the unique rows of `arr`.
r_idx : numpy.ndarray (optional)
Array containing the corresponding row indices (if `return_index`
is ``True``).
Examples
--------
Remove dupicate rows from an array:
>>> a = np.array([[0, 1], [1, 2], [1, 2], [0, 1], [2, 3]])
>>> b = unique_rows(a)
>>> b
array([[0, 1], [1, 2], [2, 3]])
See Also
--------
numpy.unique
"""
# From here, but adapted to handle any size rows
# https://mail.scipy.org/pipermail/scipy-user/2011-December/031200.html
# This seems to fail if arr.flags['OWNDATA'] is False
# this can occur when second dimension was created through broadcasting
# eg: idx = np.array([1, 2])[None, :]
if not arr.flags['OWNDATA']:
arr = arr.copy()
m = arr.shape[1]
if return_index:
u, r_idx = np.unique(arr.view(dtype=np.dtype([(str(i), arr.dtype)
for i in range(m)])),
return_index=True)
return u.view(arr.dtype).reshape(-1, m), r_idx
else:
u = np.unique(arr.view(
dtype=np.dtype([(str(i), arr.dtype) for i in range(m)])
))
return u.view(arr.dtype).reshape(-1, m)
def blocks_of(a, n, m):
"""Extract a view of ``(n, m)`` blocks along the diagonal of the array `a`.
Parameters
----------
a : numpy.ndarray
Input array, must be C contiguous and at least 2D.
n : int
Size of block in first dimension.
m : int
Size of block in second dimension.
Returns
-------
view : numpy.ndarray
A view of the original array with shape ``(nblocks, n, m)``, where
``nblocks`` is the number of times the miniblocks of shape ``(n, m)``
fit in the original.
Raises
------
ValueError
If the supplied `n` and `m` don't divide `a` into an integer number
of blocks or if `a` is not C contiguous.
Examples
--------
>>> arr = np.arange(16).reshape(4, 4)
>>> view = blocks_of(arr, 2, 2)
>>> view[:] = 100
>>> arr
array([[100, 100, 2, 3],
[100, 100, 6, 7],
[ 8, 9, 100, 100],
[ 12, 13, 100, 100]])
Notes
-----
`n`, `m` must divide `a` into an identical integer number of blocks. Please
note that if the block size is larger than the input array, this number will
be zero, resulting in an empty view!
Uses strides and therefore requires that the array is C contiguous.
Returns a view, so editing this modifies the original array.
.. versionadded:: 0.12.0
"""
# based on:
# http://stackoverflow.com/a/10862636
# but generalised to handle non square blocks.
if not a.flags['C_CONTIGUOUS']:
raise ValueError("Input array is not C contiguous.")
nblocks = a.shape[0] // n
nblocks2 = a.shape[1] // m
if not nblocks == nblocks2:
raise ValueError("Must divide into same number of blocks in both"
" directions. Got {} by {}"
"".format(nblocks, nblocks2))
new_shape = (nblocks, n, m)
new_strides = (n * a.strides[0] + m * a.strides[1],
a.strides[0], a.strides[1])
return np.lib.stride_tricks.as_strided(a, new_shape, new_strides)
class Namespace(dict):
"""Class to allow storing attributes in new namespace. """
def __getattr__(self, key):
# a.this causes a __getattr__ call for key = 'this'
try:
return dict.__getitem__(self, key)
except KeyError:
six.raise_from(AttributeError('"{}" is not known in the namespace.'
.format(key)), None)
def __setattr__(self, key, value):
dict.__setitem__(self, key, value)
def __delattr__(self, key):
try:
dict.__delitem__(self, key)
except KeyError:
six.raise_from(
AttributeError('"{}" is not known in the namespace.'
.format(key)),
None)
def __eq__(self, other):
try:
# this'll allow us to compare if we're storing arrays
assert_equal(self, other)
except AssertionError:
return False
return True
def ltruncate_int(value, ndigits):
"""Truncate an integer, retaining least significant digits
Parameters
----------
value : int
value to truncate
ndigits : int
number of digits to keep
Returns
-------
truncated : int
only the `ndigits` least significant digits from `value`
Examples
--------
>>> ltruncate_int(123, 2)
23
>>> ltruncate_int(1234, 5)
1234
"""
return int(str(value)[-ndigits:])
def flatten_dict(d, parent_key=tuple()):
"""Flatten a nested dict `d` into a shallow dict with tuples as keys.
Parameters
----------
d : dict
Returns
-------
dict
Note
-----
Based on https://stackoverflow.com/a/6027615/
by user https://stackoverflow.com/users/1897/imran
.. versionadded:: 0.18.0
"""
items = []
for k, v in d.items():
if type(k) != tuple:
new_key = parent_key + (k, )
else:
new_key = parent_key + k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
def static_variables(**kwargs):
"""Decorator equipping functions or methods with static variables.
Static variables are declared and initialized by supplying keyword arguments
and initial values to the decorator.
Example
-------
>>> @static_variables(msg='foo calls', calls=0)
... def foo():
... foo.calls += 1
... print("{}: {}".format(foo.msg, foo.calls))
...
>>> foo()
foo calls: 1
>>> foo()
foo calls: 2
.. note:: Based on https://stackoverflow.com/a/279586
by `Claudiu <https://stackoverflow.com/users/15055/claudiu>`_
.. versionadded:: 0.19.0
"""
def static_decorator(func):
for kwarg in kwargs:
setattr(func, kwarg, kwargs[kwarg])
return func
return static_decorator
# In a lot of Atom/Residue/SegmentGroup methods such as center_of_geometry() and
# the like, results are biased if the calling group is not unique, i.e., if it
# contains duplicates.
# We therefore raise a `DuplicateWarning` whenever an affected method is called
# from a non-unique group. Since several of the affected methods involve calls
# to other affected methods, simply raising a warning in every affected method
# would potentially lead to a massive amount of warnings. This is exactly where
# the `warn_if_unique` decorator below comes into play. It ensures that a
# warning is only raised once for a method using this decorator, and suppresses
# all such warnings that would potentially be raised in methods called by that
# method. Of course, as it is generally the case with Python warnings, this is
# *not threadsafe*.
@static_variables(warned=False)
def warn_if_not_unique(groupmethod):
"""Decorator triggering a :class:`~MDAnalysis.exceptions.DuplicateWarning`
if the underlying group is not unique.
Assures that during execution of the decorated method only the first of
potentially multiple warnings concerning the uniqueness of groups is shown.
Raises
------
:class:`~MDAnalysis.exceptions.DuplicateWarning`
If the :class:`~MDAnalysis.core.groups.AtomGroup`,
:class:`~MDAnalysis.core.groups.ResidueGroup`, or
:class:`~MDAnalysis.core.groups.SegmentGroup` of which the decorated
method is a member contains duplicates.
.. versionadded:: 0.19.0
"""
@wraps(groupmethod)
def wrapper(group, *args, **kwargs):
# Proceed as usual if the calling group is unique or a DuplicateWarning
# has already been thrown:
if group.isunique or warn_if_not_unique.warned:
return groupmethod(group, *args, **kwargs)
# Otherwise, throw a DuplicateWarning and execute the method.
method_name = ".".join((group.__class__.__name__, groupmethod.__name__))
# Try to get the group's variable name(s):
caller_locals = inspect.currentframe().f_back.f_locals.items()
group_names = []
for name, obj in caller_locals:
try:
if obj is group:
group_names.append("'{}'".format(name))
except:
pass
if not group_names:
group_name = "'unnamed {}'".format(group.__class__.__name__)
elif len(group_names) == 1:
group_name = group_names[0]
else:
group_name = " a.k.a. ".join(sorted(group_names))
group_repr = repr(group)
msg = ("{}(): {} {} contains duplicates. Results might be biased!"
"".format(method_name, group_name, group_repr))
warnings.warn(message=msg, category=DuplicateWarning, stacklevel=2)
warn_if_not_unique.warned = True
try:
result = groupmethod(group, *args, **kwargs)
finally:
warn_if_not_unique.warned = False
return result
return wrapper
def check_coords(*coord_names, **options):
"""Decorator for automated coordinate array checking.
This decorator is intended for use especially in
:mod:`MDAnalysis.lib.distances`.
It takes an arbitrary number of positional arguments which must correspond
to names of positional arguments of the decorated function.
It then checks if the corresponding values are valid coordinate arrays.
If all these arrays are single coordinates (i.e., their shape is ``(3,)``),
the decorated function can optionally return a single coordinate (or angle)
instead of an array of coordinates (or angles). This can be used to enable
computations of single observables using functions originally designed to
accept only 2-d coordinate arrays.
The checks performed on each individual coordinate array are:
* Check that coordinate arrays are of type :class:`numpy.ndarray`.
* Check that coordinate arrays have a shape of ``(n, 3)`` (or ``(3,)`` if
single coordinates are allowed; see keyword argument `allow_single`).
* Automatic dtype conversion to ``numpy.float32``.
* Optional replacement by a copy; see keyword argument `enforce_copy` .
* If coordinate arrays aren't C-contiguous, they will be automatically
replaced by a C-contiguous copy.
* Optional check for equal length of all coordinate arrays; see optional
keyword argument `check_lengths_match`.
Parameters
----------
*coord_names : tuple
Arbitrary number of strings corresponding to names of positional
arguments of the decorated function.
**options : dict, optional
* **enforce_copy** (:class:`bool`, optional) -- Enforce working on a
copy of the coordinate arrays. This is useful to ensure that the input
arrays are left unchanged. Default: ``True``
* **allow_single** (:class:`bool`, optional) -- Allow the input
coordinate array to be a single coordinate with shape ``(3,)``.
* **convert_single** (:class:`bool`, optional) -- If ``True``, single
coordinate arrays will be converted to have a shape of ``(1, 3)``.
Only has an effect if `allow_single` is ``True``. Default: ``True``
* **reduce_result_if_single** (:class:`bool`, optional) -- If ``True``
and *all* input coordinates are single, a decorated function ``func``
will return ``func()[0]`` instead of ``func()``. Only has an effect if
`allow_single` is ``True``. Default: ``True``
* **check_lengths_match** (:class:`bool`, optional) -- If ``True``, a
:class:`ValueError` is raised if not all coordinate arrays contain the
same number of coordinates. Default: ``True``
Raises
------
ValueError
If the decorator is used without positional arguments (for development
purposes only).
If any of the positional arguments supplied to the decorator doesn't
correspond to a name of any of the decorated function's positional
arguments.
If any of the coordinate arrays has a wrong shape.
TypeError
If any of the coordinate arrays is not a :class:`numpy.ndarray`.
If the dtype of any of the coordinate arrays is not convertible to
``numpy.float32``.
Example
-------
>>> @check_coords('coords1', 'coords2')
... def coordsum(coords1, coords2):
... assert coords1.dtype == np.float32
... assert coords2.flags['C_CONTIGUOUS']
... return coords1 + coords2
...
>>> # automatic dtype conversion:
>>> coordsum(np.zeros(3, dtype=np.int64), np.ones(3))
array([1., 1., 1.], dtype=float32)
>>>
>>> # automatic handling of non-contiguous arrays:
>>> coordsum(np.zeros(3), np.ones(6)[::2])
array([1., 1., 1.], dtype=float32)
>>>
>>> # automatic shape checking:
>>> coordsum(np.zeros(3), np.ones(6))
ValueError: coordsum(): coords2.shape must be (3,) or (n, 3), got (6,).
.. versionadded:: 0.19.0
"""
enforce_copy = options.get('enforce_copy', True)
allow_single = options.get('allow_single', True)
convert_single = options.get('convert_single', True)
reduce_result_if_single = options.get('reduce_result_if_single', True)
check_lengths_match = options.get('check_lengths_match',
len(coord_names) > 1)
if not coord_names:
raise ValueError("Decorator check_coords() cannot be used without "
"positional arguments.")
def check_coords_decorator(func):
fname = func.__name__
code = func.__code__
argnames = code.co_varnames
nargs = len(code.co_varnames)
ndefaults = len(func.__defaults__) if func.__defaults__ else 0
# Create a tuple of positional argument names:
nposargs = code.co_argcount - ndefaults
posargnames = argnames[:nposargs]
# The check_coords() decorator is designed to work only for positional
# arguments:
for name in coord_names:
if name not in posargnames:
raise ValueError("In decorator check_coords(): Name '{}' "
"doesn't correspond to any positional "
"argument of the decorated function {}()."
"".format(name, func.__name__))
def _check_coords(coords, argname):
if not isinstance(coords, np.ndarray):
raise TypeError("{}(): Parameter '{}' must be a numpy.ndarray, "
"got {}.".format(fname, argname, type(coords)))
is_single = False
if allow_single:
if (coords.ndim not in (1, 2)) or (coords.shape[-1] != 3):
raise ValueError("{}(): {}.shape must be (3,) or (n, 3), "
"got {}.".format(fname, argname,
coords.shape))
if coords.ndim == 1:
is_single = True
if convert_single:
coords = coords[None, :]
else:
if (coords.ndim != 2) or (coords.shape[1] != 3):
raise ValueError("{}(): {}.shape must be (n, 3), got {}."
"".format(fname, argname, coords.shape))
try:
coords = coords.astype(np.float32, order='C', copy=enforce_copy)
except ValueError:
six.raise_from(
TypeError(
"{}(): {}.dtype must be convertible to float32,"
" got {}.".format(fname, argname, coords.dtype)),
None)
return coords, is_single
@wraps(func)
def wrapper(*args, **kwargs):
# Check for invalid function call:
if len(args) != nposargs:
# set marker for testing purposes:
wrapper._invalid_call = True
if len(args) > nargs:
# too many arguments, invoke call:
return func(*args, **kwargs)
for name in posargnames[:len(args)]:
if name in kwargs:
# duplicate argument, invoke call:
return func(*args, **kwargs)
for name in posargnames[len(args):]:
if name not in kwargs:
# missing argument, invoke call:
return func(*args, **kwargs)
for name in kwargs:
if name not in argnames:
# unexpected kwarg, invoke call:
return func(*args, **kwargs)
# call is valid, unset test marker:
wrapper._invalid_call = False
args = list(args)
ncoords = []
all_single = allow_single
for name in coord_names:
idx = posargnames.index(name)
if idx < len(args):
args[idx], is_single = _check_coords(args[idx], name)
all_single &= is_single
ncoords.append(args[idx].shape[0])
else:
kwargs[name], is_single = _check_coords(kwargs[name],
name)
all_single &= is_single
ncoords.append(kwargs[name].shape[0])
if check_lengths_match and ncoords:
if ncoords.count(ncoords[0]) != len(ncoords):
raise ValueError("{}(): {} must contain the same number of "
"coordinates, got {}."
"".format(fname, ", ".join(coord_names),
ncoords))
# If all input coordinate arrays were 1-d, so should be the output:
if all_single and reduce_result_if_single:
return func(*args, **kwargs)[0]
return func(*args, **kwargs)
return wrapper
return check_coords_decorator
#------------------------------------------------------------------
#
# our own deprecate function, derived from numpy (see
# https://github.com/MDAnalysis/mdanalysis/pull/1763#issuecomment-403231136)
#
# From numpy/lib/utils.py 1.14.5 (used under the BSD 3-clause licence,
# https://www.numpy.org/license.html#license) and modified
def _set_function_name(func, name):
func.__name__ = name
return func
class _Deprecate(object):
"""
Decorator class to deprecate old functions.
Refer to `deprecate` for details.
See Also
--------
deprecate
.. versionadded:: 0.19.0
"""
def __init__(self, old_name=None, new_name=None,
release=None, remove=None, message=None):
self.old_name = old_name
self.new_name = new_name
if release is None:
raise ValueError("deprecate: provide release in which "
"feature was deprecated.")
self.release = str(release)
self.remove = str(remove) if remove is not None else remove
self.message = message
def __call__(self, func, *args, **kwargs):
"""
Decorator call. Refer to ``decorate``.
"""
old_name = self.old_name
new_name = self.new_name
message = self.message
release = self.release
remove = self.remove
if old_name is None:
try:
old_name = func.__name__
except AttributeError:
old_name = func.__name__
if new_name is None:
depdoc = "`{0}` is deprecated!".format(old_name)
else:
depdoc = "`{0}` is deprecated, use `{1}` instead!".format(
old_name, new_name)
warn_message = depdoc
remove_text = ""
if remove is not None:
remove_text = "`{0}` will be removed in release {1}.".format(
old_name, remove)
warn_message += "\n" + remove_text
if message is not None:
warn_message += "\n" + message
def newfunc(*args, **kwds):
"""This function is deprecated."""
warnings.warn(warn_message, DeprecationWarning, stacklevel=2)
return func(*args, **kwds)
newfunc = _set_function_name(newfunc, old_name)
# Build the doc string
# First line: func is deprecated, use newfunc instead!
# Normal docs follows.
# Last: .. deprecated::
# make sure that we do not mess up indentation, otherwise sphinx
# docs do not build properly
try:
doc = dedent_docstring(func.__doc__)
except TypeError:
doc = ""
deprecation_text = dedent_docstring("""\n\n
.. deprecated:: {0}
{1}
{2}
""".format(release,
message if message else depdoc,
remove_text))
doc = "{0}\n\n{1}\n{2}\n".format(depdoc, doc, deprecation_text)
newfunc.__doc__ = doc
try:
d = func.__dict__
except AttributeError:
pass
else:
newfunc.__dict__.update(d)
return newfunc
def deprecate(*args, **kwargs):
"""Issues a DeprecationWarning, adds warning to `old_name`'s
docstring, rebinds ``old_name.__name__`` and returns the new
function object.
This function may also be used as a decorator.
It adds a restructured text ``.. deprecated:: release`` block with
the sphinx deprecated role to the end of the docs. The `message`
is added under the deprecation block and contains the `release` in
which the function was deprecated.
Parameters
----------
func : function
The function to be deprecated.
old_name : str, optional
The name of the function to be deprecated. Default is None, in
which case the name of `func` is used.
new_name : str, optional
The new name for the function. Default is None, in which case the
deprecation message is that `old_name` is deprecated. If given, the
deprecation message is that `old_name` is deprecated and `new_name`
should be used instead.
release : str
Release in which the function was deprecated. This is given as
a keyword argument for technical reasons but is required; a
:exc:`ValueError` is raised if it is missing.
remove : str, optional
Release for which removal of the feature is planned.
message : str, optional
Additional explanation of the deprecation. Displayed in the
docstring after the warning.
Returns
-------
old_func : function
The deprecated function.
Examples
--------
When :func:`deprecate` is used as a function as in the following
example,
.. code-block:: python
oldfunc = deprecate(func, release="0.19.0", remove="1.0",
message="Do it yourself instead.")
then ``oldfunc`` will return a value after printing
:exc:`DeprecationWarning`; ``func`` is still available as it was
before.
When used as a decorator, ``func`` will be changed and issue the
warning and contain the deprecation note in the do string.
.. code-block:: python
@deprecate(release="0.19.0", remove="1.0",
message="Do it yourself instead.")
def func():
\"\"\"Just pass\"\"\"
pass
The resulting doc string (``help(func)``) will look like:
.. code-block:: reST
`func` is deprecated!
Just pass.
.. deprecated:: 0.19.0
Do it yourself instead.
`func` will be removed in 1.0.
(It is possible but confusing to change the name of ``func`` with
the decorator so it is not recommended to use the `new_func`
keyword argument with the decorator.)
.. versionadded:: 0.19.0
"""
# Deprecate may be run as a function or as a decorator
# If run as a function, we initialise the decorator class
# and execute its __call__ method.
if args:
fn = args[0]
args = args[1:]
return _Deprecate(*args, **kwargs)(fn)
else:
return _Deprecate(*args, **kwargs)
#
#------------------------------------------------------------------
def dedent_docstring(text):
"""Dedent typical python doc string.
Parameters
----------
text : str
string, typically something like ``func.__doc__``.
Returns
-------
str
string with the leading common whitespace removed from each
line
See Also
--------
textwrap.dedent
.. versionadded:: 0.19.0
"""
lines = text.splitlines()
if len(lines) < 2:
return text.lstrip()
# treat first line as special (typically no leading whitespace!) which messes up dedent
return lines[0].lstrip() + "\n" + textwrap.dedent("\n".join(lines[1:]))
def check_box(box):
"""Take a box input and deduce what type of system it represents based on
the shape of the array and whether all angles are 90 degrees.
Parameters
----------
box : array_like
The unitcell dimensions of the system, which can be orthogonal or
triclinic and must be provided in the same format as returned by
:attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n
``[lx, ly, lz, alpha, beta, gamma]``.
Returns
-------
boxtype : {``'ortho'``, ``'tri_vecs'``}
String indicating the box type (orthogonal or triclinic).
checked_box : numpy.ndarray
Array of dtype ``numpy.float32`` containing box information:
* If `boxtype` is ``'ortho'``, `cecked_box` will have the shape ``(3,)``
containing the x-, y-, and z-dimensions of the orthogonal box.
* If `boxtype` is ``'tri_vecs'``, `cecked_box` will have the shape
``(3, 3)`` containing the triclinic box vectors in a lower triangular
matrix as returned by
:meth:`~MDAnalysis.lib.mdamath.triclinic_vectors`.
Raises
------
ValueError
If `box` is not of the form ``[lx, ly, lz, alpha, beta, gamma]``
or contains data that is not convertible to ``numpy.float32``.
See Also
--------
MDAnalysis.lib.mdamath.triclinic_vectors
.. versionchanged: 0.19.0
* Enforced correspondence of `box` with specified format.
* Added automatic conversion of input to :class:`numpy.ndarray` with
dtype ``numpy.float32``.
* Now also returns the box in the format expected by low-level functions
in :mod:`~MDAnalysis.lib.c_distances`.
* Removed obsolete box types ``tri_box`` and ``tri_vecs_bad``.
"""
from .mdamath import triclinic_vectors # avoid circular import
box = np.asarray(box, dtype=np.float32, order='C')
if box.shape != (6,):
raise ValueError("Invalid box information. Must be of the form "
"[lx, ly, lz, alpha, beta, gamma].")
if np.all(box[3:] == 90.):
return 'ortho', box[:3]
return 'tri_vecs', triclinic_vectors(box)
|
python
|
# -*- coding: utf-8 -*-
import argparse
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from pytube import cli, StreamQuery, Caption, CaptionQuery
parse_args = cli._parse_args
@mock.patch("pytube.cli.YouTube")
def test_download_when_itag_not_found(youtube):
youtube.streams = mock.Mock()
youtube.streams.all.return_value = []
youtube.streams.get_by_itag.return_value = None
with pytest.raises(SystemExit):
cli.download_by_itag(youtube, 123)
youtube.streams.get_by_itag.assert_called_with(123)
@mock.patch("pytube.cli.YouTube")
@mock.patch("pytube.Stream")
def test_download_when_itag_is_found(youtube, stream):
stream.itag = 123
youtube.streams = StreamQuery([stream])
with patch.object(
youtube.streams, "get_by_itag", wraps=youtube.streams.get_by_itag
) as wrapped_itag:
cli.download_by_itag(youtube, 123)
wrapped_itag.assert_called_with(123)
youtube.register_on_progress_callback.assert_called_with(cli.on_progress)
stream.download.assert_called()
@mock.patch("pytube.cli.YouTube")
@mock.patch("pytube.Stream")
def test_display_stream(youtube, stream):
stream.itag = 123
stream.__repr__ = MagicMock(return_value="")
youtube.streams = StreamQuery([stream])
with patch.object(youtube.streams, "all", wraps=youtube.streams.all) as wrapped_all:
cli.display_streams(youtube)
wrapped_all.assert_called()
stream.__repr__.assert_called()
@mock.patch("pytube.cli.YouTube")
def test_download_caption_with_none(youtube):
caption = Caption(
{"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"}
)
youtube.captions = CaptionQuery([caption])
with patch.object(
youtube.captions, "all", wraps=youtube.captions.all
) as wrapped_all:
cli.download_caption(youtube, None)
wrapped_all.assert_called()
@mock.patch("pytube.cli.YouTube")
def test_download_caption_with_language_found(youtube):
youtube.title = "video title"
caption = Caption(
{"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"}
)
caption.download = MagicMock(return_value="file_path")
youtube.captions = CaptionQuery([caption])
cli.download_caption(youtube, "en")
caption.download.assert_called_with(title="video title", output_path=None)
@mock.patch("pytube.cli.YouTube")
def test_download_caption_with_language_not_found(youtube):
caption = Caption(
{"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"}
)
youtube.captions = CaptionQuery([caption])
with patch.object(
youtube.captions, "all", wraps=youtube.captions.all
) as wrapped_all:
cli.download_caption(youtube, "blah")
wrapped_all.assert_called()
def test_display_progress_bar(capsys):
cli.display_progress_bar(bytes_received=25, filesize=100, scale=0.55)
out, _ = capsys.readouterr()
assert "25.0%" in out
@mock.patch("pytube.Stream")
@mock.patch("io.BufferedWriter")
def test_on_progress(stream, writer):
stream.filesize = 10
cli.display_progress_bar = MagicMock()
cli.on_progress(stream, "", writer, 7)
cli.display_progress_bar.assert_called_once_with(3, 10)
def test_parse_args_falsey():
parser = argparse.ArgumentParser()
args = cli._parse_args(parser, ["http://youtube.com/watch?v=9bZkp7q19f0"])
assert args.url == "http://youtube.com/watch?v=9bZkp7q19f0"
assert args.build_playback_report is False
assert args.itag is None
assert args.list is False
assert args.verbosity == 0
def test_parse_args_truthy():
parser = argparse.ArgumentParser()
args = cli._parse_args(
parser,
[
"http://youtube.com/watch?v=9bZkp7q19f0",
"--build-playback-report",
"-c",
"en",
"-l",
"--itag=10",
],
)
assert args.url == "http://youtube.com/watch?v=9bZkp7q19f0"
assert args.build_playback_report is True
assert args.itag == 10
assert args.list is True
@mock.patch("pytube.cli.YouTube", return_value=None)
def test_main_download_by_itag(youtube):
parser = argparse.ArgumentParser()
args = parse_args(parser, ["http://youtube.com/watch?v=9bZkp7q19f0", "--itag=10"])
cli._parse_args = MagicMock(return_value=args)
cli.download_by_itag = MagicMock()
cli.main()
youtube.assert_called()
cli.download_by_itag.assert_called()
@mock.patch("pytube.cli.YouTube", return_value=None)
def test_main_build_playback_report(youtube):
parser = argparse.ArgumentParser()
args = parse_args(
parser, ["http://youtube.com/watch?v=9bZkp7q19f0", "--build-playback-report"]
)
cli._parse_args = MagicMock(return_value=args)
cli.build_playback_report = MagicMock()
cli.main()
youtube.assert_called()
cli.build_playback_report.assert_called()
@mock.patch("pytube.cli.YouTube", return_value=None)
def test_main_display_streams(youtube):
parser = argparse.ArgumentParser()
args = parse_args(parser, ["http://youtube.com/watch?v=9bZkp7q19f0", "-l"])
cli._parse_args = MagicMock(return_value=args)
cli.display_streams = MagicMock()
cli.main()
youtube.assert_called()
cli.display_streams.assert_called()
@mock.patch("pytube.cli.YouTube", return_value=None)
def test_main_download_caption(youtube):
parser = argparse.ArgumentParser()
args = parse_args(parser, ["http://youtube.com/watch?v=9bZkp7q19f0", "-c"])
cli._parse_args = MagicMock(return_value=args)
cli.download_caption = MagicMock()
cli.main()
youtube.assert_called()
cli.download_caption.assert_called()
@mock.patch("pytube.cli.YouTube", return_value=None)
@mock.patch("pytube.cli.download_by_resolution")
def test_download_by_resolution_flag(youtube, download_by_resolution):
parser = argparse.ArgumentParser()
args = parse_args(parser, ["http://youtube.com/watch?v=9bZkp7q19f0", "-r", "320p"])
cli._parse_args = MagicMock(return_value=args)
cli.main()
youtube.assert_called()
download_by_resolution.assert_called()
@mock.patch("pytube.cli.Playlist")
def test_download_with_playlist(playlist):
cli.safe_filename = MagicMock(return_value="safe_title")
parser = argparse.ArgumentParser()
args = parse_args(parser, ["https://www.youtube.com/playlist?list=PLyn"])
cli._parse_args = MagicMock(return_value=args)
cli.main()
playlist.assert_called()
@mock.patch("pytube.cli.YouTube")
@mock.patch("pytube.StreamQuery")
@mock.patch("pytube.Stream")
def test_download_by_resolution(youtube, stream_query, stream):
stream_query.get_by_resolution.return_value = stream
youtube.streams = stream_query
cli._download = MagicMock()
cli.download_by_resolution(youtube=youtube, resolution="320p", target="test_target")
cli._download.assert_called_with(stream, target="test_target")
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# cssyacc/block.py
#
# class for block
# ----------------------------------------------------------------
# copyright (c) 2014 - Domen Ipavec
# Distributed under The MIT License, see LICENSE
# ----------------------------------------------------------------
from cssyacc.statement import Statement
from cssyacc.ruleset import Ruleset
from cssyacc.comment import Comment
from cssyacc.whitespace import Whitespace
class Block:
def __init__(self, el, t, ln1, ln2):
import cssqc.parser
self.elements = el
self.lb_lineno = ln1
self.rb_lineno = ln2
if t is not None \
and len(t) > 0:
# remove trailing ws and comments from t
# make t a statement and append everything
following = []
while type(t[-1]) is Whitespace \
or type(t[-1]) is Comment:
following.append(t.pop())
self.elements.append(Statement(t, ln2, False))
self.elements += following
self.statements = 0
self.blocks = 0
for e in self.elements:
if type(e) is Statement:
self.statements += 1
elif type(e) is Ruleset:
self.blocks += 1
i = cssqc.parser.CSSQC.getInstance()
if i is not None:
i.register(self.__class__.__name__, self)
def isOneLiner(self):
return self.statements <= 1 and self.blocks == 0
def __str__(self):
return ''.join(map(str, self.elements))
def __len__(self):
return len(self.elements)
def __eq__(self, other):
if type(self) != type(other):
return False
return self.elements == other.elements\
and self.lb_lineno == other.lb_lineno \
and self.rb_lineno == other.rb_lineno
def __repr__(self):
return '<Block>\n ' + '\n '.join(map(repr, self.elements)) + '\n</Block>'
|
python
|
# liberate - Add the specified block to the list of available blocks. As part
# of the liberation process, check the block's buddy to see if it can be
# combined with the current block. If so, combine them, then recursively
# call liberate.
# @param block The block to be liberated
def liberate(block):
# S1 - Check if buddy is available
buddy = get_buddy(block)
if (is_avail(buddy)):
# S2 - Combine with Buddy and recursively call liberate()
remove_block(buddy)
merged = merge_blocks(block, buddy)
liberate(merged)
else:
# S3 - Add the block to the list of available blocks
block->tag = FREE
add_block(block)
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.