content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
import torch
import getopt
import math
import numpy
import os
import PIL
import PIL.Image
import sys
import torch.nn.functional as F
import torchvision.transforms as transforms
import skimage.io as io
import numpy as np
from skimage import morphology
from scipy import ndimage
import math
transform = transforms.Compose([transforms.ToTensor()])
revtransf = transforms.Compose([transforms.ToPILImage()])
class Network(torch.nn.Module):
def __init__(self, gpu=None):
super(Network, self).__init__()
self.moduleVggOne = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False)
)
self.moduleVggTwo = torch.nn.Sequential(
torch.nn.MaxPool2d(kernel_size=2, stride=2),
torch.nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False)
)
self.moduleVggThr = torch.nn.Sequential(
torch.nn.MaxPool2d(kernel_size=2, stride=2),
torch.nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False)
)
self.moduleVggFou = torch.nn.Sequential(
torch.nn.MaxPool2d(kernel_size=2, stride=2),
torch.nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False)
)
self.moduleVggFiv = torch.nn.Sequential(
torch.nn.MaxPool2d(kernel_size=2, stride=2),
torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False),
torch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
torch.nn.ReLU(inplace=False)
)
self.moduleScoreOne = torch.nn.Conv2d(in_channels=64, out_channels=1, kernel_size=1, stride=1, padding=0)
self.moduleScoreTwo = torch.nn.Conv2d(in_channels=128, out_channels=1, kernel_size=1, stride=1, padding=0)
self.moduleScoreThr = torch.nn.Conv2d(in_channels=256, out_channels=1, kernel_size=1, stride=1, padding=0)
self.moduleScoreFou = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0)
self.moduleScoreFiv = torch.nn.Conv2d(in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0)
self.moduleCombine = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=5, out_channels=1, kernel_size=1, stride=1, padding=0),
torch.nn.Sigmoid()
)
self.gpu = gpu
if gpu is not None:
self.cuda(gpu)
# end
def forward(self, tensorInput):
if self.gpu is not None:
tensorInput = tensorInput.cuda(self.gpu)
tensorBlue = (tensorInput[:, 0:1, :, :] * 255.0) - 127.5
tensorGreen = (tensorInput[:, 1:2, :, :] * 255.0) - 127.5
tensorRed = (tensorInput[:, 2:3, :, :] * 255.0) - 127.5
tensorInput = torch.cat([ tensorBlue, tensorGreen, tensorRed ], 1)
vggOne = self.moduleVggOne(tensorInput)
vggTwo = self.moduleVggTwo(vggOne)
vggThr = self.moduleVggThr(vggTwo)
vggFou = self.moduleVggFou(vggThr)
vggFiv = self.moduleVggFiv(vggFou)
scoreOne = self.moduleScoreOne(vggOne)
scoreTwo = self.moduleScoreTwo(vggTwo)
scoreThr = self.moduleScoreThr(vggThr)
scoreFou = self.moduleScoreFou(vggFou)
scoreFiv = self.moduleScoreFiv(vggFiv)
H = tensorInput.size(2)
W = tensorInput.size(3)
scoreOne = torch.nn.functional.interpolate(input=scoreOne, size=(H, W), mode='bilinear', align_corners=False)
scoreTwo = torch.nn.functional.interpolate(input=scoreTwo, size=(H, W), mode='bilinear', align_corners=False)
scoreThr = torch.nn.functional.interpolate(input=scoreThr, size=(H, W), mode='bilinear', align_corners=False)
scoreFou = torch.nn.functional.interpolate(input=scoreFou, size=(H, W), mode='bilinear', align_corners=False)
scoreFiv = torch.nn.functional.interpolate(input=scoreFiv, size=(H, W), mode='bilinear', align_corners=False)
scoreFin = self.moduleCombine(torch.cat([ scoreOne, scoreTwo, scoreThr, scoreFou, scoreFiv ], 1))
return F.sigmoid(1 - scoreTwo)
##########################################################
torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
EdgeDet = Network(gpu = 0)
EdgeDet.load_state_dict(torch.load('./checkpoints/hed.pkl'))
framDir = './dataset/frame'
saveDir = './dataset/dismap'
for clipDir in sorted(os.listdir(framDir)):
clipPath = os.path.join(framDir, clipDir)
savePath = os.path.join(saveDir, clipDir)
if not os.path.exists(savePath):
os.mkdir(savePath)
for index, frame in enumerate(sorted(os.listdir(clipPath))):
inDir = '%s%s%s%s%s' % (framDir, '/', clipDir, '/', frame)
ouDir = '%s%s%s%s%s%s' % (saveDir, '/', clipDir, '/', frame.split('.')[0], '.npy')
imgt = io.imread(inDir).astype(np.float32)/255.0
imgt = transform(imgt)
imgt = imgt.unsqueeze(0).to(device)
edgmap = np.asarray(revtransf(EdgeDet(imgt).cpu()[0]))
edgmap = edgmap / 255.0
newmap = np.zeros(edgmap.shape)
newmap[edgmap > 1.0/(1 + math.exp(-0.5))] = 1.0
dismap = ndimage.distance_transform_edt(newmap)
np.save(ouDir, dismap)
|
python
|
import ssl
import sys
import json
import os
import requests
import toml
import atexit
import re
import traceback
from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
# GLOBAL_VARS
DEBUG = False
# CONFIG
VC_CONFIG = '/var/openfaas/secrets/vcconfig'
service_instance = None
class bgc:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
if(os.getenv("write_debug")):
sys.stderr.write(f"{bgc.WARNING}WARNING!! DEBUG has been enabled for this function. Sensitive information could be printed to sysout{bgc.ENDC} \n")
DEBUG = True
def debug(s):
if DEBUG:
sys.stderr.write(s + " \n") # Syserr only get logged on the console logs
sys.stderr.flush()
def init():
"""
Load the config and set up a connection to vc
"""
global service_instance
# Load the Config File
debug(f'{bgc.HEADER}Reading Configuration files: {bgc.ENDC}')
debug(f'{bgc.OKBLUE}VC Config File > {bgc.ENDC}{VC_CONFIG}')
try:
with open(VC_CONFIG, 'r') as vcconfigfile:
vcconfig = toml.load(vcconfigfile)
vchost = vcconfig['vcenter']['server']
vcuser = vcconfig['vcenter']['user']
vcpass = vcconfig['vcenter']['pass']
except OSError as err:
return f'Could not read vcenter configuration: {err}', 500
except KeyError as err:
return f'Mandatory configuration key not found: {err}', 500
try: # If we already have a valid session then return
sessionid = service_instance.content.sessionManager.currentSession.key
if service_instance.content.sessionManager.SessionIsActive(sessionid, vcuser):
return
except Exception:
debug(f'{bgc.WARNING}Init VC Connection...{bgc.ENDC}')
sslContext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
if(os.getenv("insecure_ssl")):
sslContext.verify_mode = ssl.CERT_NONE
debug(f'{bgc.OKBLUE}Initialising vCenter connection...{bgc.ENDC}')
try:
service_instance = connect.SmartConnect(host=vchost,
user=vcuser,
pwd=vcpass,
port=443,
sslContext=sslContext)
atexit.register(connect.Disconnect, service_instance)
except IOError as err:
return f'Error connecting to vCenter: {err}', 500
if not service_instance:
return 'Unable to connect to vCenter host with supplied credentials', 400
def getManagedObjectTypeName(mo):
"""
Returns the short type name of the passed managed object
e.g. VirtualMachine
Args:
mo (vim.ManagedEntity)
"""
return mo.__class__.__name__.rpartition(".")[2]
def getManagedObject(obj):
"""
Convert an object as received from the event router in to a pyvmomi managed object
Args:
obj (object): object received from the event router
"""
mo = None
try:
moref = obj['Value']
type = obj['Type']
except KeyError as err:
traceback.print_exc(limit=1, file=sys.stderr) # providing traceback since it helps debug the exact key that failed
return f'Invalid JSON, required key not found > KeyError: {err}', 500
if hasattr(vim, type):
typeClass = getattr(vim, type)
mo = typeClass(moref)
mo._stub = service_instance._stub
try:
debug(f'{bgc.OKBLUE}Managed object > {bgc.ENDC}{moref} has name {mo.name} and type {getManagedObjectTypeName(mo)}')
return mo
except vmodl.fault.ManagedObjectNotFound as err:
debug(f'{bgc.FAIL}{err.msg}{bgc.ENDC}')
return None
def getViObjectPath(obj):
"""
Gets the full path to the passed managed object
Args:
obj (vim.ManagedObject): VC managed object
"""
path = ""
while obj != service_instance.content.rootFolder:
path = f'/{obj.name}{path}'
obj = obj.parent
return path
def filterVcObject(obj, filter):
"""
Takes a VC managed object and tests it against a filter
If it doesn't match, a tuple (reason, code) describing why
is returned, otherwise returns true.
Args:
obj (vim.ManagedObject): VC managed Object
filter (str): Regex filter string
"""
if obj and filter:
moType = getManagedObjectTypeName(obj)
objPath = getViObjectPath(obj)
debug(f'{bgc.OKBLUE}{moType} Path > {bgc.ENDC}{objPath}')
try:
if not re.search(filter, objPath):
debug(f'{bgc.WARNING}Filter "{filter}" does not match {moType} path "{objPath}". Exiting{bgc.ENDC}')
return f'Filter "{filter}" does not match {moType} path "{objPath}"', 200
else:
debug(f'{bgc.OKBLUE}Match > {bgc.ENDC}Filter matched {moType} path')
except re.error as err:
debug(f'{bgc.FAIL}Invalid regex pattern specified - {err.msg} at pos {err.pos}{bgc.ENDC}')
return f'Invalid regex pattern specified - {err.msg} at pos {err.pos}', 500
debug(f'{bgc.WARNING}Object or filter not specified, skipping > Obj: {obj}, Filter: {filter}{bgc.ENDC}')
def handle(req):
"""
Handle a request to the function
Args:
req (str): request body
"""
# Initialise a connection to vCenter
res = init()
if isinstance(res, tuple): # Tuple is returned if an error occurred
return res
vcinfo = service_instance.RetrieveServiceContent().about
debug(f'Connected to {vcinfo.fullName} ({vcinfo.instanceUuid})')
# Load the Events that function gets from vCenter through the Event Router
debug(f'{bgc.HEADER}Reading Cloud Event: {bgc.ENDC}')
debug(f'{bgc.OKBLUE}Event > {bgc.ENDC}{req}')
try:
cevent = json.loads(req)
except json.JSONDecodeError as err:
return f'Invalid JSON > JSONDecodeError: {err}', 500
debug(f'{bgc.HEADER}Validating Input data: {bgc.ENDC}')
debug(f'{bgc.OKBLUE}Event > {bgc.ENDC}{json.dumps(cevent, indent=4, sort_keys=True)}')
try:
# CloudEvent - simple validation
event = cevent['data']
except KeyError as err:
traceback.print_exc(limit=1, file=sys.stderr) # providing traceback since it helps debug the exact key that failed
return f'Invalid JSON, required key not found > KeyError: {err}', 500
except AttributeError as err:
traceback.print_exc(limit=1, file=sys.stderr) # providing traceback since it helps debug the exact key that failed
return f'Invalid JSON, data not iterable > AttributeError: {err}', 500
debug(f'{bgc.HEADER}Validation passed! Applying object filters:{bgc.ENDC}')
# Loop through the event data parameters and find managed objects
for name, value in event.items():
if type(value) == dict: # a dict is probably a VC managed object reference
for moName, moRef in value.items():
# Search the items of the dict and look for contained dicts with a 'Type' property
if type(moRef) == dict and 'Type' in moRef:
# Get the relevant filter_... environment variable
objFilter = eval(f'os.getenv("filter_{name.lower()}", default=".*")')
# Get a vc managed object
mo = getManagedObject(moRef)
# Test the filter
moType = getManagedObjectTypeName(mo)
debug(f'{bgc.OKBLUE}Apply Filter > {bgc.ENDC}"{name.lower()}" object ({moType}): "filter_{name.lower()}" = {objFilter}')
res = filterVcObject(mo, objFilter)
if isinstance(res, tuple): # Tuple is returned if the object didn't match the filter
return res
func = os.getenv("call_function", False)
if func:
debug(f'{bgc.HEADER}All filters matched. Calling chained function {func}{bgc.ENDC}')
try:
res = requests.post(f'http://gateway.openfaas:8080/function/{func}', req)
return res.text, res.status_code
except Exception as err:
traceback.print_exc(limit=1, file=sys.stderr) # providing traceback since it helps debug the exact key that failed
sys.stderr.flush()
return f'Unexpected error occurred calling chained function "{func}" > Exception: {err}', 500
debug(f'{bgc.FAIL}call_function must be specified!{bgc.ENDC}')
return "call_function must be specified", 400
#
# Unit Test - helps testing the function locally
# Uncomment r=handle('...') to test the function with the event samples provided below test without deploying to OpenFaaS
#
if __name__ == '__main__':
VC_CONFIG = 'vc-secrets.toml'
DEBUG = True
os.environ['insecure_ssl'] = 'true'
os.environ['filter_vm'] = '/\w*/vm/Infrastructure/'
os.environ['call_function'] = 'veba-echo'
#
# FAILURE CASES :Invalid Inputs
#
# handle('')
# handle('"test":"ok"')
# handle('{"test":"ok"}')
# handle('{"data":"ok"}')
#
# SUCCESS CASES :Invalid vc objects
#
# handle('{"id":"c7a6c420-f25d-4e6d-95b5-e273202e1164","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"DrsVmPoweredOnEvent","time":"2020-07-02T15:16:13.533866543Z","data":{"Key":130278,"ChainId":130273,"CreatedTime":"2020-07-02T15:16:11.213467Z","UserName":"Administrator","Datacenter":{"Name":"Lab","Datacenter":{"Type":"Datacenter","Value":"datacenter-2"}},"ComputeResource":{"Name":"Lab","ComputeResource":{"Type":"ClusterComputeResource","Value":"domain-c47"}},"Host":{"Name":"esxi03.lab","Host":{"Type":"HostSystem","Value":"host-9999"}},"Vm":{"Name":"Bad VM","Vm":{"Type":"VirtualMachine","Value":"vm-9999"}},"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"DRS powered on Bad VM on esxi01.lab in Lab","ChangeTag":"","Template":false},"datacontenttype":"application/json"}')
#
# SUCCESS CASES
#
# Standard : UserLogoutSessionEvent
# handle('{"id":"17e1027a-c865-4354-9c21-e8da3df4bff9","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"UserLogoutSessionEvent","time":"2020-04-14T00:28:36.455112549Z","data":{"Key":7775,"ChainId":7775,"CreatedTime":"2020-04-14T00:28:35.221698Z","UserName":"machine-b8eb9a7f","Datacenter":null,"ComputeResource":null,"Host":null,"Vm":null,"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"User [email protected] logged out (login time: Tuesday, 14 April, 2020 12:28:35 AM, number of API invocations: 34, user agent: pyvmomi Python/3.7.5 (Linux; 4.19.84-1.ph3; x86_64))","ChangeTag":"","IpAddress":"127.0.0.1","UserAgent":"pyvmomi Python/3.7.5 (Linux; 4.19.84-1.ph3; x86_64)","CallCount":34,"SessionId":"52edf160927","LoginTime":"2020-04-14T00:28:35.071817Z"},"datacontenttype":"application/json"}')
# Eventex : vim.event.ResourceExhaustionStatusChangedEvent
# handle('{"id":"0707d7e0-269f-42e7-ae1c-18458ecabf3d","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/eventex","subject":"vim.event.ResourceExhaustionStatusChangedEvent","time":"2020-04-14T00:20:15.100325334Z","data":{"Key":7715,"ChainId":7715,"CreatedTime":"2020-04-14T00:20:13.76967Z","UserName":"machine-bb9a7f","Datacenter":null,"ComputeResource":null,"Host":null,"Vm":null,"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"vCenter Log File System Resource status changed from Yellow to Green on vcsa.lab ","ChangeTag":"","EventTypeId":"vim.event.ResourceExhaustionStatusChangedEvent","Severity":"info","Message":"","Arguments":[{"Key":"resourceName","Value":"storage_util_filesystem_log"},{"Key":"oldStatus","Value":"yellow"},{"Key":"newStatus","Value":"green"},{"Key":"reason","Value":" "},{"Key":"nodeType","Value":"vcenter"},{"Key":"_sourcehost_","Value":"vcsa.lab"}],"ObjectId":"","ObjectType":"","ObjectName":"","Fault":null},"datacontenttype":"application/json"}')
# Standard : DrsVmPoweredOnEvent
handle('{"id":"c7a6c420-f25d-4e6d-95b5-e273202e1164","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"DrsVmPoweredOnEvent","time":"2020-07-02T15:16:13.533866543Z","data":{"Key":130278,"ChainId":130273,"CreatedTime":"2020-07-02T15:16:11.213467Z","UserName":"Administrator","Datacenter":{"Name":"Lab","Datacenter":{"Type":"Datacenter","Value":"datacenter-2"}},"ComputeResource":{"Name":"Lab","ComputeResource":{"Type":"ClusterComputeResource","Value":"domain-c47"}},"Host":{"Name":"esxi03.lab","Host":{"Type":"HostSystem","Value":"host-3523"}},"Vm":{"Name":"Test VM","Vm":{"Type":"VirtualMachine","Value":"vm-82"}},"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"DRS powered on Test VM on esxi03.lab in Lab","ChangeTag":"","Template":false},"datacontenttype":"application/json"}')
# Standard : VmPoweredOffEvent
# handle('{"id":"d77a3767-1727-49a3-ac33-ddbdef294150","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"VmPoweredOffEvent","time":"2020-04-14T00:33:30.838669841Z","data":{"Key":7825,"ChainId":7821,"CreatedTime":"2020-04-14T00:33:30.252792Z","UserName":"Administrator","Datacenter":{"Name":"PKLAB","Datacenter":{"Type":"Datacenter","Value":"datacenter-3"}},"ComputeResource":{"Name":"esxi01.lab","ComputeResource":{"Type":"ComputeResource","Value":"domain-s29"}},"Host":{"Name":"esxi01.lab","Host":{"Type":"HostSystem","Value":"host-31"}},"Vm":{"Name":"Test VM","Vm":{"Type":"VirtualMachine","Value":"vm-33"}},"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"Test VM on esxi01.lab in PKLAB is powered off","ChangeTag":"","Template":false},"datacontenttype":"application/json"}')
# Standard : DvsPortLinkUpEvent
# handle('{"id":"a10f8571-fc2a-40db-8df6-8284cecf5720","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"DvsPortLinkUpEvent","time":"2020-07-02T15:16:13.43892986Z","data":{"Key":130277,"ChainId":130277,"CreatedTime":"2020-07-02T15:16:11.207727Z","UserName":"","Datacenter":{"Name":"Lab","Datacenter":{"Type":"Datacenter","Value":"datacenter-2"}},"ComputeResource":null,"Host":null,"Vm":null,"Ds":null,"Net":null,"Dvs":{"Name":"Lab Switch","Dvs":{"Type":"VmwareDistributedVirtualSwitch","Value":"dvs-22"}},"FullFormattedMessage":"The dvPort 2 link was up in the vSphere Distributed Switch Lab Switch in Lab","ChangeTag":"","PortKey":"2","RuntimeInfo":null},"datacontenttype":"application/json"}')
# Standard : DatastoreRenamedEvent
# handle('{"id":"369b403a-6729-4b0b-893e-01383c8307ba","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"DatastoreRenamedEvent","time":"2020-07-02T21:44:11.09338265Z","data":{"Key":130669,"ChainId":130669,"CreatedTime":"2020-07-02T21:44:08.578289Z","UserName":"","Datacenter":{"Name":"Lab","Datacenter":{"Type":"Datacenter","Value":"datacenter-2"}},"ComputeResource":null,"Host":null,"Vm":null,"Ds":null,"Net":null,"Dvs":null,"FullFormattedMessage":"Renamed datastore from esxi04-local to esxi04-localZ in Lab","ChangeTag":"","Datastore":{"Name":"esxi04-localZ","Datastore":{"Type":"Datastore","Value":"datastore-3313"}},"OldName":"esxi04-local","NewName":"esxi04-localZ"},"datacontenttype":"application/json"}')
# Standard : DVPortgroupRenamedEvent
# handle('{"id":"aab77fd1-41ed-4b51-89d3-ef3924b09de1","source":"https://vcsa01.lab/sdk","specversion":"1.0","type":"com.vmware.event.router/event","subject":"DVPortgroupRenamedEvent","time":"2020-07-03T19:36:38.474640186Z","data":{"Key":132376,"ChainId":132375,"CreatedTime":"2020-07-03T19:36:32.525906Z","UserName":"Administrator","Datacenter":{"Name":"Lab","Datacenter":{"Type":"Datacenter","Value":"datacenter-2"}},"ComputeResource":null,"Host":null,"Vm":null,"Ds":null,"Net":{"Name":"vMotion AZ","Network":{"Type":"DistributedVirtualPortgroup","Value":"dvportgroup-3357"}},"Dvs":{"Name":"10G Switch A","Dvs":{"Type":"VmwareDistributedVirtualSwitch","Value":"dvs-3355"}},"FullFormattedMessage":"dvPort group vMotion A in Lab was renamed to vMotion AZ","ChangeTag":"","OldName":"vMotion A","NewName":"vMotion AZ"},"datacontenttype":"application/json"}')
|
python
|
from datetime import datetime
from product import Product
class Slides(Product):
def __init__(self, raw_product):
Product.__init__(self, raw_product)
bib_info = raw_product.get('slides', {})
self._parse_bib_info(bib_info)
def _parse_bib_info(self, bib_info):
self._repository = str(bib_info.get('repository', ""))
self._username = str(bib_info.get('username', ""))
self._published_date = bib_info.get('published_date', None)
if self._published_date:
datetime.strptime(str(self._published_date), "%Y-%m-%dT%H:%M:%SZ")
def __str__(self):
return unicode("genre: " + str(self._genre)
+ "\ntitle: " + str(self._title)
+ "\nauthors: " + str(self._authors)
+ "\nyear: " + str(self._year)
+ "\nfree_fulltext_host: " + str(self._free_fulltext_host)
+ "\nrepository: " + str(self._repository)
+ "\nusername: " + str(self._username)
+ "\npublished_date: " + str(self._published_date)
+ "\nhas_metrics: " + str(self._has_metrics)
+ "\nmetrics: \n" + str(self._display_metrics) + "\n")
@property
def repository(self):
return self._repository
@property
def username(self):
return self._username
@property
def published_date(self):
return self._published_date
|
python
|
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from data_crystal.settings import URL_PREFIX
from data_manager.models import Data
###############################################################################
def app_home(request):
template = loader.get_template('data_manager/home.html')
if request.user.is_authenticated():
#display "novel" data or new data/collections
data=Data.objects.all()
return HttpResponse(template.render(context,request))
else:
data=Data.objects.all()
data=data.filter(public=True)
context={
'prefix':URL_PREFIX,
'datas':data,
}
#display interesting public data
return HttpResponse(template.render(context,request))
def data(request):
print "loading here"
template = loader.get_template('data_manager/home.html')
if request.user.is_authenticated():
#display "novel" data or new data/collections
data=Data.objects.all()
return HttpResponse(template.render(context,request))
else:
data=Data.objects.all()
data=data.filter(public=True)
context={
'prefix':URL_PREFIX,
'datas':data,
}
#display interesting public data
return HttpResponse(template.render(context,request))
def data_view(request,dataid):
print dataid
data_id=request.GET#.get('data_id')
template = loader.get_template('data_manager/data_simple.html')
print data_id
if request.user.is_authenticated():
#display "novel" data or new data/collections
data=Data.objects.get(id=dataid)
context={
'prefix':URL_PREFIX,
'datas':data,
'data_id':data_id,
}
return HttpResponse(template.render(context,request))
else:
#data=data.filter(id=data_id)
data=Data.objects.get(id=dataid)
print data
context={
'prefix':URL_PREFIX,
'data':data,
'data_id':data_id,
}
#display interesting public data
return HttpResponse(template.render(context,request))
def instrument(request):
pass
def collection(request):
pass
def analysis(request):
pass
|
python
|
import argparse
import torch
import torch.nn.functional as F
from gat_conv import GATConv
from torch.nn import Linear
from datasets import get_planetoid_dataset
from snap_dataset import SNAPDataset
from suite_sparse import SuiteSparseMatrixCollection
from train_eval_cs import run
import pdb
from torch_geometric.nn import GCNConv
from torch.nn import Parameter
import os.path as osp
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, required=True)
parser.add_argument('--random_splits', type=bool, default=True)
parser.add_argument('--runs', type=int, default=10)
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--lr', type=float, default=0.0001)
parser.add_argument('--weight_decay', type=float, default=0.0005)
parser.add_argument('--early_stopping', type=int, default=10)
parser.add_argument('--hidden', type=int, default=128)
parser.add_argument('--dropout', type=float, default=0.5)
parser.add_argument('--normalize_features', type=bool, default=True)
args = parser.parse_args()
class Net(torch.nn.Module):
def __init__(self, dataset, num_features , num_classes):
super(Net, self).__init__()
self.conv1 = GCNConv(dataset.num_features, 128)
self.conv2 = GCNConv(128, num_classes)
def reset_parameters(self):
self.conv1.reset_parameters()
self.conv2.reset_parameters()
def forward(self, data, pos_edge_index, neg_edge_index, edge_index):
x = F.relu(self.conv1(data.x, edge_index))
x = self.conv2(x, pos_edge_index)
total_edge_index = torch.cat([pos_edge_index, neg_edge_index], dim=-1)
x_j = torch.index_select(x, 0, total_edge_index[0])
x_i = torch.index_select(x, 0, total_edge_index[1])
# ef, ef -> e = maybe inner product?
return F.log_softmax(x, dim=1), torch.einsum("ef,ef->e", x_i, x_j)
# ego-Facebook com-Amazon ego-gplus ego-twitter
# name = "ego-Facebook"
# path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
# dataset = SNAPDataset(path, name)
# dataset = dataset.shuffle()
# name = "{}\n------\n".format(str(dataset)[:-2])
# print(name)
# run(dataset, Net(dataset, dataset[0].num_feature, int(dataset[0].num_class)), args.runs, args.epochs, args.lr, args.weight_decay,
# args.early_stopping)
# name = "deezer-europe"
# path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name)
# dataset = SNAPDataset(path, name)
# dataset = dataset.shuffle()
# name = "{}\n------\n".format(str(dataset)[:-2])
# print(name)
# run(dataset, Net(dataset, dataset[0].num_feature, int(dataset[0].num_class)), args.runs, args.epochs, args.lr, args.weight_decay,
# args.early_stopping)
# names = ["Cora", "CiteSeer", "PubMed"]
names = ["Cora"]
for name in names:
dataset = get_planetoid_dataset(name, args.normalize_features)
name = "{}\n------\n".format(str(dataset)[:-2])
print(name)
run(dataset, Net(dataset, dataset.num_features, dataset.num_classes), args.runs, args.epochs, args.lr, args.weight_decay,
args.early_stopping)
|
python
|
import os
from config.defaults import *
if os.environ.get("ENV") == 'dev':
print("==== Loading DEV environment ====")
from config.local import *
elif os.environ.get("ENV") == 'docker':
print("==== Loading Docker environment ====")
from config.docker import *
else:
print("==== Loading HERKOU environment ====")
from config.heroku import *
|
python
|
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
from stable_baselines3.common.distributions import SquashedDiagGaussianDistribution
import torch as th
from torch.distributions.multivariate_normal import MultivariateNormal
import torch.nn as nn
from torch.nn.utils import clip_grad_norm_
from scipy.optimize import minimize
from stable_baselines3.common import logger
from stable_baselines3.common.noise import ActionNoise
from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm
from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule
from stable_baselines3.common.utils import polyak_update
from custom_algos.mpo.policies import MlpPolicy
class MPO(OffPolicyAlgorithm):
"""
Maximum A Posteriori Policy Optimization (MPO)
:param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)
:param env: The environment to learn from (if registered in Gym, can be str)
:param learning_rate: learning rate for adam optimizer,
the same learning rate will be used for all networks (Q-Values, Actor and Value function)
it can be a function of the current progress remaining (from 1 to 0)
:param buffer_size: size of the replay buffer
:param learning_starts: how many steps of the model to collect transitions for before learning starts
:param batch_size: Minibatch size for each gradient update
:param tau: the soft update coefficient ("Polyak update", between 0 and 1)
:param gamma: the discount factor
:param dual_constraint: (float) hard constraint of the dual formulation in the E-step
:param kl_mean_constraint: (float) hard constraint of the mean in the M-step
:param kl_var_constraint: (float) hard constraint of the covariance in the M-step
:param alpha: (float) scaling factor of the lagrangian multiplier in the M-step
:param lagrange_iterations: (int) number of optimization steps of the Lagrangian
:param action_samples: (int) number of additional actions
:param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit
like ``(5, "step")`` or ``(2, "episode")``.
:param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)
Set to ``-1`` means to do as many gradient steps as steps done in the environment
during the rollout.
:param action_noise: the action noise type (None by default), this can help
for hard exploration problem. Cf common.noise for the different action noise type.
:param optimize_memory_usage: Enable a memory efficient variant of the replay buffer
at a cost of more complexity.
See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195
:param target_update_interval: update the target network every ``target_network_update_freq``
gradient steps.
:param create_eval_env: Whether to create a second environment that will be
used for evaluating the agent periodically. (Only available when passing string for the environment)
:param policy_kwargs: additional arguments to be passed to the policy on creation
:param verbose: the verbosity level: 0 no output, 1 info, 2 debug
:param seed: Seed for the pseudo random generators
:param device: Device (cpu, cuda, ...) on which the code should be run.
Setting it to auto, the code will be run on the GPU if possible.
:param _init_setup_model: Whether or not to build the network at the creation of the instance
"""
def __init__(
self,
policy: Union[str, Type[MlpPolicy]],
env: Union[GymEnv, str],
learning_rate: Union[float, Schedule] = 3e-4,
buffer_size: int = int(1e6),
learning_starts: int = 5000,
batch_size: int = 256,
tau: float = 0.02,
gamma: float = 0.99,
dual_constraint: float = 0.1,
kl_mean_constraint: float = 0.1,
kl_var_constraint: float = 1e-3,
alpha: float = 10,
lagrange_iterations: int = 5,
action_samples: int = 64,
train_freq: Union[int, Tuple[int, str]] = 1,
gradient_steps: int = 4,
action_noise: Optional[ActionNoise] = None,
optimize_memory_usage: bool = False,
target_update_interval: int = 2,
tensorboard_log: Optional[str] = None,
create_eval_env: bool = False,
policy_kwargs: Dict[str, Any] = None,
verbose: int = 0,
seed: Optional[int] = 0,
device: Union[th.device, str] = "auto",
_init_setup_model: bool = True,
):
super(MPO, self).__init__(
policy,
env,
MlpPolicy,
learning_rate,
buffer_size,
learning_starts,
batch_size,
tau,
gamma,
train_freq,
gradient_steps,
action_noise,
policy_kwargs=policy_kwargs,
tensorboard_log=tensorboard_log,
verbose=verbose,
device=device,
create_eval_env=create_eval_env,
seed=seed,
optimize_memory_usage=optimize_memory_usage,
supported_action_spaces=(gym.spaces.Box),
)
self.target_update_interval = target_update_interval
self.α = alpha # scaling factor for the update step of η_μ
self.ε_dual = dual_constraint # hard constraint for the KL
self.ε_kl_μ = kl_mean_constraint # hard constraint for the KL
self.ε_kl_Σ = kl_var_constraint # hard constraint for the KL
self.lagrange_iterations = lagrange_iterations
self.action_samples = action_samples
self.critic_loss = nn.SmoothL1Loss()
if seed is not None:
np.random.seed(seed)
self.η = np.random.rand()
self.η_kl_μ = 0.0
self.η_kl_Σ = 0.0
self.η_kl = 0.0
if _init_setup_model:
self._setup_model()
def _setup_model(self) -> None:
super(MPO, self)._setup_model()
self._create_aliases()
def _create_aliases(self) -> None:
self.actor = self.policy.actor
self.actor_target = self.policy.actor_target
self.critic = self.policy.critic
self.critic_target = self.policy.critic_target
self.features_dim = self.actor.features_dim
self.action_dim = self.actor.action_dim
def train(self, gradient_steps: int, batch_size: int = 64) -> None:
# Update optimizers learning rate
optimizers = [self.actor.optimizer, self.critic.optimizer]
# Update learning rate according to lr schedule
self._update_learning_rate(optimizers)
mean_loss_q, mean_loss_p, mean_loss_l, max_kl_μ, max_kl_Σ, max_kl = [], [], [], [], [], []
actor_losses, critic_losses = [], []
for gradient_step in range(gradient_steps):
# Sample replay buffer
replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env)
batch_size = replay_data.observations.size(0)
with th.no_grad():
# Sample "action_samples" num additional actions
target_next_action_mean, target_next_action_cholesky, _ = self.actor_target.get_action_dist_params(
replay_data.next_observations)
target_next_action_dist = MultivariateNormal(target_next_action_mean, scale_tril=target_next_action_cholesky)
target_sampled_next_actions = target_next_action_dist.sample((self.action_samples,)).transpose(0, 1)
# Compute mean of q values for the samples
# Expand next_observation to match self.action_samples
expanded_next_observations = replay_data.next_observations[:, None, :].expand(-1, self.action_samples, -1)
target_sampled_next_actions_expected_q = get_min_critic_tensor(self.critic_target.forward(
expanded_next_observations.reshape(-1, self.features_dim),
target_sampled_next_actions.reshape(-1, self.action_dim)
)).reshape(batch_size, self.action_samples).mean(dim=1)
# Compute total expected return
target_sampled_expected_return = replay_data.rewards.squeeze() + (1 - replay_data.dones.squeeze()) * self.gamma * \
target_sampled_next_actions_expected_q
# Optimize the critic
critic_qs = self.critic.forward(replay_data.observations, replay_data.actions)
critic_loss = 0.5 * sum([self.critic_loss(current_q.squeeze(), target_sampled_expected_return)
for current_q in critic_qs])
critic_losses.append(critic_loss.item())
self.critic.optimizer.zero_grad()
critic_loss.backward()
self.critic.optimizer.step()
# Sample additional actions for E-Step
with th.no_grad():
target_action_mean, target_action_cholesky, _ = self.actor_target.get_action_dist_params(
replay_data.observations)
target_action_dist = MultivariateNormal(target_action_mean, scale_tril=target_action_cholesky)
sampled_actions = target_action_dist.sample((self.action_samples,))
# Compute q values for the samples
# Expand next_observation to match self.action_samples
expanded_observations = replay_data.observations[None, ...].expand(self.action_samples, -1, -1)
target_sampled_actions_expected_q = get_min_critic_tensor(self.critic_target.forward(
expanded_observations.reshape(-1, self.features_dim),
sampled_actions.reshape(-1, self.action_dim)
)).reshape(self.action_samples, batch_size)
target_sampled_actions_expected_q_np = target_sampled_actions_expected_q.cpu().numpy()
# Define dual function
def dual(η):
max_q = np.max(target_sampled_actions_expected_q_np, 0)
return η * self.ε_dual + np.mean(max_q) \
+ η * np.mean(np.log(np.mean(np.exp((target_sampled_actions_expected_q_np - max_q) / η), axis=0)))
bounds = [(1e-6, None)]
self.η = np.max([self.η, 1e-6])
res = minimize(dual, np.array([self.η]), method='SLSQP', bounds=bounds)
self.η = res.x[0]
qij = th.softmax(target_sampled_actions_expected_q / self.η, dim=0)
# M-Step
for _ in range(self.lagrange_iterations):
action_mean, action_cholesky, _ = self.actor.get_action_dist_params(replay_data.observations)
π1 = MultivariateNormal(action_mean, scale_tril=target_action_cholesky)
π2 = MultivariateNormal(target_action_mean, scale_tril=action_cholesky)
loss_p = th.mean(qij * (
π1.expand((self.action_samples, batch_size)).log_prob(sampled_actions)
+ π2.expand((self.action_samples, batch_size)).log_prob(sampled_actions)
)
)
mean_loss_p.append((-loss_p).item())
kl_μ, kl_Σ = gaussian_kl(
μ_target=target_action_mean, μ=action_mean,
A_target=target_action_cholesky, A=action_cholesky
)
max_kl_μ.append(kl_μ.item())
max_kl_Σ.append(kl_Σ.item())
self.η_kl_μ -= self.α * (self.ε_kl_μ - kl_μ).detach().item()
self.η_kl_Σ -= self.α * (self.ε_kl_Σ - kl_Σ).detach().item()
if self.η_kl_μ < 0.0:
self.η_kl_μ = 0.0
if self.η_kl_Σ < 0.0:
self.η_kl_Σ = 0.0
self.actor.optimizer.zero_grad()
actor_loss = -(loss_p
+ self.η_kl_μ * (self.ε_kl_μ - kl_μ)
+ self.η_kl_Σ * (self.ε_kl_Σ - kl_Σ)
)
actor_losses.append(actor_loss.item())
# Optimize actor
actor_loss.backward()
clip_grad_norm_(self.actor.parameters(), 0.1)
self.actor.optimizer.step()
if gradient_step % self.target_update_interval == 0:
polyak_update(self.actor.parameters(), self.actor_target.parameters(), self.tau)
polyak_update(self.critic.parameters(), self.critic_target.parameters(), self.tau)
self._n_updates += gradient_steps
logger.record("train/n_updates", self._n_updates, exclude="tensorboard")
logger.record("train/actor_loss", np.mean(actor_losses))
logger.record("train/critic_loss", np.mean(critic_losses))
logger.record("train/actor_policy_loss", np.mean(mean_loss_p))
logger.record("train/max_kl_mean", np.max(max_kl_μ))
logger.record("train/mean_kl_mean", np.mean(max_kl_μ))
logger.record("train/max_kl_std", np.max(max_kl_Σ))
logger.record("train/mean_kl_std", np.mean(max_kl_Σ))
def learn(
self,
total_timesteps: int,
callback: MaybeCallback = None,
log_interval: int = 4,
eval_env: Optional[GymEnv] = None,
eval_freq: int = -1,
n_eval_episodes: int = 5,
tb_log_name: str = "SAC",
eval_log_path: Optional[str] = None,
reset_num_timesteps: bool = True,
) -> OffPolicyAlgorithm:
return super(MPO, self).learn(
total_timesteps=total_timesteps,
callback=callback,
log_interval=log_interval,
eval_env=eval_env,
eval_freq=eval_freq,
n_eval_episodes=n_eval_episodes,
tb_log_name=tb_log_name,
eval_log_path=eval_log_path,
reset_num_timesteps=reset_num_timesteps,
)
def _excluded_save_params(self) -> List[str]:
return super(MPO, self)._excluded_save_params() + ["actor", "actor_target", "critic", "critic_target"]
def _get_torch_save_params(self) -> Tuple[List[str], List[str]]:
state_dicts = ["policy", "actor.optimizer", "critic.optimizer"]
saved_pytorch_variables = []
# saved_pytorch_variables = ["log_ent_coef"]
return state_dicts, saved_pytorch_variables
def bt(m):
return m.transpose(dim0=-2, dim1=-1)
def btr(m):
return m.diagonal(dim1=-2, dim2=-1).sum(-1)
def gaussian_kl(μ_target, μ, A_target, A):
"""
decoupled KL between two multivariate gaussian distribution
C_μ = KL(f(x|μi,Σi)||f(x|μ,Σi))
C_Σ = KL(f(x|μi,Σi)||f(x|μi,Σ))
:param μi: (B, n)
:param μ: (B, n)
:param Ai: (B, n, n)
:param A: (B, n, n)
:return: C_μ, C_Σ: mean and covariance terms of the KL
"""
n = A.size(-1)
μ_target = μ_target.unsqueeze(-1) # (B, n, 1)
μ = μ.unsqueeze(-1) # (B, n, 1)
Σ_target = A_target @ bt(A_target) # (B, n, n)
Σ = A @ bt(A) # (B, n, n)
Σ_target_inv = Σ_target.inverse() # (B, n, n)
Σ_inv = Σ.inverse() # (B, n, n)
inner_μ = ((μ - μ_target).transpose(-2, -1) @ Σ_target_inv @ (μ - μ_target)).squeeze() # (B,)
inner_Σ = th.log(Σ.det() / Σ_target.det()) - n + btr(Σ_inv @ Σ_target) # (B,)
C_μ = 0.5 * th.mean(inner_μ)
C_Σ = 0.5 * th.mean(inner_Σ)
return C_μ, C_Σ
def get_min_critic_tensor(critics):
return th.min(th.cat(critics, dim=1), dim=1, keepdim=True).values
|
python
|
import os
import urllib2
import uuid
import falcon
import mimetypes
import requests
import logging
from datetime import datetime
__author__ = 'Maged'
logging.basicConfig(filename='dropbox_upload_manager.log', level=logging.DEBUG)
WGET_CMD = '/usr/bin/wget'
ALLOWED_TYPES = (
'text/plain',
'image/gif',
'image/jpeg',
'image/png'
)
def _generate_id():
return str(uuid.uuid4())
def validate_file_type(req, resp, resource, params):
# debug: params: empty list
# debug: resource: .storage_path = /home/maged/share/Python/look_collection_json/matrices
# if req.content_type not in ALLOWED_IMAGE_TYPES:
if req.content_type not in ALLOWED_TYPES:
# from pudb import set_trace; set_trace()
msg = 'File type not allowed. Must be plain text, jpeg, png or gif'
raise falcon.HTTPBadRequest('Bad request', msg)
class Collection(object):
def __init__(self, storage_path):
self.storage_path = storage_path
def on_post(self, req, resp):
url = urllib2.unquote(req.get_header("DBX-Uri")).decode('utf8')
ext = os.path.splitext(url)[1][1:]
file_name = os.path.basename(url)
file_path = os.path.join(self.storage_path, file_name)
logging.debug("before_write")
logging.debug(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S.%f'))
with os.popen(WGET_CMD + ' -nc --no-dns-cache -4 ' + url + ' -O ' + file_path) as wget_output:
resp.status = falcon.HTTP_201 # CREATED
resp.body = file_name
logging.debug("after_write")
logging.debug(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S.%f'))
|
python
|
from unittest import TestCase, main
from os import remove
from os.path import exists, join
from datetime import datetime
from shutil import move
from biom import load_table
import pandas as pd
from qiita_core.util import qiita_test_checker
from qiita_db.analysis import Analysis, Collection
from qiita_db.job import Job
from qiita_db.user import User
from qiita_db.exceptions import QiitaDBStatusError
from qiita_db.util import get_mountpoint
from qiita_db.study import Study, StudyPerson
from qiita_db.data import ProcessedData
from qiita_db.metadata_template import SampleTemplate
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
@qiita_test_checker()
class TestAnalysis(TestCase):
def setUp(self):
self.analysis = Analysis(1)
_, self.fp = get_mountpoint("analysis")[0]
self.biom_fp = join(self.fp, "1_analysis_18S.biom")
self.map_fp = join(self.fp, "1_analysis_mapping.txt")
def tearDown(self):
with open(self.biom_fp, 'w') as f:
f.write("")
with open(self.map_fp, 'w') as f:
f.write("")
fp = join(get_mountpoint('analysis')[0][1], 'testfile.txt')
if exists(fp):
remove(fp)
mp = get_mountpoint("processed_data")[0][1]
study2fp = join(mp, "2_2_study_1001_closed_reference_otu_table.biom")
if exists(study2fp):
move(study2fp,
join(mp, "2_study_1001_closed_reference_otu_table.biom"))
def test_lock_check(self):
for status in ["queued", "running", "public", "completed",
"error"]:
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis")
new.status = status
with self.assertRaises(QiitaDBStatusError):
new._lock_check(self.conn_handler)
def test_lock_check_ok(self):
self.analysis.status = "in_construction"
self.analysis._lock_check(self.conn_handler)
def test_status_setter_checks(self):
self.analysis.status = "public"
with self.assertRaises(QiitaDBStatusError):
self.analysis.status = "queued"
def test_get_by_status(self):
self.assertEqual(Analysis.get_by_status('public'), [])
self.analysis.status = "public"
self.assertEqual(Analysis.get_by_status('public'), [1])
def test_has_access_public(self):
self.conn_handler.execute("UPDATE qiita.analysis SET "
"analysis_status_id = 6")
self.assertTrue(self.analysis.has_access(User("[email protected]")))
def test_has_access_shared(self):
self.assertTrue(self.analysis.has_access(User("[email protected]")))
def test_has_access_private(self):
self.assertTrue(self.analysis.has_access(User("[email protected]")))
def test_has_access_admin(self):
self.assertTrue(self.analysis.has_access(User("[email protected]")))
def test_has_access_no_access(self):
self.assertFalse(self.analysis.has_access(User("[email protected]")))
def test_create(self):
sql = "SELECT EXTRACT(EPOCH FROM NOW())"
time1 = float(self.conn_handler.execute_fetchall(sql)[0][0])
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis")
self.assertEqual(new.id, 3)
sql = ("SELECT analysis_id, email, name, description, "
"analysis_status_id, pmid, EXTRACT(EPOCH FROM timestamp) "
"FROM qiita.analysis WHERE analysis_id = 3")
obs = self.conn_handler.execute_fetchall(sql)
self.assertEqual(obs[0][:-1], [3, '[email protected]', 'newAnalysis',
'A New Analysis', 1, None])
self.assertTrue(time1 < float(obs[0][-1]))
def test_create_parent(self):
sql = "SELECT EXTRACT(EPOCH FROM NOW())"
time1 = float(self.conn_handler.execute_fetchall(sql)[0][0])
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
self.assertEqual(new.id, 3)
sql = ("SELECT analysis_id, email, name, description, "
"analysis_status_id, pmid, EXTRACT(EPOCH FROM timestamp) "
"FROM qiita.analysis WHERE analysis_id = 3")
obs = self.conn_handler.execute_fetchall(sql)
self.assertEqual(obs[0][:-1], [3, '[email protected]', 'newAnalysis',
'A New Analysis', 1, None])
self.assertTrue(time1 < float(obs[0][-1]))
sql = "SELECT * FROM qiita.analysis_chain WHERE child_id = 3"
obs = self.conn_handler.execute_fetchall(sql)
self.assertEqual(obs, [[1, 3]])
def test_retrieve_owner(self):
self.assertEqual(self.analysis.owner, "[email protected]")
def test_retrieve_name(self):
self.assertEqual(self.analysis.name, "SomeAnalysis")
def test_retrieve_description(self):
self.assertEqual(self.analysis.description, "A test analysis")
def test_set_description(self):
self.analysis.description = "New description"
self.assertEqual(self.analysis.description, "New description")
def test_retrieve_samples(self):
exp = {1: ['1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196',
'1.SKM9.640192', '1.SKM4.640180']}
self.assertEqual(self.analysis.samples, exp)
def test_retrieve_dropped_samples(self):
# Create and populate second study to do test with
info = {
"timeseries_type_id": 1,
"metadata_complete": True,
"mixs_compliant": True,
"number_samples_collected": 25,
"number_samples_promised": 28,
"portal_type_id": 3,
"study_alias": "FCM",
"study_description": "Microbiome of people who eat nothing but "
"fried chicken",
"study_abstract": "Exploring how a high fat diet changes the "
"gut microbiome",
"emp_person_id": StudyPerson(2),
"principal_investigator_id": StudyPerson(3),
"lab_person_id": StudyPerson(1)
}
metadata_dict = {
'SKB8.640193': {'physical_location': 'location1',
'has_physical_specimen': True,
'has_extracted_data': True,
'sample_type': 'type1',
'required_sample_info_status': 'received',
'collection_timestamp':
datetime(2014, 5, 29, 12, 24, 51),
'host_subject_id': 'NotIdentified',
'Description': 'Test Sample 1',
'str_column': 'Value for sample 1',
'latitude': 42.42,
'longitude': 41.41},
'SKD8.640184': {'physical_location': 'location1',
'has_physical_specimen': True,
'has_extracted_data': True,
'sample_type': 'type1',
'required_sample_info_status': 'received',
'collection_timestamp':
datetime(2014, 5, 29, 12, 24, 51),
'host_subject_id': 'NotIdentified',
'Description': 'Test Sample 2',
'str_column': 'Value for sample 2',
'latitude': 4.2,
'longitude': 1.1},
'SKB7.640196': {'physical_location': 'location1',
'has_physical_specimen': True,
'has_extracted_data': True,
'sample_type': 'type1',
'required_sample_info_status': 'received',
'collection_timestamp':
datetime(2014, 5, 29, 12, 24, 51),
'host_subject_id': 'NotIdentified',
'Description': 'Test Sample 3',
'str_column': 'Value for sample 3',
'latitude': 4.8,
'longitude': 4.41},
}
metadata = pd.DataFrame.from_dict(metadata_dict, orient='index')
Study.create(User("[email protected]"), "Test study 2", [1], info)
SampleTemplate.create(metadata, Study(2))
mp = get_mountpoint("processed_data")[0][1]
study_fp = join(mp, "2_study_1001_closed_reference_otu_table.biom")
ProcessedData.create("processed_params_uclust", 1, [(study_fp, 6)],
study=Study(2), data_type="16S")
self.conn_handler.execute(
"INSERT INTO qiita.analysis_sample (analysis_id, "
"processed_data_id, sample_id) VALUES "
"(1,2,'2.SKB8.640193'), (1,2,'2.SKD8.640184'), "
"(1,2,'2.SKB7.640196')")
samples = {1: ['1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196'],
2: ['2.SKB8.640193', '2.SKD8.640184']}
self.analysis._build_biom_tables(samples, 10000,
conn_handler=self.conn_handler)
exp = {1: {'1.SKM4.640180', '1.SKM9.640192'},
2: {'2.SKB7.640196'}}
self.assertEqual(self.analysis.dropped_samples, exp)
def test_retrieve_data_types(self):
exp = ['18S']
self.assertEqual(self.analysis.data_types, exp)
def test_retrieve_shared_with(self):
self.assertEqual(self.analysis.shared_with, ["[email protected]"])
def test_retrieve_biom_tables(self):
exp = {"18S": join(self.fp, "1_analysis_18S.biom")}
self.assertEqual(self.analysis.biom_tables, exp)
def test_all_associated_filepaths(self):
exp = {12, 13, 14, 15}
self.assertEqual(self.analysis.all_associated_filepath_ids, exp)
def test_retrieve_biom_tables_none(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
self.assertEqual(new.biom_tables, None)
def test_set_step(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
new.step = 2
sql = "SELECT * FROM qiita.analysis_workflow WHERE analysis_id = 3"
obs = self.conn_handler.execute_fetchall(sql)
self.assertEqual(obs, [[3, 2]])
def test_set_step_twice(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
new.step = 2
new.step = 4
sql = "SELECT * FROM qiita.analysis_workflow WHERE analysis_id = 3"
obs = self.conn_handler.execute_fetchall(sql)
self.assertEqual(obs, [[3, 4]])
def test_retrieve_step(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
new.step = 2
self.assertEqual(new.step, 2)
def test_retrieve_step_new(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
with self.assertRaises(ValueError):
new.step
def test_retrieve_step_locked(self):
self.analysis.status = "public"
with self.assertRaises(QiitaDBStatusError):
self.analysis.step = 3
def test_retrieve_jobs(self):
self.assertEqual(self.analysis.jobs, [1, 2])
def test_retrieve_jobs_none(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
self.assertEqual(new.jobs, None)
def test_retrieve_pmid(self):
self.assertEqual(self.analysis.pmid, "121112")
def test_retrieve_pmid_none(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
self.assertEqual(new.pmid, None)
def test_set_pmid(self):
self.analysis.pmid = "11211221212213"
self.assertEqual(self.analysis.pmid, "11211221212213")
def test_retrieve_mapping_file(self):
exp = join(self.fp, "1_analysis_mapping.txt")
obs = self.analysis.mapping_file
self.assertEqual(obs, exp)
self.assertTrue(exists(exp))
def test_retrieve_mapping_file_none(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis", Analysis(1))
obs = new.mapping_file
self.assertEqual(obs, None)
# def test_get_parent(self):
# raise NotImplementedError()
# def test_get_children(self):
# raise NotImplementedError()
def test_add_samples(self):
new = Analysis.create(User("[email protected]"), "newAnalysis",
"A New Analysis")
new.add_samples([(1, '1.SKB8.640193'), (1, '1.SKD5.640186')])
exp = {1: ['1.SKB8.640193', '1.SKD5.640186']}
self.assertEqual(new.samples, exp)
def test_remove_samples_both(self):
self.analysis.remove_samples(proc_data=(1, ),
samples=('1.SKB8.640193', ))
exp = {1: ['1.SKD8.640184', '1.SKB7.640196', '1.SKM9.640192',
'1.SKM4.640180']}
self.assertEqual(self.analysis.samples, exp)
def test_remove_samples_samples(self):
self.analysis.remove_samples(samples=('1.SKD8.640184', ))
exp = {1: ['1.SKB8.640193', '1.SKB7.640196', '1.SKM9.640192',
'1.SKM4.640180']}
self.assertEqual(self.analysis.samples, exp)
def test_remove_samples_processed_data(self):
self.analysis.remove_samples(proc_data=(1, ))
exp = {}
self.assertEqual(self.analysis.samples, exp)
def test_share(self):
self.analysis.share(User("[email protected]"))
self.assertEqual(self.analysis.shared_with, ["[email protected]",
"[email protected]"])
def test_unshare(self):
self.analysis.unshare(User("[email protected]"))
self.assertEqual(self.analysis.shared_with, [])
def test_get_samples(self):
obs = self.analysis._get_samples()
exp = {1: ['1.SKB7.640196', '1.SKB8.640193', '1.SKD8.640184',
'1.SKM4.640180', '1.SKM9.640192']}
self.assertEqual(obs, exp)
def test_build_mapping_file(self):
samples = {1: ['1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196']}
self.analysis._build_mapping_file(samples,
conn_handler=self.conn_handler)
obs = self.analysis.mapping_file
self.assertEqual(obs, self.map_fp)
with open(self.map_fp) as f:
mapdata = f.readlines()
# check some columns for correctness
obs = [line.split('\t')[0] for line in mapdata]
exp = ['#SampleID', '1.SKB8.640193', '1.SKD8.640184',
'1.SKB7.640196']
self.assertEqual(obs, exp)
obs = [line.split('\t')[1] for line in mapdata]
exp = ['BarcodeSequence', 'AGCGCTCACATC', 'TGAGTGGTCTGT',
'CGGCCTAAGTTC']
self.assertEqual(obs, exp)
obs = [line.split('\t')[2] for line in mapdata]
exp = ['LinkerPrimerSequence', 'GTGCCAGCMGCCGCGGTAA',
'GTGCCAGCMGCCGCGGTAA', 'GTGCCAGCMGCCGCGGTAA']
self.assertEqual(obs, exp)
obs = [line.split('\t')[19] for line in mapdata]
exp = ['host_subject_id', '1001:M7', '1001:D9',
'1001:M8']
self.assertEqual(obs, exp)
obs = [line.split('\t')[47] for line in mapdata]
exp = ['tot_org_carb', '5.0', '4.32', '5.0']
self.assertEqual(obs, exp)
obs = [line.split('\t')[-1] for line in mapdata]
exp = ['Description\n'] + ['Cannabis Soil Microbiome\n'] * 3
self.assertEqual(obs, exp)
def test_build_mapping_file_duplicate_samples(self):
samples = {1: ['1.SKB8.640193', '1.SKB8.640193', '1.SKD8.640184']}
with self.assertRaises(ValueError):
self.analysis._build_mapping_file(samples,
conn_handler=self.conn_handler)
def test_build_biom_tables(self):
samples = {1: ['1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196']}
self.analysis._build_biom_tables(samples, 100,
conn_handler=self.conn_handler)
obs = self.analysis.biom_tables
self.assertEqual(obs, {'18S': self.biom_fp})
table = load_table(self.biom_fp)
obs = set(table.ids(axis='sample'))
exp = {'1.SKB8.640193', '1.SKD8.640184', '1.SKB7.640196'}
self.assertEqual(obs, exp)
obs = table.metadata('1.SKB8.640193')
exp = {'Study':
'Identification of the Microbiomes for Cannabis Soils',
'Processed_id': 1}
self.assertEqual(obs, exp)
def test_build_files(self):
self.analysis.build_files()
def test_build_files_raises_type_error(self):
with self.assertRaises(TypeError):
self.analysis.build_files('string')
with self.assertRaises(TypeError):
self.analysis.build_files(100.5)
def test_build_files_raises_value_error(self):
with self.assertRaises(ValueError):
self.analysis.build_files(0)
with self.assertRaises(ValueError):
self.analysis.build_files(-10)
def test_add_file(self):
fp = join(get_mountpoint('analysis')[0][1], 'testfile.txt')
with open(fp, 'w') as f:
f.write('testfile!')
self.analysis._add_file('testfile.txt', 'plain_text', '18S')
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.filepath WHERE filepath_id = 19')
exp = [[19, 'testfile.txt', 9, '3675007573', 1, 1]]
self.assertEqual(obs, exp)
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.analysis_filepath WHERE filepath_id = 19')
exp = [[1, 19, 2]]
self.assertEqual(obs, exp)
@qiita_test_checker()
class TestCollection(TestCase):
def setUp(self):
self.collection = Collection(1)
def test_create(self):
Collection.create(User('[email protected]'), 'TestCollection2', 'Some desc')
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.collection WHERE collection_id = 2')
exp = [[2, '[email protected]', 'TestCollection2', 'Some desc', 1]]
self.assertEqual(obs, exp)
def test_create_no_desc(self):
Collection.create(User('[email protected]'), 'Test Collection2')
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.collection WHERE collection_id = 2')
exp = [[2, '[email protected]', 'Test Collection2', None, 1]]
self.assertEqual(obs, exp)
def test_delete(self):
Collection.delete(1)
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.collection')
exp = []
self.assertEqual(obs, exp)
def test_delete_public(self):
self.collection.status = 'public'
with self.assertRaises(QiitaDBStatusError):
Collection.delete(1)
obs = self.conn_handler.execute_fetchall(
'SELECT * FROM qiita.collection')
exp = [[1, '[email protected]', 'TEST_COLLECTION',
'collection for testing purposes', 2]]
self.assertEqual(obs, exp)
def test_retrieve_name(self):
obs = self.collection.name
exp = "TEST_COLLECTION"
self.assertEqual(obs, exp)
def test_set_name(self):
self.collection.name = "NeW NaMe 123"
self.assertEqual(self.collection.name, "NeW NaMe 123")
def test_set_name_public(self):
self.collection.status = "public"
with self.assertRaises(QiitaDBStatusError):
self.collection.name = "FAILBOAT"
def test_retrieve_desc(self):
obs = self.collection.description
exp = "collection for testing purposes"
self.assertEqual(obs, exp)
def test_set_desc(self):
self.collection.description = "NeW DeSc 123"
self.assertEqual(self.collection.description, "NeW DeSc 123")
def test_set_desc_public(self):
self.collection.status = "public"
with self.assertRaises(QiitaDBStatusError):
self.collection.description = "FAILBOAT"
def test_retrieve_owner(self):
obs = self.collection.owner
exp = "[email protected]"
self.assertEqual(obs, exp)
def test_retrieve_analyses(self):
obs = self.collection.analyses
exp = [1]
self.assertEqual(obs, exp)
def test_retrieve_highlights(self):
obs = self.collection.highlights
exp = [1]
self.assertEqual(obs, exp)
def test_retrieve_shared_with(self):
obs = self.collection.shared_with
exp = ["[email protected]"]
self.assertEqual(obs, exp)
def test_add_analysis(self):
self.collection.add_analysis(Analysis(2))
obs = self.collection.analyses
exp = [1, 2]
self.assertEqual(obs, exp)
def test_remove_analysis(self):
self.collection.remove_analysis(Analysis(1))
obs = self.collection.analyses
exp = []
self.assertEqual(obs, exp)
def test_highlight_job(self):
self.collection.highlight_job(Job(2))
obs = self.collection.highlights
exp = [1, 2]
self.assertEqual(obs, exp)
def test_remove_highlight(self):
self.collection.remove_highlight(Job(1))
obs = self.collection.highlights
exp = []
self.assertEqual(obs, exp)
def test_share(self):
self.collection.share(User("[email protected]"))
obs = self.collection.shared_with
exp = ["[email protected]", "[email protected]"]
self.assertEqual(obs, exp)
def test_unshare(self):
self.collection.unshare(User("[email protected]"))
obs = self.collection.shared_with
exp = []
self.assertEqual(obs, exp)
if __name__ == "__main__":
main()
|
python
|
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='pdt-r']/div[@class='t']/div[@class='l']/h1",
'price' : "//div[@class='l']/div/p/span",
'category' : "//body/form[@id='form1']/div[@class='link']/a[@class='cmaTite']",
'description' : "//div[@class='left']/div[@class='pdbt']/div[@class='border relative']/div[@class='pd10']",
'images' : "//body/form[@id='form1']/div[@class='pdt-l']/div[@class='valig']//img/@src",
'canonical' : "",
'base_url' : "",
'brand' : ""
}
name = 'ducbinh.com.vn'
allowed_domains = ['ducbinh.com.vn']
start_urls = ['http://ducbinh.com.vn']
tracking_url = ''
sitemap_urls = ['']
sitemap_rules = [('', 'parse_item')]
sitemap_follow = []
rules = [
Rule(LinkExtractor(allow=['/\d+/\d+/']), 'parse_item'),
Rule(LinkExtractor(allow=['/\d+/']), 'parse'),
#Rule(LinkExtractor(), 'parse_item_and_links'),
]
|
python
|
"""pydantic models for GeoJSON Feature objects."""
from typing import Dict, Generic, List, Optional, TypeVar
from pydantic import Field, validator
from pydantic.generics import GenericModel
from geojson_pydantic.geometries import Geometry
from geojson_pydantic.types import BBox
Props = TypeVar("Props", bound=Dict)
Geom = TypeVar("Geom", bound=Geometry)
class Feature(GenericModel, Generic[Geom, Props]):
"""Feature Model"""
type: str = Field("Feature", const=True)
geometry: Geom
properties: Optional[Props]
id: Optional[str]
bbox: Optional[BBox]
class Config:
"""TODO: document"""
use_enum_values = True
@validator("geometry", pre=True, always=True)
def set_geometry(cls, v):
"""set geometry from geo interface or input"""
if hasattr(v, "__geo_interface__"):
return v.__geo_interface__
return v
class FeatureCollection(GenericModel, Generic[Geom, Props]):
"""FeatureCollection Model"""
type: str = Field("FeatureCollection", const=True)
features: List[Feature[Geom, Props]]
bbox: Optional[BBox]
def __iter__(self):
"""iterate over features"""
return iter(self.features)
def __len__(self):
"""return features length"""
return len(self.features)
def __getitem__(self, index):
"""get feature at a given index"""
return self.features[index]
|
python
|
"""Async version of stream-unzip (https://github.com/uktrade/stream-unzip). MIT License."""
import zlib
from struct import Struct
async def stream_unzip(zipfile_chunks, chunk_size=65536):
local_file_header_signature = b'\x50\x4b\x03\x04'
local_file_header_struct = Struct('<H2sHHHIIIHH')
zip64_compressed_size = 4294967295
zip64_size_signature = b'\x01\x00'
central_directory_signature = b'\x50\x4b\x01\x02'
async def get_byte_readers(iterable):
# Return functions to return/"replace" bytes from/to the iterable
# - _yield_all: yields chunks as they come up (often for a "body")
# - _yield_num: yields chunks as the come up, up to a fixed number of bytes
# - _get_num: returns a single `bytes` of a given length
# - _return_unused: puts "unused" bytes "back", to be retrieved by a yield/get call
chunk = b''
offset = 0
# it = iter(iterable)
it = iterable
async def _yield_all():
nonlocal chunk
nonlocal offset
while True:
if not chunk:
try:
# chunk = next(it)
chunk = await it.__anext__()
except StopAsyncIteration:
break
prev_offset = offset
prev_chunk = chunk
to_yield = min(len(chunk) - offset, chunk_size)
offset = (offset + to_yield) % len(chunk)
chunk = chunk if offset else b''
yield prev_chunk[prev_offset:prev_offset + to_yield]
async def _yield_num(num):
nonlocal chunk
nonlocal offset
while num:
if not chunk:
try:
# chunk = next(it)
chunk = await iterable.__anext__()
except StopAsyncIteration:
raise ValueError('Fewer bytes than expected in zip') from None
prev_offset = offset
prev_chunk = chunk
to_yield = min(num, len(chunk) - offset, chunk_size)
offset = (offset + to_yield) % len(chunk)
chunk = chunk if offset else b''
num -= to_yield
yield prev_chunk[prev_offset:prev_offset + to_yield]
async def _get_num(num):
return b''.join([chunk async for chunk in _yield_num(num)])
def _return_unused(unused):
nonlocal chunk
nonlocal offset
if len(unused) <= offset:
offset -= len(unused)
else:
chunk = unused + chunk[offset:]
offset = 0
return _yield_all, _yield_num, _get_num, _return_unused
yield_all, yield_num, get_num, return_unused = await get_byte_readers(zipfile_chunks)
def get_extra_data(extra, desired_signature):
extra_offset = 0
while extra_offset != len(extra):
extra_signature = extra[extra_offset:extra_offset + 2]
extra_offset += 2
extra_data_size, = Struct('<H').unpack(extra[extra_offset:extra_offset + 2])
extra_offset += 2
extra_data = extra[extra_offset:extra_offset + extra_data_size]
extra_offset += extra_data_size
if extra_signature == desired_signature:
return extra_data
async def yield_file():
version, flags, compression, mod_time, mod_date, crc_32_expected, compressed_size, uncompressed_size, file_name_len, extra_field_len = \
local_file_header_struct.unpack(await get_num(local_file_header_struct.size))
if compression not in [0, 8]:
raise ValueError('Unsupported compression type {}'.format(compression))
def _flag_bits():
for b in flags:
for i in range(8):
yield (b >> i) & 1
flag_bits = tuple(_flag_bits())
if (
flag_bits[0] # Encrypted
or flag_bits[4] # Enhanced deflate (Deflate64)
or flag_bits[5] # Compressed patched
or flag_bits[6] # Strong encrypted
or flag_bits[13] # Masked header values
):
raise ValueError('Unsupported flags {}'.format(flag_bits))
file_name = await get_num(file_name_len)
extra = await get_num(extra_field_len)
is_zip64 = compressed_size == zip64_compressed_size and uncompressed_size == zip64_compressed_size
if is_zip64:
uncompressed_size, compressed_size = Struct('<QQ').unpack(
get_extra_data(extra, zip64_size_signature))
has_data_descriptor = flags == b'\x08\x00'
if has_data_descriptor:
uncompressed_size = None
async def _decompress_deflate():
nonlocal crc_32_expected
dobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
crc_32_actual = zlib.crc32(b'')
all_iter = yield_all()
while not dobj.eof:
try:
# compressed_chunk = next(all_iter)
compressed_chunk = await all_iter.__anext__()
except StopAsyncIteration:
raise ValueError('Fewer bytes than expected in zip') from None
uncompressed_chunk = dobj.decompress(compressed_chunk, chunk_size)
if uncompressed_chunk:
crc_32_actual = zlib.crc32(uncompressed_chunk, crc_32_actual)
yield uncompressed_chunk
while dobj.unconsumed_tail and not dobj.eof:
uncompressed_chunk = dobj.decompress(dobj.unconsumed_tail, chunk_size)
if uncompressed_chunk:
crc_32_actual = zlib.crc32(uncompressed_chunk, crc_32_actual)
yield uncompressed_chunk
return_unused(dobj.unused_data)
if has_data_descriptor:
dd_optional_signature = await get_num(4)
dd_so_far_num = \
0 if dd_optional_signature == b'PK\x07\x08' else \
4
dd_so_far = dd_optional_signature[:dd_so_far_num]
dd_remaining = \
(20 - dd_so_far_num) if is_zip64 else \
(12 - dd_so_far_num)
dd = dd_so_far + await get_num(dd_remaining)
crc_32_expected, = Struct('<I').unpack(dd[:4])
if crc_32_actual != crc_32_expected:
raise ValueError('CRC-32 does not match')
async def _with_crc_32_check(chunks):
crc_32_actual = zlib.crc32(b'')
async for chunk in chunks:
crc_32_actual = zlib.crc32(chunk, crc_32_actual)
yield chunk
if crc_32_actual != crc_32_expected:
raise ValueError('CRC-32 does not match')
uncompressed_bytes = \
_with_crc_32_check(yield_num(compressed_size)) if compression == 0 else \
_decompress_deflate()
return file_name, uncompressed_size, uncompressed_bytes
while True:
signature = await get_num(len(local_file_header_signature))
if signature == local_file_header_signature:
yield await yield_file()
elif signature == central_directory_signature:
async for _ in yield_all():
pass
break
else:
raise ValueError(b'Unexpected signature ' + signature)
|
python
|
"""
Given two sequences ‘s1’ and ‘s2’, write a method to find the length
of the shortest sequence which has ‘s1’ and ‘s2’ as subsequences.
Example 2:
Input: s1: "abcf" s2:"bdcf"
Output: 5
Explanation: The shortest common super-sequence (SCS) is "abdcf".
Example 2:
Input: s1: "dynamic" s2:"programming"
Output: 15
Explanation: The SCS is "dynprogrammicng".
"""
# Time: O(n * m) Space: O(n * m)
def find_SCS_length(s1, s2):
n1, n2 = len(s1), len(s2)
dp = [[0 for _ in range(len(s2)+1)] for _ in range(len(s1)+1)]
# if one of the strings is of zero length, SCS would be equal to the length of the other string
for i in range(n1+1):
dp[i][0] = i
for j in range(n2+1):
dp[0][j] = j
for i in range(1, n1+1):
for j in range(1, n2+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])
return dp[n1][n2]
def main():
print(find_SCS_length("abcf", "bdcf"))
print(find_SCS_length("dynamic", "programming"))
main()
|
python
|
"""The yale_smart_alarm component."""
|
python
|
import numpy as np #import numpy library
#intergers
i=10
print(type(i)) #print out the data type 1
a_i = np.zeros(i,dtype=int) #declare an array of ints
print(type(a_i)) #will return ndarray
print(type(a_i[0])) #will return int64
#floats
x = 119.0 #floating point number
print(type(x)) #print out the data type of x
y = 199.0
print(type(y)) #float 199 in scie. notation
z = np.zero(i,dtype=float)
print(type(z))
print(type(z[0]))
|
python
|
"""Utilties for distributed processing"""
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
|
python
|
import os
import time
import pytest
from rhcephcompose.compose import Compose
from kobo.conf import PyConfigParser
import py.path
@pytest.fixture
def conf(fixtures_dir):
conf_file = os.path.join(fixtures_dir, 'basic.conf')
conf = PyConfigParser()
conf.load_from_file(conf_file)
return conf
class TestCompose(object):
def test_constructor(self, conf):
c = Compose(conf)
assert isinstance(c, Compose)
assert c.target == 'trees'
@pytest.mark.parametrize(('compose_type', 'suffix'), [
('production', ''),
('nightly', '.n'),
('test', '.t'),
('ci', '.ci'),
])
def test_output_dir(self, conf, tmpdir, monkeypatch, compose_type, suffix):
monkeypatch.chdir(tmpdir)
conf['compose_type'] = compose_type
c = Compose(conf)
compose_date = time.strftime('%Y%m%d')
expected = 'trees/RHCEPH-2.0-Ubuntu-x86_64-{0}{1}.0'.format(
compose_date, suffix)
assert c.output_dir == expected
@pytest.mark.parametrize(('release_version', 'expected'), [
('2', 'RHCEPH-2-Ubuntu-x86_64-latest'),
('2.0', 'RHCEPH-2-Ubuntu-x86_64-latest'),
('2.0.0', 'RHCEPH-2.0-Ubuntu-x86_64-latest'),
])
def test_latest_name(self, conf, release_version, expected):
conf['release_version'] = release_version
c = Compose(conf)
assert c.latest_name == expected
def test_symlink_latest(self, conf, tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
c = Compose(conf)
os.makedirs(c.output_dir)
c.symlink_latest()
result = os.path.realpath('trees/RHCEPH-2-Ubuntu-x86_64-latest')
assert result == os.path.realpath(c.output_dir)
def test_create_repo(self, conf, tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
c = Compose(conf)
# TODO: use real list of binaries here
c.create_repo(str(tmpdir), 'xenial', [])
distributions_path = tmpdir.join('conf/distributions')
assert distributions_path.check(file=True)
expected = '''\
Codename: xenial
Suite: stable
Components: main
Architectures: amd64 i386
Origin: Red Hat, Inc.
Description: Ceph distributed file system
DebIndices: Packages Release . .gz .bz2
DscIndices: Sources Release .gz .bz2
Contents: .gz .bz2
'''
assert distributions_path.read() == expected
class TestComposeValidate(object):
@pytest.fixture
def tmp_fixtures_dir(self, fixtures_dir, tmpdir):
""" Copy our fixture files to a tmpdir for modification. """
orig = py.path.local(fixtures_dir)
orig.copy(tmpdir)
return tmpdir
def test_ok(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
# validate() should not raise RuntimeError here.
c.validate()
def test_no_builds(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
c.builds = {}
with pytest.raises(RuntimeError):
c.validate()
def test_missing_builds_file(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
tmp_fixtures_dir.remove(c.builds['trusty'])
with pytest.raises(RuntimeError):
c.validate()
def test_missing_comps_file(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
tmp_fixtures_dir.remove(c.comps['trusty'])
with pytest.raises(RuntimeError):
c.validate()
def test_missing_variants_file(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
tmp_fixtures_dir.remove(c.variants_file)
with pytest.raises(RuntimeError):
c.validate()
def test_missing_extra_file(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
extra_file = os.path.join('extra_files', c.extra_files[0]['file'])
tmp_fixtures_dir.remove(extra_file)
with pytest.raises(RuntimeError):
c.validate()
def test_wrong_dist(self, tmp_fixtures_dir, conf, monkeypatch):
monkeypatch.chdir(tmp_fixtures_dir)
c = Compose(conf)
# Re-assign our "xenial" builds list so it will contain an (incorrect)
# build with "trusty" in the Name-Version-Release.
c.builds['xenial'] = c.builds['trusty']
with pytest.raises(RuntimeError):
c.validate()
class TestComposeReleaseVersion(object):
def test_product_version_fallback(self, conf, tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
del conf['release_version']
conf['product_version'] = '3'
c = Compose(conf)
assert c.release_version == '3'
class TestComposeReleaseShort(object):
@pytest.fixture
def newconf(self, conf):
conf['release_short'] = 'FOOPRODUCT'
return conf
def test_output_dir(self, newconf, tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
c = Compose(newconf)
compose_date = time.strftime('%Y%m%d')
expected = 'trees/FOOPRODUCT-2.0-Ubuntu-x86_64-%s.t.0' % compose_date
assert c.output_dir == expected
def test_symlink_latest(self, newconf, tmpdir, monkeypatch):
monkeypatch.chdir(tmpdir)
c = Compose(newconf)
os.makedirs(c.output_dir)
c.symlink_latest()
result = os.path.realpath('trees/FOOPRODUCT-2-Ubuntu-x86_64-latest')
assert result == os.path.realpath(c.output_dir)
|
python
|
# Copyright 2020 The TensorFlow Probability 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.
# ============================================================================
"""Utilities for writing distributed log prob functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import custom_gradient as tfp_custom_gradient
from tensorflow_probability.python.math import gradient as math_gradient
from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import
JAX_MODE = False
if JAX_MODE:
from jax import lax # pylint: disable=g-import-not-at-top
def canonicalize_axis_name(axis_name):
"""Converts an input into a list of axis strings."""
if not axis_name:
return []
if (isinstance(axis_name, str) or
not isinstance(axis_name, collections.Iterable)):
return [axis_name]
return list(axis_name)
def psum(x, axis_name=None):
if JAX_MODE:
axis_name = canonicalize_axis_name(axis_name)
for name in axis_name:
x = lax.psum(x, name)
return x
ctx = tf.distribute.get_replica_context()
return ctx.all_reduce('sum', x)
def pmean(x, axis_name=None):
if JAX_MODE:
axis_name = canonicalize_axis_name(axis_name)
for name in axis_name:
x = lax.pmean(x, name)
return x
ctx = tf.distribute.get_replica_context()
return ctx.all_reduce('mean', x)
def get_axis_index(axis_name=None):
if JAX_MODE:
return lax.axis_index(axis_name)
ctx = tf.distribute.get_replica_context()
return ctx.replica_id_in_sync_group
def get_axis_size(axis_name=None):
if JAX_MODE:
return lax.psum(1, axis_name)
ctx = tf.distribute.get_replica_context()
return ctx.num_replicas_in_sync
class _DummyGrads(object):
"""Wraps gradients to preserve structure when computing a custom gradient."""
def __init__(self, grads):
self.grads = grads
def tree_flatten(self):
return (self.grads,), ()
@classmethod
def tree_unflatten(cls, _, xs):
return cls(*xs)
def __repr__(self):
return f'_DummyGrads({self.grads})'
if JAX_MODE:
from jax import tree_util # pylint: disable=g-import-not-at-top
tree_util.register_pytree_node_class(_DummyGrads)
def make_psum_function(fn, in_axes, out_axes):
"""Constructs a function that psums over outputs and corrects input gradients.
Given a function `fn`, this `make_psum_function` returns a new one that
includes psums over terms according to axis names provided in `out_axes`. It
also adds psums for the vector-Jacobian product of the outputs of `fn` w.r.t.
its inputs according to `in_axes` if there are axes in the outputs that are
not present in an input.
Args:
fn: a callable to be transformed to have psums at its outputs and on the
gradients to its inputs.
in_axes: A structure of axis names that should match the structure of the
input to `fn`. If the set of input axes for an input value does not match
the output axes of a particular output value, the gradient of that output
value w.r.t. the input value will be psum-ed over the axes present in the
output but not the input.
out_axes: A structure of axis names that should match the structure of the
output of `fn`. The outputs of `fn` will be psum-med according to their
respective output axes.
Returns:
A new function that applies psums on to the output of the original
function and corrects the gradient with respect to its inputs.
"""
if not isinstance(in_axes, tuple):
in_axes = (in_axes,)
def _psum_fn_fwd(*args):
nest.assert_shallow_structure(args, in_axes)
out_parts = fn(*args)
nest.assert_shallow_structure(out_parts, out_axes)
map_out_axes = nest.map_structure_up_to(out_parts, canonicalize_axis_name,
out_axes)
total_out_parts = nest.map_structure_up_to(
out_parts,
lambda out_part, axis_name: ( # pylint: disable=g-long-lambda
psum(out_part, axis_name=axis_name) if axis_name else out_part),
out_parts,
map_out_axes)
return total_out_parts, (args, out_parts)
def _psum_fn_bwd(args_and_out_parts, gs):
args, out_parts = args_and_out_parts
map_in_axes = nest.map_structure_up_to(args, canonicalize_axis_name,
in_axes)
map_out_axes = nest.map_structure_up_to(out_parts, canonicalize_axis_name,
out_axes)
def flat_fn(flat_args):
unflat_args = tf.nest.pack_sequence_as(args, flat_args)
out_parts = fn(*unflat_args)
return tf.nest.flatten(out_parts)
# Operate with flattened lists, to make it easier to tease-out individual
# outputs for the local grads.
flat_value = tf.nest.flatten(args)
flat_gs = tf.nest.flatten(gs)
local_grads = [
math_gradient.value_and_gradient( # pylint: disable=g-complex-comprehension
lambda *val: flat_fn(val)[out_idx], # pylint: disable=cell-var-from-loop
flat_value,
output_gradients=out_g)[1] for out_idx, out_g in enumerate(flat_gs)
]
# Transpose.
local_grads = list(zip(*local_grads))
# Repack.
local_grads = tf.nest.pack_sequence_as(args, [
_DummyGrads(tf.nest.pack_sequence_as(out_parts, v)) for v in local_grads
])
def value_grad(v, in_axis_names, term_grads):
"""Computes reductions of output gradients.
A `log_prob_parts` function takes in a list of values and outputs
a log density for each input to the function. The vector-Jacobian
product (VJP) of a `log_prob_parts` function thus needs to compute the
gradient of each output term w.r.t. each input value. This function
overrides the default VJP of an output term `j` w.r.t to an input
value `i` to include an all-reduce-sum when:
1) The gradient of `j` w.r.t. `i` is connected.
2) `j` is a sharded term and `i` is an unsharded value.
If these conditions do not hold, the gradient remains the same and
either corresponds to:
1) The gradient of a sharded term w.r.t to a sharded value
2) The gradient of an unsharded term w.r.t. to an unsharded value.
3) The gradient of an unsharded term w.r.t. to an sharded value.
In any of these cases, no all-reduce-sum is necessary.
Args:
v: The output term of a `log_prob_part` function.
in_axis_names: A list of axis names indicating whether or not the output
term is sharded or not, `None` if no sharding.
term_grads: The gradient of the output term w.r.t. to each of the input
values to the `log_prob_part` function.
Returns:
The vector Jacobian product of `v` w.r.t. the input parts of the
`log_prob_parts` function.
"""
term_grads = term_grads.grads
def psum_grads(term_grad, out_axis_names):
if term_grad is not None:
psum_axes = [
axis_name for axis_name in out_axis_names
if axis_name not in in_axis_names
]
if psum_axes:
term_grad = psum(term_grad, axis_name=psum_axes)
return term_grad
total_grad = nest.map_structure_up_to(term_grads, psum_grads, term_grads,
map_out_axes)
if all([grad is None for grad in tf.nest.flatten(total_grad)]):
return None
return tf.add_n([
v for v in tf.nest.flatten(total_grad)
if tfp_custom_gradient.is_valid_gradient(v)
])
out = nest.map_structure_up_to(args, value_grad, args, map_in_axes,
local_grads)
return out
@tfp_custom_gradient.custom_gradient(
vjp_fwd=_psum_fn_fwd, vjp_bwd=_psum_fn_bwd)
def psum_fn(*args):
return _psum_fn_fwd(*args)[0]
return psum_fn
def make_sharded_log_prob_parts(log_prob_parts_fn, axis_names):
"""Constructs a log prob parts function that all-reduces over terms.
Given a log_prob_parts function, this function will return a new one that
includes all-reduce sums over terms according to the `is_sharded` property. It
will also add all-reduce sums for the gradient of sharded terms w.r.t.
unsharded terms.
Args:
log_prob_parts_fn: a callable that takes in a structured value and returns a
structure of log densities for each of the terms, that when summed returns
a locally correct log-density.
axis_names: a structure of values that matches the input and output of
`log_prob_parts_fn`. Each value in `axis_names` is either `None, a string
name of a mapped axis in the JAX backend or any non-`None` value in TF
backend, or an iterable thereof corresponding to multiple sharding axes.
If the `axis_name` is not `None`, the returned function will add
all-reduce sum(s) for its term in the log prob calculation. If it is
`None`, the returned function will have an all-reduce sum over the
gradient of sharded terms w.r.t. to the unsharded value.
Returns:
A new log prob parts function that can be run inside of a strategy.
"""
return make_psum_function(log_prob_parts_fn, (axis_names,), axis_names)
|
python
|
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
{
'includes': [
'../../../../../../common_settings.gypi', # Common settings
],
'targets': [
{
'target_name': 'G722',
'type': '<(library)',
'include_dirs': [
'../interface',
],
'direct_dependent_settings': {
'include_dirs': [
'../interface',
],
},
'sources': [
'../interface/g722_interface.h',
'g722_interface.c',
'g722_encode.c',
'g722_decode.c',
'g722_enc_dec.h',
],
},
{
'target_name': 'G722Test',
'type': 'executable',
'dependencies': [
'G722',
],
'sources': [
'../testG722/testG722.cpp',
],
'conditions': [
['OS=="linux"', {
'cflags': [
'-fexceptions', # enable exceptions
],
}],
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
|
python
|
'''
Created on Jul 13, 2018
@author: friedl
'''
import subprocess
import sys
def run_bwa_aln(genome_index, fastq_in_file, sai_out_file, bwa_path='bwa', threads=1, R_param=None):
''' calls bwa aln '''
# build bwa command
command = [bwa_path, 'aln', '-t', str(threads), '-f', sai_out_file]
if(R_param is not None):
command+=['-R', str(R_param)]
command+=[genome_index, fastq_in_file]
# execute bwa command
print('Running command:\n'+' '.join(command))
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
sys.stderr.write('Error in BWA call \n'+' '.join(command))
raise
|
python
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Given the taxonomy output from AlchemyAPI, for each level of taxonomies, extract the graph
so that the taxons in this level are connected based on
***Jaccardi score*** for the users sharing these taxons in their tweets
"""
import codecs
from collections import defaultdict, OrderedDict
import json
import re
import glob, os
import math
import itertools
f_in = "tweets_taxonomy_clean.JSON"
#f_in = "testme"
f_in_user_ids = "user_IDs.dat"
IN_DIR = "../../../DATA/taxonomy_stats"
#
# taxonomy has user names and we need ids
#
def read_user_IDs():
user_ids = defaultdict(str)
with codecs.open(f_in_user_ids,'r', encoding='utf8') as f:
for line in f:
line = line.split()
user_id = line[0]
user = line[1]
user_ids[user] = user_id
return user_ids
#
# go through taxonomy file and save the co-ccurence networks on
# different levels of taxonomy
#
def read_save_taxonomy_graph():
docSentiment_sum = defaultdict(int)
taxonomies_sum = [defaultdict(list)]*5
# One needs to be careful with this dedinition of dict
# the code works without those 5 lines below, but it
# creates a copies of the data in one dict, instead of 5 different ones
# as i would expect!!!
taxonomies_sum[0] = defaultdict(list)
taxonomies_sum[1] = defaultdict(list)
taxonomies_sum[2] = defaultdict(list)
taxonomies_sum[3] = defaultdict(list)
taxonomies_sum[4] = defaultdict(list)
user_ids = read_user_IDs()
cnt = 0
with codecs.open(f_in,'r', encoding='utf8') as input_file:
for line7s in input_file:
try:
line = json.loads(line7s)
user_name = line["_id"]
user_id = user_ids[user_name]
taxonomy_all = line["taxonomy"]
#keywords = taxonomy_all["keywords"]
#entities = taxonomy_all["entities"]
taxonomy = taxonomy_all["taxonomy"]
docSentiment = taxonomy_all["docSentiment"]
concepts = taxonomy_all["concepts"]
except KeyError:
#print line7s
continue
sentiment = docSentiment["type"]
if sentiment == "neutral":
docSentiment_sum[sentiment] += 1
else:
if not sentiment in docSentiment_sum:
docSentiment_sum[sentiment] = defaultdict(int)
old_score = docSentiment_sum[sentiment][0]
old_cnt = docSentiment_sum[sentiment][1]
old_mixed_cnt = docSentiment_sum[sentiment][2]
try:
new_score = old_score + float(docSentiment["score"])
except KeyError:
continue
new_cnt = old_cnt + 1
try:
new_mixed_cnt = old_mixed_cnt + int(docSentiment["mixed"])
except KeyError:
continue
docSentiment_sum[sentiment] = (new_score, new_cnt, new_mixed_cnt)
# just take taxonomy for which Alchemy is confident
for el in taxonomy:
try:
if el["confident"] == "no":
continue
except: KeyError
taxonomy_tree = el["label"]
taxonomy_tree = taxonomy_tree.split("/")
taxonomy_tree.pop(0)
levels = len(taxonomy_tree)
# go through the levels, from 0 until max 5
for i in range(levels):
tax_class = taxonomy_tree[i]
# if this is a new user for this taxon: append him
if user_id not in taxonomies_sum[i][tax_class]:
taxonomies_sum[i][tax_class].append(user_id)
cnt += 1
com_size = cnt
N = cnt
print cnt
print 'Total taxons on different levels found ', len(taxonomies_sum[0]), \
len(taxonomies_sum[1]),len(taxonomies_sum[2]), \
len(taxonomies_sum[3]), len(taxonomies_sum[4])
print "Total Sentiments found ", len(docSentiment_sum)
for i in range(5):
f_out_name = "graph/Jaccard/vth20_level_" + str(i) + ".tab"
# now we record the scores for each taxonomy edge for each of the levels i
with codecs.open(f_out_name,'w', encoding='utf8') as f:
# for an edge (el0, el1) we go through elements of the level twice
for el0 in taxonomies_sum[i]:
for el1 in taxonomies_sum[i]:
# and check that they are different, no self-loops
if el0 >= el1:
continue
# set of users for one taxon and for the other
set0 = set(taxonomies_sum[i][el0])
set1 = taxonomies_sum[i][el1]
# frequency of each element is equal
# the number of users who talked about it
# so the lenght of the array of users recorded
fel0 = len(set0)
fel1 = len(set1)
# formula for intersect
intersect = len(set0.intersection(set1))
# let us not record 0 weight edge == no co-occurence
if intersect < 20:
continue
# formula for union
union = len(set0.union(set1))
# formula for Jaccard score
Jaccard = intersect / float(union)
# write to the file all:
# taxon1, taxon2, frequency 1, frequency 2, interect, Jaccard score
f.write(str(el0) + "\t" + str(el1) + "\t" \
+ str(fel0) + "\t" + str(fel1) + "\t" \
+ str(intersect) + "\t" + str(Jaccard) + "\n ")
def main():
os.chdir(IN_DIR)
read_save_taxonomy_graph()
main()
|
python
|
# Copyright 2017 Neosapience, Inc.
#
# 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 unittest
import darkon
import tensorflow as tf
import numpy as np
from .tf_util import weight_variable, bias_variable
_num_train_data = 20
_dim_features = 5
_num_test_data = 3
_classes = 2
_batch_size = 4
_num_iterations = 5
def nn_graph():
# create graph
x = tf.placeholder(tf.float32, name='x_placeholder')
y = tf.placeholder(tf.int32, name='y_placeholder')
with tf.name_scope('fc1'):
W_fc1 = weight_variable([_dim_features, _classes], 'weight')
b_fc1 = bias_variable([_classes], 'bias')
op_fc1 = tf.add(tf.matmul(x, W_fc1), b_fc1)
# set loss function
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=op_fc1)
cross_entropy = tf.reduce_mean(cross_entropy)
return x, y, cross_entropy
class TestInfluence(unittest.TestCase):
def setUp(self):
# init tf default graph
tf.reset_default_graph()
# dataset feeder
class MyFeeder(darkon.InfluenceFeeder):
def __init__(self):
self.train_x = np.random.uniform(size=_num_train_data * _dim_features).reshape([_num_train_data, -1])
self.train_y = np.random.randint(_classes, size=_num_train_data).reshape([-1])
self.test_x = np.random.uniform(size=_num_test_data * _dim_features).reshape([_num_test_data, -1])
self.test_y = np.random.randint(_classes, size=_num_test_data).reshape([-1])
self.train_y = np.eye(_classes)[self.train_y]
self.test_y = np.eye(_classes)[self.test_y]
def reset(self):
np.random.seed(97)
def train_batch(self, batch_size):
idx = np.random.choice(_num_train_data - batch_size + 1, 1)[0]
return self.train_x[idx:idx+batch_size], self.train_y[idx:idx+batch_size]
def train_one(self, index):
return self.train_x[index], self.train_y[index]
def test_indices(self, indices):
return self.test_x[indices], self.test_y[indices]
x, y, cross_entropy = nn_graph()
# open session
self.sess = tf.InteractiveSession()
saver = tf.train.Saver()
saver.restore(self.sess, tf.train.latest_checkpoint('test/data'))
self.graph_origin = tf.get_default_graph().as_graph_def()
# initialize influence function
self.insp = darkon.Influence(workspace='./tmp',
feeder=MyFeeder(),
loss_op_train=cross_entropy,
loss_op_test=cross_entropy,
x_placeholder=x,
y_placeholder=y)
def tearDown(self):
self.sess.close()
# def test_freeze_graph(self):
# saver = tf.train.Saver()
# with tf.Session() as sess:
# # sess.run(tf.global_variables_initializer())
# saver.restore(sess, tf.train.latest_checkpoint('test/data-origin'))
# saver.save(sess, 'test/data/model', global_step=0)
def test_influence(self):
test_indices = [0]
approx_params = {'scale': 10,
'num_repeats': 3,
'recursion_depth': 2,
'recursion_batch_size': _batch_size}
# get influence scores for all trainset
result = self.insp.upweighting_influence_batch(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_batch_size=_batch_size,
train_iterations=_num_iterations,
force_refresh=True)
# get influence scores for all trainset
result2 = self.insp.upweighting_influence_batch(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_batch_size=_batch_size,
train_iterations=_num_iterations,
force_refresh=False)
self.assertEqual(_batch_size * _num_iterations, len(result2))
self.assertTrue(np.all(result == result2))
selected_trainset = [2, 3, 0, 9, 14, 19, 8]
result_partial = self.insp.upweighting_influence(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_indices=selected_trainset,
num_total_train_example=_num_train_data,
force_refresh=False)
self.assertEqual(7, len(result_partial))
def test_influence_sampling(self):
test_indices = [0]
approx_batch_size = _batch_size
approx_params = {'scale': 10,
'num_repeats': 3,
'recursion_depth': 2,
'recursion_batch_size': approx_batch_size}
result = self.insp.upweighting_influence_batch(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_batch_size=_batch_size,
train_iterations=_num_iterations,
force_refresh=False)
self.assertEqual(_batch_size * _num_iterations, len(result))
num_batch_sampling = 2
result2 = self.insp.upweighting_influence_batch(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_batch_size=_batch_size,
train_iterations=_num_iterations,
subsamples=num_batch_sampling,
force_refresh=False)
self.assertEqual(num_batch_sampling * _num_iterations, len(result2))
result = result.reshape(_num_iterations, _batch_size)
result2 = result2.reshape(_num_iterations, num_batch_sampling)
result = result[:, :num_batch_sampling]
self.assertTrue(np.all(result == result2))
def test_unknown_approx_key(self):
test_indices = [0]
approx_params = {'unknown_param': 1}
self.assertRaises(RuntimeError,
self.insp.upweighting_influence_batch,
self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_batch_size=_batch_size,
train_iterations=_num_iterations)
def test_default_approx_params(self):
test_indices = [0]
r = self.insp.upweighting_influence_batch(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=None,
train_batch_size=_batch_size,
train_iterations=_num_iterations)
r2 = self.insp.upweighting_influence_batch(self.sess,
test_indices,
_batch_size,
None,
_batch_size,
_num_iterations)
self.assertTrue(np.all(r == r2))
def test_approx_filename(self):
test_indices = [0]
approx_params = {'scale': 10,
'num_repeats': 3,
'recursion_depth': 2,
'recursion_batch_size': _batch_size}
inv_hvp_filename = 'ihvp.c089c98599898bfb0e7f920c9dfe533af38b5481.npz'
self.insp.ihvp_config.update(approx_params)
self.assertEqual(inv_hvp_filename, self.insp._approx_filename(self.sess, test_indices))
test_indices = [1]
self.assertNotEqual(inv_hvp_filename, self.insp._approx_filename(self.sess, test_indices))
test_indices = [0]
self.insp.ihvp_config.update(scale=1)
self.assertNotEqual(inv_hvp_filename, self.insp._approx_filename(self.sess, test_indices))
def test_approx_filename_for_weight(self):
test_indices = [0]
filename_1 = self.insp._approx_filename(self.sess, test_indices)
filename_2 = self.insp._approx_filename(self.sess, test_indices)
self.assertEqual(filename_1, filename_2)
self.sess.run(tf.global_variables_initializer())
filename_3 = self.insp._approx_filename(self.sess, test_indices)
self.assertNotEqual(filename_1, filename_3)
def test_graph_dangling(self):
test_indices = [0]
approx_params = {'scale': 10,
'num_repeats': 3,
'recursion_depth': 2,
'recursion_batch_size': _batch_size}
graph_influence_init = tf.get_default_graph().as_graph_def()
self.assertNotEqual(self.graph_origin, graph_influence_init)
self.insp.upweighting_influence(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_indices=[0],
num_total_train_example=_num_train_data,
force_refresh=True)
graph_first_executed = tf.get_default_graph().as_graph_def()
self.assertEqual(graph_influence_init, graph_first_executed)
self.insp.upweighting_influence(self.sess,
test_indices=test_indices,
test_batch_size=_batch_size,
approx_params=approx_params,
train_indices=[0],
num_total_train_example=_num_train_data,
force_refresh=True)
graph_second_executed = tf.get_default_graph().as_graph_def()
self.assertEqual(graph_first_executed, graph_second_executed)
|
python
|
# problems init file
from tigerforecast.problems.core import Problem
from tigerforecast.problems.sp500 import SP500
from tigerforecast.problems.uci_indoor import UCI_Indoor
from tigerforecast.problems.enso import ENSO
from tigerforecast.problems.crypto import Crypto
from tigerforecast.problems.random import Random
from tigerforecast.problems.arma import ARMA
from tigerforecast.problems.unemployment import Unemployment
from tigerforecast.problems.lds_time_series import LDS_TimeSeries
from tigerforecast.problems.rnn_time_series import RNN_TimeSeries
from tigerforecast.problems.lstm_time_series import LSTM_TimeSeries
from tigerforecast.problems.my_problem import MyProblem
# registration tools
from tigerforecast.problems.registration import problem_registry, problem_register, problem
from tigerforecast.problems.custom import register_custom_problem, CustomProblem
# ---------- Time-series ----------
problem_register(
id='Random-v0',
entry_point='tigerforecast.problems:Random',
)
problem_register(
id='MyProblem-v0',
entry_point='tigerforecast.problems:MyProblem',
)
problem_register(
id='ARMA-v0',
entry_point='tigerforecast.problems:ARMA',
)
problem_register(
id='SP500-v0',
entry_point='tigerforecast.problems:SP500',
)
problem_register(
id='UCI-Indoor-v0',
entry_point='tigerforecast.problems:UCI_Indoor',
)
problem_register(
id='Crypto-v0',
entry_point='tigerforecast.problems:Crypto',
)
problem_register(
id='Unemployment-v0',
entry_point='tigerforecast.problems:Unemployment',
)
problem_register(
id='ENSO-v0',
entry_point='tigerforecast.problems:ENSO',
)
problem_register(
id='LDS-TimeSeries-v0',
entry_point='tigerforecast.problems:LDS_TimeSeries',
)
problem_register(
id='RNN-TimeSeries-v0',
entry_point='tigerforecast.problems:RNN_TimeSeries',
)
problem_register(
id='LSTM-TimeSeries-v0',
entry_point='tigerforecast.problems:LSTM_TimeSeries',
)
|
python
|
import sys
sys.path.append('..')
import torch.nn as nn
import torch
class ConvBlock(nn.Module):
"""Layer to perform a convolution followed by LeakyReLU
"""
def __init__(self, in_channels, out_channels):
super(ConvBlock, self).__init__()
self.conv = Conv3x3(in_channels, out_channels)
self.nonlin = nn.LeakyReLU(inplace=True)
def forward(self, x):
out = self.conv(x)
out = self.nonlin(out)
return out
class Conv3x3(nn.Module):
"""Layer to pad and convolve input
"""
def __init__(self, in_channels, out_channels, use_refl=True):
super(Conv3x3, self).__init__()
if use_refl:
self.pad = nn.ReflectionPad2d(1)
else:
self.pad = nn.ZeroPad2d(1)
self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)
def forward(self, x):
out = self.pad(x)
out = self.conv(out)
return out
class dispHead(nn.Module):
def __init__(self):
super(dispHead, self).__init__()
outD = 1
self.covd1 = torch.nn.Sequential(nn.ReflectionPad2d(1),
torch.nn.Conv2d(in_channels=192, out_channels=256, kernel_size=3, stride=1,
padding=0, bias=True),
torch.nn.LeakyReLU(inplace=True)).cuda()
self.covd2 = torch.nn.Sequential(nn.ReflectionPad2d(1),
torch.nn.Conv2d(in_channels=256, out_channels=outD, kernel_size=3, stride=1,
padding=0, bias=True)).cuda()
def forward(self, x):
return self.covd2(self.covd1(x))
class BasicMotionEncoder(nn.Module):
def __init__(self):
super(BasicMotionEncoder, self).__init__()
# inD = 1
self.convc1 = ConvBlock(128, 160)
self.convc2 = ConvBlock(160, 128)
self.convf1 = torch.nn.Sequential(
nn.ReflectionPad2d(3),
torch.nn.Conv2d(in_channels=1, out_channels=64, kernel_size=7, padding=0, bias=True),
torch.nn.LeakyReLU(inplace=True))
self.convf2 = torch.nn.Sequential(
nn.ReflectionPad2d(1),
torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, padding=0, bias=True),
torch.nn.LeakyReLU(inplace=True))
self.conv = ConvBlock(128 + 32, 192 - 1)
def forward(self, depth, corr):
cor = self.convc1(corr)
cor = self.convc2(cor)
dep = self.convf1(depth)
dep = self.convf2(dep)
cor_depth = torch.cat([cor, dep], dim=1)
out = self.conv(cor_depth)
return torch.cat([out, depth], dim=1)
class BasicUpdateBlock(nn.Module):
def __init__(self):
super(BasicUpdateBlock, self).__init__()
self.encoder = BasicMotionEncoder()
self.flow_head = dispHead()
self.mask = nn.Sequential(
nn.ReflectionPad2d(1),
nn.Conv2d(192, 324, 3),
nn.LeakyReLU(inplace=True),
nn.Conv2d(324, 64 * 9, 1, padding=0))
def forward(self, net, corr, depth):
net = self.encoder(depth, corr)
delta_depth = self.flow_head(net)
# scale mask to balence gradients
mask = .25 * self.mask(net)
return net, mask, delta_depth
|
python
|
import os
import pickle
import socket
import threading
import time
from cryptography.fernet import Fernet
from scripts import encryption
from scripts.consts import MessageTypes
# IP = socket.gethostbyname(socket.gethostname())
IP = 'localhost'
PORT = 8004
class Server:
def __init__(self):
self.active_connections = {}
self.build_socket()
def build_socket(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((IP, PORT))
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.listen(5)
def broadcast(self, msg, address_key=None):
for key, client in self.active_connections.items():
if not address_key or key != address_key:
encrypted_msg = self.encode_message(client['cipher'], msg)
msg_type = MessageTypes.MESSAGE if address_key else MessageTypes.SERVER_CLOSED
self.send_to_client(client['client'], MessageTypes.MESSAGE, payload=encrypted_msg)
def get_clients(self):
(client, address) = self.server.accept()
address_key = str(address[0]) + str(address[1])
self.active_connections[address_key] = {
'client': client,
'username': None,
'sym_key': None,
'cipher': None,
'logged_in': False,
}
client_thread = threading.Thread(
target=self.get_client_messages,
args=((client, address_key))
)
client_thread.daemon = True
client_thread.start()
def get_client_messages(self, client, address_key):
self.send_to_client(client, MessageTypes.PUBLIC_KEY)
while True:
data = client.recv(1024)
if not data:
username = self.active_connections[address_key]['username']
username = username if username else 'User'
self.broadcast(
f'[SERVER]: {username} has left the room.',
address_key=address_key
)
del self.active_connections[address_key]
client.close()
break
else:
self.handle_data(address_key, pickle.loads(data))
def handle_data(self, address_key, data):
client_info = self.active_connections[address_key]
if data['type'] == MessageTypes.PUBLIC_KEY:
public_key, pub_key_hash = data['payload']
key_info = self.generate_sym_key(address_key, public_key, pub_key_hash)
client_info['sym_key'] = key_info[0]
client_info['cipher'] = Fernet(key_info[0])
self.send_sym_key(client_info['client'], key_info)
elif data['type'] == MessageTypes.SYM_KEY:
if data['payload']:
self.send_to_client(client_info['client'], MessageTypes.USERNAME)
else:
print('KEY REJECTED')
elif data['type'] == MessageTypes.USERNAME:
client_info['username'] = data['payload']
client_info['logged_in'] = True
self.broadcast(
f'[SERVER]: {client_info["username"]} has joined the room.',
address_key=address_key
)
self.send_to_client(client_info['client'], MessageTypes.CONNECTED)
elif data['type'] == MessageTypes.MESSAGE:
msg = self.decode_message(client_info, data['payload'])
self.broadcast(
f'[{client_info["username"]}]: {msg}',
address_key=address_key
)
def generate_sym_key(self, address_key, public_key, pub_key_hash):
hash_matches = encryption.check_key_hash(pickle.dumps(public_key), pub_key_hash)
if hash_matches:
key_info = encryption.generate_symmetric_keys(public_key)
return key_info
def send_sym_key(self, client, key_info):
self.send_to_client(
client,
MessageTypes.SYM_KEY,
payload=key_info[1:]
)
def send_to_client(self, client, msg_type, payload=None, **kwargs):
client.send(pickle.dumps({
'type': msg_type,
'payload': payload,
**kwargs
}))
def encode_message(self, cipher, message):
msg = cipher.encrypt(pickle.dumps(message))
return msg
def decode_message(self, client_info, message):
cipher = client_info['cipher']
msg = pickle.loads(cipher.decrypt(message))
return msg
def run(self):
print(f'Server running on {IP}:{PORT}')
try:
while True:
self.get_clients()
except KeyboardInterrupt:
self.broadcast('Server closed')
print('Closing Server')
while len(self.active_connections) > 0:
print(len(self.active_connections) > 0)
time.sleep(0.1)
finally:
self.server.close()
if __name__ == '__main__':
server = Server()
server.run()
|
python
|
#!/usr/bin/env python
import pytest
import os
import sys
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from pathlib import Path
from dselib.thread import initTLS
initTLS()
from dselib.context import DSEContext
from dselib.defaults import Defaults
from dselib.dir import GetHomeDirectory
from dselib.path import normalizePath
def context(varfile=None):
"""returns the DSE context object for this script."""
try:
myself = __file__
except NameError:
myself = sys.argv[0]
return DSEContext(myself, varfile)
me = context('test_config')
def test_1():
logger.info("Validating Defaults() instance defaults ...")
defaults = Defaults(logger)
assert defaults.ID_KEY == 'CDefaults'
assert defaults.VERSION == "1.0"
assert defaults.PLATFORM == 'platform'
assert defaults.SECTION == 'section'
assert defaults.DEFAULT == 'default'
assert defaults.EXPANDU == 'expanduser'
assert defaults.EXPANDV == 'expandvars'
assert defaults.GETDICT == 'asdict'
assert defaults.VALUE == 'value'
assert defaults.NORMALIZE == 'normalize'
assert defaults.DESCRIPTION == 'description'
assert defaults.FILENAME == 'defaults.def'
assert isinstance(defaults.filename, Path)
assert defaults.filename == Path(defaults.FILENAME)
assert defaults.logger == logger
def _reset_config(d):
logger.info("Testing reset() method ...")
assert d.reset() == d
assert len(d) == 1
assert d.dictionary().get(d.ID_KEY) == d.VERSION
def _load_config_all_types(d):
logger.info("Loading config with all data types ...")
d.add('int', 42)
d.add('float', 42.0)
d.add('str', '42')
d.add('list', [42,42.0])
d.add('tuple', (42,42.0))
d.add('dict', {'a':2})
d.add('complex', {'a':2, 'b': [0,1,2], 'c': {'z': 'zed', 'y': 42}})
d.add('platform', '42', nt='24', default='42.0')
assert d.get('int') == 42
assert d.get('float') == 42.0
assert d.get('str') == '42'
assert d.get('list') == [42,42.0]
assert d.get('tuple') == (42,42.0)
assert d.get('dict') == {'a':2}
assert d.get('complex').get('a') == 2
assert d.get('complex').get('b') == [0,1,2]
assert d.get('complex').get('c').get('z') == 'zed'
assert d.get('complex').get('c').get('y') == 42
assert d.get('platform') == '42.0' if os.name == 'posix' else '24'
assert d.get('platform', platform='nt') == '24'
def _test_add_update(d):
logger.info("Testing add/update methods ...")
# add existing key, then update existing key
d.add('int', 38)
assert d.get('int') == 38
d.update('int',17)
assert d.get('int') == 17
# add new key by using update, delete, then try to get it
d.update('int2',7)
assert d.get('int2') == 7
d.delete('int2')
with pytest.raises(ValueError):
d.get('int2')
# test adding a platform variable and then forcing the error conditions
# test the platform we aren't running on so we can check the default value logic too
varname = 'pdeltest'
defvalu = 'defaultValue'
plat2test = 'nt' if os.name == 'posix' else 'posix'
platvalue = {'nt': 'ntval', 'posix': 'posixval'}
d.add(varname, defvalu, nt='ntval', posix='posixval')
assert d.get(varname, platform=plat2test) == platvalue[plat2test]
d.delete(varname, platform=plat2test)
# now we should get the default value
assert d.get(varname, platform=plat2test) == defvalu
# we deleted the nt platform, can't delete it again
with pytest.raises(ValueError):
d.delete(varname, platform=plat2test)
# make sure my platform still has a value
assert d.get(varname) == platvalue[os.name]
# now delete my platform value and get the default
d.delete(varname, platform=os.name)
assert d.get(varname) == defvalu
# now delete the default value and get the default
d.delete(varname, platform='default')
with pytest.raises(ValueError):
d.get(varname)
# Try to remove the platform attribute
with pytest.raises(ValueError):
d.delete(varname, platform='platform')
# again, but in a section variable
# test adding a platform variable and then forcing the error conditions
# add section
sectname = 'psectiontest'
varname = 'pdeltest'
d.addSection(sectname)
# add section implicitly by adding section variable
d.addSectionVariable(sectname, varname, defvalu, nt=platvalue['nt'], posix=platvalue['posix'])
# delete the platform value we are testing
assert d.get(varname, section=sectname, platform=plat2test) == platvalue[plat2test]
d.delete(varname, section=sectname, platform=plat2test)
# we deleted the platform variant, now we should get the default value
assert d.get(varname, section=sectname, platform=plat2test) == defvalu
# we deleted the nt platform, can't delete it again
with pytest.raises(ValueError):
d.delete(varname, platform=plat2test)
# remove the default
d.delete(varname, section=sectname, platform='default')
# now there is no default and no platform variant
with pytest.raises(ValueError):
d.get(varname, section=sectname, platform=plat2test)
# we deleted the nt platform, can't get it no more
with pytest.raises(ValueError):
assert d.get(varname, section=sectname, platform=plat2test) != platvalue[plat2test]
# you cannot delete the platform attribute
with pytest.raises(ValueError):
d.delete(varname, section=sectname, platform='platform')
# delete default then platform
def _test_expansion(d):
logger.info("Testing expansion logic ...")
# add key starting with ~, then check expansion
d.add('homedir', '~', normalize=True)
assert Path(d.get('homedir')) == GetHomeDirectory()
assert d.get('homedir', expanduser=False) == '~'
d.update('homedir', '/~')
assert Path(d.get('homedir')) == normalizePath('/~')
# add key starting with %, then check expansion
expandvar = 'expandvar'
d.add(expandvar, '%')
assert d.get(expandvar) == '%'
testvar = 'TestVar'
testval = 'my.test.value'
os.environ[testvar] = testval
# test '%testvar'
expandvarval = f'%{testvar}'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == expandvarval
# test '%testvar%'
expandvarval = f'%{testvar}%'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == testval
# test at start '%testvar%-start'
expandvarval = f'%{testvar}%-start'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == f'{testval}-start'
# test at end 'ending-%testvar%'
expandvarval = f'ending-%{testvar}%'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == f'ending-{testval}'
# test in middle 'middle-%testvar%-middle'
expandvarval = f'middle-%{testvar}%-middle'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == f'middle-{testval}-middle'
# test with '$testvar'
expandvarval = f'${testvar}'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == testval
# test with '${testvar}'
expandvarval = '${' + testvar + '}'
d.update(expandvar, expandvarval)
assert d.get(expandvar) == testval
# test with '~/${testvar}/%testvar%'
expandvarval = '~/${' + testvar + '}/' + f'%{testvar}%'
d.update(expandvar, expandvarval, normalize=True)
assert Path(d.get(expandvar)) == (normalizePath(GetHomeDirectory() / testval / testval))
def test_2(tmpdir):
logger.info("Validating Defaults() instance defaults ...")
defaults = Defaults(logger)
tempConfig = Path(tmpdir) / 'cfgfile.json'
logger.info(f"tempConfig={tempConfig}")
defaults.filename = tempConfig
assert defaults.filename == tempConfig
assert defaults.save() == defaults
assert defaults.saveReturnCode == 0
assert defaults.filename.is_file() == True
_reset_config(defaults)
_load_config_all_types(defaults)
_test_add_update(defaults)
_test_expansion(defaults)
def _test_platform(d, validate=True):
logger.info("Testing platform defaults ...")
d.add('SHELL', darwin='zsh', nt='cmd.exe', posix='bash', linux='bash')
if validate:
with pytest.raises(ValueError):
d.get('SHELL', platform='win32')
with pytest.raises(ValueError):
d.get('SHELL', platform='invalid')
if os.name == 'posix':
assert d.get('SHELL') == d.get('SHELL', platform=sys.platform)
else:
assert d.get('SHELL') == 'cmd.exe'
assert d.get('SHELL', platform='nt') == 'cmd.exe'
assert d.get('SHELL', platform='darwin') == 'zsh'
assert d.get('SHELL', platform='posix') == 'bash'
assert d.get('SHELL', platform='linux') == 'bash'
varname = 'PlatformDefault'
d.update(varname,
normalize=True,
default='~/utils/twotemp',
nt='~\\Windows\\twotemp',
posix='~/posix/twotemp',
darwin='~/macos/twotemp')
if validate:
# there isn't a win32, so on os.name == 'nt', if sys.platform=='win32' should return nt
if os.name == 'nt' and sys.platform == 'win32':
assert d.get(varname) == d.get(varname, platform='nt')
# on Windows, it should return the path lowercased
assert d.get(varname, platform='nt') == os.path.normcase(f'{GetHomeDirectory()}\\windows\\twotemp')
else:
assert d.get(varname) == d.get(varname, platform=sys.platform)
# on posix, since os.sep != path[1:1], it will return value unchanged
assert d.get(varname, platform='nt') == '~\\Windows\\twotemp'
assert Path(d.get(varname, platform='win32')) == normalizePath(f'{GetHomeDirectory()}/utils/twotemp')
assert Path(d.get(varname, platform='posix')) == normalizePath(f'{GetHomeDirectory()}/posix/twotemp')
assert Path(d.get(varname, platform='darwin')) == normalizePath(f'{GetHomeDirectory()}/macos/twotemp')
# add tests to make sure the keys we think are there exist and
# that no keys we don't expect are not there
def _test_section(d, validate=True):
logger.info("Testing section defaults ...")
# add section
d.addSection('lonelySection')
if validate:
# add existing section
with pytest.raises(KeyError):
d.addSection('lonelySection')
# add section implicitly by adding section variable
d.addSectionVariable('section42', 'my-path', '~/utils/twotemp')
if validate:
# these will probably need a class, because they are going to be different on Windows due to normuser/normcase
assert d.get('my-path', section='section42') == f'{GetHomeDirectory(normalize=False)}/utils/twotemp'
# add section implicitly by adding section variable
d.updateSectionVariable('section42', 'my-path', '~/Utils/twoTemp', normalize=True)
if validate:
# these will probably need a class, because they are going to be different on Windows due to normuser/normcase
assert Path(d.get('my-path', section='section42')) == normalizePath(f'{GetHomeDirectory()}/Utils/twoTemp')
# add section with description
section = 'section24'
descrip = 'This is section 24'
d.addSection(section, description=descrip)
d.addSectionVariable(section, 'SHR_NAME', '/net/name/fubar')
if validate:
sectdict = d.get(section)
assert sectdict[d.SECTION] == True
assert sectdict[d.DESCRIPTION] == descrip
def _test_section_platform(d, validate=True):
logger.info("Testing section platform defaults ...")
section = 'section42'
varname = 'my-plat'
# try to trick it into thinking it's not a platform var
d.addSectionVariable(section,
varname,
'cool-plat',
nt='boring',
posix='exciting',
default='None',
platform=False)
if validate:
sectdict = d.get(section)
assert sectdict[d.SECTION] == True
vardict = d.get(varname, section=section, asdict=True)
assert vardict[d.PLATFORM] == True
assert d.get(varname, section=section, platform='nt') == 'boring'
assert d.get(varname, section=section, platform='posix') == 'exciting'
assert d.get(varname, section=section, platform='default') == 'None'
assert d.get(varname, section=section, platform='win32') == 'None'
varname = 'my-plat-true'
# add a default value but then override it
d.addSectionVariable(section,
varname,
'cool-plat',
nt='boring',
posix='exciting',
default='None')
if validate:
vardict = d.get(varname, section=section, asdict=True)
assert vardict[d.PLATFORM] == True
assert d.get(varname, section=section, platform='nt') == 'boring'
assert d.get(varname, section=section, platform='posix') == 'exciting'
assert d.get(varname, section=section, platform='default') == 'None'
assert d.get(varname, section=section, platform='win32') == 'None'
varname = 'my-plat-with-default'
# add a default value (using update) but don't override it
d.updateSectionVariable(section,
varname,
'cool-plat',
nt='boring',
posix='exciting')
if validate:
vardict = d.get(varname, section=section, asdict=True)
assert vardict[d.PLATFORM] == True
assert d.get(varname, section=section, platform='nt') == 'boring'
assert d.get(varname, section=section, platform='posix') == 'exciting'
assert d.get(varname, section=section, platform='default') == 'cool-plat'
assert d.get(varname, section=section, platform='win32') == 'cool-plat'
def test_3(tmpdir):
logger.info("Validating Defaults() platform, section and section platform defaults ...")
defaults = Defaults(logger)
tempConfig = Path(tmpdir) / 'cfgfile.json'
logger.info(f"tempConfig={tempConfig}")
defaults.filename = tempConfig
assert defaults.filename == tempConfig
assert defaults.save() == defaults
assert defaults.saveReturnCode == 0
assert defaults.filename.is_file() == True
_test_platform(defaults)
_test_section(defaults)
_test_section_platform(defaults)
defaults.save()
def _validate_config_files(defaults, d2, order):
logger.info( f"Validating {order[0]} keys in {order[1]}")
for key in defaults:
varvalue = defaults.get(key)
if isinstance(varvalue, dict):
logger.info(f"Validating {key=} is a section key ...")
assert defaults.SECTION in varvalue and varvalue[defaults.SECTION]
else:
logger.info(f"Validating {key=}={defaults.get(key)=}")
assert key in d2
assert defaults.get(key) == d2.get(key)
logger.info(f"------ validating platform keys in root ------")
for platformKey in defaults.platformDefaults():
logger.info(f"\t{platformKey=}")
vardict = defaults.get(platformKey, asdict=True)
# make sure this is a platform key and it is set to true
assert defaults.PLATFORM in vardict and vardict[defaults.PLATFORM]
assert defaults.get(platformKey) == d2.get(platformKey)
logger.info(f"------ dump of platform keys in defaults.platformDefaults(section='foo') ------")
for fooPlatKey in defaults.platformDefaults(section="foo"):
# This section should not exist, so if we get keys it's broken
assert False
section = 'section42'
logger.info(f"------ dump of keys in defaults.platformDefaults(section={section}) ------")
for s42PlatKey in defaults.platformDefaults(section):
logger.info(f"\tProcessing [{section}]{s42PlatKey=}")
vardict = defaults.get(s42PlatKey, section=section, asdict=True)
# make sure this is a platform key and it is set to true
assert defaults.PLATFORM in vardict and vardict[defaults.PLATFORM]
assert defaults.get(s42PlatKey, section=section) == d2.get(s42PlatKey, section=section)
logger.info(f"------ validating sections ------")
for section in defaults.sections():
logger.info(f"\tProcessing {section} ...")
sectdict = defaults.get(section)
assert isinstance(sectdict, dict)
assert defaults.SECTION in sectdict and sectdict[defaults.SECTION]
assert section in d2.sections()
logger.info(f"\tChecking keys in {section}")
for key in defaults.sectionKeys(section=section):
logger.info(f"\t\tValidating key {key} ...")
assert defaults.get(key, section=section) == d2.get(key, section=section)
def test_4(tmpdir):
logger.info("Validating Defaults() save then load ...")
defaults = Defaults(logger)
tempConfig = Path(tmpdir) / 'cfgfile.json'
logger.info(f"tempConfig={tempConfig}")
defaults.filename = tempConfig
assert defaults.filename == tempConfig
assert defaults.save() == defaults
assert defaults.saveReturnCode == 0
assert defaults.filename.is_file() == True
d2 = Defaults(logger).load(defaults.filename)
_validate_config_files(defaults, d2, ('default', 'd2'))
_validate_config_files(d2, defaults, ('d2', 'default'))
_test_platform(defaults)
_test_section(defaults)
_test_section_platform(defaults)
defaults.save()
d2.load(d2.filename)
_validate_config_files(defaults, d2, ('default', 'd2'))
_validate_config_files(d2, defaults, ('d2', 'default'))
def _loadsectiontoenv():
logger.info("Validating Defaults().loadSectionToEnv()")
d = Defaults(logger)
varname = 'env_simple_var'
varvalue = 'env_simple_value'
varvalue2 = 'env_simple_value_override'
assert varname not in os.environ
d.add(varname, varvalue)
assert d.get(varname) == varvalue
logger.info(f"\tPutting {varname} into os.environ with value {varvalue}")
# load config to environ, check return value and value of key in env
assert d.loadSectionToEnv(None) == True
assert os.environ.get(varname) == varvalue
logger.info(f"\tSetting {varname}={varvalue2} in os.environ and reload env")
# change env key value and try to load again. env value should stick
os.environ[varname] = varvalue2
assert d.loadSectionToEnv(None) == True
assert os.environ[varname] == varvalue2
logger.info(f"\tForce load into environment and check {varname}={varvalue}")
# force load. dict value should be overwritten
assert d.loadSectionToEnv(None, force=True) == True
assert os.environ[varname] == varvalue
def test_5():
logger.info("Validating loadSectionToEnv, loadSectionToDict, loadDefaultsToDict APIs")
d = Defaults(logger)
varname = 'simple'
varvalue = True
d.add(varname, varvalue)
assert d.get(varname) == varvalue
logger.info("Validating Defaults().loadDefaultsToDict()")
# make sure passing in invalid type raises correct exception
with pytest.raises(TypeError):
d.loadDefaultsToDict([])
# load config to dict, check return value and value of key in dict
mydict = {}
assert d.loadDefaultsToDict(mydict) == True
assert mydict.get(varname) == varvalue
# change dict key value and try to load again. dict value should stick
mydict[varname] = False
assert d.loadDefaultsToDict(mydict) == True
assert mydict[varname] == False
# change dict key value and force load. dict value should be overwritten
assert d.loadDefaultsToDict(mydict, force=True) == True
assert mydict[varname] == varvalue
# now load a bunch of keys into the config
_test_platform(d, validate=False)
_test_section(d, validate=False)
_test_section_platform(d, validate=False)
# now load them to our dictionary and check it
mydict = {}
assert d.loadDefaultsToDict(mydict) == True
for key in mydict:
logger.info(f"\tChecking {key=} in config")
if not isinstance(mydict[key], dict):
assert mydict[key] == d.get(key)
else:
for sectionKey in mydict[key]:
logger.info(f"\t\tChecking mydict[{key}][{sectionKey}] in config")
assert mydict[key][sectionKey] == d.get(sectionKey, section=key)
logger.info("Validating Defaults().loadSectionToDict()")
for section in d.sections():
logger.info(f"\tLoading section {section}")
mydict = {}
assert d.loadSectionToDict(mydict, section) == True
for key in mydict:
if not isinstance(mydict[key], dict):
logger.info(f"\t\tChecking {mydict[key]} in config")
assert mydict[key] == d.get(key, section=section)
else:
logger.info(f"\t\tChecking mydict[{key}] as dict in config")
for sectionKey in mydict[key]:
logger.info(f"\t\t\tChecking mydict[{key}][{sectionKey}] in config")
logger.info(f"\t\t\t{mydict[key][sectionKey]=}")
assert mydict[key][sectionKey] == d.get(sectionKey, section=key)
_loadsectiontoenv()
def _dump():
d = Defaults(logger).load(me.defname())
logger.info(f"Dumping the entire dictionary")
d.dump()
logger.info(f"Dumping the sections in the defaults dictionary")
for s in d.sections():
d.dumpSection(s, '.*')
def _dumpSection(regex):
logger.info(f"Dumping sections that match '{regex}'")
d = Defaults(logger).load(me.defname())
try:
d.dumpSection(regex, '.*')
except Exception as err:
logger.error(f"{err}")
if __name__ == '__main__':
pytest.main(['-k', 'test_defaults.py'])
|
python
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 20:06:01 2015
@author: Thomas
"""
# Python standard library imports
import csv
import os
def main():
costs = []
for file in os.listdir("reformatted/"):
print 'getting data from.. ' + file
cost_total = []
cost_2000 = []
cost_2001 = []
cost_2002 = []
cost_2003 = []
cost_2004 = []
cost_2005 = []
cost_2006 = []
cost_2007 = []
cost_2008 = []
cost_2009 = []
cost_2010 = []
cost_2011 = []
cost_2012 = []
cost_2013 = []
cost_2014 = []
cost_2015 = []
name = "reformatted/" + file
with open(name, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ",")
next(csvfile)
for row in reader:
date = str(row[4])
date = date[-4:]
cost = row[10]
cost = cost.replace(';', '.')
cost = float(cost)
if cost > 2000 and cost < 30000:
if date < "2015":
cost_2015.append(cost)
if date < "2014":
cost_2014.append(cost)
if date < "2013":
cost_2013.append(cost)
if date < "2012":
cost_2012.append(cost)
if date < "2011":
cost_2011.append(cost)
if date < "2010":
cost_2010.append(cost)
if date < "2009":
cost_2009.append(cost)
if date < "2008":
cost_2008.append(cost)
if date < "2007":
cost_2007.append(cost)
if date < "2006":
cost_2006.append(cost)
if date < "2005":
cost_2005.append(cost)
if date < "2004":
cost_2004.append(cost)
if date < "2003":
cost_2003.append(cost)
if date < "2002":
cost_2002.append(cost)
if date < "2001":
cost_2001.append(cost)
if date < "2000":
cost_2000.append(cost)
cost_total.append(cost)
else:
pass
try:
cost2015 = sum(cost_2015) / len(cost_2015)
except ZeroDivisionError:
cost2015 = 0
try:
cost2014 = sum(cost_2014) / len(cost_2014)
except ZeroDivisionError:
cost2014 = 0
try:
cost2013 = sum(cost_2013) / len(cost_2013)
except ZeroDivisionError:
cost2013 = 0
try:
cost2012 = sum(cost_2012) / len(cost_2012)
except ZeroDivisionError:
cost2012 = 0
try:
cost2011 = sum(cost_2011) / len(cost_2011)
except ZeroDivisionError:
cost2011 = 0
try:
cost2010 = sum(cost_2010) / len(cost_2010)
except ZeroDivisionError:
cost2010 = 0
try:
cost2009 = sum(cost_2009) / len(cost_2009)
except ZeroDivisionError:
cost2009 = 0
try:
cost2008 = sum(cost_2008) / len(cost_2008)
except ZeroDivisionError:
cost2008 = 0
try:
cost2007 = sum(cost_2007) / len(cost_2007)
except ZeroDivisionError:
cost2007 = 0
try:
cost2006 = sum(cost_2006) / len(cost_2006)
except ZeroDivisionError:
cost2006 = 0
try:
cost2005 = sum(cost_2005) / len(cost_2005)
except ZeroDivisionError:
cost2005 = 0
try:
cost2004 = sum(cost_2004) / len(cost_2004)
except ZeroDivisionError:
cost2004 = 0
try:
cost2003 = sum(cost_2003) / len(cost_2003)
except ZeroDivisionError:
cost2003 = 0
try:
cost2002 = sum(cost_2002) / len(cost_2002)
except ZeroDivisionError:
cost2002 = 0
try:
cost2001 = sum(cost_2001) / len(cost_2001)
except ZeroDivisionError:
cost2001 = 0
try:
cost2000 = sum(cost_2000) / len(cost_2000)
except ZeroDivisionError:
cost2000 = 0
try:
costtotal = sum(cost_total) / len(cost_total)
except ZeroDivisionError:
costtotal = 0
all_costs = [int(cost2015), int(cost2014), int(cost2013), int(cost2012),
int(cost2011), int(cost2010), int(cost2009), int(cost2008),
int(cost2007), int(cost2006), int(cost2005), int(cost2004),
int(cost2003), int(cost2002), int(cost2001), int(cost2000),
int(costtotal)]
costs.append(all_costs)
dates = ['1/1/2015', '1/1/2014', '1/1/2013', '1/1/2012',
'1/1/2011', '1/1/2010', '1/1/2009', '1/1/2008',
'1/1/2007', '1/1/2006', '1/1/2005', '1/1/2004',
'1/1/2003', '1/1/2002', '1/1/2001', '1/1/2000', "total"]
for x, file in enumerate(os.listdir("reformatted/")):
name = "normalized_costs_growth/" + "cost_per_size_" + file
with open(name, 'wb') as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Cost/size'])
for i in range(17):
writer.writerow([dates[i], costs[x][i]])
if __name__ == '__main__':
main()
|
python
|
class SveaException(Exception):
pass
class MissingFiles(SveaException):
pass
class DtypeError(SveaException):
pass
class PathError(SveaException):
pass
class PermissionError(SveaException):
pass
class MissingSharkModules(SveaException):
pass
|
python
|
from __future__ import print_function
import yaml
from cloudmesh.common.util import path_expand
from cloudmesh.shell.command import PluginCommand
from cloudmesh.shell.command import command, map_parameters
from cloudmesh.openapi3.function.server import Server
from cloudmesh.common.console import Console
from cloudmesh.common.debug import VERBOSE
from cloudmesh.openapi3.function import generator
import sys, pathlib
from importlib import import_module
from cloudmesh.openapi3.function import register
class Openapi3Command(PluginCommand):
# noinspection PyUnusedLocal
@command
def do_openapi3(self, args, arguments):
"""
::
Usage:
openapi3 generate FUNCTION [YAML]
--baseurl=BASEURL
--filename=FILENAME
--yamldirectory=DIRECTORY
[--verbose]
openapi3 server start YAML
NAME
[--directory=DIRECTORY]
[--port=PORT]
[--server=SERVER]
[--verbose]
openapi3 server stop NAME
openapi3 server list [NAME]
/*OLD*/
openapi3 register add NAME ENDPOINT
openapi3 register remove NAME
openapi3 register list NAME
openapi3 register add
[--endpoint=URL]
[--version=VERSION]
[--location=LOCATION]
[--code=CODE]
[--status=STATUS]
openapi3 register remove
[--endpoint=URL]
[--version=VERSION]
[--cloud=CLOUD]
[--code=CODE]
[--status=STATUS]
openapi3 register list
[--endpoint=URL]
[--version=VERSION]
[--cloud=CLOUD]
[--code=CODE]
[--status=STATUS]
openapi3 tbd
openapi3 tbd merge [SERVICES...] [--dir=DIR] [--verbose]
openapi3 tdb list [--dir=DIR]
openapi3 tbd description [SERVICES...] [--dir=DIR]
openapi3 tbd md FILE [--indent=INDENT]
openapi3 tbd codegen [SERVICES...] [--srcdir=SRCDIR]
[--destdir=DESTDIR]
Arguments:
DIR The directory of the specifications
FILE The specification
SRCDIR The directory of the specifications
DESTDIR The directory where the generated code should be put
Options:
--verbose specifies to run in debug mode [default: False]
--port=PORT the port for the server [default: 8080]
--directory=DIRECTORY the directory in which the server is run [default: ./]
--server=SERVER teh server [default: flask]
Description:
This command does some useful things.
"""
map_parameters(arguments,
'verbose',
'port',
'directory',
'yamldirectory',
'baseurl',
'filename',
'endpoint',
'version',
'cloud',
'code',
'status'
)
arguments.debug = arguments.verbose
VERBOSE(arguments)
if arguments.generate:
try:
function = arguments.FUNCTION
yamlfile = arguments.YAML
baseurl = path_expand(arguments.baseurl)
filename = arguments.filename.strip().split(".")[0]
yamldirectory = path_expand(arguments.yamldirectory)
sys.path.append(baseurl)
module_name = pathlib.Path(f"{filename}").stem
imported_module = import_module(module_name)
func_obj = getattr(imported_module, function)
setattr(sys.modules[module_name], function, func_obj)
openAPI = generator.Generator()
rc = openAPI.generate_openapi(func_obj, baseurl.split("\\")[-1], yamldirectory, yamlfile)
if rc != 0:
Console.error("Failed to generate openapi yaml")
raise Exception
except Exception as e:
print(e)
elif arguments.server and arguments.start:
try:
s = Server(
spec=arguments.YAML,
directory=arguments.directory,
port=arguments.port,
server=arguments.wsgi,
debug=arguments.debug)
s._run()
except FileNotFoundError:
Console.error("specification file not found")
except Exception as e:
print(e)
elif arguments.server and arguments.stop:
raise NotImplementedError
elif arguments.register and arguments.add:
try:
reg = register(
endpoint=arguments.URL,
version=arguments.VERSION,
cloud=arguments.CLOUD,
code=arguments.CODE,
status=arguments.STATUS)
reg._add()
except Exception as e:
print(e)
elif arguments.register and arguments.remove:
try:
reg = register(
endpoint=arguments.URL,
version=arguments.VERSION,
cloud=arguments.CLOUD,
code=arguments.CODE,
status=arguments.STATUS)
reg._remove()
except Exception as e:
print(e)
elif arguments.register and arguments.list:
try:
reg = register(
endpoint=arguments.URL,
version=arguments.VERSION,
cloud=arguments.CLOUD,
code=arguments.CODE,
status=arguments.STATUS)
reg._list()
except Exception as e:
print(e)
'''
arguments.wsgi = arguments["--server"]
m = Manager(debug=arguments.debug)
arguments.dir = path_expand(arguments["--dir"] or ".")
# pprint(arguments)
if arguments.list:
files = m.get(arguments.dir)
print("List of specifications")
print(79 * "=")
print('\n'.join(files))
elif arguments.merge:
d = m.merge(arguments.dir, arguments.SERVICES)
print(yaml.dump(d, default_flow_style=False))
elif arguments.description:
d = m.description(arguments.dir, arguments.SERVICES)
elif arguments.md:
converter = OpenAPIMarkdown()
if arguments["--indent"] is None:
indent = 1
else:
indent = int(arguments["--indent"])
filename = arguments["FILE"]
converter.title(filename, indent=indent)
converter.convert_definitions(filename, indent=indent + 1)
converter.convert_paths(filename, indent=indent + 1)
elif arguments.codegen:
m.codegen(arguments.SERVICES, arguments.dir)
elif arguments.server and arguments.stop:
print("implement me")
return ""
'''
|
python
|
#! /usr/bin/env python
"""
Author: Scott H. Hawley
Based on paper,
A SOFTWARE FRAMEWORK FOR MUSICAL DATA AUGMENTATION
Brian McFee, Eric J. Humphrey, and Juan P. Bello
https://bmcfee.github.io/papers/ismir2015_augmentation.pdf
"""
from __future__ import print_function
import numpy as np
import librosa
from random import getrandbits
import sys, getopt, os
from multiprocessing import Pool
from functools import partial
def random_onoff(): # randomly turns on or off
return bool(getrandbits(1))
# returns a list of augmented audio data, stereo or mono
def augment_audio(
y,
sr,
n_augment=0,
allow_speedandpitch=True,
allow_pitch=True,
allow_speed=True,
allow_dyn=True,
allow_noise=True,
allow_timeshift=True,
tab="",
quiet=False,
):
mods = [y] # always returns the original as element zero
length = y.shape[0]
for i in range(n_augment):
if not quiet:
print(tab + "augment_audio: ", i + 1, "of", n_augment)
y_mod = y.copy()
count_changes = 0
# change speed and pitch together
if (allow_speedandpitch) and random_onoff():
length_change = np.random.uniform(low=0.9, high=1.1)
speed_fac = 1.0 / length_change
if not quiet:
print(tab + " resample length_change = ", length_change)
tmp = np.interp(
np.arange(0, len(y), speed_fac), np.arange(0, len(y)), y
)
# tmp = resample(y,int(length*lengt_fac)) # signal.resample is too slow
minlen = min(
y.shape[0], tmp.shape[0]
) # keep same length as original;
y_mod *= 0 # pad with zeros
y_mod[0:minlen] = tmp[0:minlen]
count_changes += 1
# change pitch (w/o speed)
if (allow_pitch) and random_onoff():
bins_per_octave = 24 # pitch increments are quarter-steps
pitch_pm = 4 # +/- this many quarter steps
pitch_change = pitch_pm * 2 * (np.random.uniform() - 0.5)
if not quiet:
print(tab + " pitch_change = ", pitch_change)
y_mod = librosa.effects.pitch_shift(
y, sr, n_steps=pitch_change, bins_per_octave=bins_per_octave
)
count_changes += 1
# change speed (w/o pitch),
if (allow_speed) and random_onoff():
speed_change = np.random.uniform(low=0.9, high=1.1)
if not quiet:
print(tab + " speed_change = ", speed_change)
tmp = librosa.effects.time_stretch(y_mod, speed_change)
minlen = min(
y.shape[0], tmp.shape[0]
) # keep same length as original;
y_mod *= 0 # pad with zeros
y_mod[0:minlen] = tmp[0:minlen]
count_changes += 1
# change dynamic range
if (allow_dyn) and random_onoff():
dyn_change = np.random.uniform(
low=0.5, high=1.1
) # change amplitude
if not quiet:
print(tab + " dyn_change = ", dyn_change)
y_mod = y_mod * dyn_change
count_changes += 1
# add noise
if (allow_noise) and random_onoff():
noise_amp = 0.005 * np.random.uniform() * np.amax(y)
if random_onoff():
if not quiet:
print(tab + " gaussian noise_amp = ", noise_amp)
y_mod += noise_amp * np.random.normal(size=length)
else:
if not quiet:
print(tab + " uniform noise_amp = ", noise_amp)
y_mod += noise_amp * np.random.normal(size=length)
count_changes += 1
# shift in time forwards or backwards
if (allow_timeshift) and random_onoff():
timeshift_fac = (
0.2 * 2 * (np.random.uniform() - 0.5)
) # up to 20% of length
if not quiet:
print(tab + " timeshift_fac = ", timeshift_fac)
start = int(length * timeshift_fac)
if start > 0:
y_mod = np.pad(y_mod, (start, 0), mode="constant")[
0 : y_mod.shape[0]
]
else:
y_mod = np.pad(y_mod, (0, -start), mode="constant")[
0 : y_mod.shape[0]
]
count_changes += 1
# last-ditch effort to make sure we made a change (recursive/sloppy, but...works)
if 0 == count_changes:
if not quiet:
print("No changes made to signal, trying again")
mods.append(
augment_audio(y, sr, n_augment=1, tab=" ", quiet=quiet)[1]
)
else:
mods.append(y_mod)
return mods
def augment_one_file(file_list, n_augment, quiet, file_index):
infile = file_list[file_index]
if os.path.isfile(infile):
print(
" Operating on file ",
infile,
", making ",
n_augment,
" augmentations...",
sep="",
)
y, sr = librosa.load(infile, sr=None)
mods = augment_audio(y, sr, n_augment=n_augment, quiet=quiet)
for i in range(len(mods) - 1):
filename_no_ext = os.path.splitext(infile)[0]
ext = os.path.splitext(infile)[1]
outfile = filename_no_ext + "_aug" + str(i + 1) + ext
if not quiet:
print(" mod = ", i + 1, ": saving file", outfile, "...")
librosa.output.write_wav(outfile, mods[i + 1], sr)
else:
print(" *** File", infile, "does not exist. Skipping.")
return
def main(args):
np.random.seed(1)
quiet = args.quiet
# read in every file on the list, augment it lots of times, output all those
file_indices = tuple(range(len(args.file)))
cpu_count = os.cpu_count()
pool = Pool(cpu_count)
pool.map(
partial(augment_one_file, args.file, args.N, args.quiet), file_indices
)
"""
for infile in args.file:
if os.path.isfile(infile):
print(" Operating on file ",infile,", making ",args.N," augmentations...",sep="")
y, sr = librosa.load(infile, sr=None)
mods = augment_audio(y, sr, n_augment=args.N, quiet=quiet)
for i in range(len(mods)-1):
filename_no_ext = os.path.splitext(infile)[0]
ext = os.path.splitext(infile)[1]
outfile = filename_no_ext+"_aug"+str(i+1)+ext
if not quiet:
print(" mod = ",i+1,": saving file",outfile,"...")
librosa.output.write_wav(outfile,mods[i+1],sr)
else:
print(" *** File",infile,"does not exist. Skipping.")
"""
return
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Perform data augmentation")
parser.add_argument(
"-q", "--quiet", help="quiet mode; reduce output", action="store_true"
)
parser.add_argument(
"-t",
"--test",
help="test on sample data (takes precedence over other args)",
action="store_true",
)
parser.add_argument(
"N", help="number of augmentations to generate", type=int
)
parser.add_argument("file", help="sound files to augment", nargs="*")
args = parser.parse_args()
print(args)
main(args)
|
python
|
text = input()
for index, letter in enumerate(text):
if letter == ":":
print(letter + text[index + 1])
|
python
|
class Node:
def __init__(self, val):
self.val = val
self.left = left
self.right = right
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
|
python
|
import argparse
import datetime
import fnmatch
import os
import pickle
import re
from time import time
from typing import List
import tensorflow.keras
import numpy
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from ClassWeightCalculator import ClassWeightCalculator
from reporting import TelegramNotifier, GoogleSpreadsheetReporter, sklearn_reporting
from reporting.TrainingHistoryPlotter import TrainingHistoryPlotter
from datasets.TrainingDatasetProvider import TrainingDatasetProvider
from datasets.DirectoryIteratorWithBoundingBoxes import DirectoryIteratorWithBoundingBoxes
from models.ConfigurationFactory import ConfigurationFactory
def train_model(dataset_directory: str, model_name: str, stroke_thicknesses: List[int],
width: int, height: int,
staff_line_vertical_offsets: List[int], training_minibatch_size: int,
optimizer: str, dynamic_learning_rate_reduction: bool, use_fixed_canvas: bool, datasets: List[str],
class_weights_balancing_method: str,
save_after_every_epoch: bool,
resume_from_checkpoint: str,
send_telegram_messages: bool):
image_dataset_directory = os.path.join(dataset_directory, "images")
bounding_boxes = None
bounding_boxes_cache = os.path.join(dataset_directory, "bounding_boxes.txt")
print("Loading configuration and data-readers...")
start_time = time()
number_of_classes = len(os.listdir(os.path.join(image_dataset_directory, "training")))
training_configuration = ConfigurationFactory.get_configuration_by_name(model_name, optimizer, width, height,
training_minibatch_size, number_of_classes)
if training_configuration.performs_localization() and bounding_boxes is None:
# Try to unpickle
with open(bounding_boxes_cache, "rb") as cache:
bounding_boxes = pickle.load(cache)
if not training_configuration.performs_localization():
bounding_boxes = None
train_generator = ImageDataGenerator(rotation_range=training_configuration.rotation_range,
zoom_range=training_configuration.zoom_range
)
training_data_generator = DirectoryIteratorWithBoundingBoxes(
directory=os.path.join(image_dataset_directory, "training"),
image_data_generator=train_generator,
target_size=(training_configuration.input_image_rows,
training_configuration.input_image_columns),
batch_size=training_configuration.training_minibatch_size,
bounding_boxes=bounding_boxes,
)
training_steps_per_epoch = np.math.ceil(training_data_generator.samples / training_data_generator.batch_size)
validation_generator = ImageDataGenerator()
validation_data_generator = DirectoryIteratorWithBoundingBoxes(
directory=os.path.join(image_dataset_directory, "validation"),
image_data_generator=validation_generator,
target_size=(
training_configuration.input_image_rows,
training_configuration.input_image_columns),
batch_size=training_configuration.training_minibatch_size,
bounding_boxes=bounding_boxes)
validation_steps_per_epoch = np.math.ceil(validation_data_generator.samples / validation_data_generator.batch_size)
test_generator = ImageDataGenerator()
test_data_generator = DirectoryIteratorWithBoundingBoxes(
directory=os.path.join(image_dataset_directory, "test"),
image_data_generator=test_generator,
target_size=(training_configuration.input_image_rows,
training_configuration.input_image_columns),
batch_size=training_configuration.training_minibatch_size,
shuffle=False,
bounding_boxes=bounding_boxes)
test_steps_per_epoch = np.math.ceil(test_data_generator.samples / test_data_generator.batch_size)
model = training_configuration.classifier()
model.summary()
print("Model {0} created.".format(training_configuration.name()))
initial_epoch = 0
if resume_from_checkpoint:
# Try to parse epoch from checkpoint filename. Checkpoint files written by this program
# are of the form <start>_<configname>-<epoch>.h5.
# The regular expression assumes there are no dashes in configname, otherwise
# the initial epoch will just be 0. That is harmless unless you have parameters that
# depend on the epoch.
m = re.match('[\d-]+_[^-]+-(\d+).h5', resume_from_checkpoint)
if m and m.groups() and len(m.groups() == 1):
initial_epoch = int(m.groups()[0]) + 1
# This will not restore parameters that are adapted dynamically during training since
# afaik not all of them get saved to the model checkpoint.
model.load_weights(resume_from_checkpoint)
print("Model {0} weights loaded from checkpoint {1}. Training will resume from epoch {2}".format(
training_configuration.name(),
resume_from_checkpoint,
initial_epoch))
print(training_configuration.summary())
start_of_training = datetime.date.today()
monitor_variable = 'val_accuracy'
if training_configuration.performs_localization():
monitor_variable = 'val_output_class_accuracy'
best_model_path = "{0}_{1}".format(start_of_training, training_configuration.name())
if save_after_every_epoch:
model_checkpoint = ModelCheckpoint(best_model_path + "-{epoch:02d}.h5", monitor=monitor_variable,
save_best_only=True, verbose=1, save_freq='epoch')
else:
model_checkpoint = ModelCheckpoint(best_model_path+".h5", monitor=monitor_variable,
save_best_only=True, verbose=1)
early_stop = EarlyStopping(monitor=monitor_variable,
patience=training_configuration.number_of_epochs_before_early_stopping,
verbose=1)
learning_rate_reduction = ReduceLROnPlateau(monitor=monitor_variable,
patience=training_configuration.number_of_epochs_before_reducing_learning_rate,
verbose=1,
factor=training_configuration.learning_rate_reduction_factor,
min_lr=training_configuration.minimum_learning_rate)
tensorboard_callback = TensorBoard(
log_dir="./logs/{0}_{1}/".format(start_of_training, training_configuration.name()))
if dynamic_learning_rate_reduction:
callbacks = [model_checkpoint, early_stop, tensorboard_callback, learning_rate_reduction]
else:
print("Learning-rate reduction on Plateau disabled")
callbacks = [model_checkpoint, early_stop, tensorboard_callback]
class_weight_calculator = ClassWeightCalculator()
class_weights = class_weight_calculator.calculate_class_weights(image_dataset_directory,
method=class_weights_balancing_method,
class_indices=training_data_generator.class_indices)
if class_weights_balancing_method is not None:
print("Using {0} method for obtaining class weights to compensate for an unbalanced dataset.".format(
class_weights_balancing_method))
print("Training on dataset...")
history = model.fit_generator(
generator=training_data_generator,
steps_per_epoch=training_steps_per_epoch,
epochs=training_configuration.number_of_epochs,
callbacks=callbacks,
validation_data=validation_data_generator,
validation_steps=validation_steps_per_epoch,
class_weight=class_weights,
initial_epoch=initial_epoch
)
best_model = None
if not save_after_every_epoch:
print("Loading best model from check-point and testing...")
best_model = tensorflow.keras.models.load_model(best_model_path + '.h5')
else:
print("Loading latest model from check-point and testing...")
latest_mtime = 0
latest_file = None
pattern = best_model_path + '*.h5'
for f in os.listdir('.'):
if fnmatch.fnmatch(f, pattern):
fd = os.open(f, os.O_RDONLY)
st = os.fstat(fd)
mt = st.st_mtime
if not latest_file or mt > latest_mtime:
latest_mtime = mt
latest_file = f
print('latest model file is {0}'.format(latest_file))
best_model = tensorflow.keras.models.load_model(latest_file)
test_data_generator.reset()
file_names = test_data_generator.filenames
class_labels = os.listdir(os.path.join(image_dataset_directory, "test"))
# Notice that some classes have so few elements, that they are not present in the test-set and do not
# appear in the final report. To obtain the correct classes, we have to enumerate all non-empty class
# directories inside the test-folder and use them as labels
names_of_classes_with_test_data = [
class_name for class_name in class_labels
if os.listdir(os.path.join(image_dataset_directory, "test", class_name))]
true_classes = test_data_generator.classes
predictions = best_model.predict_generator(test_data_generator, steps=test_steps_per_epoch)
if training_configuration.performs_localization():
predicted_classes = numpy.argmax(predictions[0], axis=1)
else:
predicted_classes = numpy.argmax(predictions, axis=1)
test_data_generator.reset()
evaluation = best_model.evaluate_generator(test_data_generator, steps=test_steps_per_epoch)
classification_accuracy = 0
print("Reporting classification statistics with micro average")
report = sklearn_reporting.classification_report(true_classes, predicted_classes, digits=3,
target_names=names_of_classes_with_test_data, average='micro')
print(report)
print("Reporting classification statistics with macro average")
report = sklearn_reporting.classification_report(true_classes, predicted_classes, digits=3,
target_names=names_of_classes_with_test_data, average='macro')
print(report)
print("Reporting classification statistics with weighted average")
report = sklearn_reporting.classification_report(true_classes, predicted_classes, digits=3,
target_names=names_of_classes_with_test_data, average='weighted'
)
print(report)
indices_of_misclassified_files = [i for i, e in enumerate(true_classes - predicted_classes) if e != 0]
misclassified_files = [file_names[i] for i in indices_of_misclassified_files]
misclassified_files_actual_prediction_indices = [predicted_classes[i] for i in indices_of_misclassified_files]
misclassified_files_actual_prediction_classes = [class_labels[i] for i in
misclassified_files_actual_prediction_indices]
print("Misclassified files:")
for i in range(len(misclassified_files)):
print("\t{0} is incorrectly classified as {1}".format(misclassified_files[i],
misclassified_files_actual_prediction_classes[i]))
for i in range(len(best_model.metrics_names)):
current_metric = best_model.metrics_names[i]
print("{0}: {1:.5f}".format(current_metric, evaluation[i]))
if current_metric == 'accuracy' or current_metric == 'output_class_acc':
classification_accuracy = evaluation[i]
print("Total Accuracy: {0:0.5f}%".format(classification_accuracy * 100))
print("Total Error: {0:0.5f}%".format((1 - classification_accuracy) * 100))
end_time = time()
execution_time_in_seconds = round(end_time - start_time)
print("Execution time: {0:.1f}s".format(end_time - start_time))
training_result_image = "{1}_{0}_{2:.1f}p.png".format(training_configuration.name(), start_of_training,
classification_accuracy * 100)
TrainingHistoryPlotter.plot_history(history, training_result_image)
datasets_string = str.join(",", datasets)
notification_message = "Training on {0} dataset with model {1} finished. " \
"Accuracy: {2:0.5f}%".format(datasets_string, model_name, classification_accuracy * 100)
if send_telegram_messages:
TelegramNotifier.send_message_via_telegram(notification_message, training_result_image)
else:
print(notification_message)
dataset_size = training_data_generator.samples + validation_data_generator.samples + test_data_generator.samples
stroke_thicknesses_string = ",".join(map(str, stroke_thicknesses))
staff_line_vertical_offsets_string = ",".join(map(str, staff_line_vertical_offsets))
image_sizes = "{0}x{1}px".format(training_configuration.input_image_rows,
training_configuration.input_image_columns)
data_augmentation = "{0}% zoom, {1}° rotation".format(int(training_configuration.zoom_range * 100),
training_configuration.rotation_range)
today = "{0:02d}.{1:02d}.{2}".format(start_of_training.day, start_of_training.month, start_of_training.year)
balancing_method = "None" if class_weights_balancing_method is None else class_weights_balancing_method
GoogleSpreadsheetReporter.append_result_to_spreadsheet(dataset_size=dataset_size, image_sizes=image_sizes,
stroke_thicknesses=stroke_thicknesses_string,
staff_lines=staff_line_vertical_offsets_string,
model_name=model_name, data_augmentation=data_augmentation,
optimizer=optimizer,
early_stopping=training_configuration.number_of_epochs_before_early_stopping,
reduction_patience=training_configuration.number_of_epochs_before_reducing_learning_rate,
learning_rate_reduction_factor=training_configuration.learning_rate_reduction_factor,
minibatch_size=training_minibatch_size,
initialization=training_configuration.initialization,
initial_learning_rate=training_configuration.get_initial_learning_rate(),
accuracy=classification_accuracy,
date=today,
use_fixed_canvas=use_fixed_canvas,
datasets=datasets_string,
execution_time_in_seconds=execution_time_in_seconds,
balancing_method=balancing_method)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.register("type", "bool", lambda v: v.lower() == "true")
parser.add_argument("--dataset_directory", type=str, default="data",
help="The directory, that is used for storing the images during training")
parser.add_argument("--model_name", type=str, default="res_net_4",
help="The model used for training the network. Run ListAvailableConfigurations.ps1 or "
"models/ConfigurationFactory.py to get a list of all available configurations")
parser.add_argument("--use_existing_dataset_directory", dest="delete_and_recreate_dataset_directory",
action='store_false',
help="Whether to delete and recreate the dataset-directory (by downloading the appropriate "
"files from the internet, extracting and generating images) or simply use whatever data "
"currently is inside of that directory.")
parser.set_defaults(delete_and_recreate_dataset_directory=True)
parser.add_argument("--minibatch_size", default=16, type=int,
help="Size of the minibatches for training, typically one of 8, 16, 32, 64 or 128")
parser.add_argument("--optimizer", default="Adadelta", type=str,
help="The optimizer used for the training, can be SGD, Adam or Adadelta")
parser.add_argument("--no_dynamic_learning_rate_reduction", dest="dynamic_learning_rate_reduction",
action="store_false",
help="True, if the learning rate should not be scheduled to be reduced on a plateau.")
parser.set_defaults(dynamic_learning_rate_reduction=True)
parser.add_argument("--class_weights_balancing_method", default=None, type=str,
help="The optional weight balancing method for handling unbalanced datasets. If provided,"
"valid choices are simple or skBalance. 'simple' uses 1/sqrt(#samples_per_class) as "
"weights for samples from each class to compensate for classes that are underrepresented."
"'skBalance' uses the Python SkLearn module to calculate more sophisticated weights.")
parser.add_argument("--telegram_messages", dest="send_telegram_messages", action="store_true",
help="Send messages via telegram")
parser.set_defaults(send_telegram_messages=False)
parser.add_argument("--save_after_every_epoch", dest="save_after_every_epoch", action="store_true",
help="Write a checkpoint after every epoch")
parser.set_defaults(save_after_every_epoch=False)
parser.add_argument("--resume_from_checkpoint", dest="resume_from_checkpoint", default=None, type=str,
help="Load checkpoint from file specified.")
TrainingDatasetProvider.add_arguments_for_training_dataset_provider(parser)
flags, unparsed = parser.parse_known_args()
offsets = []
if flags.offsets != "":
offsets = [int(o) for o in flags.offsets.split(',')]
stroke_thicknesses_for_generated_symbols = [int(s) for s in flags.stroke_thicknesses.split(',')]
if flags.datasets == "":
raise Exception("No dataset selected. Specify the dataset for the training via the --dataset parameter")
datasets = flags.datasets.split(',')
if flags.delete_and_recreate_dataset_directory:
training_dataset_provider = TrainingDatasetProvider(flags.dataset_directory)
training_dataset_provider.recreate_and_prepare_datasets_for_training(
datasets=datasets, width=flags.width,
height=flags.height,
use_fixed_canvas=flags.use_fixed_canvas,
stroke_thicknesses_for_generated_symbols=stroke_thicknesses_for_generated_symbols,
staff_line_spacing=flags.staff_line_spacing,
staff_line_vertical_offsets=offsets,
random_position_on_canvas=flags.random_position_on_canvas)
training_dataset_provider.resize_all_images_to_fixed_size(flags.width, flags.height)
training_dataset_provider.split_dataset_into_training_validation_and_test_set()
train_model(dataset_directory=flags.dataset_directory,
model_name=flags.model_name,
stroke_thicknesses=stroke_thicknesses_for_generated_symbols,
width=flags.width,
height=flags.height,
staff_line_vertical_offsets=offsets,
training_minibatch_size=flags.minibatch_size,
optimizer=flags.optimizer,
dynamic_learning_rate_reduction=flags.dynamic_learning_rate_reduction,
use_fixed_canvas=flags.use_fixed_canvas,
datasets=datasets,
class_weights_balancing_method=flags.class_weights_balancing_method,
save_after_every_epoch=flags.save_after_every_epoch,
resume_from_checkpoint=flags.resume_from_checkpoint,
send_telegram_messages=flags.send_telegram_messages)
# To run in in python console
# dataset_directory = 'data'
# model_name = 'res_net_3_small'
# delete_and_recreate_dataset_directory = True
# stroke_thicknesses = [3]
# width = 96
# height = 192
# staff_line_vertical_offsets = None
# staff_line_spacing = 14
# training_minibatch_size = 32
# optimizer = 'Adadelta'
# dynamic_learning_rate_reduction = True
|
python
|
lst = ["A","guru","sabarish","kumar"]
last=lst[-1]
length=0
for i in lst:
length=length+1
if i == last:
break
print("The length of list :",length)
|
python
|
def dp(n, k):
if
|
python
|
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://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.
#
# When you publish or redistribute any data created with VulnerableCode or any VulnerableCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with VulnerableCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# VulnerableCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# VulnerableCode is a free software tool from nexB Inc. and others.
# Visit https://github.com/nexB/vulnerablecode/ for support and download.
from vulnerabilities.data_source import Advisory
from vulnerabilities.data_source import DataSource
from vulnerabilities.data_source import Reference
from vulnerabilities.data_source import VulnerabilitySeverity
from vulnerabilities.helpers import fetch_yaml
from vulnerabilities.severity_systems import scoring_systems
URL = "https://ftp.suse.com/pub/projects/security/yaml/suse-cvss-scores.yaml"
class SUSESeverityScoreDataSource(DataSource):
def updated_advisories(self):
advisories = []
score_data = fetch_yaml(URL)
advisories.append(self.to_advisory(score_data))
return advisories
@staticmethod
def to_advisory(score_data):
advisories = []
for cve_id in score_data:
severities = []
for cvss_score in score_data[cve_id]["cvss"]:
score = None
vector = None
if cvss_score["version"] == 2.0:
score = VulnerabilitySeverity(
system=scoring_systems["cvssv2"], value=str(cvss_score["score"])
)
vector = VulnerabilitySeverity(
system=scoring_systems["cvssv2_vector"], value=str(cvss_score["vector"])
)
elif cvss_score["version"] == 3:
score = VulnerabilitySeverity(
system=scoring_systems["cvssv3"], value=str(cvss_score["score"])
)
vector = VulnerabilitySeverity(
system=scoring_systems["cvssv3_vector"], value=str(cvss_score["vector"])
)
elif cvss_score["version"] == 3.1:
score = VulnerabilitySeverity(
system=scoring_systems["cvssv3.1"], value=str(cvss_score["score"])
)
vector = VulnerabilitySeverity(
system=scoring_systems["cvssv3.1_vector"], value=str(cvss_score["vector"])
)
severities.extend([score, vector])
advisories.append(
Advisory(
vulnerability_id=cve_id,
summary="",
impacted_package_urls=[],
references=[Reference(url=URL, severities=severities)],
)
)
return advisories
|
python
|
#!/usr/bin/env python3
# encoding: utf-8
import re
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
import torch
import torch.nn as nn
import math
import numpy as np
import time
import os
import sys
import torchvision
#__all__ = ['DenseNet121','DenseNet169','ResNet50','ResNet101']
model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',
'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',
'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
}
def Densenet121(pretrained=False, classes = 1000, **kwargs):
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16),
**kwargs)
if pretrained:
# '.'s are no longer allowed in module names, but pervious _DenseLayer
# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
# They are also in the checkpoints in model_urls. This pattern is used
# to find such keys.
pattern = re.compile(
r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
state_dict = model_zoo.load_url(model_urls['densenet121'])
for key in list(state_dict.keys()):
res = pattern.match(key)
if res:
new_key = res.group(1) + res.group(2)
state_dict[new_key] = state_dict[key]
del state_dict[key]
new_state_dict = model.state_dict()
for k in state_dict:
if k in new_state_dict:
#print(k)
new_state_dict[k] = state_dict[k]
model.load_state_dict(new_state_dict)
# modeify
num_ftrs = model.classifier.in_features
model.classifier = nn.Sequential(
nn.Linear(num_ftrs, num_ftrs),
nn.Dropout(p=0.9),
nn.Linear(num_ftrs, classes)
)
return model
def Densenet169(pretrained=False, classes =1000, **kwargs):
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32),
**kwargs)
if pretrained:
# '.'s are no longer allowed in module names, but pervious _DenseLayer
# has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
# They are also in the checkpoints in model_urls. This pattern is used
# to find such keys.
pattern = re.compile(
r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
state_dict = model_zoo.load_url(model_urls['densenet169'])
for key in list(state_dict.keys()):
res = pattern.match(key)
if res:
new_key = res.group(1) + res.group(2)
state_dict[new_key] = state_dict[key]
del state_dict[key]
new_state_dict = model.state_dict()
for k in state_dict:
if k in new_state_dict:
new_state_dict[k] = state_dict[k]
model.load_state_dict(new_state_dict)
# modeify
num_ftrs = model.classifier.in_features
model.classifier = nn.Sequential(
nn.Linear(num_ftrs, num_ftrs),
nn.Dropout(p=0.9),
nn.Linear(num_ftrs, classes)
)
return model
class _DenseLayer(nn.Sequential):
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):
super(_DenseLayer, self).__init__()
self.add_module('norm1', nn.BatchNorm2d(num_input_features)),
self.add_module('relu1', nn.ReLU(inplace=True)),
self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *
growth_rate, kernel_size=1, stride=1, bias=False)),
self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),
self.add_module('relu2', nn.ReLU(inplace=True)),
self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,
kernel_size=3, stride=1, padding=1, bias=False)),
self.drop_rate = drop_rate
def forward(self, x):
new_features = super(_DenseLayer, self).forward(x)
if self.drop_rate > 0:
new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)
return torch.cat([x, new_features], 1)
class _DenseBlock(nn.Sequential):
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate)
self.add_module('denselayer%d' % (i + 1), layer)
class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features):
super(_Transition, self).__init__()
self.add_module('norm', nn.BatchNorm2d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,
kernel_size=1, stride=1, bias=False))
self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))
class DenseNet(nn.Module):
r"""Densenet-BC model class, based on
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
Args:
growth_rate (int) - how many filters to add each layer (`k` in paper)
block_config (list of 4 ints) - how many layers in each pooling block
num_init_features (int) - the number of filters to learn in the first convolution layer
bn_size (int) - multiplicative factor for number of bottle neck layers
(i.e. bn_size * k features in the bottleneck layer)
drop_rate (float) - dropout rate after each dense layer
num_classes (int) - number of classification classes
"""
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, gray = False):
super(DenseNet, self).__init__()
if gray:
self.features = nn.Sequential(OrderedDict([
('gconv', nn.Conv2d(1, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
('norm0', nn.BatchNorm2d(num_init_features)),
('relu0', nn.ReLU(inplace=True)),
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
]))
else:
# First convolution
self.features = nn.Sequential(OrderedDict([
('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
('norm0', nn.BatchNorm2d(num_init_features)),
('relu0', nn.ReLU(inplace=True)),
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
]))
# Each denseblock
num_features = num_init_features
for i, num_layers in enumerate(block_config):
block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,
bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate)
self.features.add_module('denseblock%d' % (i + 1), block)
num_features = num_features + num_layers * growth_rate
if i != len(block_config) - 1:
trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)
self.features.add_module('transition%d' % (i + 1), trans)
num_features = num_features // 2
# Final batch norm
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
# Linear layer
self.classifier = nn.Linear(num_features, num_classes)
self.Sigmoid = nn.Sigmoid()
# Official init from torch repo.
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.constant_(m.bias, 0)
def forward(self, x):
features = self.features(x)
out = F.relu(features, inplace=True)
out_after_pooling = F.adaptive_avg_pool2d(out, (1,1)).view(features.size(0), -1)
out = self.classifier(out_after_pooling)
out = self.Sigmoid(out)
return out
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
for p in self.parameters():
p.requires_grad = False
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, gray = False, img_size = 224):
self.inplanes = 64
super(ResNet, self).__init__()
self.boxes = None
self.gconv1 = None
if gray:
self.gconv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3,bias=False)
else:
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
if img_size == 224:
self.avgpool = nn.AvgPool2d(7, stride=1) # for 224*224
else:
self.avgpool = nn.AvgPool2d(14, stride=1) # for 448*448
self.fc = nn.Linear(512 * block.expansion, num_classes)
self.Sigmoid = nn.Sigmoid()
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
if self.gconv1:
x = self.gconv1(x)
else:
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
#print(x.shape)
x = self.Sigmoid(x)
return x
def ResNet50(pretrained=False, classes = 1000, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
pretrained_state = model_zoo.load_url(model_urls['resnet50'])
ori_state = model.state_dict()
for k in pretrained_state:
if k in ori_state:
ori_state[k] = pretrained_state[k]
model.load_state_dict(ori_state)
model.fc = nn.Sequential(
nn.Linear(2048,2048),
nn.ReLU(inplace=True),
nn.Dropout(p=0.9),
nn.Linear(2048, classes),
)
return model
def ResNet101(pretrained=False, classes = 1000, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
pretrained_state = model_zoo.load_url(model_urls['resnet101'])
ori_state = model.state_dict()
for k in pretrained_state:
if k in ori_state:
ori_state[k] = pretrained_state[k]
model.load_state_dict(ori_state)
model.fc = nn.Sequential(
nn.Linear(2048,2048),
nn.ReLU(inplace=True),
nn.Dropout(p=0.9),
nn.Linear(2048, classes),
)
return model
|
python
|
from django.apps import AppConfig
class BizcontactsConfig(AppConfig):
name = 'bizcontacts'
|
python
|
'''
--- Day 9: Encoding Error ---
With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you.
Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon connection, the port outputs a series of numbers (your puzzle input).
The data appears to be encrypted with the eXchange-Masking Addition System (XMAS) which, conveniently for you, is an old cypher with an important weakness.
XMAS starts by transmitting a preamble of 25 numbers. After that, each number you receive should be the sum of any two of the 25 immediately previous numbers. The two numbers will have different values, and there might be more than one such pair.
For example, suppose your preamble consists of the numbers 1 through 25 in a random order. To be valid, the next number must be the sum of two of those numbers:
26 would be a valid next number, as it could be 1 plus 25 (or many other pairs, like 2 and 24).
49 would be a valid next number, as it is the sum of 24 and 25.
100 would not be valid; no two of the previous 25 numbers sum to 100.
50 would also not be valid; although 25 appears in the previous 25 numbers, the two numbers in the pair must be different.
Suppose the 26th number is 45, and the first number (no longer an option, as it is more than 25 numbers ago) was 20. Now, for the next number to be valid, there needs to be some pair of numbers among 1-19, 21-25, or 45 that add up to it:
26 would still be a valid next number, as 1 and 25 are still within the previous 25 numbers.
65 would not be valid, as no two of the available numbers sum to it.
64 and 66 would both be valid, as they are the result of 19+45 and 21+45 respectively.
Here is a larger example which only considers the previous 5 numbers (and has a preamble of length 5):
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
In this example, after the 5-number preamble, almost every number is the sum of two of the previous 5 numbers; the only number that does not follow this rule is 127.
The first step of attacking the weakness in the XMAS data is to find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the first number that does not have this property?
Your puzzle answer was 1398413738.
The first half of this puzzle is complete! It provides one gold star: *
-- Part Two ---
The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1.
Again consider the above example:
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
In this list, adding up all of the numbers from 15 through 40 produces the invalid number from step 1, 127. (Of course, the contiguous set of numbers in your actual list might be much longer.)
To find the encryption weakness, add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing 62.
What is the encryption weakness in your XMAS-encrypted list of numbers?
Your puzzle answer was 169521051.
Both parts of this puzzle are complete! They provide two gold stars: **
'''
test_data = [ 35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576 ]
def bad_num_search( data, preamble_size, start_idx, desired_val ):
preamble_list = data[ start_idx:preamble_size ]
for num in preamble_list:
search_val = desired_val - num
if search_val in preamble_list:
return True
return False
def find_bad_number( data, preamble_size ):
bad_number = 0
start_idx = 0
for number in data[ preamble_size: ]:
# print( 'Number {0}'.format( number ) )
if not bad_num_search( data, preamble_size, start_idx, number ):
bad_number = number
break
else:
preamble_size += 1
start_idx += 1
return bad_number
def find_encryption_set( data, desired_val ):
val = [ ]
for idx, item in enumerate( data ):
if sum( val ) < desired_val:
# print( 'Too low: {0}'.format( sum( val ) ) )
val.append( item )
elif sum( val ) > desired_val:
# print( 'Too high: {0}'.format( sum( val ) ) )
val.pop( 0 )
val.append( item )
while sum( val ) > desired_val:
val.pop( 0 )
elif sum( val ) == desired_val:
encryption_weakness = min( val ) + max( val )
return encryption_weakness
return 0
if __name__ == "__main__":
DEBUG = False
input = r'D:\Projects\Python\Personal\Advent_of_Code\2020\day_09_input.txt'
# input = r'D:\Dropbox\Projects\Python\Advent_of_Code\2020\day_09_input.txt'
data = [ ]
bad_number = 0
encryption_weakness = 0
preamble_size = 25
with open( input, 'r' ) as input_file:
data = [ int( line.strip( ) ) for line in input_file.readlines( ) ]
if DEBUG:
data = test_data
preamble_size = 5
bad_number = find_bad_number( data, preamble_size )
encryption_weakness = find_encryption_set( data, bad_number )
print( '\nThe bad number is: {0}'.format( bad_number ) )
print( '\nThe encryption weakness is: {0}'.format( encryption_weakness ) )
|
python
|
import os
import subprocess
import unittest
from fs import open_fs
from celery import Celery, group
import magic
from fs.copy import copy_file
from parameterized import parameterized
app = Celery('test_generators')
app.config_from_object('unoconv.celeryconfig')
app.conf.update({'broker_url': 'amqp://guest:guest@localhost:5672'})
generate_preview_jpg = app.signature('unoconv.tasks.generate_preview_jpg')
generate_preview_png = app.signature('unoconv.tasks.generate_preview_png')
generate_pdf = app.signature('unoconv.tasks.generate_pdf')
example_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk('example-files') for f in filenames]
class TestFile(unittest.TestCase):
BUCKET_NAME_INPUT = 'unoconv-input'
BUCKET_NAME_OUTPUT = 'unoconv-output'
INPUT_FS_URL_HOST = f's3://minio:minio123@{BUCKET_NAME_INPUT}?endpoint_url=http://localhost:9000'
INPUT_FS_URL = f's3://minio:minio123@{BUCKET_NAME_INPUT}?endpoint_url=http://minio:9000'
OUTPUT_FS_URL_HOST = f's3://minio:minio123@{BUCKET_NAME_OUTPUT}?endpoint_url=http://localhost:9000'
OUTPUT_FS_URL = f's3://minio:minio123@{BUCKET_NAME_OUTPUT}?endpoint_url=http://minio:9000'
def setUp(self):
with open_fs(self.INPUT_FS_URL_HOST) as fs:
fs.glob("**").remove()
with open_fs(self.OUTPUT_FS_URL_HOST) as fs:
fs.glob("**").remove()
def tearDown(self):
with open_fs(self.INPUT_FS_URL_HOST) as fs:
fs.glob("**").remove()
with open_fs(self.OUTPUT_FS_URL_HOST) as fs:
fs.glob("**").remove()
@parameterized.expand([('jpg',), ('png',), ('pdf',)])
def test_unsupported(self, output_format: str):
if output_format == 'jpg':
generator = generate_preview_jpg
elif output_format == 'png':
generator = generate_preview_png
elif output_format == 'pdf':
generator = generate_pdf
else:
raise RuntimeError('Unsupported output format {}.'.format(output_format))
task = generator.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': '/dev/null',
'output_fs_url': self.OUTPUT_FS_URL,
'output_file': f'output.{output_format}',
'mime_type': 'application/octet-stream',
'extension': '.unsupported',
'timeout': 10,
})
self.assertRaises(ValueError, lambda: task.apply_async().get())
@parameterized.expand([('jpg',), ('png',), ('pdf',)])
def test_input_file_not_found(self, output_format: str):
if output_format == 'jpg':
generator = generate_preview_jpg
elif output_format == 'png':
generator = generate_preview_png
elif output_format == 'pdf':
generator = generate_pdf
else:
raise RuntimeError('Unsupported output format {}.'.format(output_format))
task = generator.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': 'does-not-exist',
'output_fs_url': self.OUTPUT_FS_URL,
'output_file': f'output.{output_format}',
'mime_type': 'application/vnd.oasis.opendocument.text',
'extension': '.odt',
'timeout': 10,
})
self.assertRaises(FileNotFoundError, lambda: task.apply_async().get())
@parameterized.expand([('jpg',), ('png',), ('pdf',)])
def test_output_wrong_fs(self, output_format: str):
if output_format == 'jpg':
generator = generate_preview_jpg
elif output_format == 'png':
generator = generate_preview_png
elif output_format == 'pdf':
generator = generate_pdf
else:
raise RuntimeError('Unsupported output format {}.'.format(output_format))
task = generator.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': '/dev/null',
'output_fs_url': 'this-is-invalid',
'output_file': f'output.{output_format}',
'mime_type': 'application/vnd.oasis.opendocument.text',
'extension': '.odt',
'timeout': 10,
})
self.assertRaises(RuntimeError, lambda: task.apply_async().get())
@parameterized.expand([('jpg',), ('png',)])
def test_wrong_dimensions(self, output_format: str):
if output_format == 'jpg':
generator = generate_preview_jpg
elif output_format == 'png':
generator = generate_preview_png
else:
raise RuntimeError('Unsupported output format {}.'.format(output_format))
for pixel_height, pixel_width in [(None, 800), (800, None), (-1, None), (None, -1)]:
task = generator.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': '/dev/null',
'output_fs_url': self.OUTPUT_FS_URL,
'output_file': f'output.{output_format}',
'mime_type': 'application/vnd.oasis.opendocument.text',
'extension': '.odt',
'pixel_height': pixel_height,
'pixel_width': pixel_width,
'timeout': 10,
})
self.assertRaises(ValueError, lambda: task.apply_async().get())
def test_quality_out_of_range(self):
for quality in [-1, 0, 101]:
task = generate_preview_jpg.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': '/dev/null',
'output_fs_url': self.OUTPUT_FS_URL,
'output_file': 'jpg',
'mime_type': 'application/vnd.oasis.opendocument.text',
'extension': '.odt',
'pixel_height': 800,
'pixel_width': 800,
'quality': quality,
'timeout': 10,
})
self.assertRaises(ValueError, lambda: task.apply_async().get())
def test_compression_out_of_range(self):
for compression in [-1, 0, 10]:
task = generate_preview_png.clone(
kwargs={
'input_fs_url': 'osfs:///',
'input_file': '/dev/null',
'output_fs_url': self.OUTPUT_FS_URL,
'output_file': 'png',
'mime_type': 'application/vnd.oasis.opendocument.text',
'extension': '.odt',
'pixel_height': 800,
'pixel_width': 800,
'compression': compression,
'timeout': 10,
})
self.assertRaises(ValueError, lambda: task.apply_async().get())
if __name__ == '__main__':
unittest.main()
|
python
|
from .base import BaseDocument
import markdown
import html_parser
class MarkdownDocument(BaseDocument):
def __init__(self, path):
self.path = path
def read(self):
self.document = open(self.path, "r")
text = self.document.read()
html = markdown.markdown(text)
return html_parser.html_to_text(html)
def close(self):
self.document.close()
super().close()
|
python
|
while True:
try:
string = input()
print(string)
except EOFError:
break
|
python
|
# Eerst met PCA. Deze resulteert nu in 3 coponenten, waarvoor je dus twee plot nodig hebt
pca = PCA()
pcas = pca.fit_transform(X)
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(121)
plt.scatter(pcas[:, 0], pcas[:, 1], c=color, cmap=plt.cm.Spectral)
ax = fig.add_subplot(122)
plt.scatter(pcas[:, 2], pcas[:, 1], c=color, cmap=plt.cm.Spectral);
print("PCA vindt compenenten die de S projecteren en die loodrecht van boven op de S kijken.")
print("Dit helpt je verder weinig.....")
# Dan een poging met IsoMap en t-SNE
from sklearn.manifold import Isomap, TSNE
import time
# Initialiseer vast een plot
fig = plt.figure(figsize=(12, 8))
t0 = time.time()
# Het initialisren, fitten en transformeren kan ook in 1 regel!
# Gebruik n_components=2 als je twee dimensies wilt!
Y = Isomap(n_components=2).fit_transform(X)
# Onderstaande drie regels zouden equivalent zijn aan de regel hierboven:
# mapper = Isomap(n_neighbors=n_neighbors, n_components=n_components)
# mapper.fit(X)
# Y = mapper.transform(X)
t1 = time.time()
ax = fig.add_subplot(121)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("Isomap (%.2g sec)" % (t1 - t0))
t0 = time.time()
#t-SNE heeft meerdere hyperparameters, hier kun je mee spelen tot je blij bent!
# Gebruik n_components=2 als je twee dimensies wilt!
Y = TSNE(n_components=2, n_iter=2000).fit_transform(X)
t1 = time.time()
ax = fig.add_subplot(122)
plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral)
plt.title("t-SNE (%.2g sec)" % (t1 - t0))
|
python
|
# Copyright (c) 2019 Dan Ryan
# MIT License <https://opensource.org/licenses/mit>
from __future__ import absolute_import, unicode_literals
import collections
import csv
import io
import pathlib
import sqlite3
import tempfile
import uuid
from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union
import pandas as pd
import sqlparse
from airflow.exceptions import AirflowException
from airflow.hooks.base_hook import BaseHook
from simple_salesforce.api import Salesforce, exception_handler
class StreamingSalesforce(Salesforce):
def query_streaming(self, query, include_deleted=False, **kwargs):
url = self.base_url + ("queryAll/" if include_deleted else "query/")
params = {"q": query}
# `requests` will correctly encode the query string passed as `params`
return self._call_salesforce(
"GET", url, name="query", params=params, stream=True, **kwargs
)
def query_more_streaming(
self,
next_records_identifier,
identifier_is_url=False,
include_deleted=False,
**kwargs,
):
if identifier_is_url:
# Don't use `self.base_url` here because the full URI is provided
url = f"https://{self.sf_instance}{next_records_identifier}"
else:
endpoint = "queryAll" if include_deleted else "query"
url = f"{self.base_url}{endpoint}/{next_records_identifier}"
return self._call_salesforce("GET", url, name="query_more", stream=True, **kwargs)
class SalesforceHook(BaseHook):
"""
Salesforce connection hook.
..note:: Uses `simple_salesforce <https://github.com/simple-salesforce/>`_
with `requests <https://github.com/requests/requests>`_ for all connections
and queries to Salesforce.
"""
conn_name_attr = "conn_id"
default_conn_name = "salesforce_default"
def __init__(self, conn_id: str = "salesforce_default", *args, **kwargs) -> None:
self.conn_id: str = conn_id
self._args = args
self._kwargs = kwargs
self.connection = self.get_connection(self.conn_id)
self.session: Optional[StreamingSalesforce] = None
def login(self) -> "SalesforceHook":
"""
Establishes a connection to Salesforce.
:return: The current object instance
:rtype: SalesforceHook
"""
if isinstance(self.session, StreamingSalesforce):
return self
self.log.info(f"establishing connection to salesforce {self.connection.host!r}")
extras: Dict[str, str] = self.connection.extra_dejson
auth_type: str = extras.get("auth_type", "password")
auth_kwargs: Dict[str, Union[Optional[str], bool]] = {}
sandbox = extras.get("sandbox", False) in ("yes", "y", "1", 1, True)
if auth_type == "direct":
auth_kwargs = {
"instance_url": self.connection.host,
"session_id": self.connection.password,
}
else:
auth_kwargs = {
"username": self.connection.login,
"password": self.connection.password,
"security_token": extras.get("security_token"),
# "instance_url": self.connection.host,
"sandbox": sandbox,
}
self.log.info("Signing into salesforce...")
self.log.info(f"Using username: {self.connection.login} with sandbox={sandbox!s}")
self.session = StreamingSalesforce(**auth_kwargs) # type: ignore
if not self.session:
self.log.error(f"Failed connecting to salesforce: {self.session}")
raise AirflowException("Connection failure during salesforce connection!")
return self
def _parse_identifiers(self, sql: str) -> Tuple[str, List[str]]:
"""
Parses a sql statement for the first identifier list.
:param sql: The sql statement to parse
:type sql: str
:return: A tuple of the table name and the list of identifiers
:rtype: Tuple[str, List[str]]
"""
table_name: str = ""
columns: List[str] = []
statements: List[Any] = sqlparse.parse(sql)
# NOTE: only parses first full statement
for token in statements[0].tokens:
if isinstance(token, (sqlparse.sql.IdentifierList,)):
for identifier in token:
if (
isinstance(identifier, (sqlparse.sql.Identifier,))
or identifier.ttype in (sqlparse.tokens.Keyword,)
or identifier.value.lower() in ("type", "alias")
):
columns.append(identifier.value)
elif isinstance(token, (sqlparse.sql.Identifier,)) or token.ttype in (
sqlparse.tokens.Keyword,
):
table_name = token.value
return (table_name, columns)
def _extract_columns(self, sql: str, replace: Dict[str, str] = None) -> List[str]:
"""
Extracts column names from a given sql statement.
:param sql: The sql statement to parse
:type sql: str
:param replace: Character replacement for the column names, defaults to None
:param replace: Dict, optional
:return: The extracted column names
:rtype: List[str]
"""
if replace is None:
replace = {}
columns: List[str] = []
for field in self._parse_identifiers(sql)[-1]:
for (old, new) in replace.items():
field = field.replace(old, new)
columns.append(field)
return columns
def _extract_row(self, result: collections.OrderedDict) -> List[Any]:
"""
Extracts the rows from a given result from querying Salesforce.
:param result: The result to extract rows from
:type result: collections.OrderedDict
:return: A list of values
:rtype: list
"""
values: List[Any] = []
for (column, value) in result.items():
if column.lower() not in ("attributes",):
if isinstance(value, collections.OrderedDict):
values.extend(self._extract_row(value))
else:
values.append(value)
return values
def _get_results(self, sql: str, url: str = None, gen_uuid: str = None, **kwargs):
"""
Query the session instance for a response using the supplied sql or next url
:param str sql: Sql to execute
:param Optional[str] url: Url to visit, (default: None)
:param Optional[str] gen_uuid: UUID for the session, (default: None)
:return: A response instance from the session
:rtype: :class:`requests.PreparedResponse`
"""
assert self.session
if not url:
kwargs.update({"include_deleted": True})
return self.session.query_streaming(sql, **kwargs)
return self.session.query_more_streaming(url, identifier_is_url=True)
def _gen_result_frames(
self,
sql: str,
columns: List[str],
page: int = 1,
url: str = None,
gen_uuid: str = None,
include_headers: bool = False,
**kwargs,
) -> Optional[pd.DataFrame]:
"""
Generates results from executing a sql statement.
:param str sql: The sql statement to execute
:param Optional[str] url: The url of the next page of results (default: None)
:param Optional[str] gen_uuid: The session-specific UUID (default: None)
:return: A generator over the :class:`pd.DataFrame` instances from the results
:rtype: Generator
"""
if not gen_uuid:
gen_uuid = str(uuid.uuid4())
try:
df = pd.read_json(
self._get_results(sql, url=url, gen_uuid=gen_uuid).iter_lines(),
lines=True,
chunk=1,
)
except Exception:
df = pd.read_json(self._get_results(sql, url=url, gen_uuid=gen_uuid).text)
new_df = pd.DataFrame.from_records(
df.records.apply(lambda x: {k: v for k, v in x.items() if k != "attributes"})
)
df["page"] = page
if not df["records"].count():
return new_df
df["page"] = page
unique_records = df.done.unique()
try:
done = unique_records[0]
except IndexError:
done = True
if new_df.columns.size < 1:
new_df.columns = [c.replace(".", "_") for c in columns]
else:
new_df.columns = new_df.columns.str.lower()
joined_tables: Dict[str, Set[str]] = collections.defaultdict(set)
join_columns = [col for col in columns if "." in col]
for col in join_columns:
table, _, col_name = col.partition(".")
joined_tables[table].add(col_name)
for table in joined_tables:
table_df = new_df[table].apply(pd.Series)
table_df = table_df.drop("attributes", axis=1).add_prefix(f"{table}_")
table_df.columns = table_df.columns.str.lower()
new_df = pd.concat([new_df.drop([table], axis=1), table_df], axis=1)
columns = [c.replace(".", "_").lower() for c in columns]
new_df = new_df[columns]
yield new_df
next_url = None
if not done:
page += 1
next_url = df.nextRecordsUrl.unique()[0]
for next_df in self._gen_result_frames(
sql,
columns=columns,
url=next_url,
gen_uuid=gen_uuid,
include_headers=False,
):
yield next_df
def dump_sqlite(
self, sql: str, filepath: str, table: str, parameters: List[str], **kwargs
):
"""Dump the results of the supplied sql to the target sqlite database
:param str sql: Parameterized soql to use for querying
:param str filepath: Filepath to export results to
:param str table: The target table
:param List[str] parameters: Parameters to use as arguments to the soql
:return: A count of the rows written
:rtype: int
"""
if not self.session:
self.login()
if parameters is None:
parameters = []
if len(parameters) > 0:
sql = sql % tuple(parameters)
kwargs.update({"include_deleted": True})
columns = [col for col in self._extract_columns(sql)]
filepath = pathlib.Path(filepath).absolute().as_posix()
sqlite_conn = sqlite3.connect(filepath)
rows = 0
include_headers = True
for df in self._gen_result_frames(
sql, columns=columns, include_headers=include_headers, **kwargs
):
rows += len(df)
df.to_sql(
table, con=sqlite_conn, if_exists="append", chunksize=200, index=False
)
return rows
def dump_csv(
self,
sql: str,
filepath: str,
parameters: List[str],
include_headers: bool = True,
**kwargs,
) -> int:
"""Dump the results of the requested sql to CSV
:param str sql: Parameterized soql to use for querying
:param str filepath: Filepath to export results to
:param List[str] parameters: Parameters to use as arguments to the soql
:param bool include_headers: Whether to include headers in the output, defaults to True
:return: A count of the rows written
:rtype: int
"""
if not self.session:
self.login()
if parameters is None:
parameters = []
if len(parameters) > 0:
sql = sql % tuple(parameters)
kwargs.update({"include_deleted": True})
columns = [col for col in self._extract_columns(sql)]
temp_dir = tempfile.TemporaryDirectory(prefix="salesforce", suffix="csvs")
if not filepath:
tmpfile = tempfile.NamedTemporaryFile(
prefix="airflow",
suffix="salesforce.csv",
delete=False,
dir=temp_dir.name,
encoding="utf-8",
)
filepath = tmpfile.name
tmpfile.close()
rows = 0
for df in self._gen_result_frames(
sql,
columns=columns,
temp_dir=temp_dir,
temp_file=filepath,
include_headers=include_headers,
**kwargs,
):
rows += len(df)
df.to_csv(
filepath,
chunksize=200,
header=include_headers,
encoding="utf-8",
index=False,
mode="a",
)
if include_headers:
include_headers = False
return rows
def _gen_results(
self, sql: str, url: str = None, gen_uuid: str = None, **kwargs
) -> Generator[List[Any], None, None]:
"""
Generates results from executing a sql statement.
:param str sql: The sql statement to execute
:param Optional[str] url: The url of the next page of results (default: None)
:param Optional[str] gen_uuid: The session-specific UUID (default: None)
:return: A generator which resulting rows from executing the given sql
:rtype: Generator
"""
# create generation uuid to show what logs are part of the same process
if not gen_uuid:
gen_uuid = str(uuid.uuid4())
results = self._get_results(sql, url=url, gen_uuid=gen_uuid)
if not results:
yield []
next_url = None
for row in results.get("records", []):
yield self._extract_row(row)
if not results["done"]:
next_url = results.get("nextRecordsUrl", None)
for row in self._gen_results(sql, url=next_url, gen_uuid=gen_uuid):
yield row
def query(
self,
sql: str,
parameters: List[str] = None,
include_headers: bool = True,
**kwargs,
) -> Generator[List[Any], None, None]:
"""
Generates the results from executing a given sql statement
:param sql: The given sql statement to execute
:type sql: str
:param parameters: The parameters to use for the sql, defaults to None
:type parameters: List[str], optional
:param include_headers: True to include columns as the first result,
defaults to True
:type include_headers: bool, optional
:return: A generator which iterates over results from executing the givne sql
:rtype: Generator
"""
if parameters is None:
parameters = []
if len(parameters) > 0:
sql = sql % tuple(parameters)
kwargs.update({"include_deleted": True})
self.log.info(f"executing query {sql!r}")
if include_headers:
yield self._extract_columns(sql, replace={".": "_"})
self.login()
for row in self._gen_results(sql, **kwargs):
yield row
def export(
self,
sql: str,
filepath: str,
parameters: List[str] = None,
include_headers: bool = True,
**kwargs,
) -> str:
"""
Exports the result of executing sql to a given filepath.
:param sql: The sql statement to execute
:type sql: str
:param filepath: The filepath to export results to
:type filepath: str
:param parameters: The parameters to use for the sql, defaults to None
:type parameters: List[str], optional
:param include_headers: True to include columns as the first result,
defaults to True
:type include_headers: bool, optional
:return: The resulting exported filepath
:rtype: str
"""
self.log.info(f"writing results of sql {sql!r} to {filepath!r}")
if not parameters:
parameters = []
rowcount = self.dump_csv(
sql=sql, filepath=filepath, parameters=parameters, include_headers=True
)
self.log.info(f"*** TASK COMPLETE ***: Wrote {rowcount!s} rows!")
return filepath
|
python
|
import abc
import flask
from flask import jsonify, make_response
from ..app.swagger_schema import Resource, Schema
from ..extensions.audit import AuditLog
from ..logger.app_loggers import logger
from ..swagger import AfterResponseEventType, BeforeRequestEventType, BeforeResponseEventType
class ResourceResponse:
""" """
response = {}
headers: dict = {}
http_code = 200
audit = None
def make_audit_log(self, **args):
"""
:param **args:
"""
self.audit = AuditLog(**args)
def make_response(self, as_json: bool = True):
"""
:param as_json: bool: (Default value = True)
"""
data = jsonify(self.response) if as_json else self.response
response = make_response(data, self.http_code)
if self.headers:
for key, value in self.headers.items():
response.headers[key] = value
response.audit = self.audit
return response
def for_json(self) -> dict:
""" """
return {
"response": self.response,
"headers": self.headers,
"http_code": self.http_code,
}
class AutomaticResource(Resource):
""" """
route = "/"
endpoint = "root"
_swagger_schema: Schema = None
before_request: BeforeRequestEventType = None
before_response: BeforeResponseEventType = None
db_table: dict = None
def __init__(
self,
before_request: BeforeRequestEventType = None,
before_response: BeforeResponseEventType = None,
after_response: AfterResponseEventType = None,
):
self.before_response = before_response
self.before_request = before_request
if after_response:
@flask.after_this_request
def response_processor(response):
"""
:param response:
"""
after_response.on_event(**{"resource": self, "response": response})
return response
@abc.abstractmethod
def request(self, **args) -> ResourceResponse:
"""
:param **args:
"""
pass
@abc.abstractmethod
def validate_request(self, **args):
"""
:param **args:
"""
pass
def process_request(self, **args):
"""
:param **args:
"""
logger.debug("Request start", extra=args)
before_response_event = None
before_request_event = None
request_args = {**args, **{"before_request_event": before_request_event, "before_response_event": before_response_event}}
if self.before_request:
logger.debug("Before request event trigger", extra=request_args)
before_request_event = self.before_request.on_event(**{"resource": self}, **request_args)
request_args["before_request_event"] = before_request_event
logger.debug("Validate request event trigger", extra={**request_args})
validation_output = self.validate_request(**request_args)
request_args["validation_output"] = validation_output
response = self.request(**request_args)
if self.before_response:
logger.debug("Before response event trigger", extra=request_args)
before_response_event = self.before_response.on_event(
**{
"resource": self,
"response": response,
},
**request_args,
)
request_args["before_response_event"] = before_response_event
request_args["response"] = response
logger.debug("Response finish", extra=request_args)
return response.make_response()
|
python
|
# -*- coding: utf-8 -*-
"""
Module for common converters settings and functions
"""
import os
from config import log, root_directory, DEFAULT_LANGUAGE
def db_get_statistic(models_list):
"""
:return:
"""
log.info("Start to get statistic of imported items:")
[log.info("%s: %s", model.__name__, model.query.count())
for model in models_list if model.__load_to_db__]
log.info("Finish to get statistic of imported items\n")
def db_get_property_info(cls, prop: str):
"""
:param cls:
:param prop:
:return:
"""
objects_str = [getattr(obj, prop) for obj in cls.query.all()]
print("NUMBER OF OBJECTS: %s" % len(objects_str))
maxi = max(objects_str, key=len)
print("MAX LENGTH: %s (for '%s')" % (len(maxi), maxi))
mini = min(objects_str, key=len)
print("MIN LENGTH: %s (for '%s')" % (len(mini), mini))
|
python
|
from django.conf.urls import url
from django.contrib.auth.views import logout
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^change_city/$', views.change_city, name='change_city'),
url(r'^parse/$', views.parse, name='parse'),
url(r'^logout/$', logout, {'next_page': '/'}, name='logout'),
url(r'^login/$', views.auth, name='login'),
url(r'^registration/$', views.registration, name='registration'),
]
|
python
|
max_n1 = int(input())
max_n2 = int(input())
max_n3 = int(input())
for num1 in range(2, max_n1 + 1, 2):
for num2 in range(2, max_n2 + 1):
for num3 in range(2, max_n3 + 1, 2):
if num2 == 2 or num2 == 3 or num2 == 5 or num2 == 7:
print(f"{num1} {num2} {num3}")
|
python
|
from typing import Callable, Dict, Tuple, Any
__all__ = ['HandlerResponse', 'Handler']
HandlerResponse = Tuple[int, Dict[str, str], str]
Handler = Callable[[Dict[str, Any], Dict[str, str]], HandlerResponse]
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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
#
# https://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 argparse
import pwnlib
import challenge_pb2
import struct
import sys
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.asymmetric import ec
CHANNEL_CIPHER_KDF_INFO = b"Channel Cipher v1.0"
CHANNEL_MAC_KDF_INFO = b"Channel MAC v1.0"
IV = b'\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff'
class AuthCipher(object):
def __init__(self, secret, cipher_info, mac_info):
self.cipher_key = self.derive_key(secret, cipher_info)
self.mac_key = self.derive_key(secret, mac_info)
def derive_key(self, secret, info):
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=16,
salt=None,
info=info,
)
return hkdf.derive(secret)
def encrypt(self, iv, plaintext):
cipher = Cipher(algorithms.AES(self.cipher_key), modes.CTR(iv))
encryptor = cipher.encryptor()
ct = encryptor.update(plaintext) + encryptor.finalize()
h = hmac.HMAC(self.mac_key, hashes.SHA256())
h.update(iv)
h.update(ct)
mac = h.finalize()
out = challenge_pb2.Ciphertext()
out.iv = iv
out.data = ct
out.mac = mac
return out
def handle_pow(tube):
raise NotImplemented()
def read_message(tube, typ):
n = struct.unpack('<L', tube.recvnb(4))[0]
buf = tube.recvnb(n)
msg = typ()
msg.ParseFromString(buf)
return msg
def write_message(tube, msg):
buf = msg.SerializeToString()
tube.send(struct.pack('<L', len(buf)))
tube.send(buf)
def curve2proto(c):
assert(c.name == 'secp224r1')
return challenge_pb2.EcdhKey.CurveID.SECP224R1
def key2proto(key):
assert(isinstance(key, ec.EllipticCurvePublicKey))
out = challenge_pb2.EcdhKey()
out.curve = curve2proto(key.curve)
x, y = key.public_numbers().x, key.public_numbers().y
out.public.x = x.to_bytes((x.bit_length() + 7) // 8, 'big')
out.public.y = y.to_bytes((y.bit_length() + 7) // 8, 'big')
return out
def proto2key(key):
assert(isinstance(key, challenge_pb2.EcdhKey))
assert(key.curve == challenge_pb2.EcdhKey.CurveID.SECP224R1)
curve = ec.SECP224R1()
x = int.from_bytes(key.public.x, 'big')
y = int.from_bytes(key.public.y, 'big')
public = ec.EllipticCurvePublicNumbers(x, y, curve)
return ec.EllipticCurvePublicKey.from_encoded_point(curve, public.encode_point())
def run_session(port):
tube = pwnlib.tubes.remote.remote('127.0.0.1', port)
print(tube.recvuntil('== proof-of-work: '))
if tube.recvline().startswith(b'enabled'):
handle_pow()
server_hello = read_message(tube, challenge_pb2.ServerHello)
server_key = proto2key(server_hello.key)
print(server_hello)
private_key = ec.generate_private_key(ec.SECP224R1())
client_hello = challenge_pb2.ClientHello()
client_hello.key.CopyFrom(key2proto(private_key.public_key()))
print(client_hello)
write_message(tube, client_hello)
shared_key = private_key.exchange(ec.ECDH(), server_key)
print(shared_key)
channel = AuthCipher(shared_key, CHANNEL_CIPHER_KDF_INFO, CHANNEL_MAC_KDF_INFO)
msg = challenge_pb2.SessionMessage()
msg.encrypted_data.CopyFrom(channel.encrypt(IV, b'hello'))
write_message(tube, msg)
print('msg:', msg)
reply = read_message(tube, challenge_pb2.SessionMessage)
print('reply:', reply)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--port', metavar='P', type=int, default=1337, help='challenge #port')
args = parser.parse_args()
run_session(args.port)
return 0
if __name__ == '__main__':
sys.exit(main())
|
python
|
import sys
# cyheifloader allows specifying the path to heif.dll on Windows
# using the environment variable LIBHEIF_PATH.
from cyheifloader import cyheif
from PIL import Image
from PIL.ExifTags import TAGS
# Print libheif version
print(f'LibHeif Version: {cyheif.get_heif_version()}')
file_name = sys.argv[1] if len(sys.argv) > 1 else 'sample.heic'
file_name = str.encode(file_name, 'UTF-8')
print(f'Processing {file_name}')
# Print EXIF data from HEIF file
print('Getting EXIF Data from EXIF')
exif = cyheif.get_exif_data(file_name)
exif_readable = {TAGS.get(k):v for (k,v) in exif.items()}
print(exif_readable)
# Get pillow image from HEIF file
print('Getting Pillow Image from HEIC')
pil_img = cyheif.get_pil_image(file_name)
pil_img_exif = pil_img.getexif()
# Resize pillow image
pil_img = pil_img.resize((pil_img.width // 32, pil_img.height // 32))
print('showing image')
pil_img.show()
# Save pillow image as jpeg
print('Saving Pillow Image as JPEG')
pil_img.save('sample.jpg', 'JPEG', exif=pil_img.getexif().tobytes())
pil_img.save('sample.png', 'PNG', exif=pil_img.getexif().tobytes())
# Update EXIF data in input HEIF file and save it to output HEIF file
print('Updating EXIF data in HEIC')
pil_img_exif[0x010F] = 'A test image for CyHeif'
cyheif.write_exif_data(file_name, b'sample_exif.heic', pil_img_exif)
# Write pillow image to output HEIF file
print('Writing Pillow Image to HEIC')
cyheif.write_pil_image(pil_img, b'sample_from_pil.heic')
|
python
|
from bibliopixel.animation.matrix import Matrix
try:
from websocket import create_connection
except ImportError:
create_connection = None
import threading
import numpy as np
WS_FRAME_WIDTH = 640
WS_FRAME_HEIGHT = 480
WS_FRAME_SIZE = WS_FRAME_WIDTH * WS_FRAME_HEIGHT
def clamp(v, _min, _max):
return max(min(v, _max), _min)
def lerp(n, low, high):
return clamp((n - low) / (high - low), 0.0, 1.0)
def rebin(a, shape):
sh = shape[0], a.shape[0] // shape[0], shape[1], a.shape[1] // shape[1]
return a.reshape(sh).mean(-1).mean(1)
def thread_lock():
e = threading.Event()
e.lock = e.clear
e.release = e.set
e.is_released = e.is_set
e.release()
return e
class ws_thread(threading.Thread):
def __init__(self, server):
super().__init__()
self.setDaemon(True)
self._stop = threading.Event()
self._reading = thread_lock()
self.dt = np.dtype(np.uint16)
self.dt = self.dt.newbyteorder('<')
self._data = [np.zeros(WS_FRAME_SIZE, self.dt),
np.zeros(WS_FRAME_SIZE, self.dt)]
self._buf = False
self.ws = create_connection("ws://{}/".format(server))
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def get_frame(self):
self._reading.lock()
d = np.copy(self._data[0 if self._buf else 1])
self._reading.release()
return d
def run(self):
while not self.stopped():
d = self.ws.recv()
d = np.frombuffer(d, dtype=self.dt)
self._reading.wait()
self._data[1 if self._buf else 0] = d
self._buf = not self._buf
self.ws.close()
class KimotionShader(object):
def __init__(self, anim):
self.anim = anim
self.width = self.anim.width
self.height = self.anim.height
self.led = self.anim._led
class SandStorm(KimotionShader):
def __init__(self, anim, min_z=440, max_z=1100,
near_color=[229, 107, 0], near_z=760,
mid_color=[40, 0, 114],
far_color=[2, 2, 12], far_z=1100):
super().__init__(anim)
self.min_z = float(min_z)
self.max_z = float(max_z)
self.near_color = np.array(near_color)
self.near_z = float(near_z)
self.mid_color = np.array(mid_color)
self.mid_z = ((self.max_z + self.near_z) / 2.0)
self.far_color = np.array(far_color)
self.far_z = float(far_z)
self.z_colors = np.array([self.z_color(z) for z in range(0, int(Kimotion.max_depth) + 1)]).tolist()
def z_color(self, z):
z = float(z)
alpha = 1.0
if z <= self.mid_z:
ns = lerp(z, self.near_z, self.mid_z)
color = (1.0 - ns) * self.near_color + ns * self.mid_color
else: # z must be between self.mid_z and FAR_Z
fs = lerp(z, self.mid_z, self.far_z)
color = (1.0 - fs) * self.mid_color + fs * self.far_color
alpha = 1.0 - lerp(z, self.min_z, self.max_z)
if z <= -self.min_z:
alpha = 0.0
# gl_FragColor = vec4(color, alpha) * texture2D( texture, gl_PointCoord )
return (color * alpha).astype(np.uint8).tolist()
def render(self, frame):
for y in range(self.height):
for x in range(self.width):
c = self.z_colors[frame[y][x]]
self.led.set(x, y, c)
class Kimotion(Matrix):
max_depth = 1200.0
shaders = {
"Sandstorm": SandStorm
}
def __init__(self, layout, server="localhost:1337", mirror=True, crop=True, shader="Sandstorm", **kwargs):
super().__init__(layout, **kwargs)
self.server = server
self.mirror = mirror
self.crop = crop
self.fw = WS_FRAME_WIDTH
self.fh = WS_FRAME_HEIGHT
# TODO: Implement something to actually use this
# Right now needs 4:3 aspect display
self.frame_aspect = (float(WS_FRAME_WIDTH) / float(WS_FRAME_HEIGHT))
self.aspect = (float(self.width) / float(self.height))
self.resize_box = (self.width, self.height)
self.crop_box = (0, 0, self.width, self.height)
if self.frame_aspect > self.aspect:
self.resize_box[0] = int(self.height * self.frame_aspect)
half = (self.resize_box[0] - self.width) / 2
self.crop_box[0] = half
self.crop_box[2] = self.resize_box[0] - half
elif self.frame_aspect < self.aspect:
self.resize_box[1] = int(self.width / self.aspect)
half = (self.resize_box[1] - self.height) / 2
self.crop_box[1] = half
self.crop_box[3] = self.resize_box[1] - half
self.shader = Kimotion.shaders[shader](self, **kwargs)
self._ws_thread = ws_thread(self.server)
self._ws_thread.start()
def _exit(self, type, value, traceback):
self._ws_thread.stop()
def step(self, amt=1):
d = self._ws_thread.get_frame()
d = d.reshape(WS_FRAME_HEIGHT, WS_FRAME_WIDTH)
if self.mirror:
d = np.fliplr(d)
d = rebin(d, (self.height, self.width)).astype(np.uint16)
self.shader.render(d)
|
python
|
import os
import json
from pathlib import Path
import yaml
import unittest
import click
from click.testing import CliRunner
os.environ['QA_TESTING'] = 'true'
# Missing:
# - tests with --share
# - tests with CI=ON CI_COMMIT=XXXXXX
class TestQaCli(unittest.TestCase):
@classmethod
def setUpClass(self):
self.previous_cwd = os.getcwd()
root_repo = Path(__file__).resolve().parent.parent
os.chdir(root_repo / 'qaboard/sample_project')
# we create some files...
os.system("mkdir -p cli_tests/dir; touch cli_tests/a.jpg; touch cli_tests/b.jpg; touch cli_tests/dir/c.jpg")
database = str(Path())
images = {'images': {
"globs": ['*.jpg'],
"inputs": ['cli_tests'],
"database": {"linux": database, "windows": database}
}
}
# TODO: use a temp file?
with Path('image.batches.yaml').open('w') as f:
f.write(yaml.dump(images))
os.environ['QA_DATABASE'] = database
os.environ['QA_OFFLINE'] = 'true'
os.environ['QA_STORAGE'] = str(root_repo.resolve())
@classmethod
def TearDownClass(self):
os.chdir(self.previous_cwd)
def setUp(self):
from importlib import reload
import qaboard
qaboard = reload(qaboard)
def qa_(*argv):
runner = CliRunner(mix_stderr=False)
result = runner.invoke(qaboard.qa, argv, obj={}, auto_envvar_prefix='QA', color=False)
if result.exception:
print("EXCEPTION: ", result.exception)
if result.exc_info and result.exception:
import traceback
exc_type, exc_value, exc_traceback = result.exc_info
click.secho(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)), fg='red')
# traceback.print_exception(exc_type, exc_value, exc_traceback)
# traceback.print_tb(exc_traceback)
if result.exit_code:
print("EXIT CODE:", result.exit_code)
print('stdout:', result.stdout)
try:
print('stderr:', result.stderr)
except:
pass
return result
self.qa = qa_
def test_help(self):
result = self.qa('--help')
assert result.exit_code == 0
assert 'Usage:' in result.output
def test_run(self):
result = self.qa('run', '-i', 'cli_tests/a.jpg', 'echo "{input_path} => {output_dir}"')
assert result.exit_code == 0
assert 'a.jpg =>' in result.output
assert "'is_failed': False" in result.output
result = self.qa('run', '-i', '/dev/null', 'echo "{input_path} => {output_dir}"')
assert result.exit_code == 0
assert '/dev/null =>' in result.output
assert "'is_failed': False" in result.output
def test_get(self):
result = self.qa('get', 'commit_id')
assert result.exit_code == 0
def test_batch(self):
result = self.qa('--dryrun', 'batch', 'cli_tests')
assert result.exit_code == 0
result = self.qa('--dryrun', 'batch', '/dev/null')
assert result.exit_code == 0
def test_batch_list(self):
result = self.qa('--dryrun', 'batch', '--batches-file', 'image.batches.yaml', 'images', '--list')
tests = json.loads(result.stdout)
assert len(tests) == 3
assert result.exit_code == 0
def test_batch_list_output_dirs(self):
result = self.qa('--dryrun', 'batch', '--batches-file', 'image.batches.yaml', 'images', '--list-output-dirs')
output_dirs = result.stdout.splitlines()
assert len(output_dirs) == 3
assert result.exit_code == 0
def test_batch_list_inputs(self):
result = self.qa('--dryrun', 'batch', '--batches-file', 'image.batches.yaml', 'images', '--list-inputs')
output_dirs = result.stdout.splitlines()
assert len(output_dirs) == 3
assert result.exit_code == 0
def test_runner_local(self):
result = self.qa('batch', '--batches-file', 'image.batches.yaml', 'images', '--runner=local', 'echo "{input_path} => {output_dir}"')
print('stdout:', result.stdout)
print('stderr:', result.stderr)
assert result.exit_code == 0
# we test with --share, but really being offline is a problem here..
result = self.qa('--share', 'batch', '--batches-file', 'image.batches.yaml', 'images', '--runner=local', 'echo "{input_path} => {output_dir}"')
print('stdout:', result.stdout)
print('stderr:', result.stderr)
assert result.exit_code == 0
@unittest.skip("Not tested in the OSS version yet")
def test_runner_lsf(self):
result = self.qa('batch', '--batches-file', 'image.batches.yaml', 'images', '--runner=lsf', 'echo "{input_path} => {output_dir}"')
assert result.exit_code == 0
# we also test subprojects
os.chdir('subproject')
result = self.qa('batch', '--batches-file', 'image.batches.yaml', 'images', '--runner=local', 'echo "{input_path} => {output_dir}"')
@unittest.skip("FIXME: decide what to do by default with artifacts in the OSS version")
def test_save_artifacts(self):
result = self.qa('save-artifacts')
print('stdout:', result.stdout)
# print('stderr:', result.stderr)
assert result.exit_code == 0
# => Gitlab/QA-Board: 404: Project not found
def test_init(self):
import tempfile
prev = os.getcwd()
with tempfile.TemporaryDirectory() as tmp_dir:
os.chdir(tmp_dir)
assert not os.system('git init')
assert not os.system('echo OK > file')
assert not os.system('git add file')
assert not os.system('git commit -m "first commit"')
# assert not os.system('git remote add origin git@gitlab-srv:common-infrastructure/qaboard.git')
# assert not os.system('git remote add origin [email protected]:Samsung/qaboard.git')
assert not os.system('git remote add origin https://github.com/Samsung/qaboard.git')
assert not os.system('qa init')
assert not os.system('qa get project')
os.chdir(prev)
@unittest.skip("tendency to fail for no reason")
def test_batch_lsf_interrupt(self):
# https://stackoverflow.com/a/59303823/5993501
from multiprocessing import Queue, Process
from threading import Timer
from time import sleep
from os import kill, getpid
from signal import SIGINT
q = Queue()
# Running out app in SubProcess and after a while using signal sending
# SIGINT, results passed back via channel/queue
def background():
Timer(2, lambda: kill(getpid(), SIGINT)).start()
result = self.qa('batch', '--batches-file', 'image.batches.yaml', 'images', '--runner=lsf', 'echo "{input_path} => {output_dir}"')
q.put(('exit_code', result.exit_code))
q.put(('output', result.output))
p = Process(target=background)
p.start()
results = {}
while p.is_alive():
sleep(0.1)
else:
while not q.empty():
key, value = q.get()
results[key] = value
# print(results['output'])
assert "Aborted." in results['output']
# we could also check for "bkill" if we run with QA_BATCH_VERBOSE=1
if __name__ == '__main__':
unittest.main()
|
python
|
ASCII_MAZE = """
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
S | | | | | |
+-+ + +-+-+ + + + + +-+ + + +-+-+-+ + + +
| | | | | | | | | | | | | | |
+ + +-+ + +-+ + +-+-+ +-+-+ +-+-+ + + + +
| | | | | | | |
+-+-+-+-+-+ +-+-+ +-+ +-+-+ +-+-+-+-+-+ +
| | | | | | | | | |
+ +-+ + +-+-+ + +-+ +-+-+ + + + + +-+-+ +
| | | | | | | | | | | |
+ +-+-+ + +-+ +-+-+-+ + +-+-+ +-+ + +-+-+
| | | | | | | | | |
+-+-+-+-+-+ +-+ + + + +-+-+ + + + +-+-+ +
| | | | | | | | | | |
+ +-+-+ + +-+ +-+ +-+ + +-+-+ + +-+-+-+-+
| | | | | | | | | | |
+ + + +-+-+ +-+ +-+ + +-+ +-+-+-+-+ + + +
| | | | | | | | | | | |
+-+-+ + + + + +-+-+ + + +-+ +-+-+ +-+-+ +
| | | | | | | | | |
+-+-+-+ + + +-+-+-+-+-+-+ +-+ +-+-+ + + +
| | | | | | | | |
+ +-+-+-+-+-+ + +-+-+-+-+-+ +-+ + +-+-+ +
| | | | | | | | | | |
+ +-+ + +-+ + +-+ +-+ + +-+ + +-+-+-+-+-+
| | | | | | | | | | | |
+ + +-+ + +-+ + +-+ + +-+ +-+-+-+ + +-+ +
| | | | | | | | | | | |
+ + + +-+-+ + +-+ + + +-+-+-+ +-+-+-+ +-+
| | | | | | | | |
+ +-+ + + + + + +-+-+ + +-+-+-+-+-+ +-+-+
| | | | | | | | | | |
+-+-+ + +-+-+ +-+-+-+-+ + + + +-+ +-+-+ +
| | | | | | | | | | |
+ +-+-+-+-+-+-+ + +-+ + + +-+-+ +-+ + +-+
| | | | | | | | | |
+ + +-+-+ + + +-+-+ +-+-+ +-+ + + +-+-+ +
| | | | | | | | | | |
+-+-+ + +-+ +-+ +-+ + +-+-+-+-+-+ + + + +
| | | | | | E
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
"""
PATH, START, EXIT, VISITED, SOLUTION = " SE.o"
class Maze():
def __init__(self, ascii_maze):
self.maze = [list(row) for row in ascii_maze.splitlines()]
self.start_y = [row.count(START) for row in self.maze].index(1)
self.start_x = self.maze[self.start_y].index(START)
def __repr__(self):
return "\n".join("".join(row) for row in self.maze)
def solve(self, x=None, y=None):
if x is None:
x, y = self.start_x, self.start_y
if self.maze[y][x] in (PATH, START):
self.maze[y][x] = VISITED
if (self.solve(x + 1, y) or self.solve(x - 1, y) or
self.solve(x, y + 1) or self.solve(x, y - 1)):
self.maze[y][x] = SOLUTION
return True
elif self.maze[y][x] == EXIT:
return True
return False
if __name__ == '__main__':
maze = Maze(ASCII_MAZE)
if maze.solve():
print(maze)
else:
print("No solution")
|
python
|
from Instruments.devGlobalFunctions import devGlobal
class CounterClass(devGlobal):
# Human readable name for the gui, note: Needs to be unique
name = "Counter"
def __init__(self, *args):
devGlobal.__init__(self, *args)
self.func_list = self.func_list + [
self.Ch1GetCounts,
self.Ch2GetCounts,
self.Ch1SetInputImp,
self.Ch2SetInputImp,
self.Ch1InputThreshold,
self.Ch2InputThreshold,
self.Ch1setManualOrAutoTrigger,
self.Ch2setManualOrAutoTrigger,
self.dispCh1plusCh2,
self.dispCh1divCh2,
self.Ch1Pause,
self.Ch2Pause,
self.Ch1SetCountTime,
self.Ch2SetCountTime,
]
self.label_list = self.label_list + [
'Ch1 Get\nCounts', #1
'Ch2 Get\nCounts', #2
'Ch1 Set\nInput Imp', #3
'Ch2 Set\nInput Imp', #4
'Ch1 Set Input\nThresh', #5
'Ch2 Set Input\nThresh', #6
'Ch1 Man/Auto\nTrigger', #7
'Ch2 Man/Auto\nTrigger', #8
'Display\nCh1 + Ch2', #9
'Display\nCh1 / Ch2', #10
'Ch1 Pause', #11
'Ch2 Pause', #12
'Ch1 Set\nCount Time', #13
'Ch2 Set\nCount Time' #14
]
def Ch1GetCounts(self, event):
StringInit = "Get Counts Ch1 from "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2GetCounts(self, event):
StringInit = "Get Counts Ch2 from "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch1SetInputImp(self, event):
param = self.GetParamVector()
StringInit = "Set Ch1 Input Impedance to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2SetInputImp(self, event):
param = self.GetParamVector()
StringInit = "Set Ch2 Input Impedance to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch1InputThreshold(self, event):
param = self.GetParamVector()
StringInit = "Set Ch1 Input Threshold to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2InputThreshold(self, event):
param = self.GetParamVector()
StringInit = "Set Ch2 Input Threshold to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch1setManualOrAutoTrigger(self, event):
param = self.GetParamVector()
StringInit = "Set Ch1 Trigger to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2setManualOrAutoTrigger(self, event):
param = self.GetParamVector()
StringInit = "Set Ch2 Trigger to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def dispCh1plusCh2(self, event):
StringInit = "Get Ch1+Ch2 from "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def dispCh1divCh2(self, event):
StringInit = "Get Ch1/Ch2 from "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch1Pause(self, event):
StringInit = "Pause Ch1 Counts on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2Pause(self, event):
StringInit = "Pause Ch2 Counts on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch1SetCountTime(self, event):
param = self.GetParamVector()
StringInit = "Set Ch1 Count Time to " + param[2] + " on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
def Ch2SetCountTime(self, event):
param = self.GetParamVector()
StringInit = "Set Ch2 Count Time to " + param[2] + "on "
self.cmdString = StringInit + self.com_type + self.address
print(self.cmdString)
# IMPORTANT Don't forget this line (and remember to use the class name above)
instrument = CounterClass
|
python
|
from . import config
from .genome import Genome
class Population():
def __init__(self, default=True):
self.genomes = []
self.speciesRepresentatives = []
self.species = 0
if default:
self.initialize()
def initialize(self):
for i in range(config.populationSize):
self.genomes.append(Genome())
|
python
|
from __future__ import print_function
import setuptools
import sys
# Convert README.md to reStructuredText.
if {'bdist_wheel', 'sdist'}.intersection(sys.argv):
try:
import pypandoc
except ImportError:
print('WARNING: You should install `pypandoc` to convert `README.md` '
'to reStructuredText to use as long description.',
file=sys.stderr)
else:
print('Converting `README.md` to reStructuredText to use as long '
'description.')
long_description = pypandoc.convert('README.md', 'rst')
setuptools.setup(
name='glamkit-collections',
use_scm_version={'version_scheme': 'post-release'},
author='Interaction Consortium',
author_email='[email protected]',
url='https://github.com/ixc/glamkit-collections',
description='Boilerplate for modelling collections of collecting institutions.',
long_description=locals().get('long_description', ''),
packages=setuptools.find_packages(),
include_package_data=True,
install_requires=[
'django-icekit',
'django-object-actions>=0.7', # See: https://github.com/crccheck/django-object-actions/issues/45
'Django>=1.7',
'pyparsing',
'unidecode',
'django-admin-sortable2',
'edtf>=2.0.1',
],
extras_require={
'api': [
'djangorestframework',
'django-rest-swagger',
'djangorestframework-filters',
'djangorestframework-queryfields',
],
'colors': [
'webcolors==1.5',
'colormath==2.1.1',
'colorweave==0.1+0.ce27c83b4e06a8185531538fa11c18c5ea2c1aba.ixc',
],
},
setup_requires=['setuptools_scm'],
)
|
python
|
# Module to describe all the potential commands that the Renogy Commander
# supports.
#
# Author: Darin Velarde
#
#
from collections import namedtuple
# I typically don't like import * but I actually need every symbol from
# conversions.
from conversions import *
# Register
# ** immutable data type **
# Represents a queryable register/coil/statistical parameter/etc.
class Register(namedtuple("Register", ["name",
"desc",
"unit",
"times",
"numWords"])):
"""
@type name: string
@param name: The display text of the register.
@type desc: string
@param desc: A longer description for use in a GUI or similar use-case.
@type unit: function pointer
@param unit: A function pointer that will do the conversion from bytes to
the readable value.
@type times: int
@param times: The multiplier that was used when setting this value.
@type numWords: int
@param numWords: The number of 16 bit words (registers) to read.
"""
__slots__ = ()
# For clarity I am letting these lines be long. I am less concerned with brevity
# here. Right or wrong, that's the choice I made.
REGISTERS = {
# Coils
2: Register("Manual control the load", "When the load is manual mode, 1-manual on, 0 -manual off", MANUALMODE, 1, 1),
5: Register("Enable load test mode", "1 Enable, 0 Disable(normal)", ENABLETEST, 1, 1),
6: Register("Force the load on/off", "1 Turn on, 0 Turn off (used for temporary test of the load)", OFFON, 1, 1),
0x2000: Register("Over temperature inside the device", "Over temperature inside device", OVERTEMP, 1, 1),
0x200C: Register("Night", "1-Night, 0-Day", DAYNIGHT, 1, 1),
# Input registers
0x3000: Register("Charging equipment rated input voltage", "PV array rated voltage", V, 100, 1),
0x3001: Register("Charging equipment rated input current", "PV array rated current", A, 100, 1),
0x3002: Register("Charging equipment rated input power", "PV array rated power (low 16 bits)", W, 100, 2),
0x3004: Register("Charging equipment rated output voltage", None, V, 100, 1),
0x3005: Register("Charging equipment rated output current", "Rated charging current to battery", A, 100, 1),
0x3006: Register("Charging equipment rated output power", "Rated charging power to battery", W, 100, 2),
0x3008: Register("Charging mode", "0001H-PWM", CHARGINGMODE, None, 1),
0x300E: Register("Rated output current of load", None, A, 100, 1),
0x3100: Register("Charging equipment input voltage", "Solar charge controller--PV array voltage", V, 100, 1),
0x3101: Register("Charging equipment input current", "Solar charge controller--PV array current", A, 100, 1),
0x3102: Register("Charging equipment input power", "Solar charge controller--PV array power", W, 100, 2),
0x3104: Register("Charging equipment output voltage", "Battery voltage", V, 100, 1),
0x3105: Register("Charging equipment output current", "Battery charging current", A, 100, 1),
0x3106: Register("Charging equipment output power", "Battery charging power", W, 100, 2),
0x310C: Register("Disharging equipment output voltage", "Load voltage voltage", V, 100, 1),
0x310D: Register("Disharging equipment output current", "Load current current", A, 100, 1),
0x310E: Register("Disharging equipment output power", "Load power", W, 100, 2),
0x3110: Register("Battery Temperature", "Battery Temperature", D, 100, 1),
0x3111: Register("Temperature inside equipment", "Temperature inside case", D, 100, 1),
0x3112: Register("Power components temperature", "Heat sink temperature of power components", D, 100, 1),
0x311A: Register("Battery SOC", "Percentage of battery's remaining capacity", P, 100, 1),
0x311B: Register("Remote battery temperature", "Battery temperature measured by remote sensor", D, 100, 1),
0x311D: Register("Battery real rated power", "Current system rated voltage (1200, 2400 represents 12v, 24v", V, 100, 1),
0x3200: Register("Battery status", "Battery real time state", BATTERYSTATUS, None, 1),
0x3201: Register("Charging equipement status", "Charging equipment status", CHARGINGEQUIPMENTSTATUS, None, 1),
0x3202: Register("Discharging equipement status", "Discharging equipment status", DISCHARGINGEQUIPMENTSTATUS, None, 1),
0x3300: Register("Maximum input (PV) today", "00: 00 Refresh every day", V, 100, 1),
0x3301: Register("Minimum input (PV) today", "00: 00 Refresh every day", V, 100, 1),
0x3302: Register("Maximum battery volt today", "00: 00 Refresh every day", V, 100, 1),
0x3303: Register("Minimum battery volt today", "00: 00 Refresh every day", V, 100, 1),
0x3304: Register("Consumed energy today", "00: 00 Clear every day", KWH, 100, 2),
0x3306: Register("Consumed energy this month", "00: 00 Clear on the first day of the month", KWH, 100, 2),
0x3308: Register("Consumed energy this year", "00: 00 Clear on 1, Jan.", KWH, 100, 2),
0x330A: Register("Total consumed energy", "Total consumed energy", KWH, 100, 2),
0x330C: Register("Generated energy today", "00: 00 Clear every day", KWH, 100, 2),
0x330E: Register("Generated energy this month", "00: 00 Clear on the first day of the month", KWH, 100, 2),
0x3310: Register("Generated energy this year", "00: 00 Clear on Jan 1", KWH, 100, 2),
0x3312: Register("Total generated energy", "Total generated energy", KWH, 100, 2),
0x331A: Register("Battery voltage", "Battery voltage", V, 100, 1),
0x331B: Register("Battery current", "Battery current", A, 1, 2),
# Holding registers
0x9000: Register("Battery type", "Battery make-up (Sealed, Gel, Flooded, User)", BATTERYTYPE, None, 1),
0x9001: Register("Battery capacity", "Rated capacity of battery", AH, 100, 1),
0x9002: Register("Temperature compensation coefficient", "Range 0-9", COEF, 1, 1),
0x9003: Register("High volt disconnect", "High volt disconnect", V, 100, 1),
0x9004: Register("Charging limit voltage", "Charging limit voltage", V, 100, 1),
0x9005: Register("Over voltage reconnect", "Over voltage reconnect", V, 100, 1),
0x9006: Register("Equalization voltage", "Equalization voltage", V, 100, 1),
0x9007: Register("Boost voltage", "Boost Voltage", V, 100, 1),
0x9008: Register("Float voltage", "Float voltage", V, 100, 1),
0x9009: Register("Boost reconnect voltage", "Boost reconnect voltage", V, 100, 1),
0x900a: Register("Low voltage reconnect", "Low voltage reconnect", V, 100, 1),
0x900b: Register("Under voltage recover", "Under voltage recover", V, 100, 1),
0x900c: Register("Under voltage warning", "Under voltage warning", V, 100, 1),
0x900d: Register("Low voltage disconnect", "Low voltage disconnect", V, 100, 1),
0x900e: Register("Discharging limit voltage", "Discharging limit voltage", V, 100, 1),
0x9013: Register("Real time clock D7-0 Sec, D15-8 Min", "Year, Month, Day, Min, Sec should be written simultaneously", RTCSECMIN, 1, 1),
0x9014: Register("Real time clock D7-0 Hour, D15-8 Day", "D7-0 Hour, D15-8 Day", RTCHOURDAY, 1, 1),
0x9015: Register("Real time clock D7-0 Month, D15-8 Year", "D7-0 Month, D15-8 Year", RTCYEARMONTH, 1, 1),
0x9017: Register("Battery temperature warning upper limit", "Battery temp warning upper limit", D, 100, 1),
0x9018: Register("Battery temperature warning lower limit", "Battery temp warning lower limit", D, 100, 1),
0x9019: Register("Controller inner temperature upper limit", "Controller inner temperature upper limit", D, 100, 1),
0x901A: Register("Controller inner temperature upper limit recover", "Controller inner temperature upper limit recover", D, 100, 1),
0x901E: Register("Night TimeThreshold Volt.(NTTV)", " PV lower lower than this value, controller would detect it as sundown", V, 100, 1),
0x901F: Register("Light signal startup (night) delay time", "PV voltage lower than NTTV, and duration exceeds the Light signal startup (night) delay time, controller would detect it as night time.", MIN, 1, 1),
0x9020: Register("Day Time Threshold Volt.(DTTV)", "PV voltage higher than this value, controller would detect it as sunrise", V, 100, 1),
0x9021: Register("Light signal turn off(day) delay time", "PV voltage higher than DTTV, and duration exceeds Light signal turn off(day, 1) delay time delay time, controller would detect it as daytime.", MIN, 1, 1),
0x903D: Register("Load controlling modes", "0000H Manual Control, 0001H Light ON/OFF, 0002H Light ON+ Timer/, 0003H Time Control", LOADCONTROLMODES, 1, 1),
0x903E: Register("Working time length 1", "The length of load output timer1, D15-D8,hour, D7-D0, minute", HOURMIN, 1, 1),
0x903F: Register("Working time length 2", "The length of load output timer2, D15-D8, hour, D7-D0, minute", HOURMIN, 1, 1),
0x9042: Register("Turn on timing 1 sec", "Turn on timing 1 sec", SEC, 1, 1),
0x9043: Register("Turn on timing 1 min", "Turn on timing 1 min", MIN, 1, 1),
0x9044: Register("Turn on timing 1 hour", "Turn on timing 1 hour", HOUR, 1, 1),
0x9045: Register("Turn off timing 1 sec", "Turn off timing 1 sec", SEC, 1, 1),
0x9046: Register("Turn off timing 1 min", "Turn off timing 1 min", MIN, 1, 1),
0x9047: Register("Turn off timing 1 hour", "Turn off timing 1 hour", HOUR, 1, 1),
0x9048: Register("Turn on timing 2 sec", "Turn on timing 2 sec", SEC, 1, 1),
0x9049: Register("Turn on timing 2 min", "Turn on timing 2 min", MIN, 1, 1),
0x904A: Register("Turn on timing 2 hour", "Turn on timing 2 hour", HOUR, 1, 1),
0x904B: Register("Turn off timing 2 sec", "Turn off timing 2 sec", SEC, 1, 1),
0x904C: Register("Turn off timing 2 min", "Turn off timing 2 min", MIN, 1, 1),
0x904D: Register("Turn off timing 2 hour", "Turn off timing 2 hour", HOUR, 1, 1),
0x9065: Register("Length of night", "Set default values of the whole night length of time. D15-D8,hour, D7-D0, minute", HOURMIN, 1, 1),
0x9067: Register("Battery rated voltage code", "0, auto recognize. 1-12V, 2-24V", BATTERYRATEDVOLTAGE, 1, 1),
0x9069: Register("Load timing control selection", "Selected timing period of the load.0, using one timer, 1-using two timer, etc", LOADTIMINGCONTROLSELECTION, 1, 1),
0x906A: Register("Default Load On/Off in manual mode", "0-off, 1-on", OFFON, 1, 1),
0x906B: Register("Equalize duration", "Usually 60-120 minutes.", MIN, 1, 1),
0x906C: Register("Boost duration", "Usually 60-120 minutes.", MIN, 1, 1),
0x906D: Register("Discharging percentage", "Usually 20%-80%. The percentage of battery's remaining capacity when stop charging", P, 1, 1),
0x906E: Register("Charging percentage", "Depth of charge, 20%-100%.", P, 1, 1),
0x9070: Register("Management modes of battery charging and discharging", "Management modes of battery charge and discharge, voltage compensation : 0 and SOC : 1.", MANAGEMENTMODES, 1, 1)}
|
python
|
# 视觉问答模型
from keras.layers import Conv2D, MaxPooling2D, Flatten
from keras.layers import Input, LSTM, Embedding, Dense
from keras.models import Model, Sequential
import keras
# First, let's define a vision model using a Sequential model.
# This model will encode an image into a vector.
vision_model = Sequential()
vision_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(224, 224, 3)))
vision_model.add(Conv2D(64, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
vision_model.add(Conv2D(128, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))
vision_model.add(Conv2D(256, (3, 3), activation='relu'))
vision_model.add(Conv2D(256, (3, 3), activation='relu'))
vision_model.add(MaxPooling2D((2, 2)))
vision_model.add(Flatten())
# Now let's get a tensor with the output of our vision model:
image_input = Input(shape=(224, 224, 3))
encoded_image = vision_model(image_input)
# Next, let's define a language model to encode the question into a vector.
# Each question will be at most 100 word long,
# and we will index words as integers from 1 to 9999.
question_input = Input(shape=(100,), dtype='int32')
embedded_question = Embedding(input_dim=10000, output_dim=256, input_length=100)(question_input)
encoded_question = LSTM(256)(embedded_question)
# Let's concatenate the question vector and the image vector:
merged = keras.layers.concatenate([encoded_question, encoded_image])
# And let's train a logistic regression over 1000 words on top:
output = Dense(1000, activation='softmax')(merged)
# This is our final model:
vqa_model = Model(inputs=[image_input, question_input], outputs=output)
# The next stage would be training this model on actual data.
|
python
|
# Generated by Django 3.1.3 on 2020-12-07 23:51
from django.db import migrations, models
import django.db.models.deletion
import django_update_from_dict
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0003_auto_20201206_1634'),
]
operations = [
migrations.CreateModel(
name='VenueCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.organization')),
],
options={
'ordering': ['name'],
},
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.CreateModel(
name='Venue',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('capacity', models.PositiveIntegerField(blank=True)),
('ic_name', models.CharField(blank=True, max_length=255)),
('ic_email', models.EmailField(blank=True, max_length=254)),
('ic_contact_number', models.CharField(blank=True, max_length=50)),
('form_data', models.JSONField()),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='venues.venuecategory')),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.organization')),
],
options={
'ordering': ['name'],
},
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.AddConstraint(
model_name='venuecategory',
constraint=models.UniqueConstraint(fields=('name', 'organization_id'), name='unique_organization_venue_category'),
),
migrations.AddConstraint(
model_name='venue',
constraint=models.UniqueConstraint(fields=('organization_id', 'name', 'category_id'), name='unique_organization_venue'),
),
]
|
python
|
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, get_object_or_404, render
from django.template import loader
from django.contrib import messages
from django.conf import settings
import collections
from django.core.mail import send_mail
from django.template import loader
import json
from datetime import datetime
from .forms import UserUpdateForm as userupdateform
from .forms import ProfileUpdateForm as profile_update_form
import urllib
from linkup.constants import PrivacyChoices, StateChoices
from linkup.models import (
Event,
Poll,
UserPollChoice,
PollChoice,
DatetimeChoice,
LocationChoice,
UserEventChoice,
)
from .constants import (
event_category_choices,
event_importance_choices,
privacy_choices,
)
def return_statistics():
polls_count = Poll.objects.count()
events_count = Event.objects.count()
users_count = User.objects.count()
return {
'polls_count': polls_count,
'events_count': events_count,
'users_count': users_count
}
# Index page function
def index(request):
template = loader.get_template('index.html')
context = {
'title': 'Link Up'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# About page function
def about(request):
template = loader.get_template('about.html')
context = {
'title': 'About'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# EVENT FUNCTIONS ###
# Datetime duration Function
# It takes two arguments and return a string
def period(d1, d2):
s1 = d1[:10]
s2 = d2[:10]
start= d1[11:]
end= d2[11:]
d1 = datetime.strptime(s1, "%d/%m/%Y")
d2 = datetime.strptime(s2, "%d/%m/%Y")
d = abs((d2 - d1).days)
start_dt = datetime.strptime(start, '%H:%M')
end_dt = datetime.strptime(end, '%H:%M')
diff = (end_dt - start_dt)
diff = str(diff)
if diff[0] == '-':
if diff[12].isdigit():
diff = diff[8:13]
else:
diff = diff[8:12]
else:
if start[0:2] =='00':
if diff[1].isdigit():
diff = diff[:5]
else:
diff = diff[:4]
else:
diff = diff[:5]
if diff[0:2].isdigit():
diff = f'{diff[0:2]}h {diff[3:]}m'
else:
diff = f'{diff[0:1]}h {diff[2:4]}m'
if diff.find('00m') != -1:
diff = diff[:diff.find('00')]
if diff.find('0h') != -1:
diff = diff[diff.find('0h')+2:]
if d !=0:
if diff.isspace() :
return (f'{d} days')
else:
return (f'{d} days,{diff}')
else:
return (f'{diff}')
# Event List Function
# Return Event list page with paginator to 10 per page
def event_list(request):
events = Event.objects.all()
template = loader.get_template('event_list.html')
paginator = Paginator(events, 10)
page = request.GET.get('page', 1)
events = paginator.get_page(page)
context = {
'data': events,
'title': 'Link Up Event List'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Result Event Funtion
# Return The actual result or an event
def result (request, pk=None):
event = get_object_or_404(Event, pk=pk)
template = loader.get_template('event_detail/result.html')
options = []
datetime_choices = DatetimeChoice.objects.filter(event=event)
# Used to create the table to display event details
for d in datetime_choices:
option = {"content":"", "period":'',"users":[], "count":''}
persons = []
for x in UserEventChoice.objects.filter(event=event, datetime_choices=d):
persons.append(x.creator.username)
option['content'] = d.content
try:
s1 = str(d.content)
option['period'] = period(s1[:s1.find('-')-1],s1[s1.find('-')+2:])
except:
option['period'] = ''
option['users'] = persons
option['count'] = len(persons)
options.append(option)
context = {
'event': event,
'options':options
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Event detail Function
# Returns the event details relating to event stage
def event_detail(request, pk=None):
event = get_object_or_404(Event, pk=pk)
if event.privacy == PrivacyChoices.PRIVATE:
if (request.user in event.invited_users.all()) or (request.user == event.creator or request.user.is_superuser):
if event.state == StateChoices.OPENED:
template = loader.get_template('event_detail/opened.html')
datetime_choices = DatetimeChoice.objects.filter(event=event)
options = []
for d in datetime_choices:
try:
s1 = str(d.content)
option = {'pk':d.pk, 'content':d.content, 'period': period(s1[:s1.find('-')-1],s1[s1.find('-')+2:])}
except:
option = {'pk':d.pk, 'content':d.content, 'period':''}
options.append(option)
context = {
'event': event,
'options': options
}
if request.user.id :
if UserEventChoice.objects.filter(creator=request.user, event=event).first() is not None:
context = {
'event': event,
'options': options,
'btn':1,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
template = loader.get_template('event_detail/close.html')
e = UserEventChoice.objects.filter(event=event)
choices_list = []
for i in e:
choice = {'datetime_choices' : i.datetime_choices.first().content,'location_choices':i.location_choices.first().content,'creator':i.creator.username}
choices_list.append(choice)
ddd = [x['datetime_choices'] for x in choices_list]
lll = [x['location_choices'] for x in choices_list]
d = [item for item, count in collections.Counter(ddd).items() if count > 1]
if len(d) != 0:
best_date = len([c for c in ddd if c ==[item for item, count in collections.Counter(ddd).items() if count > 1][0]])
else:
best_date = 1
l = [item for item, count in collections.Counter(lll).items() if count > 1]
if len(l) != 0:
best_location = len([c for c in lll if c ==[item for item, count in collections.Counter(lll).items() if count > 1][0]])
else:
best_location = 1
template = loader.get_template('event_detail/close.html') # Outputs answers
context = {
'event': event,
'best_date':best_date,
'best_location':best_location
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
messages.warning(request, 'This is a private event and you are not invited !')
return redirect('event_list')
elif event.privacy == PrivacyChoices.PUBLIC:
if event.state == StateChoices.ClOSE:
e = UserEventChoice.objects.filter(event=event)
choices_list = []
for i in e:
choice = {'datetime_choices' : i.datetime_choices.first().content,'location_choices':i.location_choices.first().content,'creator':i.creator.username}
choices_list.append(choice)
ddd = [x['datetime_choices'] for x in choices_list]
lll = [x['location_choices'] for x in choices_list]
d = [item for item, count in collections.Counter(ddd).items() if count > 1]
if len(d) != 0:
best_date = len([c for c in ddd if c ==[item for item, count in collections.Counter(ddd).items() if count > 1][0]])
else:
best_date = 1
l = [item for item, count in collections.Counter(lll).items() if count > 1]
if len(l) != 0:
best_location = len([c for c in lll if c ==[item for item, count in collections.Counter(lll).items() if count > 1][0]])
else:
best_location = 1
template = loader.get_template('event_detail/close.html')
context = {
'event': event,
'best_date':best_date,
'best_location':best_location
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
template = loader.get_template('event_detail/opened.html')
datetime_choices = DatetimeChoice.objects.filter(event=event)
options = []
for d in datetime_choices:
try:
s1 = str(d.content)
option = {'pk':d.pk, 'content':d.content, 'period': period(s1[:s1.find('-')-1],s1[s1.find('-')+2:])}
except:
option = {'pk':d.pk, 'content':d.content, 'period':''}
options.append(option)
context = {
'event': event,
'options': options
}
if request.user.id :
if UserEventChoice.objects.filter(creator=request.user, event=event).first() is not None:
context = {
'event': event,
'options': options,
'btn':1,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Event create Function
# if request.user.id ==> registred user
# else ==> anonymous user
def event_new(request):
if request.method == 'GET':
template = loader.get_template('event_new.html')
context = {
'event_category_choices': event_category_choices,
'event_importance_choices': event_importance_choices,
'privacy_choices': privacy_choices
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
title = request.POST.get('title', None)
description = request.POST.get('description', None)
category = request.POST.get('category', None)
importance = request.POST.get('importance', None)
privacy = request.POST.get('privacy', None)
datetime_choices = request.POST.getlist('ddd')
datetime_choices = list(filter(None, datetime_choices))
location_choices = request.POST.getlist('location')
location_choices = list(filter(None, location_choices))
invited_users = request.POST.getlist('invited')
users = list(filter(None, invited_users))
invalid_users = []
for user in users:
username = User.objects.filter(username=user).first()
if username is None:
invalid_users.append(user)
if len(invalid_users)!=0:
for usr in invalid_users:
messages.warning(request, "{}, doesn't exit!".format(', '.join(invalid_users)))
template = loader.get_template('event_new.html')
invited_users = [ c for c in users]
loc = [ c for c in location_choices]
dat = [ c for c in datetime_choices]
context = {
'event_category_choices': event_category_choices,
'event_importance_choices': event_importance_choices,
'privacy_choices': privacy_choices,
'title':title,
'description':description,
'datetime':dat,
'location':loc,
'invited_users':invited_users
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
if title.isspace()==True or description.isspace()==True or (("".join(location_choices))=='') or (("".join(datetime_choices))==''):
template = loader.get_template('event_new.html')
invited_users = [ c for c in users]
loc = [ c for c in location_choices]
dat = [ c for c in datetime_choices]
context = {
'event_category_choices': event_category_choices,
'event_importance_choices': event_importance_choices,
'privacy_choices': privacy_choices,
'title':title,
'description':description,
'datetime':dat,
'location':loc,
}
context.update(return_statistics())
messages.warning(request, 'Event creation unsuccessful!,'+' '+' Please make sure all required information is entered')
return HttpResponse(template.render(context, request))
elif request.user.id:
try:
event = Event.objects.create(
title=title,
description=description,
category=category,
importance=importance,
privacy=privacy,
creator=request.user
)
for datetime_choice in datetime_choices:
if datetime_choice != '':
DatetimeChoice.objects.create(
content=datetime_choice,
event=event
)
for location_choice in location_choices:
if location_choice != '':
LocationChoice.objects.create(
content=location_choice,
event=event
)
if event.privacy == '0':
event.invited_users.add(request.user)
for invited_user in invited_users:
user = User.objects.filter(username=invited_user).first()
if user is not None:
event.invited_users.add(user)
messages.success(request, 'Event creation successful!')
return redirect('event_detail', pk=event.pk)
except:
messages.success(request, 'Event creation successful!')
return redirect('event_detail', pk=event.pk)
else:
try:
event = Event.objects.create(
title=title,
description=description,
category=category,
importance=importance
)
for datetime_choice in datetime_choices:
if datetime_choice != '':
DatetimeChoice.objects.create(
content=datetime_choice,
event=event
)
for location_choice in location_choices:
if location_choice != '':
LocationChoice.objects.create(
content=location_choice,
event=event
)
if event.privacy == '0':
event.invited_users.add(request.user)
for invited_user in invited_users:
user = User.objects.filter(username=invited_user).first()
if user is not None:
event.invited_users.add(user)
messages.success(request, 'Event creation successful!')
return redirect('event_detail', pk=event.pk)
except:
messages.success(request, 'Event creation successful!')
return redirect('event_detail', pk=event.pk)
# Event update Funtion
# Allows update of event prodivded user is either creator or admin (superuser)
def event_update(request,pk):
event = get_object_or_404(Event, pk=pk)
if event.state == StateChoices.ClOSE or (request.user == event.creator or request.user.is_superuser )== False:
messages.warning(request, 'Permission denied :/')
return redirect('event_detail', pk=pk)
else:
if request.method == 'GET':
e = DatetimeChoice.objects.filter(event=event)
loc = LocationChoice.objects.filter(event=event)
template = loader.get_template('event_update.html')
invited_users = [ c for c in event.invited_users.all()]
dat = [ c for c in e]
context = {
'event_category_choices': event_category_choices,
'event_importance_choices': event_importance_choices,
'privacy_choices': privacy_choices,
'title':event.title,
'datetime':dat,
'description':event.description,
'location':loc,
'invited_users':invited_users
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
title = request.POST.get('title', None)
description = request.POST.get('description', None)
category = request.POST.get('category', None)
importance = request.POST.get('importance', None)
privacy = request.POST.get('privacy', None)
datetime_choices = request.POST.getlist('ddd')
location_choices = request.POST.getlist('location')
invited_users = request.POST.getlist('invited')
if title.isspace()==True or description.isspace()==True or (("".join(location_choices))=='') or (("".join(datetime_choices))==''):
messages.warning(request, 'Event update unsuccessful, Please make sure that all required information was entered !')
e = DatetimeChoice.objects.filter(event=event)
loc = LocationChoice.objects.filter(event=event)
template = loader.get_template('event_update.html')
invited_users = [ c for c in event.invited_users.all()]
dat = [ c for c in e]
context = {
'event_category_choices': event_category_choices,
'event_importance_choices': event_importance_choices,
'privacy_choices': privacy_choices,
'title':event.title,
'datetime':dat,
'description':event.description,
'location':loc,
'invited_users':invited_users
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
event = Event.objects.filter(pk=pk).update(
title=title,
description=description,
category=category,
importance=importance,
privacy=privacy,
)
event = get_object_or_404(Event, pk=pk)
DatetimeChoice.objects.filter(event=event).delete()
for datetime_choice in datetime_choices:
if datetime_choice != '':
DatetimeChoice.objects.create(
content=datetime_choice,
event=event
)
LocationChoice.objects.filter(event=event).delete()
for location_choice in location_choices:
if location_choice != '':
LocationChoice.objects.create(
content=location_choice,
event=event
)
event.invited_users.clear()
if event.privacy == 0:
event.invited_users.add(request.user)
for invited_user in invited_users:
user = User.objects.filter(username=invited_user).first()
if user is not None:
event.invited_users.add(user)
messages.success(request, 'Event update successful')
return redirect('event_detail', pk=pk)
# Event close Function
# Allows users to close an event alongside sending notification email to participants
@login_required(login_url='/login/')
def event_close(request, pk):
event = get_object_or_404(Event, pk=pk)
if (event.state == StateChoices.ClOSE) or (request.user == event.creator or request.user.is_superuser )== False:
messages.warning(request, 'No permission!')
return redirect('event_detail', pk=pk)
else:
event.state = StateChoices.ClOSE
event.save()
messages.success(request, 'Event closed successful!')
e = UserEventChoice.objects.filter(event=event)
users = [x.creator for x in e]
if users:
for user in users:
if user.email != '':
html_message = loader.render_to_string(
'mail_template.html',
{
'title': event.title,
'type': 'event',
'link': f'http://127.0.0.1:8000/event/{event.pk}',
})
send_mail('Link Up Notification',event.title,settings.DEFAULT_FROM_EMAIL,[user.email],fail_silently=True,html_message=html_message)
# Above line sents the email
return redirect('event_detail', pk=event.pk)
# Event Choice Function
# Allows event creator to view choices of ongoing/active event poll
def event_join(request, pk):
if request.user.is_authenticated:
if request.method == 'GET':
event = get_object_or_404(Event, pk=pk)
if UserEventChoice.objects.filter(creator=request.user, event=event).first() is not None:
a = UserEventChoice.objects.filter(creator=request.user, event=event).all()
for i in a:
for j in i.datetime_choices.all():
date = j.content
for j in i.location_choices.all():
loc = j.content
event = get_object_or_404(Event, pk=pk)
template = loader.get_template('event_detail/choices.html')
try:
context = {'event': event,
'date':date,
'location':loc,
}
except:
context = {'event': event
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
template = loader.get_template('event_detail/join.html')
context = {'event': event}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
elif request.method == 'POST':
event = get_object_or_404(Event, pk=pk)
datetime_choice_pks = request.POST.getlist('datetime')
user_event_choice = UserEventChoice.objects.create(
event=event,
creator=request.user
)
for datetime_choice_pk in datetime_choice_pks:
datetime_choice = get_object_or_404(DatetimeChoice, pk=datetime_choice_pk)
user_event_choice.datetime_choices.add(datetime_choice)
location_choice_pks = request.POST.getlist('location')
for location_choice_pk in location_choice_pks:
location_choice = get_object_or_404(LocationChoice, pk=location_choice_pk)
user_event_choice.location_choices.add(location_choice)
messages.success(request, 'Join to event successfully!')
return redirect('event_detail', pk=pk)
messages.warning(request, 'Please Log In to Join !')
return redirect('event_detail', pk=pk)
# Event Submit Function
# Submission mechanismn
def event_submit(request):
pk = request.POST.get('pk', False)
event = get_object_or_404(Event, pk=pk)
if request.method == 'GET':
template = loader.get_template('event_detail/opened.html')
context = {'event': event}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
if request.user.is_authenticated:
if UserEventChoice.objects.filter(event=event, creator=request.user).count() != 0:
messages.warning(request, 'Please do not submit your choices for this event again!')
return redirect('event_detail', pk=pk)
choice_pk = request.POST.get('choice',None)
choice2_pk = request.POST.get('choice2', None)
choice = get_object_or_404(DatetimeChoice, pk=choice_pk)
choice2 = get_object_or_404(LocationChoice, pk=choice2_pk)
user_event_choice = UserEventChoice.objects.create(
event=event,
creator=request.user)
user_event_choice.datetime_choices.add(choice)
user_event_choice.location_choices.add(choice2)
messages.success(request, 'Your event submission was successful!')
return redirect('event_detail', pk=pk)
messages.warning(request, 'Please Log In to submit your choices !')
return redirect('event_detail', pk=pk)
### POOL FUNCTIONS ###
# Poll List Function
# Return Poll list page with paginator to 10 per page
def poll_list(request):
polls = Poll.objects.all()
template = loader.get_template('poll_list.html')
paginator = Paginator(polls, 5)
page = request.GET.get('page')
polls = paginator.get_page(page)
context = {
'data': polls,
'title': 'Link Up Poll List'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Result Poll Funtion
# Return The actual result for a Poll
def result_poll (request, pk=None):
poll = get_object_or_404(Poll, pk=pk)
template = loader.get_template('poll_detail/result.html')
poll_choices = []
items = PollChoice.objects.filter(poll=poll)
for item in items:
choice = {"option":item.content, "users":[], "count":0}
k = 0
c = UserPollChoice.objects.filter(poll=poll,choices=item)
for i in c:
if i.get_full_name():
choice["users"].append(i.get_full_name())
else:
k =k + 1
choice["count"] = len(choice["users"])
if k >0:
choice["users"].append("Anonymous x"+str(k))
choice["count"] = k + len(choice["users"])-1
poll_choices.append(choice)
context = {
'poll': poll,
'choices':poll_choices
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Poll list Function
# Return the list of private polls
def poll_list_private(request):
polls = Poll.objects.filter(privacy=0)
template = loader.get_template('poll_list.html')
paginator = Paginator(polls, 5)
page = request.GET.get('page')
polls = paginator.get_page(page)
context = {
'data': polls,
'title': 'Link Up Private Poll List'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Poll detail Function
# Return the detail page of an Poll relating with his state
def poll_detail(request, pk=None):
poll = get_object_or_404(Poll, pk=pk)
if poll.privacy == PrivacyChoices.PRIVATE:
if (request.user in poll.invited_users.all()) or (request.user == poll.creator):
if poll.state == StateChoices.OPENED:
template = loader.get_template('poll_detail/opened.html')
context = {'poll': poll}
if request.user.is_authenticated:
a = UserPollChoice.objects.filter(poll=poll,creator=request.user).all()
mychoices = []
for i in a:
for j in i.choices.all():
mychoices.append(j)
context = {
'poll': poll,
'mychoices': mychoices
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
template = loader.get_template('poll_detail/close.html')
poll_choices = []
items = PollChoice.objects.filter(poll=poll)
for item in items:
choice = {"option":item.content, "users":[], "count":0}
k = 0
c = UserPollChoice.objects.filter(poll=poll,choices=item)
for i in c:
if i.get_full_name():
choice["users"].append(i.get_full_name())
else:
k =k + 1
choice["count"] = len(choice["users"])
if k >0:
choice["users"].append("Anonymous x"+str(k))
choice["count"] = k + len(choice["users"])-1
poll_choices.append(choice)
best_option = max(x['count'] for x in poll_choices)
context = {
'poll': poll,
'choices':poll_choices,
'best_option':best_option,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
messages.warning(request, 'This is a private poll and you are not invited !')
from django.urls import resolve
current_url = request.resolver_match.func.__name__
redirect_to = request.META.get('HTTP_REFERER')
return HttpResponseRedirect(redirect_to)
elif poll.privacy == PrivacyChoices.PUBLIC:
if poll.state == StateChoices.ClOSE:
template = loader.get_template('poll_detail/close.html')
poll_choices = []
items = PollChoice.objects.filter(poll=poll)
for item in items:
choice = {"option":item.content, "users":[], "count":0}
k = 0
c = UserPollChoice.objects.filter(poll=poll,choices=item)
for i in c:
if i.get_full_name():
choice["users"].append(i.get_full_name())
else:
k =k + 1
choice["count"] = len(choice["users"])
if k >0:
choice["users"].append("Anonymous x"+str(k))
choice["count"] = k + len(choice["users"])-1
poll_choices.append(choice)
best_option = max(x['count'] for x in poll_choices)
context = {
'poll': poll,
'choices':poll_choices,
'best_option':best_option,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
elif poll.state == StateChoices.OPENED:
template = loader.get_template('poll_detail/opened.html')
if request.user.is_authenticated:
a = UserPollChoice.objects.filter(poll=poll,creator=request.user).all()
mychoices = []
for i in a:
for j in i.choices.all():
mychoices.append(j)
context = {
'poll': poll,
'mychoices': mychoices
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
context = {
'poll': poll,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Validator Email Function
# Check if the string argument is a valid email or not
# Return True if it a valid email format or return False if validation failed
def validateEmail(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email( email )
return True
except ValidationError:
return False
# Poll Submit Function
# Allows submitting choices for a Poll
def poll_submit(request):
pk = request.POST['pk']
poll = get_object_or_404(Poll, pk=pk)
if request.user.is_authenticated:
if UserPollChoice.objects.filter(poll=poll, creator=request.user).count() != 0:
messages.warning(request, 'Please do not submit your poll choices again!')
return redirect('poll_detail', pk=pk)
if poll.multi_choices:
user_poll_choice = UserPollChoice.objects.create(
poll=poll,
creator=request.user
)
choice_pks = request.POST.getlist('choices')
if choice_pks ==[]:
messages.warning(request, 'Your poll submission was unsuccessful !')
return redirect('poll_detail', pk=pk)
for choice_pk in choice_pks:
choice = get_object_or_404(PollChoice, pk=choice_pk)
user_poll_choice.choices.add(choice)
else:
choice_pk = request.POST['choice']
if choice_pk ==[]:
messages.warning(request, 'Your poll submission was unsuccessful !')
return redirect('poll_detail', pk=pk)
choice = get_object_or_404(PollChoice, pk=choice_pk)
user_poll_choice = UserPollChoice.objects.create(
poll=poll,
creator=request.user
)
user_poll_choice.choices.add(choice)
messages.success(request, 'Your poll submission was successful!')
return redirect('poll_detail', pk=pk)
if poll.multi_choices:
choice_pks = request.POST.getlist('choices')
if choice_pks==[]:
messages.warning(request, 'Your poll submission was unsuccessful !')
return redirect('poll_detail', pk=pk)
email = request.POST['email']
if not email:
messages.warning(request, 'Please enter an email address!')
return redirect('poll_detail', pk=pk)
exist = UserPollChoice.objects.filter(email=email)
if exist:
messages.warning(request, 'Please do not submit your poll choices again!')
return redirect('poll_detail', pk=pk)
user_poll_choice = UserPollChoice.objects.create(
poll=poll,
email=email
)
for choice_pk in choice_pks:
choice = get_object_or_404(PollChoice, pk=choice_pk)
user_poll_choice.choices.add(choice)
else:
try:
choice_pk = request.POST['choice']
email = request.POST['email']
if not email or not validateEmail(email):
raise Exception
exist = UserPollChoice.objects.filter(email=email)
if exist:
messages.warning(request, 'Please do not submit your poll choices again!')
return redirect('poll_detail', pk=pk)
choice = get_object_or_404(PollChoice, pk=choice_pk)
user_poll_choice = UserPollChoice.objects.create(
poll=poll,
email=email)
user_poll_choice.choices.add(choice)
except:
messages.warning(request, 'Your poll submission was unsuccessful !')
return redirect('poll_detail', pk=pk)
messages.success(request, 'Your poll submission was successful!')
return redirect('poll_detail', pk=pk)
# Poll create Function
# if request.user.id ==> registred user
# else ==> anonymous user
def poll_new(request):
if request.method == 'GET':
template = loader.get_template('poll_new.html')
context = {
'privacy_choices': privacy_choices,
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
title = request.POST['title']
description = request.POST['description']
multi = request.POST.get('multi', None)
if multi == 'on':
is_multi_choice = True
else:
is_multi_choice = False
choices = request.POST.getlist('choices')
choices_list = [ c for c in choices]
users = request.POST.getlist('users')
users = list(filter(None, users))
privacy = request.POST.get('privacy')
invalid_users = []
for user in users:
username = User.objects.filter(username=user).first()
if username is None:
invalid_users.append(user)
if len(invalid_users)!=0:
template = loader.get_template('poll_new.html')
context = {
'privacy_choices': privacy_choices,
'title':title,
'choices':choices_list,
'description':description,
'invited_users':users
}
context.update(return_statistics())
usrr = ''
for usr in invalid_users:
usrr+= usr + " , "
messages.warning(request, "{} does not exist!".format(usrr))
return HttpResponse(template.render(context, request))
if title.isspace()==True or (choices_list[0]=='' or choices_list[1]=='') or description.isspace()==True or ("".join(choices or None).isspace() or "".join(choices or None)=='' ) :
template = loader.get_template('poll_new.html')
context = {
'title':title,
'privacy_choices': privacy_choices,
'choices':choices_list,
'description':description,
}
context.update(return_statistics())
messages.warning(request, 'Poll creation unsuccessful, Please make sure that all required information was entered !')
return HttpResponse(template.render(context, request))
elif request.user.id:
try:
poll = Poll.objects.create(
title=title,
description=description,
multi_choices=is_multi_choice,
privacy=privacy,
creator=request.user
)
for choice_content in choices:
PollChoice.objects.create(
content=choice_content,
poll=poll
)
if privacy == '0':
for username in users:
user = User.objects.filter(username=username).first()
if user is not None:
poll.invited_users.add(user)
messages.success(request, 'Poll successfully created!')
return redirect('poll_detail', pk=poll.pk)
except:
messages.success(request, 'Poll successfully created!')
return redirect('poll_detail', pk=poll.pk)
else:
try:
poll = Poll.objects.create(
title=title,
description=description,
multi_choices=is_multi_choice
)
for choice_content in choices:
PollChoice.objects.create(
content=choice_content,
poll=poll
)
messages.success(request, 'Poll successfully created!')
return redirect('poll_detail', pk=poll.pk)
except:
messages.success(request, 'Poll update successful!')
return redirect('poll_detail', pk=poll.pk)
# Poll update Funtion
# it allows to update a Poll if the user is his creator or is an admin
@login_required
def poll_update(request,pk):
poll = get_object_or_404(Poll, pk=pk)
if poll.state == StateChoices.ClOSE or(request.user == poll.creator or request.user.is_superuser )== False:
messages.warning(request, 'Permission denied :/')
return redirect('poll_detail', pk=pk)
else:
if request.method == 'GET':
p = PollChoice.objects.filter(poll=poll)
template = loader.get_template('poll_update.html')
invited_users = [ c for c in poll.invited_users.all()]
choices_list = [ c for c in p]
context = {
'privacy_choices': privacy_choices,
'title':poll.title,
'choices':choices_list,
'description':poll.description,
'invited_users':invited_users
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
else:
title = request.POST['title']
description = request.POST['description']
multi = request.POST.get('multi', None)
if multi == 'on':
is_multi_choice = True
else:
is_multi_choice = False
choices = request.POST.getlist('choices')
users = request.POST.getlist('users')
privacy = request.POST.get('privacy')
if title.isspace()==True or description.isspace()==True or ("".join(choices or None).isspace() or "".join(choices or None)=='' ) :
messages.warning(request, 'Poll update unsuccessful')
return redirect('poll_detail', pk=pk)
else:
poll = Poll.objects.filter(pk=pk).update(
title=title,
description=description,
multi_choices=is_multi_choice,
privacy=privacy,
)
poll = get_object_or_404(Poll, pk=pk)
PollChoice.objects.filter(poll=poll).delete()
for choice_content in choices:
PollChoice.objects.create(
content=choice_content,
poll=poll)
poll.invited_users.clear()
if privacy == '0':
for username in users:
user = User.objects.filter(username=username).first()
if user is not None:
poll.invited_users.add(user)
poll.invited_users.add(request.user)
messages.success(request, 'Poll update successful')
return redirect('poll_detail', pk=pk)
# Poll close Function
# Allows to close a Poll and send a notifications email for his participants
@login_required(login_url='/login/')
def poll_close(request, pk=None):
poll = get_object_or_404(Poll, pk=pk)
if (poll.state == StateChoices.ClOSE) or (request.user == poll.creator or request.user.is_superuser )== False:
messages.warning(request, 'No permission !')
return redirect('poll_detail', pk=pk)
e = UserPollChoice.objects.filter(poll=poll)
users = [x.creator.email for x in e if x.creator]
users = users + [x.email for x in e if not x.creator]
if users:
for user in users:
html_message = loader.render_to_string(
'mail_template.html',
{
'title': poll.title,
'type': 'poll',
'link': f'http://127.0.0.1:8000/poll/{poll.pk}',
})
send_mail('Link Up Notification',poll.title,settings.DEFAULT_FROM_EMAIL,[user],fail_silently=True,html_message=html_message)
poll.state = StateChoices.ClOSE
poll.save()
messages.success(request, 'Poll closed successfully!')
return redirect('poll_detail', pk=poll.pk)
## OTHER FUNCTIONS ###
# Update User informations Function
# u_form ==> Name, Email fields
# p_form ==> Picture profile field
@login_required
def profile(request):
if request.method == 'POST':
u_form = userupdateform(request.POST, instance=request.user)
p_form = profile_update_form(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect ('profile')
else:
u_form = userupdateform(instance=request.user)
p_form = profile_update_form(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'linkup/profile_update_form.html', context)
# Dashboard Page Function
@login_required(login_url='/login/')
def user_profile(request):
template = loader.get_template('user_profile.html')
scheduling_event = request.user.event_set.filter(state=StateChoices.OPENED)[:5]
events_created = Event.objects.filter(creator=request.user)[:5]
events_invitation = Event.objects.filter(invited_users__pk=request.user.pk)[:5]
scheduled_event = request.user.event_set.filter(state=StateChoices.ClOSE)[:5]
polls_created = Poll.objects.filter(creator=request.user)[:5]
close_polls = request.user.poll_set.filter(state=StateChoices.ClOSE)[:5]
opened_polls = request.user.poll_set.filter(state=StateChoices.OPENED)[:5]
poll_invitation = Poll.objects.filter(invited_users__pk=request.user.pk)[:5]
context = {
'title':'Profile',
'scheduling_event': scheduling_event,
'events_created': events_created,
'scheduled_event': scheduled_event,
'events_invitation': events_invitation,
'polls_created': polls_created,
'close_polls': close_polls,
'opened_polls': opened_polls,
'poll_invitation': poll_invitation
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Logout Function
@login_required(login_url='/login/')
def logout_deal(request):
logout(request)
messages.success(request, 'You have successfully logged out!')
return redirect('index')
# Register Function
# With error handle infos
def register(request):
if request.user.is_authenticated:
return redirect('/')
else:
template = loader.get_template('register.html')
if request.method == 'POST':
username = request.POST['username']
user = User.objects.filter(username=username)
if username is None or username == '' or user:
if user:
messages.warning(request,"This username is already in use ! ")
else:
messages.warning(request,"This username is invalid ! ")
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
email = request.POST['email']
if email is None or email == '':
messages.warning(request,"Email address is invalid ! ")
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
password = request.POST['password']
if password is None or password == '':
messages.warning(request,"Password is invalid ! ")
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(values).encode()
req = urllib.request.Request(url, data=data)
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
if result['success']:
pass
else:
messages.warning(request,"reCAPTCHA is invalid ! ")
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Below line creates username
User.objects.create_user(
username=username,
email=email,
password=password
)
messages.success(request, 'You have successfully registered ! '+'\n'+'Now you can Log In :)')
return redirect('login')
elif request.method == 'GET':
template = loader.get_template('register.html')
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Login Function
def login_deal(request):
if request.user.is_authenticated:
return redirect('/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('/profile')
else:
messages.warning(request, 'Incorrect password or username ! ')
return redirect('login')
elif request.method == 'GET':
template = loader.get_template('login.html')
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Show more query on dashboard sections
@login_required(login_url='/login/')
def more(request, query):
if query == 'scheduled_events':
queryset = request.user.event_set.filter(state=StateChoices.ClOSE)
template = loader.get_template('event_list.html')
elif query == 'scheduling_events':
queryset = request.user.event_set.filter(state=StateChoices.OPENED)
template = loader.get_template('event_list.html')
elif query == 'events_invitation':
queryset = Event.objects.filter(invited_users__pk=request.user.pk)
template = loader.get_template('event_list.html')
elif query == 'created_events':
queryset = Event.objects.filter(creator=request.user)
template = loader.get_template('event_list.html')
elif query == 'poll_invitation':
queryset = Poll.objects.filter(invited_users__pk=request.user.pk)
template = loader.get_template('poll_list.html')
elif query == 'close_polls':
queryset = request.user.poll_set.filter(state=StateChoices.ClOSE)
template = loader.get_template('poll_list.html')
elif query == 'opened_polls':
queryset = request.user.poll_set.filter(state=StateChoices.OPENED)
template = loader.get_template('poll_list.html')
elif query == 'polls_created':
queryset = Poll.objects.filter(creator=request.user)
template = loader.get_template('poll_list.html')
paginator = Paginator(queryset, 10)
page = request.GET.get('page')
data = paginator.get_page(page)
context = {
'data': data,
'title': 'Link Up Poll List'
}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
# Change Password Function
# Allows users to change their password, error handling also applied
@login_required(login_url='/login/')
def change_password(request):
if request.method == 'POST':
old_password = request.POST.get('oldPassword')
user = authenticate(username=request.user.username, password=old_password)
if user is None:
messages.warning(request, 'All fields are required ! ')
return redirect('change_password')
new_password = request.POST.get('newPassword')
new_password_repeat = request.POST.get('newPasswordRepeat')
if (new_password.isspace=='' or new_password_repeat=='') or new_password!= new_password_repeat:
messages.warning(request, 'Your new passwords did not match ! ')
return redirect('change_password')
else:
request.user.set_password(new_password)
request.user.save()
messages.success(request, 'Your password has been changed successfully, You should re-login now !')
return redirect('index')
elif request.method == 'GET':
template = loader.get_template('change_password.html')
context = {}
context.update(return_statistics())
return HttpResponse(template.render(context, request))
|
python
|
from typing import Any # NOQA
import optuna
from optuna._experimental import experimental
from optuna._imports import try_import
with try_import() as _imports:
from catalyst.dl import Callback
if not _imports.is_successful():
Callback = object # NOQA
@experimental("2.0.0")
class CatalystPruningCallback(Callback):
"""Catalyst callback to prune unpromising trials.
Args:
trial:
A :class:`~optuna.trial.Trial` corresponding to the current evaluation of the
objective function.
metric (str):
Name of a metric, which is passed to `catalyst.core.State.valid_metrics` dictionary to
fetch the value of metric computed on validation set. Pruning decision is made based
on this value.
"""
def __init__(self, trial, metric="loss"):
# type: (optuna.trial.Trial, str) -> None
# set order=1000 to run pruning callback after other callbacks
# refer to `catalyst.core.CallbackOrder`
_imports.check()
super(CatalystPruningCallback, self).__init__(order=1000)
self._trial = trial
self.metric = metric
def on_epoch_end(self, state):
# type: (Any) -> None
current_score = state.valid_metrics[self.metric]
self._trial.report(current_score, state.epoch)
if self._trial.should_prune():
message = "Trial was pruned at epoch {}.".format(state.epoch)
raise optuna.TrialPruned(message)
|
python
|
#!/usr/bin/python
"""Copyright 2016 Google Inc. 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.
The main runner for tests used by the Cloud Print Logo Certification tool.
This suite of tests depends on the unittest runner to execute tests. It will log
results and debug information into a log file.
Before executing this program, edit _config.py and put in the proper values for
the printer being tested, and the test accounts that you are using. For the
primary test account, you need to add some OAuth2 tokens, a Client ID and a
Client Secret. Consult the README file for more details about setting up these
tokens and other needed variables in _config.py.
When testcert.py executes, some of the tests will require manual intervention,
therefore watch the output of the script while it's running.
test_id corresponds to an internal database used by Google, so don't change
those IDs. These IDs are used when submitting test results to our database.
"""
__version__ = '2.0'
import _log
import _sheets
import optparse
import os
import platform
import re
import sys
import time
import traceback
import unittest
from _common import Sleep
from _common import BlueText
from _common import GreenText
from _common import RedText
from _common import PromptAndWaitForUserAction
from _common import PromptUserAction
from _config import Constants
from _cpslib import GCPService
from _device import Device
from _oauth2 import Oauth2
from _ticket import CloudJobTicket, GCPConstants
from _transport import Transport
from _zconf import MDNS_Browser
from _zconf import Wait_for_privet_mdns_service
# Module level variables
_logger = None
_transport = None
_device = None
_oauth2 = None
_gcp = None
_sheet = None
def _ParseArgs():
"""Parse command line options."""
parser = optparse.OptionParser()
parser.add_option('--autorun',
help='Skip manual input',
default=Constants.AUTOMODE,
action="store_true",
dest='autorun')
parser.add_option('--no-autorun',
help='Do not skip manual input',
default=Constants.AUTOMODE,
action="store_false",
dest='autorun')
parser.add_option('--debug',
help='Specify debug log level [default: %default]',
default='info',
type='choice',
choices=['debug', 'info', 'warning', 'error', 'critical'],
dest='debug')
parser.add_option('--email',
help='Email account to use [default: %default]',
default=Constants.USER['EMAIL'],
dest='email')
parser.add_option('--if-addr',
help='Interface address for Zeroconf',
default=None,
dest='if_addr')
parser.add_option('--loadtime',
help='Seconds for web pages to load [default: %default]',
default=10,
type='float',
dest='loadtime')
parser.add_option('--logdir',
help='Relative directory for logfiles [default: %default]',
default=Constants.LOGFILES,
dest='logdir')
parser.add_option('--printer',
help='Name of printer [default: %default]',
default=Constants.PRINTER['NAME'],
dest='printer')
parser.add_option('--no-stdout',
help='Do not send output to stdout',
default=True,
action="store_false",
dest='stdout')
return parser.parse_args()
# The setUpModule will run one time, before any of the tests are run. The global
# keyword must be used in order to give all of the test classes access to
# these objects. This approach is used to eliminate the need for initializing
# all of these objects for each and every test class.
def setUpModule():
global _device
global _gcp
global _logger
global _oauth2
global _transport
# Initialize globals and constants
options, unused_args = _ParseArgs()
_logger = _log.GetLogger('LogoCert', logdir=options.logdir,
loglevel=options.debug, stdout=options.stdout)
_oauth2 = Oauth2(_logger)
# Retrieve access + refresh tokens
_oauth2.GetTokens()
# Wait to receive Privet printer advertisements. Timeout in 30 seconds
printer_service = Wait_for_privet_mdns_service(30, Constants.PRINTER['NAME'],
_logger)
if printer_service is None:
_logger.info("No printers discovered under "+ options.printer)
sys.exit()
privet_port = None
if hasattr(printer_service, 'port'):
privet_port = int(printer_service.port)
_logger.debug('Privet advertises port: %d', privet_port)
_gcp = GCPService(Constants.AUTH["ACCESS"])
_device = Device(_logger, Constants.AUTH["ACCESS"], _gcp,
privet_port= privet_port if 'PORT' not in Constants.PRINTER
else Constants.PRINTER['PORT'])
_transport = Transport(_logger)
if Constants.TEST['SPREADSHEET']:
global _sheet
_sheet = _sheets.SheetMgr(_logger, _oauth2.storage.get(), Constants)
# pylint: enable=global-variable-undefined
def LogTestSuite(name):
"""Log a test result.
Args:
name: string, name of the testsuite that is logging.
"""
print ('========================================'
'========================================')
print ' Starting %s testSuite'% (name)
print ('========================================'
'========================================')
if Constants.TEST['SPREADSHEET']:
row = [name,'','','','','','','']
_sheet.AddRow(row)
def isPrinterAdvertisingAsRegistered(service):
"""Checks the printer's privet advertisements and see if it is advertising
as registered or not
Args:
service: ServiceInfo, printer's service Info
Returns:
boolean, True = advertising as registered,
False = advertising as unregistered,
None = advertisement not found
"""
return ('id' in service.properties and
service.properties['id'] and
'online' in service.properties['cs'].lower())
def waitForAdvertisementRegStatus(name, is_wait_for_reg, timeout):
"""Wait for the device to privet advertise as registered or unregistered
Args:
name: string, device status to wait on
is_wait_for_reg: boolean, True for registered , False for unregistered
timeout: integer, seconds to wait for the service update
Returns:
boolean, True = status observed, False = status not observed.
"""
global _logger
end = time.time() + timeout
while time.time() < end:
service = Wait_for_privet_mdns_service(end-time.time(), name, _logger)
if service is None:
_logger.info("No printers discovered under " + name)
else:
is_registered = isPrinterAdvertisingAsRegistered(service)
if is_registered is is_wait_for_reg:
return True
return False
def writeRasterToFile(file_path, content):
""" Save a raster image to file
Args:
file_path: string, file path to write to
content: string, content to write
"""
f = open(file_path, 'wb')
f.write(content)
f.close()
print "Wrote Raster file:%s to disk" % file_path
def getRasterImageFromCloud(pwg_path, img_path):
""" Submit a GCP print job so that the image is coverted to a supported raster
file that can be downloaded. Then download the raster image from the cloud
and save it to disk
Args:
pwg_path: string, destination file path of the pwg_raster image
img_path: string, src file path of the image to convert from
"""
#
cjt = CloudJobTicket()
if Constants.CAPS['COLOR']:
cjt.AddColorOption(GCPConstants.COLOR)
print 'Generating pwg-raster via cloud print'
output = _gcp.Submit(_device.dev_id, img_path,
'LocalPrinting Raster Setup', cjt)
if not output['success']:
print 'ERROR: Cloud printing failed.'
raise
else:
try:
_gcp.WaitJobStateIn(output['job']['id'], _device.dev_id,
GCPConstants.IN_PROGRESS)
except AssertionError:
print 'GCP ERROR: Job not observed to be in progress.'
raise
else:
try:
res = _gcp.FetchRaster(output['job']['id'])
except AssertionError:
print "ERROR: FetchRaster() failed."
print "LocalPrinting suite cannot run without raster files."
raise
else:
writeRasterToFile(pwg_path, res)
print '[Configurable timeout] PRINTING'
_gcp.WaitJobStateIn(output['job']['id'], _device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
def getLocalPrintingRasterImages():
""" Checks to see if the raster images used for local printing exist on the
machine, generate and store to disk if not
"""
if not os.path.exists(Constants.IMAGES['PWG1']):
print '\n%s not found.'% (Constants.IMAGES['PWG1'])
print 'Likely that this is the first time LocalPrinting suite is run.'
getRasterImageFromCloud(Constants.IMAGES['PWG1'], Constants.IMAGES['PNG7'])
if not os.path.exists(Constants.IMAGES['PWG2']):
print '\n%s not found.' % (Constants.IMAGES['PWG2'])
print 'Likely that this is the first time LocalPrinting suite is run.'
getRasterImageFromCloud(Constants.IMAGES['PWG2'], Constants.IMAGES['PDF10'])
class LogoCert(unittest.TestCase):
"""Base Class to drive Logo Certification tests."""
def shortDescription(self):
'''Overriding the docstring printout function'''
doc = self._testMethodDoc
msg = doc and doc.split("\n")[0].strip() or None
return BlueText('\n=================================='
'====================================\n' + msg + '\n')
@classmethod
def setUpClass(cls, suite=None):
options, unused_args = _ParseArgs()
cls.loadtime = options.loadtime
cls.username = options.email
cls.autorun = options.autorun
cls.printer = options.printer
cls.monochrome = GCPConstants.MONOCHROME
cls.color = (GCPConstants.COLOR if Constants.CAPS['COLOR']
else cls.monochrome)
# Refresh access token in case it has expired
_oauth2.RefreshToken()
_device.auth_token = Constants.AUTH['ACCESS']
_gcp.auth_token = Constants.AUTH['ACCESS']
suite_name = cls.__name__ if suite is None else suite.__name__
LogTestSuite(suite_name)
def ManualPass(self, test_id, test_name, print_test=True):
"""Take manual input to determine if a test passes.
Args:
test_id: integer, testid in TestTracker database.
test_name: string, name of test.
print_test: boolean, True = print test, False = not print test.
Returns:
boolean: True = Pass, False = Fail.
If self.autorun is set to true, then this method will pause and return True.
"""
if self.autorun:
if print_test:
notes = 'Manually examine printout to verify correctness.'
else:
notes = 'Manually verify the test produced the expected result.'
self.LogTest(test_id, test_name, 'Passed', notes)
Sleep('AUTO_RUN')
return True
print 'Did the test produce the expected result?'
result = ''
while result.lower() not in ['y','n']:
result = PromptAndWaitForUserAction('Enter "y" or "n"')
try:
self.assertEqual(result.lower(), 'y')
except AssertionError:
notes = PromptAndWaitForUserAction('Type in additional notes for test '
'failure, hit return when finished')
self.LogTest(test_id, test_name, 'Failed', notes)
return False
else:
self.LogTest(test_id, test_name, 'Passed')
return True
def CheckAndRefreshToken(self):
"""Refresh oauth access token and updates dependent objects accordingly"""
# Oauth Access tokens expire in 1 hr, but we refresh every 30 minutes just
# to stay on the safe side
if time.time() > Constants.AUTH['PREV_TOKEN_TIME'] + 1800:
_oauth2.RefreshToken()
_device.auth_token = Constants.AUTH['ACCESS']
_gcp.auth_token = Constants.AUTH['ACCESS']
def LogTest(self, test_id, test_name, result, notes=''):
"""Log a test result.
Args:
test_id: integer, test id in the TestTracker application.
test_name: string, name of the test.
result: string, ["Passed", "Failed", "Skipped", "Not Run"]
notes: string, notes to include with the test result.
"""
failure = False if result.lower() in ['passed','skipped','n/a'] else True
console_result = RedText(result) if failure else GreenText(result)
console_test_name = RedText(test_name) if failure else GreenText(test_name)
print '' # For spacing
_logger.info('Test ID: %s', test_id)
_logger.info('Result: %s', console_result)
_logger.info('Name: %s', console_test_name)
if notes:
console_notes = RedText(notes) if failure else GreenText(notes)
_logger.info('Notes: %s', console_notes)
if Constants.TEST['SPREADSHEET']:
row = [str(test_id), test_name, result, notes,'','','']
if failure:
# If failed, generate the cmd that to rerun this testcase
# Get module name - name of this python script
module = 'testcert'
# Get the caller's class name
testsuite = sys._getframe(1).f_locals['self'].__class__.__name__
# Since some testcases contain multiple test ids, we cannot simply use
# test_name to invoke the testcase it belongs to
# Use traceback to get a list of functions in the callstack that begins
# with test, the current testcase is the last entry on the list
pattern = r', in (test.+)\s'
testcase = [re.search(pattern, x).group(1) for x in
traceback.format_stack() if
re.search(pattern, x) is not None][-1]
row.append('python -m unittest %s.%s.%s' %(module,testsuite,testcase))
_sheet.AddRow(row)
@classmethod
def GetDeviceDetails(cls):
_device.GetDeviceDetails()
if not _device.name:
_logger.error('Error finding device via privet.')
_logger.error('Check printer model in _config file.')
raise unittest.SkipTest('Could not find device via privet.')
else:
_logger.debug('Printer name: %s', _device.name)
_logger.debug('Printer status: %s', _device.status)
for k in _device.details:
_logger.debug(k)
_logger.debug(_device.details[k])
_logger.debug('===============================')
_device.GetDeviceCDD(_device.dev_id)
for k in _device.cdd:
_logger.debug(k)
_logger.debug(_device.cdd[k])
_logger.debug('===============================')
class SystemUnderTest(LogoCert):
"""Record details about the system under test and test environment."""
def testRecordTestEnv(self):
"""Record test environment details to Google Sheets."""
test_id = '459f04a4-7109-404c-b9e3-64573a077a65'
test_name = 'Test Environment'
os_type = '%s %s' % (platform.system(), platform.release())
python_version = sys.version
notes = 'OS: %s\n' % os_type
notes += 'Python: %s\n' % python_version
notes += 'Code Version: %s' % self.getCodeVersion()
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterDetails(self):
"""Record printer details to Google Sheets."""
test_id = 'ec2f8266-6c3e-4ebd-a7b5-df4792a5d93a'
test_name = 'Printer Details'
notes = 'Manufacturer: %s\n' % Constants.PRINTER['MANUFACTURER']
notes += 'Model: %s\n' % Constants.PRINTER['MODEL']
notes += 'Name: %s\n' % Constants.PRINTER['NAME']
notes += 'Device Status: %s\n' % Constants.PRINTER['STATUS']
notes += 'Firmware: %s\n' % Constants.PRINTER['FIRMWARE']
notes += 'Serial Number: %s\n' % Constants.PRINTER['SERIAL']
notes += self.getCAPS()
self.LogTest(test_id, test_name, 'Passed', notes)
def getCAPS(self):
caps = 'CAPS = {\n'
for k,v in Constants.CAPS.iteritems():
caps += " '%s': %s,\n" % (k,v)
caps += '}\n'
return caps
def getCodeVersion(self):
version = 'N/A'
if os.path.isfile('version'):
with open('version', ) as f:
version = f.read()
return version
class Privet(LogoCert):
"""Verify device integrates correctly with the Privet protocol.
These tests should be run before a device is registered.
"""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsUnregistered()
def testPrivetInfoAPI(self):
"""Verify device responds to PrivetInfo API requests."""
test_id = '7201b68f-de0b-4e93-a1a6-d674af9ec6ec'
test_name = 'PrivetAPI.Info'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('x-privet-token', _device.privet_info)
except AssertionError:
notes = 'No x-privet-token found. Error in privet info API.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'X-Privet-Token: %s' % _device.privet_info['x-privet-token']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIManufacturer(self):
"""Verify device PrivetInfo API contains manufacturer field."""
test_id = '58fedd52-3bc4-472b-897e-55ee5675fa5c'
test_name = 'PrivetInfoAPI.Manufacturer'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('manufacturer', _device.privet_info)
except AssertionError:
notes = 'manufacturer not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Manufacturer: %s' % _device.privet_info['manufacturer']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIModel(self):
"""Verify device PrivetInfo API contains model field."""
test_id = 'a0421845-9477-487f-8674-4203cbe6801b'
test_name = 'PrivetInfoAPI.Model'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('model', _device.privet_info)
except AssertionError:
notes = 'model not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Model: %s' % _device.privet_info['model']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIFirmware(self):
"""Verify device PrivetInfo API contains firmware field."""
test_id = '4c055e06-02aa-436d-b700-80f184e84f47'
test_name = 'PrivetInfoAPI.Firmware'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('firmware', _device.privet_info)
except AssertionError:
notes = 'firmware not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Firmware: %s' % _device.privet_info['firmware']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIUpdateUrl(self):
"""Verify device PrivetInfo API contains update_url field."""
test_id = 'd469199f-fcbd-4a83-90bf-772453be2b09'
test_name = 'PrivetInfoAPI.UpdateURL'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('update_url', _device.privet_info)
except AssertionError:
notes = '(OPTIONAL) update_url not found in privet info.'
self.LogTest(test_id, test_name, 'Skipped', notes)
raise
else:
notes = 'update_url: %s' % _device.privet_info['update_url']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIVersion(self):
"""Verify device PrivetInfo API contains version field."""
test_id = '7a5c02f3-26f6-4df4-b8c8-953bedd4ba2d'
test_name = 'PrivetInfoAPI.Version'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
valid_versions = ['1.0', '1.1', '1.5', '2.0']
try:
self.assertIn('version', _device.privet_info)
except AssertionError:
notes = 'version not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['version'], valid_versions)
except AssertionError:
notes = 'Incorrect GCP Version in privetinfo: %s' % (
_device.privet_info['version'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Version: %s' % _device.privet_info['version']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoDeviceState(self):
"""Verify device PrivetInfo API contains DeviceState and valid value."""
test_id = 'c3ea4263-3745-4d69-8dd4-578f5e5a336b'
test_name = 'PrivetInfoAPI.DeviceState'
valid_states = ['idle', 'processing', 'stopped']
try:
self.assertIn('device_state', _device.privet_info)
except AssertionError:
notes = 'device_state not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['device_state'], valid_states)
except AssertionError:
notes = 'Incorrect device_state in privet info: %s' % (
_device.privet_info['device_state'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device state: %s' % _device.privet_info['device_state']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoConnectionState(self):
"""Verify device PrivetInfo contains ConnectionState and valid value."""
test_id = '8ab9ac16-0c6e-47ec-a24e-c5ad4f77abb2'
test_name = 'PrivetInfoAPI.ConnectionState'
valid_states = ['online', 'offline', 'connecting', 'not-configured']
try:
self.assertIn('connection_state', _device.privet_info)
except AssertionError:
notes = 'connection_state not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['connection_state'], valid_states)
except AssertionError:
notes = 'Incorrect connection_state in privet info: %s' % (
_device.privet_info['connection_state'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Connection state: %s' % _device.privet_info['connection_state']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetAccessTokenAPI(self):
"""Verify unregistered device Privet AccessToken API returns correct rc."""
test_id = 'ffa0d9dc-840f-486a-a890-91773fc2b12d'
test_name = 'PrivetAPI.AccessToken'
api = 'accesstoken'
expected_return_code = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_code)
except AssertionError:
notes = ('Incorrect return code from %s: Got %d, Expected %d.\n'
% (_device.privet_url[api], response.status_code,
expected_return_code))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned response code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetCapsAPI(self):
"""Verify unregistered device Privet Capabilities API returns correct rc."""
test_id = '3bd87d10-301d-43b4-b959-96ede9537526'
test_name = 'PrivetAPI.Capabilities'
api = 'capabilities'
expected_return_code = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_code)
except AssertionError:
notes = ('Incorrect return code from %s: Got %d, Expected %d.\n'
% (_device.privet_url[api], response.status_code,
expected_return_code))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetPrinterAPI(self):
"""Verify unregistered device Privet Printer API returns correct rc."""
test_id = 'c957966b-b63c-4827-94fa-1bf1fe930638'
test_name = 'PrivetAPI.Printer'
api = 'printer'
expected_return_codes = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_codes)
except AssertionError:
notes = 'Incorrect return code, found %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetUnknownURL(self):
"""Verify device returns 404 return code for unknown url requests."""
test_id = '12119bbe-7707-44f3-8743-8cde0696dcd0'
test_name = 'PrivetAPI.UnknownURL'
response = _transport.HTTPGet(_device.privet_url['INVALID'],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 404)
except AssertionError:
notes = 'Wrong return code received. Received %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Received correct return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetRegisterAPI(self):
"""Verify unregistered device exposes register API."""
test_id = 'f875316e-7189-4321-8ac7-bf5e1bd53d8d'
test_name = 'PrivetAPI.Register'
success = _device.StartPrivetRegister()
try:
self.assertTrue(success)
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Privet registration API working correctly'
self.LogTest(test_id, test_name, 'Passed', notes)
# Cancel the registration so the printer is not in an unknown state
_device.CancelRegistration()
def testPrivetRegistrationInvalidParam(self):
"""Verify device return error if invalid registration param given."""
test_id = 'b2d25268-86aa-41f5-8891-3a5e29c4dbff'
test_name = 'PrivetAPI.RegistrationInvalidParam'
url = _device.privet_url['register']['invalid']
params = {'user': Constants.USER['EMAIL']}
response = _transport.HTTPPost(url, headers=_device.headers, params=params)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Response code from invalid registration params: %d' % (
response.status_code)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
info = response.json()
try:
self.assertIn('error', info)
except AssertionError:
notes = 'Did not find error message. Error message: %s' % (
info)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Received correct error code and response: %d\n%s' % (
response.status_code, info)
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
def testPrivetInfoAPIEmptyToken(self):
"""Verify device returns code 200 if Privet Token is empty."""
test_id = '1c3d8852-0130-49e1-baab-396fabb774a9'
test_name = 'PrivetInfoAPI.EmptyToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_empty)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIInvalidToken(self):
"""Verify device returns code 200 if Privet Token is invalid."""
test_id = '83eafa05-bfe4-480a-8a24-c44e57b78252'
test_name = 'PrivetInfoAPI.InvalidToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_invalid)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIMissingToken(self):
"""Verify device returns code 400 if Privet Token is missing."""
test_id = 'bdd2be1d-1ee1-4348-b95d-59916947e10b'
test_name = 'PrivetInfoAPI.MissingToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_missing)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 400)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testDeviceRegistrationInvalidClaimToken(self):
"""Verify a device will not register if the claim token is invalid."""
test_id = '80afa1d1-bd62-4534-87e6-49f9905f6973'
test_name = 'PrivetAPI.RegistrationInvalidClaimToken'
try:
self.assertTrue(_device.StartPrivetRegister())
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
_device.claim_token = 'INVALID'
_device.automated_claim_url = (
'https://www.google.com/cloudprint/confirm?token=INVALID')
try:
self.assertFalse(_device.SendClaimToken(Constants.AUTH['ACCESS']))
except AssertionError:
notes = 'Device accepted invalid claim token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device did not accept invalid claim token.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
def testDeviceRegistrationInvalidUserAuthToken(self):
"""Verify a device will not register if the user auth token is invalid."""
test_id = 'ac798d92-4789-4e0e-ad59-da5ce5ae0be2'
test_name = 'PrivetAPI.RegistrationInvalidUserAuthToken'
try:
self.assertTrue(_device.StartPrivetRegister())
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
if Constants.CAPS['PRINTER_PANEL_UI'] or Constants.CAPS['WEB_URL_UI']:
PromptUserAction('ACCEPT the registration request on the Printer '
'Panel or Web UI and wait...')
try:
self.assertTrue(_device.GetPrivetClaimToken())
except AssertionError:
notes = 'Error getting claim token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertFalse(_device.SendClaimToken('INVALID_USER_AUTH_TOKEN'))
except AssertionError:
notes = 'Claim token accepted with invalid User Auth Token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Claim token not accepted with invalid user auth token.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
class Printer(LogoCert):
"""Verify printer provides necessary details."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
LogoCert.GetDeviceDetails()
def testPrinterName(self):
"""Verify printer provides a name."""
test_id = '56f55e15-a170-4963-8523-eedd69877892'
test_name = 'CDD.name'
try:
self.assertIsNotNone(_device.name)
except AssertionError:
notes = 'No printer name found.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
_logger.info('Printer name found in details.')
try:
self.assertIn(Constants.PRINTER['NAME'], _device.name)
except AssertionError:
notes = 'NAME in _config.py does not match. Found %s' % _device.name
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('name', _device.cdd)
except AssertionError:
notes = 'Printer CDD missing printer name.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
_logger.info('Printer name found in CDD.')
try:
self.assertIn(Constants.PRINTER['NAME'], _device.cdd['name'])
except AssertionError:
notes = ('NAME in _config.py does not match name in CDD. Found %s in CDD'
% _device.cdd['name'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer name: %s' % _device.name
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterStatus(self):
"""Verify printer has online status."""
test_id = '0197ce66-ab79-4b0c-be02-c78325cda7fe'
test_name = 'CDD.Status'
try:
self.assertIsNotNone(_device.status)
except AssertionError:
notes = 'Device has no status.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('ONLINE', _device.status)
except AssertionError:
notes = 'Device is not online. Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterModel(self):
"""Verify printer provides a model string."""
test_id = '5be33583-4acb-4e6f-9c28-cbf4070839bd'
test_name = 'CDD.model'
try:
self.assertIn('model', _device.details)
except AssertionError:
notes = 'Model is missing from the printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn(Constants.PRINTER['MODEL'], _device.details['model'])
except AssertionError:
notes = 'Model incorrect, printer details: %s' % _device.details['model']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('model', _device.cdd)
except AssertionError:
notes = 'Model is missing from the printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn(Constants.PRINTER['MODEL'], _device.cdd['model'])
except AssertionError:
notes = 'Printer model has unexpected value. Found %s' % (
_device.cdd['model'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Model: %s' % _device.details['model']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterManufacturer(self):
"""Verify printer provides a manufacturer string."""
test_id = '2df537db-2de1-433e-94e0-cf87782d76db'
test_name = 'CDD.manufacturer'
try:
self.assertIn('manufacturer', _device.details)
except AssertionError:
notes = 'Manufacturer in not set in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn(Constants.PRINTER['MANUFACTURER'],
_device.details['manufacturer'])
except AssertionError:
notes = 'Manufacturer is not in printer details. Found %s' % (
_device.details['manufacturer'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('manufacturer', _device.cdd)
except AssertionError:
notes = 'Manufacturer is not set in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn(Constants.PRINTER['MANUFACTURER'],
_device.cdd['manufacturer'])
except AssertionError:
notes = 'Manufacturer not found in printer CDD. Found %s' % (
_device.cdd['manufacturer'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Manufacturer: %s' % _device.details['manufacturer']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterUUID(self):
"""Verify printer provides a UUID ( equilvalent to serial number )."""
test_id = '777cb00b-7297-4268-8d76-b96ef98df30f'
test_name = 'CDD.SerialNumber'
try:
self.assertIn('uuid', _device.details)
except AssertionError:
notes = 'Serial number not found in device details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.details['uuid']), 1)
except AssertionError:
notes = 'Serial number does is not valid number.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Serial Number: %s' % _device.details['uuid']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterGCPVersion(self):
"""Verify printer provides GCP Version supported."""
test_id = '36d37e66-5aac-446a-bcaf-3815dc2169da'
test_name = 'CDD.gcpVersion'
try:
self.assertIn('gcpVersion', _device.details)
except AssertionError:
notes = 'GCP Version not found in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertEqual('2.0', _device.details['gcpVersion'])
except AssertionError:
notes = 'Version 2.0 not found in GCP Version support. Found %s' % (
_device.details['gcpVersion'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('gcpVersion', _device.cdd)
except AssertionError:
notes = 'GCP Version not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertEqual('2.0', _device.cdd['gcpVersion'])
except AssertionError:
notes = 'Version 2.0 not found in GCP Version. Found %s' % (
_device.cdd['gcpVersion'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'GCP Version: %s' % _device.details['gcpVersion']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterFirmwareVersion(self):
"""Verify printer provides a firmware version."""
test_id = '139b03d7-117b-4e20-ba7d-6a3968d03804'
test_name = 'CDD.Firmware'
try:
self.assertIn('firmware', _device.details)
except AssertionError:
notes = 'Firmware version is missing in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.details['firmware']), 1)
except AssertionError:
notes = 'Firmware version is not correctly identified.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('firmware', _device.cdd)
except AssertionError:
notes = 'Firmware version is missing in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['firmware']), 1)
except AssertionError:
notes = 'Firmware version is not correctly identified in CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Firmware version: %s' % _device.details['firmware']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterType(self):
"""Verify printer provides a type."""
test_id = '2e2e0414-2775-4a41-be17-5698c14f85b6'
test_name = 'CDD.PrinterType'
try:
self.assertIn('type', _device.details)
except AssertionError:
notes = 'Printer Type not found in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('GOOGLE', _device.details['type'])
except AssertionError:
notes = 'Incorrect Printer Type in details. Found %s' % (
_device.details['type'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('type', _device.cdd)
except AssertionError:
notes = 'Printer Type not found in printer CDD'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('GOOGLE', _device.cdd['type'])
except AssertionError:
notes = 'Incorrect Printer Type in CDD. Found %s' % _device.cdd['type']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer Type: %s' % _device.details['type']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterFirmwareUpdateUrl(self):
"""Verify printer provides a firmware update URL."""
test_id = 'dbc975aa-6005-4b00-9ead-c9ce42f387f2'
test_name = 'CDD.UpdateURL'
try:
self.assertIn('updateUrl', _device.details)
except AssertionError:
notes = 'Firmware update url not found in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(
_device.details['updateUrl']), 10)
except AssertionError:
notes = 'Firmware Update URL is not valid in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('updateUrl', _device.cdd)
except AssertionError:
notes = 'Firmware update Url not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['updateUrl']), 10)
except AssertionError:
notes = 'Firmware Update URL is not valid in CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Firmware Update URL: %s' % (
_device.details['updateUrl'])
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterProxy(self):
"""Verify that printer provides a proxy."""
test_id = '5740c76a-7d69-4304-a5f4-e263fb98a5ce'
test_name = 'CDD.PrinterProxy'
try:
self.assertIn('proxy', _device.details)
except AssertionError:
notes = 'Proxy not found in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.details['proxy']), 1)
except AssertionError:
notes = 'Proxy is not valid value.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('proxy', _device.cdd)
except AssertionError:
notes = 'Proxy not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['proxy']), 1)
except AssertionError:
notes = 'Proxy is not valid value.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer Proxy: %s' % _device.details['proxy']
self.LogTest(test_id, test_name, 'Passed', notes)
def testSetupUrl(self):
"""Verify the printer provides a setup URL."""
test_id = '7811e41d-90ea-44c5-b522-ea45751ef6a0'
test_name = 'CDD.SetupURL'
try:
self.assertIn('setupUrl', _device.cdd)
except AssertionError:
notes = 'Setup URL not found in CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['setupUrl']), 10)
except AssertionError:
notes = 'Setup URL is not a valid. Found %s' % _device.cdd['setupUrl']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Setup URL: %s' % _device.cdd['setupUrl']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterID(self):
"""Verify Printer has a PrinterID."""
test_id = '6503a6b0-5e69-4165-ae7a-27d080f995f0'
test_name = 'CDD.ID'
try:
self.assertIsNotNone(_device.dev_id)
except AssertionError:
notes = 'Printer ID not found in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.dev_id), 10)
except AssertionError:
notes = 'Printer ID is not valid in printer details.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('id', _device.cdd)
except AssertionError:
notes = 'Printer ID not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['id']), 10)
except AssertionError:
notes = 'Printer ID is not valid in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer ID: %s' % _device.dev_id
self.LogTest(test_id, test_name, 'Passed', notes)
def testLocalSettings(self):
"""Verify the printer contains local settings."""
test_id = 'd5668a87-4341-4891-9f07-7da377ce4eea'
test_name = 'CDD.local_settings'
try:
self.assertIn('local_settings', _device.cdd)
except AssertionError:
notes = 'local_settings not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('current', _device.cdd['local_settings'])
except AssertionError:
notes = 'No current settings found in local_settings.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Local settings: %s' % _device.cdd['local_settings']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCaps(self):
"""Verify the printer contains capabilities."""
test_id = 'e46a6823-0a94-4b9a-a7fd-afab3b9e5c73'
test_name = 'CDD.capabilities'
try:
self.assertIn('caps', _device.cdd)
except AssertionError:
notes = 'No capabilities found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['caps']), 10)
except AssertionError:
notes = 'Capabilities does not have required entries.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.LogTest(test_id, test_name, 'Passed')
def testUuid(self):
"""Verify the printer contains a UUID."""
test_id = '6d06cc18-6b4a-489a-bdfb-cccd7c3ee0d8'
test_name = 'CDD.UUID'
try:
self.assertIn('uuid', _device.cdd)
except AssertionError:
notes = 'uuid not found in printer CDD.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertGreaterEqual(len(_device.cdd['uuid']), 1)
except AssertionError:
notes = 'uuid is not a valid value.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'UUID: %s' % _device.cdd['uuid']
self.LogTest(test_id, test_name, 'Passed', notes)
def testDefaultDisplayName(self):
"""Verify Default Display Name is present."""
test_id = '6c0d4832-7ca5-4ab6-a483-997f2cea26f0'
test_name = 'CDD.DefaultDisplayName'
try:
self.assertIn('defaultDisplayName', _device.cdd)
except AssertionError:
notes = 'defaultDisplayName not found in printer CDD'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.LogTest(test_id, test_name, 'Passed')
def testCapsSupportedContentType(self):
"""Verify supported_content_type contains needed types."""
test_id = '87762b98-7bbf-4edd-92e8-b5495b7fc8e3'
test_name = 'CDD.supported_content_type'
try:
self.assertIn('supported_content_type', _device.cdd['caps'])
except AssertionError:
notes = 'supported_content_type missing from printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
content_types = []
for item in _device.cdd['caps']['supported_content_type']:
for k in item:
if k == 'content_type':
content_types.append(item[k])
try:
self.assertIn('image/pwg-raster', content_types)
except AssertionError:
s = 'image/pwg-raster not found in supported content types.'
notes = s + '\nFound: %s' % content_types
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Supported content types: %s' % (
_device.cdd['caps']['supported_content_type'])
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsPwgRasterConfig(self):
"""Verify printer CDD contains a pwg_raster_config parameter."""
test_id = 'eb19cc7e-556f-4356-a3b9-c2d5979fa4ca'
test_name = 'CDD.pwg_raster_config'
try:
self.assertIn('pwg_raster_config', _device.cdd['caps'])
except AssertionError:
notes = 'pwg_raster_config parameter not found in printer cdd.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'pwg_raster_config: %s' % (
_device.cdd['caps']['pwg_raster_config'])
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsInputTrayUnit(self):
"""Verify input_tray_unit is in printer capabilities."""
test_id = '3998c0b2-1277-4e60-b7ff-7ac28c5d8aba'
test_name = 'CDD.input_tray_unit'
try:
self.assertIn('input_tray_unit', _device.cdd['caps'])
except AssertionError:
notes = 'input_tray_unit not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'input_tray_unit: %s' % _device.cdd['caps']['input_tray_unit']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsOutputBinUnit(self):
"""Verify output_bin_unit is in printer capabilities."""
test_id = '438bb772-119f-42e5-a624-d0a543edba95'
test_name = 'CDD.output_bin_unit'
try:
self.assertIn('output_bin_unit', _device.cdd['caps'])
except AssertionError:
notes = '(OPTIONAL) output_bin_unit not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Skipped', notes)
raise
else:
notes = 'output_bin_unit: %s' % _device.cdd['caps']['output_bin_unit']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsMarker(self):
"""Verify marker is in printer capabilities."""
test_id = '6932133f-b2b4-420e-a95e-5d5ec2a70d8e'
test_name = 'CDD.marker'
try:
self.assertIn('marker', _device.cdd['caps'])
except AssertionError:
notes = 'marker not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'marker: %s' % _device.cdd['caps']['marker']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsCover(self):
"""Verify cover is in printer capabilities."""
test_id = '17145e5e-8bea-46cc-b9bc-c8e0c396756b'
test_name = 'CDD.cover'
try:
self.assertIn('cover', _device.cdd['caps'])
except AssertionError:
notes = 'cover not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'cover: %s' % _device.cdd['caps']['cover']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsColor(self):
"""Verify color is in printer capabilities."""
test_id = '2835bd83-2009-4864-82e4-33ae7e424557'
test_name = 'CDD.color'
try:
self.assertIn('color', _device.cdd['caps'])
except AssertionError:
notes = 'color not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'color: %s' % _device.cdd['caps']['color']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsDuplex(self):
"""Verify duplex is in printer capabilities."""
test_id = '75fbbffe-5530-4523-a4b8-4dfd0b9aee08'
test_name = 'CDD.duplex'
if not Constants.CAPS['DUPLEX']:
if ('duplex' in _device.cdd['caps'] and
'option' in _device.cdd['caps']['duplex'] and
len(_device.cdd['caps']['duplex']['option']) > 1):
# Possible for printers with no duplex support to have the duplex
# option in the CDD but with only 1 type: "NO_DUPLEX"
notes = 'Error in _config file, DUPLEX should be True'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
self.LogTest(test_id, test_name, 'Skipped', 'Duplex not supported')
return
try:
self.assertIn('duplex', _device.cdd['caps'])
except AssertionError:
notes = 'duplex not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'duplex: %s' % _device.cdd['caps']['duplex']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsCopies(self):
"""Verify copies is in printer capabilities."""
test_id = '2c87558d-d6a5-4f36-b10c-8e77aad2b53a'
test_name = 'CDD.copies'
if not Constants.CAPS['COPIES_CLOUD']:
if 'copies' in _device.cdd['caps']:
notes = 'Error in _config file, COPIES_CLOUD should be True'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
self.LogTest(test_id, test_name, 'Skipped', 'Copies not supported')
return
try:
self.assertIn('copies', _device.cdd['caps'])
except AssertionError:
notes = 'copies not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'copies: %s' % _device.cdd['caps']['copies']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsDpi(self):
"""Verify dpi is in printer capabilities."""
test_id = '40cb422c-f1e6-49ea-936a-62c9bb667f13'
test_name = 'CDD.dpi'
try:
self.assertIn('dpi', _device.cdd['caps'])
except AssertionError:
notes = 'dpi not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'dpi: %s' % _device.cdd['caps']['dpi']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsMediaSize(self):
"""Verify media_size is in printer capabilities."""
test_id = '69c8f693-ad42-4a77-b239-4f40205fca85'
test_name = 'CDD.media_size'
try:
self.assertIn('media_size', _device.cdd['caps'])
except AssertionError:
notes = 'media_size not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'media_size: %s' % _device.cdd['caps']['media_size']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsCollate(self):
"""Verify collate is in printer capabilities."""
test_id = '4f398f26-9770-49f0-9e34-523bd41d8f1c'
test_name = 'CDD.collate'
if not Constants.CAPS['COLLATE']:
if 'collate' in _device.cdd['caps']:
notes = 'Error in _config file, COLLATE should be True'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
notes = 'Printer does not support collate.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
try:
self.assertIn('collate', _device.cdd['caps'])
except AssertionError:
notes = 'collate not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'collate: %s' % _device.cdd['caps']['collate']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsPageOrientation(self):
"""Verify page_orientation is not in printer capabilities."""
test_id = '317fcdca-e663-41f9-b48a-8779dfe2f1ad'
test_name = 'CDD.page_orientation'
if Constants.CAPS['LAYOUT_ISSUE']:
notes = 'Chrome issue in local printing requires orientation in caps.'
self.LogTest(test_id, test_name, 'Skipped', notes)
else:
try:
self.assertNotIn('page_orientation', _device.cdd['caps'])
except AssertionError:
notes = 'page_orientation found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'page_orientation not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsMargins(self):
"""Verify margin is appropriately set/unset in printer capabilities."""
test_id = '7d60c7c7-08ed-45f2-9e39-1a50d45467a6'
test_name = 'OptionalInCDD.margins'
if not Constants.CAPS['MARGIN']:
print ('The Margins option in _config.py set to False, '
'so "margins" is NOT expected in the CDD')
try:
self.assertNotIn('margins', _device.cdd['caps'])
except AssertionError:
notes = ('"margins" found in printer capabilities. '
'Ensure the Margins option in _config.py is correctly set.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'margins not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
else:
print ('The Margins option in _config.py set to True, '
'so "margins" is expected in the CDD')
try:
self.assertIn('margins', _device.cdd['caps'])
except AssertionError:
notes = ('"margins" not found in printer capabilities. '
'Ensure the Margins option in _config.py is correctly set.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'margins found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsFitToPage(self):
"""Verify fit_to_page is not in printer capabilities."""
test_id = 'c29ae530-3395-4136-9289-47e93e9975da'
test_name = 'NotInCDD.fit_to_page'
try:
self.assertNotIn('fit_to_page', _device.cdd['caps'])
except AssertionError:
notes = 'fit_to_page found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'fit_to_page not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsPageRange(self):
"""Verify page_range is not in printer capabilities."""
test_id = '52873b94-ef48-4601-975e-4d90f2a85d51'
test_name = 'NotInCDD.page_range'
try:
self.assertNotIn('page_range', _device.cdd['caps'])
except AssertionError:
notes = 'page_range found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'page_range not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsReverseOrder(self):
"""Verify reverse_order is not in printer capabilities."""
test_id = '4004adbd-9322-402b-8e63-942b710cbaad'
test_name = 'NotInCDD.reverse_order'
try:
self.assertNotIn('reverse_order', _device.cdd['caps'])
except AssertionError:
notes = 'reverse_order found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'reverse_order not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsHash(self):
"""Verify printer CDD contains a capsHash."""
test_id = 'a9cbdeb3-c8a8-405c-a317-940a0b761f55'
test_name = 'CDD.capsHash'
try:
self.assertIn('capsHash', _device.cdd)
except AssertionError:
notes = 'capsHash not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'capsHash found in printer cdd.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsCertificationID(self):
"""Verify printer has a certificaionID and it is correct."""
test_id = '5ad8b344-4326-4456-a874-054b56bf68cc'
test_name = 'CDD.certificationID'
try:
self.assertIn('certificationId', _device.cdd)
except AssertionError:
notes = 'certificationId not found in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(Constants.PRINTER['CERTID'],
_device.cdd['certificationId'])
except AssertionError:
notes = 'Certification ID: %s, expected %s' % (
_device.cdd['certificationId'], Constants.PRINTER['CERTID'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Certification ID: %s' % _device.cdd['certificationId']
self.LogTest(test_id, test_name, 'Passed', notes)
def testCapsResolvedIssues(self):
"""Verify printer contains resolvedIssues in printer capabilities."""
test_id = 'f461801f-bc2e-416c-8949-d6d9971f05b1'
test_name = 'CDD.resolvedIssues'
try:
# Three scenarios that can each pass this test
# 1) field is totally omitted
# 2) field is an empty list
# 3) field is a list with one element, an empty string
self.assertTrue('resolvedIssues' not in _device.cdd or # omitted
not _device.cdd['resolvedIssues'] or # empty list
(len(_device.cdd['resolvedIssues']) == 1 and # empty str
not _device.cdd['resolvedIssues'][0] ))
except AssertionError:
notes = 'resolvedIssues found with elements in printer capabilities.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = ('resolvedIssues not found or found with an empty element in '
'printer capabilities.')
self.LogTest(test_id, test_name, 'Passed', notes)
class PreRegistration(LogoCert):
"""Tests to be run before device is registered."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
cls.sleep_time = 60
_device.assertPrinterIsUnregistered()
def testDeviceAdvertisePrivet(self):
"""Verify printer under test advertises itself using Privet."""
test_id = '5a24949f-1c78-4a7d-8f52-4f4c57b78f76'
test_name = 'Privet.Discoverable'
print 'Listening for the printer\'s advertisements for up to 60 seconds'
service = Wait_for_privet_mdns_service(60, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Device is not found advertising in privet'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
is_registered = isPrinterAdvertisingAsRegistered(service)
try:
self.assertFalse(is_registered)
except AssertionError:
notes = 'Device is advertising as a registered device'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device is advertising as an unregistered device'
self.LogTest(test_id, test_name, 'Passed', notes)
def testDeviceSleepingAdvertisePrivet(self):
"""Verify sleeping printer advertises itself using Privet."""
test_id = 'e8528e4d-370b-43a3-aee2-ad6f048dc367'
test_name = 'Privet.SleepModeAdvertise'
print 'Put the printer in sleep mode.'
PromptAndWaitForUserAction('Press ENTER when printer is sleeping.')
print 'Listening for the printer\'s advertisements for up to 60 seconds'
service = Wait_for_privet_mdns_service(60, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Device is not found advertising in privet'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
is_registered = isPrinterAdvertisingAsRegistered(service)
try:
self.assertFalse(is_registered)
except AssertionError:
notes = 'Device not advertising as a registered device in sleep mode'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device is advertising as an unregistered device in sleep mode'
self.LogTest(test_id, test_name, 'Passed', notes)
def testDeviceOffNoAdvertisePrivet(self):
"""Verify powered off device does not advertise using Privet."""
test_id = '27fba22f-e8b1-4fe2-821f-fff5ef4cac27'
test_name = 'Privet.PowerOffNotRegisteredNoAdvertise'
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
print 'Listening for the printer\'s advertisements for up to 60 seconds'
service = Wait_for_privet_mdns_service(60, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNone(service)
except AssertionError:
notes = 'Device found advertising when powered off'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device no longer advertising when powered off'
self.LogTest(test_id, test_name, 'Passed', notes)
"""Verify freshly powered on device advertises itself using Privet."""
test_id2 = '6f87d61b-8784-41be-bb38-0405f85cb2e3'
test_name2 = 'Privet.PowerOnNotRegisteredAdvertise'
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Device is not advertising in privet when freshly powered on'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
is_registered = isPrinterAdvertisingAsRegistered(service)
try:
self.assertFalse(is_registered)
except AssertionError:
notes = 'Device advertised as registered when freshly powered on'
self.LogTest(test_id2, test_name2, 'Failed', notes)
raise
else:
notes = 'Device advertised as unregistered when freshly powered on'
self.LogTest(test_id2, test_name2, 'Passed', notes)
finally:
# Get the new X-privet-token from the restart
_device.GetPrivetInfo()
def testDeviceRegistrationNotLoggedIn(self):
"""Test printer cannot be registered if user not logged in."""
test_id = '619926b7-c051-4d67-81b4-bb68bb4812a8'
test_name = 'Privet.GuestUserRegistration'
success = _device.Register('ACCEPT the registration request on Printer UI '
'and wait...', use_token=False)
try:
self.assertFalse(success)
except AssertionError:
notes = 'Able to register printer without an auth token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Not able to register printer without a valid auth token.'
self.LogTest(test_id, test_name, 'Passed', notes)
# Cancel the registration so the printer is not in an unknown state
_device.CancelRegistration()
def testDeviceCancelRegistrationPanelUI(self):
"""Test printer cancellation prevents registration."""
test_id = '842259b0-13df-496c-81bf-1f06bdd3a35f'
test_name = 'PrivetRegistration.PrinterPanelCancel'
_logger.info('Testing printer registration cancellation.')
if not Constants.CAPS['PRINTER_PANEL_UI']:
notes = 'No Printer Panel UI registration support.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Does the printer panel have an option for cancelling registration?'
result = ''
while result.lower() not in ['y', 'n']:
result = PromptAndWaitForUserAction('Enter "y" or "n"')
if result == 'n':
notes = 'No support for registration cancellation.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Testing printer registration cancellation.'
print 'Do not accept printer registration request on Printer Panel UI.'
registration_cancel_success = _device.detectRegisterCancel('CANCEL the '
'registration request on Printer '
'Panel UI and wait...')
if registration_cancel_success:
# Confirm the user's account has no registered printers
res = _gcp.Search(_device.name)
try:
# Assert that 'printers' list is empty
self.assertFalse(res['printers'])
except AssertionError:
notes = 'Unable to cancel registration request from Printer Panel UI.'
self.LogTest(test_id, test_name, 'Failed', notes)
PromptAndWaitForUserAction('Make sure printer is unregistered before '
'proceeding. Press ENTER to continue')
raise
else:
notes = 'Cancelled registration attempt from Printer Panel UI.'
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Error cancelling registration process.'
self.LogTest(test_id, test_name, 'Failed', notes)
_device.CancelRegistration()
def testDeviceCancelRegistrationWebUI(self):
"""Test printer cancellation prevents registration."""
test_id = '29194599-2629-44a0-b3c9-c5e54c5cec80'
test_name = 'PrivetRegistration.PrinterURLCancel'
_logger.info('Testing printer registration cancellation from '
'printer web UI.')
if not Constants.CAPS['WEB_URL_UI']:
notes = 'No Printer Web UI registration support.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Testing printer registration cancellation.'
print 'Do not accept printer registration request on Printer Web UI.'
registration_cancel_success = _device.detectRegisterCancel('CANCEL the '
'registration request on Printer '
'Web UI and wait...')
if registration_cancel_success:
# Confirm the user's account has no registered printers
res = _gcp.Search(_device.name)
try:
# Assert that 'printers' list is empty
self.assertFalse(res['printers'])
except AssertionError:
notes = 'Unable to cancel registration request.'
self.LogTest(test_id, test_name, 'Failed', notes)
PromptAndWaitForUserAction('Make sure printer is unregistered before '
'proceeding. Press ENTER to continue')
raise
else:
notes = 'Cancelled registration attempt from Printer Web UI.'
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Error cancelling registration process.'
self.LogTest(test_id, test_name, 'Failed', notes)
_device.CancelRegistration()
class Registration(LogoCert):
"""Test device registration."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsUnregistered()
def test_01_DeviceRegistrationTimeOut(self):
"""Verify printer registration times out properly"""
test_id = '1ce516e7-f831-465c-9ceb-2af9050b0dd9'
test_name = 'PrivetRegistration.NoUserAction'
if not (Constants.CAPS['PRINTER_PANEL_UI'] or Constants.CAPS['WEB_URL_UI']):
notes = 'Printer automatically accepts registration requests.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
ui_str = 'printer panel' if Constants.CAPS['PRINTER_PANEL_UI'] else 'web'
print 'Do not select accept/cancel registration from the %s U/I.' % ui_str
print 'Wait for the registration request to time out.'
# Timeout test
success = _device.StartPrivetRegister()
if success:
PromptAndWaitForUserAction('Press ENTER once the printer registration '
'times out.')
# Confirm the user's account has no registered printers
res = _gcp.Search(_device.name)
try:
self.assertFalse(res['printers'])
except AssertionError:
notes = ('Not able to cancel printer registration from '
'printer UI timeout.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer registration cancelled from printer UI timeout.'
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Not able to initiate printer registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def test_02_DeviceRegistrationPanelUI(self):
"""Verify printer panel UI shows registration prompt"""
test_id = 'dd233ea2-42e2-4a1e-a9ff-4df727edd591'
test_name = 'PrivetRegistration.PrinterPanelAccept'
if not Constants.CAPS['PRINTER_PANEL_UI']:
notes = 'No printer panel UI registration support.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
# Verify printer must accept registration requests on the printer panel
print 'Validate that the printer panel UI correctly showed a GCP '
print 'registration request during the previous "timeout" test'
print 'If printer does not have accept/cancel on printer panel,'
print 'Fail this test.'
self.ManualPass(test_id, test_name, print_test=False)
def test_03_DeviceRegistrationWebUI(self):
"""Verify Web URL UI shows registration prompt"""
test_id = 'e6a0cd4a-6db6-441d-9733-c7fb8e163ddc'
test_name = 'PrivetRegistration.PrinterURLAccept'
if not Constants.CAPS['WEB_URL_UI']:
notes = 'No Printer Web UI registration support.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
# Verify printer must accept registration requests on the printer panel
print 'Validate that the web URL UI correctly showed a GCP '
print 'registration request during the previous "timeout" test'
print 'If printer does not show a accept/cancel on Printer Web UI,'
print 'Fail this test.'
self.ManualPass(test_id, test_name, print_test=False)
def test_04_DeviceRegistration(self):
"""Verify printer registration using Privet
This test function actually executes three tests.
1- User1 successfully registers
2- User2 cannot register after User1 has begun registration process
3- Printer correctly advertises as registered after registration
"""
test_id = 'a2cefbe9-9c8b-4987-966c-c0da7343be17'
test_name = 'Privet.Registration'
test_id2 = '5b8b6d1d-618a-40c5-a16b-89de96b62262'
test_name2 = 'Privet.RegistrationMultipleUsers'
test_id3 = '5c3ccd4d-6d04-40b7-8dad-89164964b42d'
test_name3 = 'Privet.RegistrationAdvertise'
# Register user1
print 'Initiating a registration attempt for User1'
success = _device.StartPrivetRegister(user=Constants.USER['EMAIL'])
try:
self.assertTrue(success)
except AssertionError:
notes = 'Not able to register user1. Privet call /register/start failed'
self.LogTest(test_id, test_name, 'Failed', notes)
_device.CancelRegistration(user=Constants.USER['EMAIL'])
raise
else:
try:
success = _device.Register('User2 simultaneous registration attempt',
user=Constants.USER2['EMAIL'],
no_action=True, wait_for_user=False)
except EnvironmentError:
notes = ('Simultaneous registration failed. '
'getClaimToken() from User2\'s registration attempt '
'should not return the \'pending_user_action\' error msg. '
'The printer should reject User2\'s attempt since User1\'s '
'registration is already under way.')
self.LogTest(test_id2, test_name2, 'Failed', notes)
_device.CancelRegistration()
raise
else:
try:
self.assertFalse(success)
except AssertionError:
notes = 'Simultaneous registration succeeded.'
self.LogTest(test_id2, test_name2, 'Failed', notes)
raise
else:
notes = 'Simultaneous registration failed.'
self.LogTest(test_id2, test_name2, 'Passed', notes)
if Constants.CAPS['PRINTER_PANEL_UI'] or Constants.CAPS['WEB_URL_UI']:
PromptUserAction('ACCEPT the registration request from %s on the '
'Printer Panel or Web UI and wait...'
% Constants.USER['EMAIL'])
# Finish the registration process
success = False
if _device.GetPrivetClaimToken():
if _device.ConfirmRegistration(_device.auth_token):
success = _device.FinishPrivetRegister()
try:
self.assertTrue(success)
except AssertionError:
notes = 'User1 failed to register.'
self.LogTest(test_id, test_name, 'Failed', notes)
_device.CancelRegistration()
raise
else:
print 'Waiting up to 5 minutes to complete the registration.'
success = waitForAdvertisementRegStatus(Constants.PRINTER['NAME'],
True, 300)
try:
self.assertTrue(success)
except AssertionError:
notes = ('Registered device not found advertising '
'or found advertising as unregistered')
self.LogTest(test_id3, test_name3, 'Failed', notes)
else:
notes = 'Registered device found advertising correctly'
self.LogTest(test_id3, test_name3, 'Passed', notes)
res = _gcp.Search(_device.name)
try:
self.assertTrue(res['printers'])
except AssertionError:
notes = 'Registered printer not found via the GCP Search API.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = ('Successfully found registered printer via the GCP '
'Search API')
self.LogTest(test_id, test_name, 'Passed', notes)
class LocalDiscovery(LogoCert):
"""Tests Local Discovery functionality."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
def toggleOnLocalPrinting(self):
"""Turns on local printing"""
print ('Re-enabling local printing in case it turned off along with '
'local discovery')
setting = {'pending': {'printer/local_printing_enabled': True}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
print ('Error turning on Local Printing. Please manually renable Local '
'Printing and continue testing')
return
# Give the printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id,
'printer/local_printing_enabled', True)
if not success:
print 'Failed to detect update before timing out.'
else:
print 'Local printing toggled on successfully'
def testLocalDiscoveryToggle(self):
"""Verify printer behaves correctly when local discovery is toggled."""
test_id = '72133bd8-c945-4364-aa2b-69a2ee088c59'
test_name = 'GCP.LocalDiscoveryToggle'
notes = None
notes2 = None
setting = {'pending': {'local_discovery': False}}
print "Toggling off local discovery"
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes = 'Error turning off Local Discovery.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
# Give printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id, 'local_discovery', False)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Local Discovery was not disabled within 60 seconds.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Local Discovery successfully disabled'
# Should not be any advertisements from the printer anymore
print ('Listening for advertisements for 60 seconds, there should NOT '
'be any from the printer')
service = Wait_for_privet_mdns_service(60, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNone(service)
except AssertionError:
notes = 'Local Discovery disabled but privet advertisements detected.'
self.LogTest(test_id, test_name, 'Failed', notes)
print 'Attempting to toggle Local Discovery back on'
setting = {'pending': {'local_discovery': True}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
print 'Update error, please manually re-enable Local Discovery'
else:
print 'Local Discovery successfully re-enabled'
raise
else:
print 'Success, no printer advertisements detected'
notes = 'Local Discovery successfully disabled'
setting = {'pending': {'local_discovery': True}}
print "Toggling on local discovery"
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes2 = 'Error turning on Local Discovery.'
self.LogTest(test_id, test_name, 'Failed', notes + '\n' + notes2)
raise
else:
# Give printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id, 'local_discovery', True)
try:
self.assertTrue(success)
except AssertionError:
notes2 = 'Local Discovery was not enabled within 60 seconds.'
self.LogTest(test_id, test_name, 'Failed', notes2)
self.toggleOnLocalPrinting()
raise
else:
print 'Local Discovery successfully enabled'
print ('Listening for advertisements for up to 60 seconds, '
'there should be advertisements from the printer')
service = Wait_for_privet_mdns_service(60, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes2 = ('Local Discovery enabled, '
'but no privet advertisements detected.')
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
else:
print 'Printer advertisements detected'
finally:
self.toggleOnLocalPrinting()
notes2 = 'Local Discovery successfully enabled'
notes = notes + '\n' + notes2
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterOnAdvertiseLocally(self):
"""Verify printer sends start up advertisement packets when turned on.
"""
test_id = '79ae01a8-9af8-4666-9186-fd822158bb30'
test_name = 'Printer.TurnOn'
print 'This test should begin with the printer turned off.'
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Printer did not make privet packet.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer broadcast privet packet.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
# Get the new X-privet-token from the restart
_device.GetPrivetInfo()
def testPrinterOffSendGoodbyePacket(self):
"""Verify printer sends goodbye packet when turning off."""
test_id = 'c76fb24b-22ce-4c44-a692-df91697b759c'
test_name = 'Printer.TurnOff'
if not Constants.CAPS['GOODBYE_PACKET']:
notes = 'Printer does not send goodbye packet.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'This test must start with the printer on and operational.'
# Need a somewhat persistent browser (for the duration of this testcase
# at least) to detect service removal
mdns_browser = MDNS_Browser(_logger)
service = mdns_browser.Wait_for_service_add(30, Constants.PRINTER['NAME'])
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Printer did not send advertisement while powered on'
self.LogTest(test_id, test_name, 'Failed')
mdns_browser.Close()
raise
PromptUserAction('Turn off the printer and wait...')
is_off = mdns_browser.Wait_for_service_remove(120,
service)
try:
self.assertTrue(is_off)
except AssertionError:
notes = 'Printer did not send goodbye packet when powered off.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer sent goodbye packet when powered off.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
mdns_browser.Close()
# Turn the printer back on
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Error receiving the power-on signal from the printer.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def testPrinterIdleNoBroadcastPrivet(self):
"""Verify idle printer doesn't send mDNS broadcasts."""
test_id = '288ca17e-65fc-4a9b-bf1f-59272a987927'
test_name = 'Printer.ExistingOnlinePrinter'
print 'Ensure printer stays on and remains in idle state.'
# Service TTL should not be updated if there are no advertisements from the
# idle printer.
mdns_browser = MDNS_Browser(_logger)
service = mdns_browser.Wait_for_service_add(30, Constants.PRINTER['NAME'])
try:
self.assertIsNotNone(service)
except AssertionError:
mdns_browser.Close()
notes = ('No printer mDNS broadcast packets found while printer '
'is powered on.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
start_ttl = mdns_browser.Get_service_ttl(service)
# Monitor the local network for privet broadcasts.
print 'Listening for network broadcasts for 60 seconds.'
time.sleep(60)
end_ttl = mdns_browser.Get_service_ttl(service)
try:
self.assertTrue(start_ttl > end_ttl)
except AssertionError:
notes = ('Found printer mDNS broadcast packets containing privet while '
'printer is idle.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = ('No printer mDNS broadcast packets containing privet were '
'found while printer is idle.')
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
mdns_browser.Close()
def testUpdateLocalSettings(self):
"""Verify printer's local settings can be updated with Update API."""
test_id = 'b88c27c6-e6fa-48e6-a19e-4e581c0f8e1c'
test_name = 'GCP.UpdateLocalPrintSettings'
# Get the current xmpp timeout value.
orig = _device.cdd['local_settings']['current']['xmpp_timeout_value']
new = orig + 600
setting = {'pending': {'xmpp_timeout_value': new}}
print 'Updating xmpp timeout value via the update interface'
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes = 'Error sending Update of local settings.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
print 'Successfully updated'
success = _gcp.WaitForUpdate(_device.dev_id, 'xmpp_timeout_value', new)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Failed to detect update before timing out.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
# Refresh the values of the device.
_device.GetDeviceCDD(_device.dev_id)
timeout = _device.cdd['local_settings']['current']['xmpp_timeout_value']
try:
self.assertEqual(timeout, new)
except AssertionError:
notes = 'Error setting xmpp_timeout_value in local settings.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Successfully set new xmpp_timeout_value in local settings.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
setting = {'pending': {'xmpp_timeout_value': orig}}
print 'Reverting the xmpp timeout value via the update interface'
res = _gcp.Update(_device.dev_id, setting=setting)
if res['success']:
print 'Successfully updated'
_gcp.WaitForUpdate(_device.dev_id, 'xmpp_timeout_value', orig)
class LocalPrinting(LogoCert):
"""Tests of local printing functionality."""
def setUp(self):
# Create a fresh CJT for each test case
self.cjt = CloudJobTicket()
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
# Need to download a few raster files that will be used to test local
# printing. Different printers support different pwg-raster resolution
# and colours. Leverage GCP for format conversion by submitting a job via
# GCP, then downloading the raster files and saving them to disk
getLocalPrintingRasterImages()
def test_01_LocalPrintNotOwner(self):
"""Verify local print on a registered printer is available to guest user."""
test_id = '465133e5-783d-4e60-882e-3c779d0421c0'
test_name = 'PrivetLocalDestination.RegisteredPrinterNotOwner'
# New instance of device that is not authenticated - contains no auth-token
guest_device = Device(_logger, None, None, privet_port=_device.port)
guest_device.GetDeviceCDDLocally()
job_id = guest_device.LocalPrint(test_name, Constants.IMAGES['PWG1'],
self.cjt, 'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Guest failed to print a pwg-raster image via local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
print 'Guest successfully printed a pwg-raster image via local printing.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_02_LocalPrintOwner(self):
"""Verify local print on a registered printer as the owner."""
test_id = '38d7736d-20e4-4474-b32f-19414c32c9ab'
test_name = 'PrivetLocalDestination.RegisteredPrinterAsOwner'
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Owner failed to print a pwg-raster image via local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
print 'Owner successfully printed a pwg-raster image via local printing.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_03_LocalPrintingToggle(self):
"""Verify printer behaves correctly when local printing toggled."""
test_id = 'fb331ad7-8ef1-4266-a35c-4ddf553e47e6'
test_name = 'GCP.LocalPrintingToggle'
notes = None
notes2 = None
print 'Disabling local printing'
setting = {'pending': {'printer/local_printing_enabled': False}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes = 'Error turning off Local Printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
# Give the printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id,
'printer/local_printing_enabled', False)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Failed to detect update before timing out.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
print 'Local print successfully turned off'
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNone(job_id)
except AssertionError:
notes = 'Able to print via privet local printing when disabled.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Not able to print locally when disabled.'
print 'Re-enabling local printing'
setting = {'pending': {'printer/local_printing_enabled': True}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes2 = 'Error turning on Local Printing.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
# Give the printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id,
'printer/local_printing_enabled', True)
try:
self.assertTrue(success)
except AssertionError:
notes2 = 'Failed to detect update before timing out.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
print 'Local print successfully enabled'
success = _device.WaitForPrivetPrinterState('idle')
try:
self.assertTrue(success)
except AssertionError:
notes2 = 'Printer not in idle state after updates.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes2 = 'Not able to print locally when enabled.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
else:
notes2 = 'Able to print via privet local printing when re-enabled.'
self.LogTest(test_id, test_name, 'Passed', notes + '\n' + notes2)
def test_04_ConversionPrintingToggle(self):
"""Verify printer behaves correctly when conversion printing is toggled."""
test_id = '991b6649-20ac-4d11-9853-e43dc60d1c49'
test_name = 'GCP.ConversionPrintToggle'
notes = None
notes2 = None
if not Constants.CAPS['CONVERSION_PRINT']:
notes = 'Conversion printing is not supported.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Disabling conversion printing'
setting = {'pending': {'printer/conversion_printing_enabled': False}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes = 'Error turning off Conversion Printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
# Give the printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id,
'printer/conversion_printing_enabled', False)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Failed to detect update before timing out.\n'
notes += ('Please confirm "CONVERSION_PRINT" param is correctly set in '
'_config.py.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
print 'Conversion printing successfully turned off'
job_id = _device.LocalPrint(test_name, Constants.IMAGES['SVG1'], self.cjt,
'image/svg+xml', check_supported_content=False)
try:
self.assertIsNone(job_id)
except AssertionError:
notes = 'Able to print via privet conversion printing when disabled.'
notes += ' Check if the filetype svg is supported locally by the printer.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = ('Not able to print file locally when conversion print is '
'disabled.')
print 'Re-enabling conversion printing'
setting = {'pending': {'printer/conversion_printing_enabled': True}}
res = _gcp.Update(_device.dev_id, setting=setting)
if not res['success']:
notes2 = 'Error turning on Conversion Printing.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
# Give the printer time to update.
success = _gcp.WaitForUpdate(_device.dev_id,
'printer/conversion_printing_enabled', True)
try:
self.assertTrue(success)
except AssertionError:
notes2 = 'Failed to detect update before timing out.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
print 'Conversion printing successfully enabled'
success = _device.WaitForPrivetPrinterState('idle')
try:
self.assertTrue(success)
except AssertionError:
notes2 = 'Printer not in idle state after updates.'
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
job_id = _device.LocalPrint(test_name, Constants.IMAGES['SVG1'], self.cjt,
'image/svg+xml', check_supported_content=False)
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes2 = ('Not able to print an svg file locally when conversion '
'printing is enabled.')
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
try:
_device.WaitJobStateIn(job_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes2 = ('Job state did not transition to Done within %s seconds.'
% (Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes2)
raise
else:
notes2 = ('Able to print an svg file via privet local printing when '
'conversion printing is re-enabled.')
self.LogTest(test_id, test_name, 'Passed', notes + '\n' + notes2)
def test_05_LocalPrintHTML(self):
"""Verify printer can local print HTML file."""
test_id = 'c93ed781-d0b5-44bc-89e2-4e5b31bafd3d'
test_name = 'LocalPrint.HTML'
if 'text/html' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print Html support')
return
job_id = _device.LocalPrint(test_name, Constants.IMAGES['HTML1'], self.cjt,
'text/html')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing %s' % Constants.IMAGES['HTML1']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'HTML file should be printed.'
print 'Fail this test if print out has errors or quality issues.'
self.ManualPass(test_id, test_name)
def test_06_LocalPrintJPG(self):
"""Verify a 1 page JPG file prints using Local Printing."""
test_id = '824f95f8-9380-4c37-9552-f6e56e2c8463'
test_name = 'LocalPrint.JPG'
if ('image/jpeg' not in _device.supported_types and
'image/pjpeg' not in _device.supported_types):
self.LogTest(test_id, test_name, 'Skipped', 'No local print Jpg support')
return
regular_jpg = Constants.IMAGES['JPG12']
progressive_jpg = Constants.IMAGES['JPG7']
print 'Local printing a regular JPEG image'
job_id = _device.LocalPrint(test_name, regular_jpg, self.cjt, 'image/jpeg')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing regular JPEG: %s' % regular_jpg
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER when the document is completely '
'printed')
print 'Local printing a progressive JPEG image'
job_id = _device.LocalPrint(test_name, progressive_jpg, self.cjt,
'image/jpeg')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing progressive JPEG: %s' % progressive_jpg
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print '2 JPG files should be printed: 1 regular and 1 progressive.'
print 'Fail this test if print outs have errors or quality issues.'
self.ManualPass(test_id, test_name)
def test_07_LocalPrintPNG(self):
"""Verify a 1 page PNG file prints using Local Printing."""
test_id = '90c3f594-6792-4c07-b747-ae217ff8178a'
test_name = 'LocalPrint.PNG'
if 'image/png' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PNG support')
return
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PNG6'], self.cjt,
'image/png')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing %s' % Constants.IMAGES['PNG6']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'PNG file should be printed.'
print 'Fail this test if print out has errors or quality issues.'
self.ManualPass(test_id, test_name)
def test_08_LocalPrintGIF(self):
"""Verify a 1 page GIF file prints using Local Printing."""
test_id = '39720f61-f142-4ef5-ba55-1efaad8a89dd'
test_name = 'LocalPrint.GIF'
if 'image/gif' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print Gif support')
return
job_id = _device.LocalPrint(test_name, Constants.IMAGES['GIF4'], self.cjt,
'image/gif')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing %s' % Constants.IMAGES['GIF4']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'GIF file should be printed.'
print 'Fail this test if print out has errors or quality issues.'
self.ManualPass(test_id, test_name)
def test_09_LocalPrintPDF(self):
"""Verify a 1 page PDF file prints using Local Printing."""
test_id = 'd6497ac5-4d15-46d4-8aee-261890180dca'
test_name = 'LocalPrint.PDF'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing %s' % Constants.IMAGES['PDF9']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'PDF file should be printed.'
print 'Fail this test if print out has errors or quality issues.'
self.ManualPass(test_id, test_name)
def test_10_LocalPrintPDFDuplex(self):
"""Verify printer respects duplex option for PDFs in local print."""
test_id = 'c1b3136f-e6c1-413d-977d-c295a8351703'
test_name = 'LocalPrint.PDFTwoSided'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
if not Constants.CAPS['DUPLEX']:
self.LogTest(test_id, test_name, 'Skipped', 'No Duplex support')
return
self.cjt.AddDuplexOption(GCPConstants.LONG_EDGE)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF10'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error printing with LONG_EDGE option in local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER when the document is completely '
'printed')
self.cjt.AddDuplexOption(GCPConstants.SHORT_EDGE)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF10'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error printing with SHORT_EDGE option in local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'The 1st print job should be printed 2-sided along the long edge.'
print 'The 2nd print job should be printed 2-sided along the short edge.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_11_LocalPrintPDFMargins(self):
"""Verify printer respects margins option for PDFs in local print."""
test_id = 'a9c482e0-9494-469c-a391-d70c171bd9c2'
test_name = 'LocalPrint.PDFMargins'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
if not Constants.CAPS['MARGIN']:
self.LogTest(test_id, test_name, 'Skipped', 'No Margin support')
return
self.LogTest(test_id, test_name, 'Skipped',
'Local Print PDF Margin not required')
return
def test_12_LocalPrintPDFLayout(self):
"""Verify printer respects layout settings for PDFs in local print."""
test_id = '151eca79-23c5-4fad-855d-2b5aad7dd9c5'
test_name = 'LocalPrint.PDFLayout'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
self.cjt.AddPageOrientationOption(GCPConstants.PORTRAIT)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with portrait layout.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with landscape layout.'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
print 'The 1st print job should be printed in portrait layout.'
print 'The 2nd print job should be printed in landscape layout.'
print 'If the layout is not correct, fail this test.'
self.ManualPass(test_id, test_name)
def test_13_LocalPrintPDFPageRange(self):
"""Verify printer respects page range for PDFs in local print."""
test_id = 'f3b2428b-2c48-411d-a7b6-c336452b36b6'
test_name = 'LocalPrint.PDFPageRange'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
self.LogTest(test_id, test_name, 'Skipped',
'Local Print PDF page range not required')
return
def test_14_LocalPrintPDFCopies(self):
"""Verify printer respects copy option for PDFs in local print."""
test_id = '1eb21d57-59f4-457e-a097-d5c4d584502f'
test_name = 'LocalPrint.PDFCopies'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
if not Constants.CAPS['COPIES_LOCAL']:
notes = 'Printer does not support copies option.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
self.cjt.AddCopiesOption(2)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with copies option.'
self.LogTest(test_id, test_name, 'Failed', notes)
else:
print 'The print job should have printed 2 copies.'
print 'If 2 copies are not printed, fail this test.'
self.ManualPass(test_id, test_name)
def test_15_LocalPrintPDFColorSelect(self):
"""Verify printer respects color option for PDFs in local print."""
test_id = 'e12ea6cc-d33f-4f94-a435-694704f7ba72'
test_name = 'LocalPrint.PDFColorSelect'
if 'application/pdf' not in _device.supported_types:
self.LogTest(test_id, test_name, 'Skipped', 'No local print PDF support')
return
if not Constants.CAPS['COLOR']:
notes = 'Printer does not support color printing.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
self.cjt.AddColorOption(GCPConstants.COLOR)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with color selected.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER when page is printed')
self.cjt.AddColorOption(GCPConstants.MONOCHROME)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PDF9'], self.cjt,
'application/pdf')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with monochrome selected.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'The 1st print job should be printed in color.'
print 'The 2nd print job should be printed in monochrome.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_16_LocalPrintPWGDuplex(self):
"""Verify printer respects duplex option for PWGs in local print."""
test_id = 'ebd264ed-e9ac-4bff-9a8b-d1b4c5af477e'
test_name = 'LocalPrint.PWGDuplex'
if not Constants.CAPS['DUPLEX']:
self.LogTest(test_id, test_name, 'Skipped', 'No Duplex support')
return
self.cjt.AddDuplexOption(GCPConstants.LONG_EDGE)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG2'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error printing with LONG_EDGE option in local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER when the document is completely '
'printed')
self.cjt.AddDuplexOption(GCPConstants.SHORT_EDGE)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG2'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error printing with SHORT_EDGE option in local printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Both print jobs should be printed in duplex regardless of edge'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_17_LocalPrintPWGColorSelect(self):
"""Verify printer respects color option for PWGs in local print."""
test_id = 'bfd5ee5e-4bef-4e8e-b64a-63fef421ae28'
test_name = 'LocalPrint.PWGColorSelect'
if not Constants.CAPS['COLOR']:
notes = 'Printer does not support color printing.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
self.cjt.AddColorOption(GCPConstants.COLOR)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with color selected.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER when page is printed')
self.cjt.AddColorOption(GCPConstants.MONOCHROME)
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing with monochrome selected.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'The 1st print job should be printed in color.'
print 'The 2nd print job should be printed in monochrome.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_18_LocalPrintPWG(self):
"""Verify printer can successfully print PWGs in local print."""
test_id = '013fb153-940a-45d2-a5fd-7112d4d1198d'
test_name = 'LocalPrint.PWG'
job_id = _device.LocalPrint(test_name, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing PWG raster file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'PWG Raster file should print successfully.'
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
def test_19_LocalPrintUpdateGcpServer(self):
"""Verify printer successfully updates GCP servers for local print."""
"""This methods tests the same underlying GCP server mechanism used"""
"""to update the Management page."""
test_id = '48d084f7-13fa-4a69-aa29-268e998f343c'
test_name = 'LocalPrint.PrintJobStatusMgtPage'
# Use timestamp to create unique title
job_title = '%s-%s' % (test_name , time.time())
job_id = _device.LocalPrint(job_title, Constants.IMAGES['PWG1'], self.cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = 'Error local printing PWG raster file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
# Local print jobs have no job_id's so we use job_title as the filter
job_exists = _gcp.WaitLocalJobExist(printer_id=_device.dev_id,
job_title=job_title)
except AssertionError:
notes = 'GCP /jobs api failed.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertTrue(job_exists)
except AssertionError:
notes = 'Local Print job not found using GCP /jobs api.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Local Print job found using GCP /jobs api.'
self.LogTest(test_id, test_name, 'Passed', notes)
class PostRegistration(LogoCert):
"""Tests to run after _device is registered."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
def waitForGcpPrinterState(self, state, timeout):
"""Wait until the GCP printer state becomes the specified status
Args:
state: string, printer state to wait for
timeout: integer, number of seconds to wait.
Returns:
boolean, True if state is observed within timeout; otherwise, False.
"""
print ('Waiting up to %s secs for printer to be in %s state.' %
(timeout, state))
print 'Polling every 5 seconds'
end = time.time() + timeout
while time.time() < end:
_device.GetDeviceDetails()
if state in _device.status:
break
# Not using Constant.SLEEP['POLL'] here since the status update
# actually takes a while
time.sleep(5)
def testDeviceDetails(self):
"""Verify printer details are provided to Cloud Print Service."""
test_id = '597a2e5d-9fe8-455b-aa3a-2f063621d2b2'
test_name = 'CDD.DeviceDetails'
try:
self.assertIsNotNone(_device.name)
except AssertionError:
notes = 'Error finding device in via privet.'
self._logger.error('Check your printer model in the _config file.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Found printer details via privet.'
_device.GetDeviceCDD(_device.dev_id)
self.LogTest(test_id, test_name, 'Passed', notes)
def testRegisteredDevicePoweredOffShowsOffline(self):
"""Verify device shows offline when it is powered off."""
test_id = '9bb02ec3-b3f5-4d26-98dd-9b493bfe226e'
test_name = 'Privet.PowerOffRegistered'
# Make sure device is in 'online' state before this test
self.waitForGcpPrinterState('ONLINE', 120)
try:
self.assertIsNotNone(_device.status)
except AssertionError:
notes = 'Device has no status.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('ONLINE', _device.status)
except AssertionError:
notes = 'Device is not online. Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
self.waitForGcpPrinterState('OFFLINE', 600)
try:
self.assertIsNotNone(_device.status)
except AssertionError:
notes = 'Device has no status.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn('OFFLINE', _device.status)
except AssertionError:
notes = 'Device is not offline. Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
PromptAndWaitForUserAction('Press ENTER to continue this testcase.')
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Error receiving the power-on signal from the printer.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
# Get the new X-privet-token from the restart
_device.GetPrivetInfo()
# Make sure device is in 'online' state before continuing testing
self.waitForGcpPrinterState('ONLINE', 120)
def testRegisteredDeviceNotDiscoverableAfterPowerOn(self):
"""Verify power cycled registered device advertises as registered."""
test_id = 'f95f07e3-6c51-49c5-8a14-29b51c5e5695'
test_name = 'Privet.RegisteredDeviceNotDiscoverableAfterPowerOn'
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
PromptUserAction('Power on the printer and wait...')
success = waitForAdvertisementRegStatus(Constants.PRINTER['NAME'],
True, 300)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Printer is advertising as an unregistered device'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer is advertising as a registered device.'
self.LogTest(test_id, test_name, 'Passed', notes)
class PrinterState(LogoCert):
"""Test that printer state is reported correctly."""
def setUp(self):
# Refresh Oauth access token if necessary
self.CheckAndRefreshToken()
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
def GetErrorMsg(self, printer_states):
"""Loop through printer messages and find the first error message.
Args:
printer_states: dictionary, contains varies printer state objects
Returns:
string: error message if found, else None
"""
for key, val in printer_states.iteritems():
for state in val:
if state['severity'] != 'NONE':
return state['message'].lower()
return None
def VerifyUiStateMessage(self, test_id, test_name, keywords_list,
suffixes = None):
"""Verify state messages.
Args:
test_id: integer, testid in TestTracker database.
test_name: string, name of test.
keywords_list: array, list of strings that should be found in the uiState.
each element in the array is looked for in the UI state
elements can be slash separated for aliasing where only
one term of the slash separated string needs to match.
ie. ['door/cover', 'open']
suffixes: tuple or string, additional allowed suffixes of uiState messages
Returns:
boolean: True = Pass, False = Fail.
"""
if 'uiState' in _device.cdd:
if 'caption' in _device.cdd['uiState']:
uiMsg = _device.cdd['uiState']['caption'].lower()
uiMsg = re.sub(r' \(.*\)$', '', uiMsg)
uiMsg.strip()
elif 'printer' in _device.cdd['uiState']:
uiMsg = self.GetErrorMsg(_device.cdd['uiState']['printer'])
if uiMsg is None:
notes = ('No error messages found in uistate[caption] or '
'uiState[printer]')
self.LogTest(test_id, test_name, 'Failed', notes)
return False
uiMsg = re.sub(r' \(.*\)$', '', uiMsg)
uiMsg.strip()
else:
notes = 'No \'caption\' attribute found inside uiState'
self.LogTest(test_id, test_name, 'Failed', notes)
return False
else:
notes = 'No \'uiState\' attribute found inside cdd'
self.LogTest(test_id, test_name, 'Failed', notes)
return False
found = False
# check for keywords
for keywords in keywords_list:
found = False
for keyword in keywords.split('/'):
if keyword.lower() in uiMsg:
found = True
break
if not found:
notes = ('required keyword(s) "%s" not in UI state message: %s' %
(keywords, uiMsg))
self.LogTest(test_id, test_name, 'Failed', notes)
return False
if suffixes is not None:
# check for suffixes
if not uiMsg.endswith(suffixes):
notes = ('None of the required suffix(s) "%s" are found in the '
'UI state message: '
'%s' % (keywords, uiMsg))
self.LogTest(test_id, test_name, 'Failed', notes)
return False
self.LogTest(test_id, test_name, 'Passed')
return True
def VerifyUiStateHealthy(self, test_id, test_name):
"""Verify ui state has no error messages.
Args:
test_id: integer, testid in TestTracker database.
test_name: string, name of test.
Returns:
boolean: True = Pass, False = Fail.
"""
is_healthy = False if 'caption' in _device.cdd['uiState'] else True
if is_healthy:
self.LogTest(test_id, test_name, 'Passed')
return True
else:
notes = ('UI shows error state with message: %s' %
_device.cdd['uiState']['caption'])
self.LogTest(test_id, test_name, 'Failed', notes)
return False
def testLostNetworkConnection(self):
"""Verify printer that loses network connection reconnects properly."""
test_id = '8c67068a-e8c0-4b3f-b85d-52977f62a3fd'
test_name = 'Printer.TestLostNetworkConnection'
print 'Test printer handles connection status when reconnecting to network.'
PromptAndWaitForUserAction('Press ENTER once printer loses '
'network connection.')
Sleep('NETWORK_DETECTION')
print 'Now reconnect printer to the network.'
PromptAndWaitForUserAction('Press ENTER once printer has '
'network connection.')
Sleep('NETWORK_DETECTION')
_device.GetDeviceDetails()
try:
self.assertIn('ONLINE', _device.status)
except AssertionError:
notes = 'Device status is not online.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device status is online.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testOpenPaperTray(self):
"""Verify if open paper tray is reported correctly."""
test_id = '09f3f838-922b-4526-b5b8-bd83806816d0'
test_name = 'Printer.OpenPaperTray'
if not Constants.CAPS['TRAY_SENSOR']:
notes = 'Printer does not have paper tray sensor.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Open the paper tray to the printer.'
PromptAndWaitForUserAction('Press ENTER once the paper tray is open.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertTrue(_device.error_state or _device.warning_state)
except AssertionError:
notes = 'Printer is not in error state with open paper tray.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
# Check state message.
# Some input trays may not be opened and be normally empty.
if not self.VerifyUiStateMessage(test_id, test_name,
['input/tray/cassette'],
suffixes=('is open',
'is empty',
'% full')):
raise
test_id2 = 'a158fe6a-125f-46e2-a382-9189eb06b5f0'
test_name2 = 'Printer.ClosePaperTray'
print 'Now close the paper tray.'
PromptAndWaitForUserAction('Press ENTER once the paper tray is closed.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertFalse(_device.error_state or _device.warning_state)
except AssertionError:
notes = 'Paper tray is closed but printer reports error.'
self.LogTest(test_id2, test_name2, 'Failed', notes)
raise
else:
if not self.VerifyUiStateHealthy(test_id2, test_name2):
raise
def testNoMediaInTray(self):
"""Verify no media in paper tray reported correctly."""
test_id = 'bb5048de-cf93-487e-a44b-9366721fa39c'
test_name = 'Printer.RemoveMediafromTray'
if not Constants.CAPS['MEDIA_SENSOR']:
notes = 'Printer does not have a paper tray sensor.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Remove all media from the paper tray.'
PromptAndWaitForUserAction('Press ENTER once all media is removed.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
if not self.VerifyUiStateMessage(test_id, test_name,
['input/tray/cassette'],
suffixes=('is empty')):
raise
test_id2 = 'a0387dea-6b87-4418-9489-41c9b4cb68d9'
test_name2 = 'Printer.PlaceMediaInTray'
print 'Place media in all paper trays.'
PromptAndWaitForUserAction('Press ENTER once you have placed paper '
'in paper tray.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
if not self.VerifyUiStateHealthy(test_id2, test_name2):
raise
def testTonerCartridge(self):
"""Verify missing/empty toner cartridge is reported correctly."""
test_id = '13c3cccd-0d72-4a04-8462-d4fa16992338'
test_name = 'Printer.RemoveTonerCartridge'
if not Constants.CAPS['TONER']:
notes = 'Printer does not contain ink toner.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return True
print 'Remove the (or one) toner cartridge from the printer.'
PromptAndWaitForUserAction('Press ENTER once the toner cartridge '
'is removed.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertTrue(_device.error_state)
except AssertionError:
notes = 'Printer is not in error state with missing toner cartridge.'
self.LogTest(test_id, test_name, 'Failed', notes)
PromptAndWaitForUserAction(
'Press ENTER once toner is replaced in printer to continue testing.')
raise
else:
if not self.VerifyUiStateMessage(test_id, test_name, ['ink/toner'],
('is removed',
'is empty',
'is low',
'pages remaining',
'%')):
PromptAndWaitForUserAction(
'Press ENTER once toner is replaced in printer to continue testing.')
raise
test_id2 = 'cbe4b5ac-7edb-41f3-a816-98aaf9522c83'
test_name2 = 'Printer.ExhaustTonerCartridge'
if not Constants.CAPS['EMPTY_INK_SENSOR']:
notes = 'Printer does not support empty toner detection.'
self.LogTest(test_id2, test_name2, 'Skipped', notes)
else:
print 'Insert an empty toner cartridge in printer.'
PromptAndWaitForUserAction('Press ENTER once an empty toner cartridge is '
'in printer.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertTrue(_device.error_state)
except AssertionError:
notes = 'Printer is not in error state with empty toner.'
self.LogTest(test_id2, test_name2, 'Failed', notes)
PromptAndWaitForUserAction(
'Press ENTER once original toner is replaced in printer to continue '
'testing.')
raise
else:
if not self.VerifyUiStateMessage(test_id2, test_name2, ['ink/toner'],
('is removed',
'is empty',
'is low',
'pages remaining',
'%')):
PromptAndWaitForUserAction(
'Press ENTER once original toner is replaced in printer to '
'continue testing.')
raise
test_id3 = 'd2bd8b57-c7c1-45b4-b458-1800c240a93a'
test_name3 = 'Printer.ReplaceTonerCartridge'
print ('Verify that the error is fixed by replacing the original '
'toner cartridge.')
PromptAndWaitForUserAction('Press ENTER once toner is replaced in printer.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertFalse(_device.error_state)
except AssertionError:
notes = 'Printer is in error state with good toner cartridge.'
self.LogTest(test_id3, test_name3, 'Failed', notes)
raise
else:
if not self.VerifyUiStateHealthy(test_id3, test_name3):
raise
def testCoverOpen(self):
"""Verify that an open door or cover is reported correctly."""
test_id = 'fd368e65-3143-48d8-83a9-24199511f262'
test_name = 'Printer.OpenCover'
if not Constants.CAPS['COVER']:
notes = 'Printer does not have a cover.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Open a cover on your printer.'
PromptAndWaitForUserAction('Press ENTER once the cover has been opened.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertTrue(_device.error_state)
except AssertionError:
notes = 'Printer is not in error state with open cover.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
if not self.VerifyUiStateMessage(test_id, test_name, ['Door/Cover'],
suffixes=('is open')):
raise
test_id2 = '57b2fd84-5328-4a39-a70e-e0ae250ff109'
test_name2 = 'Printer.CloseCover'
print 'Now close the printer cover.'
PromptAndWaitForUserAction('Press ENTER once the printer cover is closed.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertFalse(_device.error_state)
except AssertionError:
notes = 'Printer is in error state with closed cover.'
self.LogTest(test_id2, test_name2, 'Failed', notes)
raise
else:
if not self.VerifyUiStateHealthy(test_id2, test_name2):
raise
def testPaperJam(self):
"""Verify printer properly reports a paper jam with correct state."""
test_id = '1ccbf64c-17bc-4464-a943-f9b94d3f6a3f'
test_name = 'Printer.PaperJam'
print 'Cause the printer to become jammed with paper.'
PromptAndWaitForUserAction('Press ENTER once the printer '
'has become jammed.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertTrue(_device.error_state)
except AssertionError:
notes = 'Printer is not in error state with paper jam.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
if not self.VerifyUiStateMessage(test_id, test_name, ['paper jam']):
raise
test_id2 = 'd1b77fe3-9d1d-4d08-917a-6c7254ea3bd2'
test_name2 = 'Printer.RemovePaperJam'
print 'Now clear the paper jam.'
PromptAndWaitForUserAction('Press ENTER once the paper jam is clear '
'from printer.')
Sleep('PRINTER_STATE')
_device.GetDeviceDetails()
try:
self.assertFalse(_device.error_state)
except AssertionError:
notes = 'Printer is in error after paper jam was cleared.'
self.LogTest(test_id2, test_name2, 'Failed', notes)
raise
else:
if not self.VerifyUiStateHealthy(test_id2, test_name2):
raise
class JobState(LogoCert):
"""Test that print jobs are reported correctly from the printer."""
def setUp(self):
# Create a fresh CJT for each test case
self.cjt = CloudJobTicket()
# Refresh Oauth access token if necessary
self.CheckAndRefreshToken()
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
def testOnePagePrintJobState(self):
"""Verify a 1 page print job is reported correctly."""
test_id = 'a848d29b-1dd6-422a-ab3e-5f370083d278'
test_name = 'GCP.JobStateOnePagePrint'
print 'Wait for this one page print job to finish.'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['JPG6'],
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing one page JPG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
pages_printed = int(job['uiState']['progress'].split(':')[1])
self.assertEqual(pages_printed, 1)
except AssertionError:
notes = 'Pages printed is not equal to 1.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printed one page as expected. Status shows as printed.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testMultiPageJobState(self):
"""Verify a multi-page print job is reported with correct state."""
test_id = '09be688d-03c9-47a4-afaa-0c87b12c9608'
test_name = 'GCP.JobStateMultiPage'
print 'Wait until job starts printing 7 page PDF file...'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error while printing 7 page PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print ('When printer starts printing, '
'Job State should transition to in progress.')
try:
_gcp.WaitJobStateIn(output['job']['id'], _device.dev_id,
GCPConstants.IN_PROGRESS)
except AssertionError:
notes = 'Job is not "In progress" while job is still printing.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
pages_printed = int(job['uiState']['progress'].split(':')[1])
self.assertEqual(pages_printed, 7)
except AssertionError:
notes = 'Pages printed is not equal to 7.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printed 7 pages, and job state correctly updated.'
self.LogTest(test_id, test_name, 'Passed', notes)
def testJobDeletionRecovery(self):
"""Verify printer recovers from an In-Progress job being deleted."""
test_id = 'e679616c-d363-4f86-882b-d274dde44c46'
test_name = 'GCP.JobDeletionRecovery'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
if output['success']:
PromptAndWaitForUserAction('Press ENTER once the first page prints out.')
print "Deleting job mid print"
delete_res = _gcp.DeleteJob(output['job']['id'])
if delete_res['success']:
print "Job deleted successfully"
print "Give the printer time to finish printing the deleted job"
# Since it's PDF file give the job time to finish printing.
PromptAndWaitForUserAction('Press ENTER once printer is '
'finished printing')
print "Printing another job"
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PNG7'],
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing job after deleting IN_PROGRESS job.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Printer Test Page should print after job deletion.'
print 'Fail this test if Printer Test Page does not print.'
self.ManualPass(test_id, test_name)
else:
notes = 'Error deleting IN_PROGRESS job.'
_logger.error(notes)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Error printing multi-page PDF file.'
_logger.error(notes)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def testJobStateEmptyInputTray(self):
"""Validate proper /control msg when input tray is empty."""
test_id = '8ccc4b5e-becc-466f-87be-3fd9782a4769'
test_name = 'GCP.JobStateEmptyInputTray'
print 'Empty the input tray of all paper.'
PromptAndWaitForUserAction('Press ENTER once input tray has been emptied.')
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
if output['success']:
try:
job = _gcp.WaitJobStateNotIn(output['job']['id'], _device.dev_id,
[GCPConstants.QUEUED,
GCPConstants.IN_PROGRESS],
timeout = Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job not found or status transitioned into Queued or '
'In Progress within %s seconds.' %
(Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(job['semanticState']['state']['type'],
GCPConstants.STOPPED)
except AssertionError:
notes = 'Print Job is not in Stopped state.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
job_state_msg = job['uiState']['cause']
notes = 'Job State Error msg: %s' % job_state_msg
try:
#TODO: Do we really want to fail here if 'tray' is not in the msg?
self.assertIn('tray', job_state_msg)
except AssertionError:
notes += ('The Job State error message does not contain tray.')
notes += ('Note that the error message may be ok.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
PromptAndWaitForUserAction('Press ENTER after placing the papers '
'back in the input tray.')
print ('After placing the paper back, Job State should transition '
'to in progress.')
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.IN_PROGRESS)
except AssertionError:
notes = 'Job is not in progress: %s' % job['status']
_logger.error(notes)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Wait for the print job to finish.'
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within '
'%s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Job state: %s' % job['status']
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Error printing PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def testJobStateMissingToner(self):
"""Validate proper /control msg when toner or ink cartridge is missing."""
test_id = 'ad9ddb5a-57cf-404c-93cb-c576943b3efd'
test_name = 'GCP.JobStateMissingToner'
if not Constants.CAPS['TONER']:
notes = 'printer does not contain toner ink.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
print 'Remove ink cartridge or toner from the printer.'
PromptAndWaitForUserAction('Press ENTER once the toner is removed.')
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
if output['success']:
try:
job = _gcp.WaitJobStateNotIn(output['job']['id'], _device.dev_id,
[GCPConstants.QUEUED,
GCPConstants.IN_PROGRESS],
timeout = Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job not found or status transitioned into Queued or '
'In Progress within %s seconds.' %
(Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(job['semanticState']['state']['type'],
GCPConstants.STOPPED)
except AssertionError:
notes = 'Print Job is not in Stopped state.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
job_state_msg = job['uiState']['cause']
notes = 'Job State Error msg: %s' % job_state_msg
try:
# Ensure the message at least has the string or more than 4 chars.
self.assertGreater(len(job_state_msg), 4)
except AssertionError:
_logger.error('The Job State error message is insufficient')
_logger.error(notes)
_logger.error('Note that the error message may be ok.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
PromptAndWaitForUserAction('Press ENTER once the toner or ink is '
'placed back in printer.')
print ('After placing the toner back, Job State should transition '
'to in progress.')
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.IN_PROGRESS)
except AssertionError:
notes = 'Job is not in progress: %s' % job['status']
_logger.error(notes)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Wait for the print job to finish.'
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=
Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to '
'%s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Job state: %s' % job['status']
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Error printing PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def testJobStateNetworkOutage(self):
"""Validate proper /control msg when there is network outage."""
test_id = 'f7b647ba-5b73-4d71-96b9-d1ae506ee0c5'
test_name = 'GCP.JobStateNetworkOutage'
print ('This test requires the printer to be disconnected from the network '
'after the first page is printed.')
PromptAndWaitForUserAction('Press ENTER when you are prepared to '
'disconnect the network to begin the printjob')
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
if output['success']:
job_id = output['job']['id']
PromptAndWaitForUserAction('Wait for one page to print. Press ENTER '
'once network is disconnected.')
try:
_gcp.WaitJobStateIn(job_id, _device.dev_id, GCPConstants.IN_PROGRESS)
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.IN_PROGRESS, 30))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Re-establish network connection to printer.'
PromptAndWaitForUserAction('Press ENTER once printer has successfully '
'established a connection to the network.')
print ('Once network is reconnected, '
'Job state should transition to in progress.')
try:
_gcp.WaitJobStateIn(job_id, _device.dev_id, GCPConstants.IN_PROGRESS)
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.IN_PROGRESS, 30))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Wait for the print job to finish.'
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
[GCPConstants.DONE,
GCPConstants.ABORTED],
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to Done within %s seconds '
'of starting print job.'
% (Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Job state: %s' % job['status']
self.LogTest(test_id, test_name, 'Passed', notes)
else:
notes = 'Error printing PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def testJobStateWithPaperJam(self):
"""Validate proper behavior of print job when paper is jammed."""
test_id = '167ecac1-db45-4e2c-9352-98bff432d03b'
test_name = 'GCP.JobStatePaperJam'
print 'This test validates that the job state correctly transitions to '
print '"STOPPED" when a GCP job causes a paper jam while printing.\n'
print 'Place page inside print path to cause a paper jam for the next job.'
PromptAndWaitForUserAction('Press ENTER once you have prepared the '
'conditions for a paper jam. \n'
'NOTE: Printer should not be jammed yet')
print 'Submitting a 7 page document through Cloud Print.'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_name,
self.cjt)
PromptUserAction('Cause a paper jam when the printer starts printing.')
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing %s' % Constants.IMAGES['PDF9']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Verifying job is reported in error state.'
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.STOPPED)
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.'
% (GCPConstants.STOPPED, 60))
_logger.error(notes)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Now clear the print path so the printer is no longer jammed.'
PromptAndWaitForUserAction('Press ENTER once printer is clear of jam.')
print 'Verify print job prints after paper jam is cleared.'
self.ManualPass(test_id, test_name)
finally:
# Make sure printer is no longer in an error state before continuing
print 'Before continuing, make sure printer is no longer in error state'
PromptAndWaitForUserAction('Press ENTER to continue testing.')
def testJobStateIncorrectMediaSize(self):
"""Validate proper behavior when incorrect media size is selected."""
test_id = 'edea71b1-4cbe-47a5-bc96-93e33b68c0b7'
test_name = 'GCP.JobStateIncorrectMediaSize'
print 'This test is designed to select media size that is not available.'
print 'The printer should prompt the user to enter the requested size.'
print 'Load input tray with letter sized paper.'
PromptAndWaitForUserAction('Press ENTER once paper tray loaded with ONLY '
'letter sized paper.')
self.cjt.AddSizeOption(GCPConstants.A4_HEIGHT, GCPConstants.A4_WIDTH)
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PNG7'], test_name,
self.cjt)
print 'Attempting to print with A4 media size.'
print 'Fail this test if printer does not warn user to load correct size'
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing %s' % Constants.IMAGES['PNG7']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
PromptAndWaitForUserAction('Verify printer status, then press ENTER')
print 'Now load printer with A4 size paper.'
PromptAndWaitForUserAction('After placing the correct paper size, '
'press ENTER')
print 'Printer should continue printing and complete the print job.'
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.'
% (GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.ManualPass(test_id, test_name)
finally:
PromptAndWaitForUserAction('Press ENTER once printer is loaded with '
'letter size paper to continue testing. ')
def testMultipleJobsPrint(self):
"""Verify multiple jobs in queue are all printed."""
test_id = '48389666-80ae-41a9-a9ab-3112a42c84bd'
test_name = 'GCP.JobStateMultiplePrintJobs'
print 'This tests that multiple jobs in print queue are printed.'
for _ in xrange(3):
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PNG7'], test_name,
self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing %s' % Constants.IMAGES['PNG7']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
print 'Verify all 3 job printed correctly.'
print 'If all 3 Print Test pages are not printed, fail this test.'
self.ManualPass(test_id, test_name)
def testPrintToOfflinePrinter(self):
"""Validate offline printer prints all queued jobs when back online."""
test_id = '83869333-ff32-4093-a557-323887204902'
test_name = 'GCP.JobStateMultipleJobsOfflinePrinter'
print 'This tests that an offline printer will print all jobs'
print 'when it comes back online.'
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
for _ in xrange(3):
print 'Submitting job #',_,' to the print queue.'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PNG7'], test_name,
self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing %s' % Constants.IMAGES['PNG7']
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.QUEUED)
except AssertionError:
notes = 'Print job %s is not in Queued state.' %(_)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Error receiving the power-on signal from the printer.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
# Get the new X-privet-token from the restart
_device.GetPrivetInfo()
print 'Verify that all 3 print jobs are printed.'
self.ManualPass(test_id, test_name)
def testDeleteQueuedJob(self):
"""Verify deleting a queued job is properly handled by printer."""
test_id = '01808d62-7c0f-4427-90ce-29f429f1d594'
test_name = 'GCP.JobStateDeleteQueuedJob'
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
doc_to_print = Constants.IMAGES['PNG7']
print 'Attempting to add a job to the queue.'
output = _gcp.Submit(_device.dev_id, doc_to_print, test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing %s' % doc_to_print
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.QUEUED)
except AssertionError:
notes = 'Print job is not in queued state.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
print 'Attempting to delete job in queued state.'
job_delete = _gcp.DeleteJob(output['job']['id'])
try:
self.assertTrue(job_delete['success'])
except AssertionError:
notes = 'Queued job not deleted.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
PromptUserAction('Power on the printer and wait...')
service = Wait_for_privet_mdns_service(300, Constants.PRINTER['NAME'],
_logger)
try:
self.assertIsNotNone(service)
except AssertionError:
notes = 'Error receiving the power-on signal from the printer.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
# Get the new X-privet-token from the restart
_device.GetPrivetInfo()
print 'Verify printer does not go into error state because of deleted job'
self.ManualPass(test_id, test_name)
def testErrorRecovery(self):
"""Verify print recovers from malformatted print job."""
test_id = '80877c2a-f46e-4256-80d9-474ff16eb60b'
test_name = 'GCP.JobStateErrorRecovery'
print 'Submitting a malformatted PDF file.'
# First printing a malformatted PDF file. Not expected to print.
_gcp.Submit(_device.dev_id, Constants.IMAGES['PDF5'], 'Malformat', self.cjt)
# Now print a valid file.
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF9'], test_name,
self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Job did not print after malformatted print job.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print 'Verify malformatted file did not put printer in error state.'
print 'Verify print test page printed correctly.'
self.ManualPass(test_id, test_name)
def testPagesPrinted(self):
"""Verify printer properly reports number of pages printed."""
test_id = 'bfd7e2d8-e75a-4a7b-8f47-00d0c1081963'
test_name = 'GCP.JobStatePagesPrinted'
output = _gcp.Submit(_device.dev_id, Constants.IMAGES['PDF10'], test_name,
self.cjt)
print 'Printing a 3 page PDF file'
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing 3 page PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
job = _gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
pages_printed = int(job['uiState']['progress'].split(':')[1])
self.assertEqual(pages_printed, 3)
except AssertionError:
notes = 'Printer reports pages printed not equal to 3.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer reports pages printed = 3.'
self.LogTest(test_id, test_name, 'Passed', notes)
class RunAfter24Hours(LogoCert):
"""Tests to be run after printer sits idle for 24 hours."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
_logger.info('Sleeping for 1 day before running additional tests.')
print 'Sleeping for 1 day before running additional tests.'
Sleep('ONE_DAY')
def testPrinter24HoursOnline(self):
"""validate printer has online status."""
test_id = '490821e9-99b8-4f2b-a54c-6e4cfcb6f45c'
test_name = 'Printer.24HoursTest'
# Tokens have expired since the 24 hr sleep, refresh them
_oauth2.RefreshToken()
_device.auth_token = Constants.AUTH['ACCESS']
_gcp.auth_token = Constants.AUTH['ACCESS']
_device.GetDeviceDetails()
try:
self.assertIn('ONLINE', _device.status)
except AssertionError:
notes = 'Printer is not online after 24 hours.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer online after 24 hours.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
PromptAndWaitForUserAction('Press ENTER to continue testing.')
class Unregister(LogoCert):
"""Test removing device from registered status."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsRegistered()
LogoCert.GetDeviceDetails()
def testUnregisterDevice(self):
"""Unregister printer."""
test_id = 'd008a124-fb56-40de-a530-7c510f1fe078'
test_name = 'PrinterURL.Delete'
test_id2 = 'b112a9bc-4a11-4956-893c-4498ff753058'
test_name2 = 'Privet.DeleteRegisteredOnlinePrinter'
test_id3 = '8e158286-674f-486c-9a61-be2c61de20b9'
test_name3 = 'Privet.DeleteRegisteredOfflinePrinter'
print 'Printer needs to be registered to begin this testcase'
is_registered = _device.isPrinterRegistered()
try:
self.assertTrue(is_registered)
except AssertionError:
notes = 'Printer needs to be registered before this testcase runs'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
PromptAndWaitForUserAction('Press ENTER once printer is powered off')
success = _device.UnRegister(_device.auth_token)
try:
self.assertTrue(success)
except AssertionError:
notes = 'Error deleting registered printer. GCP delete API call failed'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'GCP delete API returned success.'
self.LogTest(test_id, test_name, 'Passed', notes)
PromptUserAction('Power on the printer and wait...')
print ('Wait up to 5 minutes for the printer to advertise as '
'an unregistered device')
success = waitForAdvertisementRegStatus(Constants.PRINTER['NAME'],
False, 300)
try:
self.assertTrue(success)
except AssertionError:
notes = ('Deleted device not found advertising or found advertising as '
'registered')
self.LogTest(test_id2, test_name2, 'Failed', notes)
else:
notes = 'Deleted device found advertising as unregistered device.'
self.LogTest(test_id2, test_name2, 'Passed', notes)
res = _gcp.Search(_device.name)
try:
self.assertFalse(res['printers'])
except AssertionError:
notes = 'Unregistered printer found via the GCP Search API.'
self.LogTest(test_id3, test_name3, 'Failed', notes)
raise
else:
notes = ('Unregistered printer not found via the GCP Search API')
self.LogTest(test_id3, test_name3, 'Passed', notes)
class PostUnregistration(LogoCert):
"""Test local printing on an unregistered device
This test is put at the end instead of inside PreRegistration()
because the PWG file used for printing is generated from GCP which requires
the printer to be registered
"""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsUnregistered()
def testLocalPrintGuestUserUnregisteredPrinter(self):
"""Verify local print for unregistered printer is correct."""
test_id = '379dcb9a-2287-41bc-a387-be0d8a132c25'
test_name = 'PrivetLocalDestination.UnregisteredPrinterGuestUser'
if not Constants.CAPS['LOCAL_PRINT_WITHOUT_REG']:
notes = 'Printer does not support unregistered local printing.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
if not os.path.exists(Constants.IMAGES['PWG1']):
print '%s not found.' % (Constants.IMAGES['PWG1'])
print 'LocalPrinting suite should be run before this suite'
print 'LocalPrinting will produce the raster file needed for this test'
notes = 'Run LocalPrinting suite before PostUnregistration suite'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
# New instance of device that is not authenticated - contains no auth-token
guest_device = Device(_logger, None, None, privet_port=_device.port)
guest_device.GetDeviceCDDLocally()
cjt = CloudJobTicket()
job_id = guest_device.LocalPrint(test_name, Constants.IMAGES['PWG1'], cjt,
'image/pwg-raster')
try:
self.assertIsNotNone(job_id)
except AssertionError:
notes = ('Guest failed to print a page via local printing '
'on the unregistered printer.')
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
print ('Guest successfully printed a page via local printing '
'on the unregistered printer.')
print 'If not, fail this test.'
self.ManualPass(test_id, test_name)
class CloudPrinting(LogoCert):
"""Test printing using Cloud Print."""
# class level variable for tracking token refreshes
_prev_token_time = None
def submit(self, dev_id, content, test_id, test_name, cjt, is_url=False):
"""Wrapper for submitting a print job to the printer for logging purposes
Args:
dev_id: string, target printer to print from.
content: string, url or absolute filepath of the item to print.
test_id: string, id of the testcase
test_name: string, title of the print job.
cjt: CloudJobTicket, object that defines the options of the print job
is_url: boolean, flag to identify between url's and files
Returns:
dictionary, response msg from the GCP server if successful;
otherwise, raise an exception
"""
try:
output = _gcp.Submit(dev_id, content, test_name, cjt, is_url)
return output
except AssertionError:
notes = 'Submit API failed'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
def setUp(self):
# Create a fresh CJT for each test case
self.cjt = CloudJobTicket()
# Refresh Oauth access token if necessary
self.CheckAndRefreshToken()
def waitForCloudPrintJobCompletion(self, test_id, test_name, output):
"""Wait for cloudprint job to complete within configured time.
If job does not complete within configured time, log the error and
raise an exception.
Args:
test_id: string, id of the testcase
test_name: string, title of the print job
output: dictionary, submit response from GCP server
"""
print '[Configurable timeout] PRINTING'
try:
_gcp.WaitJobStateIn(output['job']['id'],
_device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
except AssertionError:
notes = ('Job state did not transition to %s within %s seconds.' %
(GCPConstants.DONE, Constants.TIMEOUT['PRINTING']))
self.LogTest(test_id, test_name, 'Failed', notes)
print ('ERROR: Either TIMEOUT[PRINTING] is too small in _config.py or '
'Job is in error state.')
print 'Check the GCP management page to see if it is the latter.'
PromptAndWaitForUserAction('Press ENTER when problem is resolved to '
'continue testing.')
raise
def waitAndManualPass(self, test_id, test_name, output,
verification_prompt=None):
"""Wait for cloudprint job completion then prompt for manual verification.
Args:
test_id: string, id of the testcase
test_name: string, title of the print job
output: dictionary, submit response from GCP server
verification_prompt: string, manual verification prompt message
"""
self.waitForCloudPrintJobCompletion(test_id, test_name, output)
if verification_prompt:
print verification_prompt
self.ManualPass(test_id, test_name)
@classmethod
def setUpClass(cls):
cls._prev_token_time = time.time()
LogoCert.setUpClass(cls)
LogoCert.GetDeviceDetails()
def test_01_CloudPrintMediaSizeSelect(self):
"""Verify cloud printing with media size option."""
test_id = 'c8de872f-49bd-45b7-9623-8db0861aed35'
test_name = 'GCP.PageSize'
_logger.info('Testing the selection of A4 media size.')
PromptAndWaitForUserAction('Load printer with A4 size paper. '
'Select return when ready.')
self.cjt.AddSizeOption(GCPConstants.A4_HEIGHT, GCPConstants.A4_WIDTH)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error selecting A4 media size.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
finally:
PromptAndWaitForUserAction('Load printer with letter size paper. '
'Select return when ready.')
def test_02_CloudPrintPageOrientation(self):
"""Verify cloud printing with media size option."""
test_id = '5085e650-5f08-43a5-bb61-8a485a8122e9'
test_name = 'GCP.Orientation'
_logger.info('Testing the selection of non-default orientation')
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF4'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing in the non-default orientation.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_03_CloudPrintJpgDpiSetting(self):
"""Verify cloud printing a jpg with DPI option."""
test_id = 'aed7d8a4-e669-4a07-b47a-d833d1ef6b16'
test_name = 'GCP.DPI'
dpi_options = _device.cdd['caps']['dpi']['option']
for dpi_option in dpi_options:
_logger.info('Setting dpi to %s', dpi_option)
self.cjt.AddDpiOption(dpi_option['horizontal_dpi'],
dpi_option['vertical_dpi'])
output = self.submit(_device.dev_id, Constants.IMAGES['PNG8'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with dpi set to %s' % dpi_option
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitForCloudPrintJobCompletion(test_id, test_name, output)
self.ManualPass(test_id, test_name)
def test_04_CloudPrintJpg2Copies(self):
"""Verify cloud printing Jpg with copies option set to 2."""
test_id = '96d913fc-35cb-48ae-9e73-1737a36ae02a'
test_name = 'GCP.Copies'
if not Constants.CAPS['COPIES_CLOUD']:
notes = 'Copies not supported.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
_logger.info('Setting copies to 2...')
self.cjt.AddColorOption(self.color)
self.cjt.AddCopiesOption(2)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG12'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with copies = 2.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_05_CloudPrintPdfDuplexLongEdge(self):
"""Verify cloud printing a pdf with the duplex option set to long edge."""
test_id = '068e4390-0e88-4632-a2d4-83dad3b36d09'
test_name = 'GCP.DuplexLongEdge'
if not Constants.CAPS['DUPLEX']:
notes = 'Duplex not supported.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
_logger.info('Setting duplex to long edge...')
self.cjt.AddDuplexOption(GCPConstants.LONG_EDGE)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF10'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing in duplex long edge.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_06_CloudPrintPdfDuplexShortEdge(self):
"""Verify cloud printing a pdf with the duplex option set to short edge."""
test_id = '2b9eb721-48ee-46c5-bf76-6f0868a6acbf'
test_name = 'GCP.DuplexShortEdge'
if not Constants.CAPS['DUPLEX']:
notes = 'Duplex not supported.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
_logger.info('Setting duplex to short edge...')
self.cjt.AddDuplexOption(GCPConstants.SHORT_EDGE)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF10'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing in duplex short edge.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_07_CloudPrintColorSelect(self):
"""Verify cloud printing with color options."""
test_id = '1c433239-bec8-45a6-b1c1-d4190e4cc085'
test_name = 'GCP.Color'
if not Constants.CAPS['COLOR']:
notes = 'Color is not supported.'
self.LogTest(test_id, test_name, 'Skipped', notes)
return
_logger.info('Printing with color selected.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF13'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing color PDF with color selected.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_08_CloudPrintPdfReverseOrder(self):
"""Verify cloud printing a pdf with reverse order option."""
test_id = 'f7551021-cb3c-4a00-93e4-1ef619d5e15c'
test_name = 'GCP.ReverseOrder'
_logger.info('Print with reverse order flag set...')
self.cjt.AddReverseOption()
output = self.submit(_device.dev_id, Constants.IMAGES['PDF10'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing in reverse order.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_09_CloudPrintPdfPageRangePage2(self):
"""Verify cloud printing a pdf with the page range option set to 2."""
test_id = 'bf37a319-321d-4b50-9e5a-44b542dacc50'
test_name = 'GCP.PageRange'
_logger.info('Setting page range to page 2 only')
self.cjt.AddPageRangeOption(2, end=2)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with page range set to page 2 only.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_10_CloudPrintPngFillPage(self):
"""Verify cloud printing a png with the fill page option."""
test_id = 'ad1eff9e-6516-46c1-8ff9-c9de845c3e4c'
test_name = 'GCP.FillPage'
_logger.info('Setting print option to Fill Page...')
self.cjt.AddFitToPageOption(GCPConstants.FILL)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with Fill Page option.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_11_CloudPrintPngFitToPage(self):
"""Verify cloud printing a png with the fit to page option."""
test_id = '58913ffe-93c3-4405-81ac-ec592169b8a7'
test_name = 'GCP.FitToPage'
_logger.info('Setting print option to Fit to Page...')
self.cjt.AddFitToPageOption(GCPConstants.FIT)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with Fit to Page option.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_12_CloudPrintPngGrowToPage(self):
"""Verify cloud printing a png with the grow to page option."""
test_id = 'c189611b-12f0-4a2e-ba9f-3672c89206d6'
test_name = 'GCP.GrowToPage'
_logger.info('Setting print option to Grow to Page...')
self.cjt.AddFitToPageOption(GCPConstants.GROW)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with Grow To Page option.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_13_CloudPrintPngShrinkToPage(self):
"""Verify cloud printing a png with the shrink to page option."""
test_id = '00b50f0a-a196-4c4a-823c-de9547010735'
test_name = 'GCP.ShrinkToPage'
_logger.info('Setting print option to Shrink to Page...')
self.cjt.AddFitToPageOption(GCPConstants.SHRINK)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with Shrink To Page option.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_14_CloudPrintPngNoFitting(self):
"""Verify cloud printing a png with the no fitting option."""
test_id = 'b2ed2f00-e449-4805-995e-8dac5fde7ab2'
test_name = 'GCP.NoFitting'
_logger.info('Setting print option to No Fitting...')
self.cjt.AddFitToPageOption(GCPConstants.NO_FIT)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with No Fitting option.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_15_CloudPrintJpgPortrait(self):
"""Verify cloud printing a jpg with the portrait option."""
test_id = '951209b8-c615-4c5b-864b-cdbfbe80c195'
test_name = 'GCP.JPEGPortrait'
_logger.info('Print simple JPG file with portrait orientation.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.PORTRAIT)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG14'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing JPG file in portrait orientation.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_16_CloudPrintJpgLandscape(self):
"""Verify cloud printing a jpg with the landscape option."""
test_id = '007d7987-c496-45b7-a43b-4ca58625e124'
test_name = 'GCP.JPEGLandscape'
_logger.info('Print simple JPG file with landscape orientation.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG7'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing JPG file with landscape orientation.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_17_CloudPrintJpgBlacknWhite(self):
"""Verify cloud printing a jpg with the monochrome option."""
test_id = 'e725888b-1e3c-45d7-963a-19f13296c57e'
test_name = 'GCP.JPEGBlack&White'
_logger.info('Print black and white JPG file.')
self.cjt.AddColorOption(self.monochrome)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing black and white JPG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_18_CloudPrintJpgMultiImageWithText(self):
"""Verify cloud printing a multi-image jpg in landscape."""
test_id = 'b842c6a0-eff1-4070-adbd-33a0352fad81'
test_name = 'GCP.JPEGMultiImageWithText'
_logger.info('Print multi image with text JPG file.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG9'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing multi-image with text JPG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_19_CloudPrintJpgStepChartLandscape(self):
"""Verify cloud printing a step-chart jpg with the landscape option."""
test_id = '6a77f2b3-d752-4300-9ba6-7a3fe7132556'
test_name = 'GCP.JPEGStepChartLandscape'
_logger.info('Print step chart JPG file in landscape orientation.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG13'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing step chart JPG file in landscape.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_20_CloudPrintJpgLarge(self):
"""Verify cloud printing a large jpg with the landscape option."""
test_id = 'fe34f8a5-9e95-4b39-bdba-25c782d7ad09'
test_name = 'GCP.JPEGLargeImageFile'
_logger.info('Print large JPG file with landscape orientation.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['JPG3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing large JPG file in landscape.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_21_CloudPrintFilePdf(self):
"""Test cloud printing a standard, 1 page b&w PDF file."""
test_id = '289773db-af6f-4303-a859-53dce219f07e'
test_name = 'GCP.PDF'
_logger.info('Printing a black and white 1 page PDF file.')
self.cjt.AddColorOption(self.monochrome)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF4'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing 1 page, black and white PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_22_CloudPrintFileMultiPagePdf(self):
"""Test cloud printing a standard, 3 page color PDF file."""
test_id = '2beca3f9-6a43-4272-a049-613153da4de7'
test_name = 'GCP.PDFMultiPage'
_logger.info('Printing a 3 page, color PDF file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF10'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing 3 page, color PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_23_CloudPrintFileLargeColorPdf(self):
"""Test cloud printing a 20 page, color PDF file."""
test_id = 'bdd50e2d-513d-4a48-a9c1-388a88f0b7ad'
test_name = 'GCP.PDFLargeColorFile'
_logger.info('Printing a 20 page, color PDF file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing 20 page, color PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_24_CloudPrintFilePdfV1_2(self):
"""Test cloud printing PDF version 1.2 file."""
test_id = '7ab294f5-31b1-48ee-9c5a-cd77dc7cfaf3'
test_name = 'GCP.PDFVersion1.2'
_logger.info('Printing a PDF v1.2 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.2'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.2 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_25_CloudPrintFilePdfV1_3(self):
"""Test cloud printing PDF version 1.3 file."""
test_id = 'f95b8ec9-48c7-46c5-b233-50cf410a8f04'
test_name = 'GCP.PDFVersion1.3'
_logger.info('Printing a PDF v1.3 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.3 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_26_CloudPrintFilePdfV1_4(self):
"""Test cloud printing PDF version 1.4 file."""
test_id = '45da57b3-f5b9-4b6e-a40e-79ff2bd8d451'
test_name = 'GCP.PDFVersion1.4'
_logger.info('Printing a PDF v1.4 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.4'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.4 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_27_CloudPrintFilePdfV1_5(self):
"""Test cloud printing PDF version 1.5 file."""
test_id = 'e4a8a756-1ebb-47d4-9b83-17d6b0973883'
test_name = 'GCP.PDFVersion1.5'
_logger.info('Printing a PDF v1.5 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.5'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.5 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_28_CloudPrintFilePdfV1_6(self):
"""Test cloud printing PDF version 1.6 file."""
test_id = '7a35cf71-9b92-4bb8-aaf7-277d196ca42c'
test_name = 'GCP.PDFVersion1.6'
_logger.info('Printing a PDF v1.6 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.6'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.6 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_29_CloudPrintFilePdfV1_7(self):
"""Test cloud printing PDF version 1.7 file."""
test_id = 'cc58720f-ed23-4506-8a9d-c852a71ba1cb'
test_name = 'GCP.PDFVersion1.7'
_logger.info('Printing a PDF v1.7 file.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF1.7'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PDF v1.7 file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_30_CloudPrintFilePdfColorTicket(self):
"""Test cloud printing PDF file of Color Ticket in landscape orientation."""
test_id = '286cc889-88c3-4bc8-87e5-cc44c921f52d'
test_name = 'GCP.PDFColorTicket'
_logger.info('Printing PDF Color ticket in with landscape orientation.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF2'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing color boarding ticket PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_31_CloudPrintFilePdfLetterMarginTest(self):
"""Test cloud printing PDF Letter size margin test file."""
test_id = '361ae296-321d-4b6b-b84c-a2d60fb40d99'
test_name = 'GCP.PDFLetterMarginTest'
_logger.info('Printing PDF Letter Margin Test.')
output = self.submit(_device.dev_id, Constants.IMAGES['PDF3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing letter margin test PDF file 1.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitForCloudPrintJobCompletion(test_id, test_name, output)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF6'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing letter margin test PDF file 2.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
prompt = 'Two margin test print jobs should be printed.\n'
prompt += ('Verify both pages that printed have acceptable print'
' margins.\n')
self.waitAndManualPass(test_id, test_name, output,
verification_prompt=prompt)
def test_32_CloudPrintFilePdfSimpleLandscape(self):
"""Test cloud printing PDF with landscape layout."""
test_id = 'c4ed07f4-c32e-42b0-8a7d-4dae2cd2ec7b'
test_name = 'GCP.PDFLandscape'
_logger.info('Printing simple PDF file in landscape.')
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF8'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing simple PDF file in landscape.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_33_CloudPrintFilePdfColorTest(self):
"""Test cloud printing PDF Color Test file."""
test_id = '28286e1d-3b81-46b4-8372-1f97f88e5a58'
test_name = 'GCP.PDFColorTest'
_logger.info('Printing PDF Color Test page.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF11'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing Color Test PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_34_CloudPrintFilePdfComplexTicket(self):
"""Test cloud printing complex ticket PDF file."""
test_id = 'afb758a1-4a6a-40a6-92fa-005bbd9addaa'
test_name = 'GCP.PDFComplexTicket'
_logger.info('Printing PDF of complex ticket.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF14'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing complex ticket that is PDF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_35_CloudPrintFileSmallGIF(self):
"""Test cloud printing a small GIF file."""
test_id = 'd23d2310-91ab-4d62-ad21-fef3675be6c7'
test_name = 'GCP.GIFSmallFile'
_logger.info('Printing small GIF file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['GIF4'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing small GIF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_36_CloudPrintFileLargeGIF(self):
"""Test cloud printing a large GIF file."""
test_id = '3f9e7136-24bd-4007-84b0-216093bcad7b'
test_name = 'GCP.GIFLargeFile'
_logger.info('Printing large GIF file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['GIF1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing large GIF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_37_CloudPrintFileBlackNWhiteGIF(self):
"""Test cloud printing a black & white GIF file."""
test_id = '96b6f311-82e7-4eb0-817b-d50dd7a4b1ef'
test_name = 'GCP.GIFBlack&White'
_logger.info('Printing black and white GIF file.')
self.cjt.AddColorOption(self.monochrome)
output = self.submit(_device.dev_id, Constants.IMAGES['GIF3'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing black and white GIF file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_38_CloudPrintFileHTML(self):
"""Test cloud printing HTML file."""
test_id = 'ab13f135-4c39-4c9f-9352-6ae9bf2c1664'
test_name = 'GCP.HTMLFile'
_logger.info('Printing HTML file.')
output = self.submit(_device.dev_id, Constants.IMAGES['HTML1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing HTML file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_39_CloudPrintFilePngPortrait(self):
"""Test cloud printing PNG portrait file."""
test_id = '528a5015-317f-4f85-a80c-10da77c22fe2'
test_name = 'GCP.PNGPortrait'
_logger.info('Printing PNG portrait file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG8'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PNG portrait file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_40_CloudPrintFileColorPngLandscape(self):
"""Test cloud printing color PNG file."""
test_id = 'd9bdc76d-a27e-4d6b-8a72-43ec0c8ad881'
test_name = 'GCP.PNGColorLandscape'
_logger.info('Printing Color PNG file in landscape.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG2'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing Color PNG in landscape.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_41_CloudPrintFilePngWithLetters(self):
"""Test cloud printing PNG containing letters."""
test_id = 'd5e07594-f141-40b6-90fb-3e0268168936'
test_name = 'GCP.PNGTransparentWithLetters'
_logger.info('Printing PNG file with letters.')
self.cjt.AddColorOption(self.color)
self.cjt.AddPageOrientationOption(GCPConstants.LANDSCAPE)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG4'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing PNG file containing letters.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_42_CloudPrintFilePngColorImageWithText(self):
"""Test cloud printing color images with text PNG file."""
test_id = '7d9e30c2-52c2-4780-a2c4-64778ff31b36'
test_name = 'GCP.PNGColorImagesWithText'
_logger.info('Printing color images with text PNG file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG6'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing color images with text PNG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_43_CloudPrintFileLargePng(self):
"""Test cloud printing Large PNG file."""
test_id = 'b64c37cd-3ba8-4dfc-bb3b-652e1ce0e08d'
test_name = 'GCP.PNGLargeFile'
_logger.info('Printing large PNG file.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['PNG9'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing large PNG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_44_CloudPrintFileSvgSimple(self):
"""Test cloud printing simple SVG file."""
test_id = 'eb8c1076-c19d-442f-adcc-50909e1a0d73'
test_name = 'GCP.SVGSimple'
_logger.info('Printing simple SVG file.')
output = self.submit(_device.dev_id, Constants.IMAGES['SVG2'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing simple SVG file.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_45_CloudPrintFileSvgWithImages(self):
"""Test cloud printing SVG file with images."""
test_id = 'a130cd96-edce-4359-8cc9-3702c8a6e3f4'
test_name = 'GCP.SVGTransparentWithImages'
_logger.info('Printing SVG file with images.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['SVG1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing SVG file with images.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_46_CloudPrintFileTiffRegLink(self):
"""Test cloud printing TIFF file of GCP registration link."""
test_id = 'f82f3e7b-5acd-4aa2-8d72-d4c94b60fae7'
test_name = 'GCP.TIFFQRCode'
_logger.info('Printing TIFF file of GCP registration link.')
output = self.submit(_device.dev_id, Constants.IMAGES['TIFF1'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing TIFF file of GCP registration link.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_47_CloudPrintFileTiffPhoto(self):
"""Test cloud printing TIFF file of photo."""
test_id = '0bcd79a1-b850-417e-ad42-5a525d358091'
test_name = 'GCP.TIFFPhoto'
_logger.info('Printing TIFF file of photo.')
self.cjt.AddColorOption(self.color)
output = self.submit(_device.dev_id, Constants.IMAGES['TIFF2'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing TIFF file of photo.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitAndManualPass(test_id, test_name, output)
def test_48_CloudPrintMarginsOptions(self):
"""Test cloud printing with margins option."""
test_id = 'e82ef19a-f744-4ab6-a0aa-c74763907bf0'
test_name = 'GCP.Margins'
if not Constants.CAPS['MARGIN']:
self.LogTest(test_id, test_name, 'Skipped', 'No Margin support')
return
self.cjt.AddMarginOption(0, 0, 0, 0)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF9'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error printing with margins set to 0.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
self.waitForCloudPrintJobCompletion(test_id, test_name, output)
self.cjt.AddMarginOption(50000, 50000, 50000, 50000)
output = self.submit(_device.dev_id, Constants.IMAGES['PDF9'], test_id,
test_name, self.cjt)
try:
self.assertTrue(output['success'])
except AssertionError:
notes = 'Error local printing with margins set to 5cm.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
prompt = 'The 1st print job should have no margins.\n'
prompt += 'The 2nd print job should have 5cm margins for all sides.\n'
prompt += 'If the margins are not correct, fail this test.'
self.waitAndManualPass(test_id, test_name, output,
verification_prompt=prompt)
if __name__ == '__main__':
runner = unittest.TextTestRunner(verbosity=2)
suite = unittest.TestSuite()
for testsuite in Constants.TEST['RUN']:
if testsuite.startswith('#'):
continue
print 'Adding %s to list of suites to run' % (testsuite)
suite.addTest(unittest.makeSuite(globals()[testsuite]))
runner.run(suite)
|
python
|
import pygame
from Clock import Clock
from Timer import Timer
class TileManager(object):
# Call constructor
def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight, tileImage, tileType):
self.tiles = []
self.tileWidth = tileWidth
self.tileHeight = tileHeight
self.screenWidth = screenWidth
self.screenHeight = screenHeight
if tileType == "fire":
self.tileTimeLength = 5
elif tileType == "ice":
self.tileTimeLength = 10
self.tileImage = tileImage
self.tileImage = pygame.transform.scale(self.tileImage, (self.tileWidth, self.tileHeight)) # resize the image to fit the tile
self.active = []
self.activeTimer = []
# Get tiles
def getTiles(self):
return self.tiles
# Turn on/off
def setActive(self, tile, activity):
self.active[tile] = activity
# Get tile activity
def getActive(self, tile):
return self.active[tile]
# Add a tile
def addTile(self, x, y, game_Clock):
for i in range(int(self.screenHeight / self.tileHeight)): # run a for loop for the amount of tiles on the y axis
for z in range(int(self.screenWidth / self.tileWidth)): # run a for loop for the amount of tiles on the x axis
tileRect = pygame.Rect((z * self.tileWidth, i * self.tileHeight),(self.tileWidth, self.tileHeight)) # generate the tile as a pygame rectangle
if tileRect.collidepoint(x, y) == True: # check if the point lands on the tile
createTile = True
for tile in range(len(self.tiles)): # run a for loop for all existing tiles
if self.tiles[tile].center[0] == tileRect.center[0] and self.tiles[tile].center[1] == tileRect.center[1]: # if there isn't already a tile in that location
createTile = False # don't create the tile
if createTile == True: # if the tile doesn't already exist
self.tiles.append(tileRect) # create the tile on that tile
self.active.append(True) # Set the Tile Active
self.activeTimer.append(Timer(self.tileTimeLength, game_Clock.getElapsedSeconds())) # create a 10 second timer to set the tile inactive
# Update Fire tiles
def update(self, game_Clock):
for tile in range(len(self.tiles)): # run a for loop for all tiles
if self.active[tile] == True: # if the tile is active
if self.activeTimer[tile].getAlert() == True: # if the tile reached it's timer's limit
self.active[tile] = False # set the tile inactive
else: # if not
self.activeTimer[tile].update(game_Clock.getElapsedSeconds()) # update the off timer
# Draw tiles
def draw(self, canvas):
for tile in range(len(self.tiles)): # run a for loop for all existing tiles
if self.active[tile] == True: # if the tile is active
canvas.blit(self.tileImage, self.tiles[tile]) # draw the tile
class FireTileManager(object):
# Call constructor
def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight):
self.flameTile = pygame.image.load("Data/images/flame.png") # load flame image
self.tileManager = TileManager(screenWidth, screenHeight, tileWidth, tileHeight, self.flameTile, "fire")
# Get tiles
def getTiles(self):
return self.tileManager.getTiles()
# Set tile activity
def setActive(self, tile, activity):
self.tileManager.setActive(tile, activity)
# Get tile activity
def getActive(self, tile):
return self.tileManager.getActive(tile)
# Add a tile
def addTile(self, x, y, game_Clock):
self.tileManager.addTile(x, y, game_Clock)
# Update Fire tiles
def update(self, game_Clock):
self.tileManager.update(game_Clock)
# Draw tiles
def draw(self, canvas):
self.tileManager.draw(canvas)
class IceTileManager(object):
# Call constructor
def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight):
self.iceTile = pygame.image.load("Data/images/icetile.jpg").convert() # load ice tile, convert it
self.tileManager = TileManager(screenWidth, screenHeight, tileWidth, tileHeight, self.iceTile, "ice")
# Get tiles
def getTiles(self):
return self.tileManager.getTiles()
# Set tile activity
def setActive(self, tile, activity):
self.tileManager.setActive(tile, activity)
# Get tile activity
def getActive(self, tile):
return self.tileManager.getActive(tile)
# Add a tile
def addTile(self, x, y, game_Clock):
self.tileManager.addTile(x, y, game_Clock)
# Update Fire tiles
def update(self, game_Clock):
self.tileManager.update(game_Clock)
# Draw tiles
def draw(self, canvas):
self.tileManager.draw(canvas)
|
python
|
"""In this module are all SuperCollider Object related classes"""
|
python
|
# Crie um programa que peça um número ao usuário e retorne se antecessor e o seu sucessor.
print('=-'*7 'DESAFIO 7' ''=-'*7)
n = int(input('Digite um número: '))
print('Analisando o número {}, seu antecessor é {} e seu sucessor é {} '.format(n, n - 1, n + 2))
|
python
|
import pygame
from pygame.locals import QUIT, K_ESCAPE, K_a, K_d, K_s, K_SPACE
from time import time
from os.path import dirname, realpath
def main():
running, settings = load()
while running:
settings = update(settings)
draw(settings)
running = check_exit(settings)
pygame.quit()
def load():
scale = 50
screen_size = (320*scale, 210*scale)
#screen_size = (640, 420)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('pitfall replica - ULISSES GANDINI')
pygame.font.init()
game_object = {
'HUD' : [],
'player' : [],
'crocodile' : [],
'scorpion' : [],
'vine' : [],
'wood' : [],
'serpent' : [],
'bg' : [],
'ladder' : [],
'water' : [],
'hole' : [],
'water_croco' : [],
'wall' : [],
'floor' : []
}
var = {
'folder' : dirname(realpath(__file__)),
'level' : 1,
'seconds_left' : 1200,
'hp' : 2000,
'life' : 3,
'exit' : False,
'init' : time(),
'layer' : ['bg', 'ladder', 'floor', 'wall', 'water', 'hole', 'water_croco', 'wood', 'vine', 'HUD', 'player'],
'scale' : scale
}
#loading first map
game_object = load_level(game_object, var, 1)
return True, {
'screen_size' : screen_size,
'screen' : screen,
'game_object' : game_object,
'var' : var,
}
def load_level(game_object, var, what_level):
if what_level==1:
sprite = {
'idle' : [1, 0],
'running' : [5, 0.07],
'vine' : [1, 0],
'jumping' : [1, 0],
'climbing' : [2, 0]
}
game_object['player'].append(Sprite(30, 110, var['folder']+'/assets/img/player/idle0.png', (30, 380, 16, 22), \
(sprite, var['folder'] + '/assets/img/player', 'idle')))
game_object['bg'].append(Sprite(16, 13, var['folder']+'/assets/img/bg/bg.png'))
game_object['floor'].append(Sprite(16, 124, var['folder']+'/assets/img/floor/floor.png'))
game_object['wall'].append(Sprite(280, 155, var['folder']+'/assets/img/wall/wall.png'))
game_object['ladder'].append(Sprite(156, 140, var['folder']+'/assets/img/ladder/ladder.png'))
game_object['wood'].append(Sprite(260, 123, var['folder']+'/assets/img/wood/wood0.png'))
return game_object
def update(settings):
settings['var']['seconds_left'] = 1201-(time()-settings['var']['init'])
settings['game_object']['player'][0].animation.update()
player = settings['game_object']['player'][0]
k = pygame.key.get_pressed()
if k[K_d] and player.grounded:
settings['game_object']['player'][0].x +=1
settings['game_object']['player'][0].side = False
if settings['game_object']['player'][0].animation.tile == 'idle':
settings['game_object']['player'][0].animation.change('running')
elif k[K_a] and player.grounded:
settings['game_object']['player'][0].x -=1
settings['game_object']['player'][0].side = True
if settings['game_object']['player'][0].animation.tile == 'idle':
settings['game_object']['player'][0].animation.change('running')
else:
if settings['game_object']['player'][0].animation.tile == 'running':
settings['game_object']['player'][0].animation.change('idle')
if player.grounded and k[K_SPACE] and (k[K_d] or k[K_a]):
if k[K_d]:
settings['game_object']['player'][0].x_speed = 1.1
else:
settings['game_object']['player'][0].x_speed = -1.1
settings['game_object']['player'][0].y_speed = -13
settings['game_object']['player'][0].animation.change('jumping')
settings['game_object']['player'][0].grounded = False
elif player.grounded and k[K_SPACE]:
settings['game_object']['player'][0].y_speed = -13
settings['game_object']['player'][0].x_speed = 0
settings['game_object']['player'][0].animation.change('jumping')
settings['game_object']['player'][0].grounded = False
if settings['game_object']['player'][0].y_speed >0:
settings['game_object']['player'][0].y += 1
settings['game_object']['player'][0].x += settings['game_object']['player'][0].x_speed
elif settings['game_object']['player'][0].y_speed<0:
settings['game_object']['player'][0].y -= 1
settings['game_object']['player'][0].x += settings['game_object']['player'][0].x_speed
settings['game_object']['player'][0].y_speed += 1
else:
if settings['game_object']['player'][0].y !=110:
settings['game_object']['player'][0].y -= 1
settings['game_object']['player'][0].y_speed += 1
if settings['game_object']['player'][0].y >110:
settings['game_object']['player'][0].y = 110
settings['game_object']['player'][0].y_speed = 0
settings['game_object']['player'][0].animation.change('idle')
settings['game_object']['player'][0].grounded = True
return settings
def draw(settings):
mm = int(settings['var']['seconds_left']//60)
ss = int(settings['var']['seconds_left']%60)
if len(str(ss))==1: ss = '0' + str(ss)
time = str(mm) + ':' + str(ss)
hp = str(settings['var']['hp'])
game_object = settings['game_object']
layer = settings['var']['layer']
screen = settings['screen']
screen.fill((0, 0, 0))
scale = settings['var']['scale']
for name in layer:
for gO in game_object[name]:
if gO.__class__==Sprite:
temp_img = pygame.transform.scale(gO.img, (gO.img.get_width()*scale, gO.img.get_height()*scale))
temp_img = pygame.transform.flip(temp_img, gO.side, False)
screen.blit(temp_img, (gO.x*scale, gO.y*scale))
font = pygame.font.SysFont("PressStart2P", 15*scale)
for life in range(settings['var']['life']):
pygame.draw.rect(screen, (230, 230, 230), ((36+6*life)*scale, 33*scale, 3*scale, 12*scale))
screen.blit(font.render(hp, True, (230, 230, 230)), (75*scale, 17*scale))
screen.blit(font.render(time, True, (230, 230, 230)), (60*scale, 33*scale))
pygame.display.flip()
fps(60)
pass
def fps(frames):
pygame.time.Clock().tick(frames)
def check_exit(settings):
if settings['var']['exit']: return False
k = pygame.key.get_pressed()
for e in pygame.event.get():
if e.type == QUIT or k[K_ESCAPE]:
return False
return True
class Sprite():
def __init__(self, x, y, path, collider=None, animation=None):
self.x = x
self.y = y
self.path = path
self.img = pygame.image.load(path)
self.grounded = True
self.y_speed = 0
self.x_speed = 0
self.side = False
if collider != None:
# (x , y , width , height , obj)
self.collider = Collider2D(collider[0], collider[1], collider[2], collider[3], self)
if animation != None:
# (sprites , path , first , obj)
#sprites = {'anim1' : [amount, time], 'anim2' : [amount, time]}
self.animation = Animation(animation[0], animation[1], animation[2], self)
class Animation():
def __init__(self, sprites, path, first, obj):
self.sprites = sprites
self.path = path
self.tile = first
self.pos = 0
self.last_update = time()
self.obj = obj
self.obj.img = pygame.image.load(path + '/' + first + str(self.pos) + '.png')
def change(self, tile, pos=0):
self.tile = tile
self.pos = 0
self.obj.img = pygame.image.load(self.path + '/' + tile + str(pos) + '.png')
def update(self):
if time()-self.last_update>self.sprites[self.tile][1]:
if self.pos == self.sprites[self.tile][0]-1:
self.pos = 0
else:
self.pos += 1
self.obj.img = pygame.image.load(self.path + '/' + self.tile + str(self.pos) + '.png')
self.last_update = time()
class Collider2D():
def __init__(self, x, y, width, height, obj):
self.x = x
self.y = y
self.width = width
self.height = height
self.obj = obj
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.
"""A sample test module to exercise the code.
For the sake of exploratory development.
"""
import os
import yaml
from gabbi import driver
# TODO(cdent): test_pytest allows pytest to see the tests this module
# produces. Without it, the generator will not run. It is a todo because
# needing to do this is annoying and gross.
from gabbi.driver import test_pytest # noqa
from gabbi.tests import simple_wsgi
from gabbi.tests import util
TESTS_DIR = 'gabbits_unsafe_yaml'
yaml.add_constructor(u'!IsNAN', lambda loader, node: util.NanChecker())
BUILD_TEST_ARGS = dict(
intercept=simple_wsgi.SimpleWsgi,
safe_yaml=False
)
def load_tests(loader, tests, pattern):
"""Provide a TestSuite to the discovery process."""
test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
return driver.build_tests(test_dir, loader,
test_loader_name=__name__,
**BUILD_TEST_ARGS)
def pytest_generate_tests(metafunc):
test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
driver.py_test_generator(test_dir, metafunc=metafunc, **BUILD_TEST_ARGS)
|
python
|
from vplot import GetOutput
import subprocess as sub
import numpy as np
import os
cwd = os.path.dirname(os.path.realpath(__file__))
import warnings
import h5py
import multiprocessing as mp
import sys
import bigplanet as bp
def test_bpstats():
#gets the number of cores on the machine
cores = mp.cpu_count()
if cores == 1:
warnings.warn("There is only 1 core on the machine",stacklevel=3)
else:
#removes checkpoint files
cp = cwd+'/.BP_Stats'
sub.run(['rm', cp],cwd=cwd)
cp_hdf5 = cwd+'/.BP_Stats_hdf5'
sub.run(['rm', cp_hdf5],cwd=cwd)
#removes the folders from when vspace is ran
dir = cwd+'/BP_Stats'
sub.run(['rm', '-rf', dir],cwd=cwd)
sub.run(['rm', '-rf', (dir + '.hdf5')],cwd=cwd)
#runs vspace
sub.run(['python','../../vspace/vspace/vspace.py','vspace.in'],cwd=cwd)
#runs multi-planet
sub.run(['python', '../../multi-planet/multi-planet.py','vspace.in'],cwd=cwd)
#runs bigplanet
sub.run(['python', '../../bigplanet/bigplanet/bigplanet.py','vspace.in'],cwd=cwd)
#reads in the hdf5 file
file = h5py.File((dir + '.hdf5'),'r')
earth_RIC_min = bp.ExtractColumn(file,'earth_RIC_min')
earth_235UNumMan_max = bp.ExtractColumn(file,'earth_235UNumMan_max')
print(earth_235UNumMan_max)
earth_TCMB_mean = bp.ExtractColumn(file,'earth_TCMB_mean')
earth_FMeltUMan_geomean = bp.ExtractColumn(file,'earth_FMeltUMan_geomean')
earth_BLUMan_stddev = bp.ExtractColumn(file,'earth_BLUMan_stddev')
for i in range(len(earth_RIC_min)):
assert np.isclose(earth_RIC_min[i],0)
for j in range(len(earth_235UNumMan_max)):
assert np.isclose(earth_235UNumMan_max[j],2.700598e+28)
for k in range(len(earth_TCMB_mean)):
assert np.isclose(earth_TCMB_mean[k],4359.67230935)
for l in range(len(earth_FMeltUMan_geomean)):
assert np.isclose(earth_FMeltUMan_geomean[l],0.20819565)
for m in range(len(earth_BLUMan_stddev)):
assert np.isclose(earth_BLUMan_stddev[m],18.26509002)
if __name__ == "__main__":
sub.run(['python -m', '../../bigplanet/bigplanet/bigplanet.py','vspace.in','-c',cores],cwd=cwd)
test_bpstats()
|
python
|
import cv2
import pickle
import face_recognition
class recognize:
def __init__(self):
self.data = pickle.loads(open("./encodings.pickle", "rb").read())
self.detector = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")
def recognize_face(self, frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rects = self.detector.detectMultiScale(gray, scaleFactor=1.1, flags=cv2.CASCADE_SCALE_IMAGE)
boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects]
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
for encoding in encodings:
matches = face_recognition.compare_faces(self.data["encodings"], encoding)
name = 'Unknown'
if True in matches:
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
for i in matchedIdxs:
name = self.data["names"][i]
counts[name] = counts.get(name, 0) + 1
name = max(counts, key=counts.get)
names.append(name)
for ((top, right, bottom, left), name) in zip(boxes, names):
# draw the predicted face name on the image
cv2.rectangle(frame, (left, top), (right, bottom),(0, 0, 255), 2)
y = top - 15 if top - 15 > 15 else top + 15
if name == 'Unknown':
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (0, 0, 255), 2)
else:
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (0, 255, 0), 2)
return frame
|
python
|
token = 'BOT-TOKEN'
initial_extensions = ['cogs.general', 'cogs.groups', 'cogs.lights', 'cogs.scenes']
prefix = '>'
owner_only = True
owner_id = DISCORD-USER-ID
bridge_ip = 'BRIDGE-IP'
|
python
|
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# code starts here
df = pd.read_csv(path)
total_length = len(df)
print(total_length)
fico = 0
for i in df['fico'] > 700:
fico += i
print(fico)
p_a = fico/total_length
print(round(p_a, 2))
debt = 0
for i in df['purpose'] == 'debt_consolidation':
debt += i
print(debt)
p_b = debt/total_length
print(round(p_b,2))
df1 = pd.Series(df.purpose == 'debt_consolidation')
print(df1)
p_a_b = (p_a * p_b)/p_a
print(p_a_b)
p_b_a = (p_a * p_b)/p_b
print(p_b_a)
result = ((p_a_b * p_b_a)/p_b_a == p_a)
print(result)
# code ends here
# --------------
# code starts here
prob_lp = df[df['paid.back.loan']== 'Yes'].shape[0]/df.shape[0]
print(prob_lp)
prob_cs = df[df['credit.policy']== 'Yes'].shape[0]/df.shape[0]
print(prob_cs)
new_df = df[df['paid.back.loan']== 'Yes']
print(new_df)
prob_pd_cs = new_df[new_df['credit.policy'] == 'Yes'].shape[0]/new_df.shape[0]
print(p_a_b)
bayes = (prob_pd_cs * prob_lp)/prob_cs
print(bayes)
# code ends here
# --------------
# code starts here
plt.bar(df['purpose'].index, df['purpose'])
df1 = df[df['paid.back.loan']== 'No']
print(df1)
plt.bar(df1['purpose'].index, df1['purpose'])
# code ends here
# --------------
# code starts here
inst_median = df.installment.median()
inst_mean = df.installment.mean()
df.installment.hist(bins = 10)
df['log.annual.inc'].hist(bins = 10)
# code ends here
|
python
|
import requests, zipfile
import os
import pandas as pd
def gdpimporter(url, filename=None, filetype='csv'):
"""Download the zipped file, unzip, rename the unzipped files, and
outputs a dataframe along with the title from meta data.
This function downloads the zipped data from URL to the local path,
unzips and renames the files as desired. It then returns the data
frame along with the title as a tuple.
Parameters
----------
url : str
URL to the zip file (ends with .zip)
filename : str
the filename that the unzipped csv data (not the MetaData) has.
If None, 'open_canada_data.csv' will be the filename.
This argument is not useful when filetype is set to 'all'
filetype : {'csv', 'all'}, default 'csv'
the types of files that will be extracted. If 'csv', only csv
files are extracted'. If 'all', files of all types are extracted
Returns
-------
(DataFrame, str) :
A tuple containing the dataframe and the title of the data extracted
from the meta data.
Examples
--------
>>> gdpimporter("https://www150.statcan.gc.ca/n1/tbl/csv/36100400-eng.zip")
"""
# Exception handling: check if the arguments are feasible
if (filename != None) and (not isinstance(filename, str)):
raise TypeError("'filename' should be either None (default) or a string.")
if filetype not in ['csv', 'all']:
raise ValueError("'filetype' should either be 'csv' (by default) or 'all'.")
if (not isinstance(url, str)) or (not url.endswith('.zip')):
raise ValueError("'url' should be a valid url of a zipfile that ends with '.zip'.")
zipname = url.split("/")[-1] ## get the name of original zipfile
req = requests.get(url)
with open(zipname, "wb") as code:
code.write(req.content)
zipdata = zipfile.ZipFile(zipname)
zipinfos = zipdata.infolist()
if filetype == "csv":
# iterate through each file
for zipinfo in zipinfos:
# This will do the renaming
if zipinfo.filename.endswith(".csv") and not zipinfo.filename.endswith("MetaData.csv"):
if filename == None:
zipinfo.filename = f"open_canada_data.csv"
else: ## must be a str
zipinfo.filename = f"{filename}.csv"
zipdata.extract(zipinfo)
else:
for zipinfo in zipinfos:
zipdata.extract(zipinfo)
zipdata.close()
for filepath in os.listdir():
if filepath == f"{zipname[:-8]}_MetaData.csv":
metadata = pd.read_csv(filepath)
os.remove(filepath) # Clean up the metadata
continue
elif filepath.endswith('.zip'):
os.remove(filepath) # Clean up zip
continue
if filename == None:
if filepath == "open_canada_data.csv":
data = pd.read_csv(filepath)
else:
if filepath == f"{filename}.csv":
data = pd.read_csv(filepath)
return data, metadata.index[0]
|
python
|
from functools import partial
from typing import Callable, Union
import jax
import jax.numpy as np
from rbig_jax.transforms.histogram import get_hist_params
from rbig_jax.transforms.inversecdf import (
invgausscdf_forward_transform,
invgausscdf_inverse_transform,
)
from rbig_jax.transforms.kde import get_kde_params
from rbig_jax.transforms.marginal import marginal_transform
from rbig_jax.transforms.uniformize import (
uniformize_gradient,
uniformize_inverse,
uniformize_transform,
)
def gaussianize_forward(
X: np.ndarray, uni_transform_f: Callable, return_params: bool = True
):
"""Gaussianization Transformation w. Params"""
# forward uniformization function
X, params = uni_transform_f(X)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf
X = invgausscdf_forward_transform(X)
return X, params
def gaussianize_transform(X: np.ndarray, params, return_jacobian=True):
# forward uniformization function
X = uniformize_transform(X, params)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf
X = invgausscdf_forward_transform(X)
return X
def gaussianize_marginal_transform(X: np.ndarray, params):
# forward uniformization function
X = marginal_transform(X, uniformize_transform, params)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf
X = invgausscdf_forward_transform(X)
return X
def gaussianize_marginal_gradient(X: np.ndarray, params):
# Log PDF of uniformized data
Xu_ldj = np.log(marginal_transform(X, uniformize_gradient, params))
# forward uniformization function
X = marginal_transform(X, uniformize_transform, params)
# clip boundaries
X = np.clip(X, 1e-6, 1.0 - 1e-6)
# inverse cdf
X = invgausscdf_forward_transform(X)
# Log PDF for Gaussianized data
Xg_ldj = jax.scipy.stats.norm.logpdf(X)
# Full log transformation
X_ldj = Xu_ldj - Xg_ldj
return X, X_ldj
def gaussianize_inverse(X: np.ndarray, params):
# inverse cdf
X = invgausscdf_inverse_transform(X)
# inverse uniformization function
X = marginal_transform(X, uniformize_inverse, params)
return X
def gaussianize_marginal_inverse(X: np.ndarray, params):
# inverse cdf
X = invgausscdf_inverse_transform(X)
# inverse uniformization function
X = marginal_transform(X, uniformize_inverse, params)
return X
# TODO: Implement better clipping scheme for transformations
# def init_params_hist_1d(support_extension=10, precision=100, alpha=1e-5):
# param_getter = jax.jit(
# partial(
# get_params,
# support_extension=support_extension,
# precision=precision,
# alpha=alpha,
# )
# )
# return param_getter
# def init_params(support_extension=10, precision=100, alpha=1e-5, method="histogram"):
# if method == "histogram":
# param_getter = jax.jit(
# jax.vmap(
# partial(
# get_hist_params,
# support_extension=support_extension,
# precision=precision,
# alpha=alpha,
# )
# )
# )
# elif method == "kde":
# param_getter = jax.jit(
# jax.vmap(
# partial(
# get_kde_params,
# support_extension=support_extension,
# precision=precision,
# )
# )
# )
# else:
# raise ValueError(f"Unrecognized method...")
# return param_getter
def get_gauss_params_hist(X, support_extension=10, precision=1000, alpha=1e-5):
X, params = get_hist_params(
X, support_extension=support_extension, precision=precision, alpha=alpha
)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf
X = invgausscdf_forward_transform(X)
return X, params
def get_gauss_params_kde(X, support_extension=10, precision=1000, alpha=1e-5):
X, params = get_kde_params(
X, support_extension=support_extension, precision=precision
)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf
X = invgausscdf_forward_transform(X)
return X, params
def forward_gaussianize_transform(X, params):
# Unformization transformation
X = uniformize_transform(X, params)
# clip boundaries
X = np.clip(X, 1e-5, 1.0 - 1e-5)
# inverse cdf transformation
X = invgausscdf_forward_transform(X)
return X
def inverse_gaussianize_transform(X, params):
X = invgausscdf_inverse_transform(X)
# X = np.clip(X, 1e-5, 1.0 - 1e-5)
X = uniformize_inverse(X, params)
return X
def inverse_gaussianize_transform_constrained(X, params, func: Callable):
X, _ = func(X)
X = invgausscdf_inverse_transform(X)
X = uniformize_inverse(X, params)
return X
# def get_gauss_params(X, apply_func):
# X, ldX, params = apply_func(X)
# # clip boundaries
# X = np.clip(X, 1e-5, 1.0 - 1e-5)
# X = forward_inversecdf(X)
# log_prob = ldX - jax.scipy.stats.norm.logpdf(X)
# return None
# def mg_forward_transform(X, params):
# X = hist_forward_transform(X, params)
# X = invgauss_forward_transform(X)
# return X
# def mg_inverse_transform(X, params):
# X = invgauss_inverse_transform(X)
# X = hist_inverse_transform(X, params)
# return X
# def mg_gradient_transform():
# return None
# def get_gauss_params_1d(X, apply_func):
# X, ldX, params = apply_func(X)
# # clip boundaries
# X = np.clip(X, 1e-5, 1.0 - 1e-5)
# X = forward_inversecdf_1d(X)
# log_prob = ldX - jax.scipy.stats.norm.logpdf(X)
# return (
# X,
# log_prob,
# params,
# forward_gaussianization,
# inverse_gaussianization,
# )
# @jax.jit
# def forward_gaussianization(X, params):
# # transform to uniform domain
# X, Xdj = forward_uniformization(X, params)
# # clip boundaries
# X = np.clip(X, 1e-5, 1.0 - 1e-5)
# # transform to the gaussian domain
# X = forward_inversecdf(X)
# log_prob = Xdj - jax.scipy.stats.norm.logpdf(X)
# return X, log_prob
|
python
|
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict, namedtuple
from datetime import datetime, timedelta
import pkg_resources
import re
from zipfile import ZipFile
from enum import Enum, unique
from io import TextIOWrapper
Train = namedtuple("Train", ["name", "kind", "direction", "stops", "service_windows"])
Station = namedtuple("Station", ["name", "zone"])
Stop = namedtuple(
"Stop", ["arrival", "arrival_day", "departure", "departure_day", "stop_number"]
)
ServiceWindow = namedtuple(
"ServiceWindow", ["id", "name", "start", "end", "days", "removed"]
)
_BASE_DATE = datetime(1970, 1, 1, 0, 0, 0, 0)
class Trip(namedtuple("Trip", ["departure", "arrival", "duration", "train"])):
def __str__(self):
return "[{kind} {name}] Departs: {departs}, Arrives: {arrives} ({duration})".format(
kind=self.train.kind,
name=self.train.name,
departs=self.departure,
arrives=self.arrival,
duration=self.duration,
)
def __unicode__(self):
return unicode(self.__str__())
def __repr__(self):
return (
"Trip(departure={departure}, arrival={arrival}, duration={duration}, "
"train=Train(name={train}))".format(
departure=repr(self.departure),
arrival=repr(self.arrival),
duration=repr(self.duration),
train=self.train.name,
)
)
def _sanitize_name(name):
"""
Pre-sanitization to increase the likelihood of finding
a matching station.
:param name: the station name
:type name: str or unicode
:returns: sanitized station name
"""
return (
"".join(re.split("[^A-Za-z0-9]", name)).lower().replace("station", "").strip()
)
def _resolve_time(t):
"""
Resolves the time string into datetime.time. This method
is needed because Caltrain arrival/departure time hours
can exceed 23 (e.g. 24, 25), to signify trains that arrive
after 12 AM. The 'day' variable is incremented from 0 in
these situations, and the time resolved back to a valid
datetime.time (e.g. 24:30:00 becomes days=1, 00:30:00).
:param t: the time to resolve
:type t: str or unicode
:returns: tuple of days and datetime.time
"""
hour, minute, second = [int(x) for x in t.split(":")]
day, hour = divmod(hour, 24)
r = _BASE_DATE + timedelta(hours=hour, minutes=minute, seconds=second)
return day, r.time()
def _resolve_duration(start, end):
"""
Resolves the duration between two times. Departure/arrival
times that exceed 24 hours or cross a day boundary are correctly
resolved.
:param start: the time to resolve
:type start: Stop
:param end: the time to resolve
:type end: Stop
:returns: tuple of days and datetime.time
"""
start_time = _BASE_DATE + timedelta(
hours=start.departure.hour,
minutes=start.departure.minute,
seconds=start.departure.second,
days=start.departure_day,
)
end_time = _BASE_DATE + timedelta(
hours=end.arrival.hour,
minutes=end.arrival.minute,
seconds=end.arrival.second,
days=end.departure_day,
)
return end_time - start_time
_STATIONS_RE = re.compile(r"^(.+) Caltrain( Station)?$")
_RENAME_MAP = {
"SO. SAN FRANCISCO": "SOUTH SAN FRANCISCO",
"MT VIEW": "MOUNTAIN VIEW",
"CALIFORNIA AVE": "CALIFORNIA AVENUE",
}
_DEFAULT_GTFS_FILE = "data/GTFSTransitData_ct.zip"
_ALIAS_MAP_RAW = {
"SAN FRANCISCO": ("SF", "SAN FRAN"),
"SOUTH SAN FRANCISCO": (
"S SAN FRANCISCO",
"SOUTH SF",
"SOUTH SAN FRAN",
"S SAN FRAN",
"S SAN FRANCISCO",
"S SF",
"SO SF",
"SO SAN FRANCISCO",
"SO SAN FRAN",
),
"22ND ST": (
"TWENTY-SECOND STREET",
"TWENTY-SECOND ST",
"22ND STREET",
"22ND",
"TWENTY-SECOND",
"22",
),
"MOUNTAIN VIEW": "MT VIEW",
"CALIFORNIA AVENUE": (
"CAL AVE",
"CALIFORNIA",
"CALIFORNIA AVE",
"CAL",
"CAL AV",
"CALIFORNIA AV",
),
"REDWOOD CITY": "REDWOOD",
"SAN JOSE DIRIDON": ("DIRIDON", "SAN JOSE", "SJ DIRIDON", "SJ"),
"COLLEGE PARK": "COLLEGE",
"BLOSSOM HILL": "BLOSSOM",
"MORGAN HILL": "MORGAN",
"HAYWARD PARK": "HAYWARD",
"MENLO PARK": "MENLO",
}
_ALIAS_MAP = {}
for k, v in _ALIAS_MAP_RAW.items():
if not isinstance(v, list) and not isinstance(v, tuple):
v = (v,)
for x in v:
_ALIAS_MAP[_sanitize_name(x)] = _sanitize_name(k)
@unique
class Direction(Enum):
north = 0
south = 1
@unique
class TransitType(Enum):
shuttle = 0
local = 1
limited = 2
baby_bullet = 3
weekend_game_train = 4
@staticmethod
def from_trip_id(trip_id):
if trip_id[0] == "s":
return TransitType.shuttle
if trip_id[0] in ("3", "8"):
return TransitType.baby_bullet
if trip_id[0] in ("1", "4"):
return TransitType.local
if trip_id[0] in ("2", "5"):
return TransitType.limited
if trip_id[0] == "6":
return TransitType.weekend_game_train
raise ValueError(
"unable to derive transit type from trip ID: {}".format(trip_id)
)
def __str__(self):
return self.name.replace("_", " ").title()
class UnexpectedGTFSLayoutError(Exception):
pass
class UnknownStationError(Exception):
pass
class Caltrain(object):
def __init__(self, gtfs_path=None):
self.version = None
self.trains = {}
self.stations = {}
self._unambiguous_stations = {}
self._service_windows = {}
self._fares = {}
self.load_from_gtfs(gtfs_path)
def load_from_gtfs(self, gtfs_path=None):
"""
Loads a GTFS zip file and builds the data model from it.
If not specified, the internally stored GTFS zip file from
Caltrain is used instead.
:param gtfs_path: the path of the GTFS zip file to load
:type gtfs_path: str or unicode
"""
# Use the default path if not specified.
if gtfs_path is None:
gtfs_handle = pkg_resources.resource_stream(__name__, _DEFAULT_GTFS_FILE)
else:
gtfs_handle = open(gtfs_path, "rb")
with gtfs_handle as f:
self._load_from_gtfs(f)
def _load_from_gtfs(self, handle):
z = ZipFile(handle)
self.trains, self.stations = {}, {}
self._service_windows, self._fares = defaultdict(list), {}
# -------------------
# 1. Record fare data
# -------------------
fare_lookup = {}
# Create a map if (start, dest) -> price
with z.open("fare_attributes.txt", "r") as csvfile:
fare_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in fare_reader:
fare_lookup[r["fare_id"]] = tuple(int(x) for x in r["price"].split("."))
# Read in the fare IDs from station X to station Y.
with z.open("fare_rules.txt", "r") as csvfile:
fare_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in fare_reader:
if r["origin_id"] == "" or r["destination_id"] == "":
continue
k = (int(r["origin_id"]), int(r["destination_id"]))
self._fares[k] = fare_lookup[r["fare_id"]]
# ------------------------
# 2. Record calendar dates
# ------------------------
# Record the days when certain trains are active.
with z.open("calendar.txt", "r") as csvfile:
calendar_reader = csv.reader(TextIOWrapper(csvfile))
next(calendar_reader) # skip the header
for r in calendar_reader:
self._service_windows[r[0]].append(
ServiceWindow(
id=r[0],
name=r[1],
start=datetime.strptime(r[-2], "%Y%m%d").date(),
end=datetime.strptime(r[-1], "%Y%m%d").date(),
days=set(i for i, j in enumerate(r[2:9]) if int(j) == 1),
removed=False,
)
)
# Find special events/holiday windows where trains are active.
with z.open("calendar_dates.txt", "r") as csvfile:
calendar_reader = csv.reader(TextIOWrapper(csvfile))
next(calendar_reader) # skip the header
for r in calendar_reader:
when = datetime.strptime(r[1], "%Y%m%d").date()
self._service_windows[r[0]].insert(
0,
ServiceWindow(
id=r[0],
name=r[1],
start=when,
end=when,
days={when.weekday()},
removed=r[-1] == "2",
),
)
# ------------------
# 3. Record stations
# ------------------
with z.open("stops.txt", "r") as csvfile:
trip_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in trip_reader:
# From observation, non-numeric stop IDs are useless information
# that should be skipped.
if not r["stop_id"].isdigit():
continue
stop_name = _STATIONS_RE.match(r["stop_name"]).group(1).strip().upper()
self.stations[r["stop_id"]] = {
"name": _RENAME_MAP.get(stop_name, stop_name).title(),
"zone": int(r["zone_id"]) if r["zone_id"] else -1,
}
# ---------------------------
# 4. Record train definitions
# ---------------------------
with z.open("trips.txt", "r") as csvfile:
train_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in train_reader:
train_dir = int(r["direction_id"])
transit_type = TransitType.from_trip_id(r["trip_id"])
service_windows = self._service_windows[r["service_id"]]
self.trains[r["trip_id"]] = Train(
name=r["trip_short_name"] if r["trip_short_name"] else r["trip_id"],
kind=transit_type,
direction=Direction(train_dir),
stops={},
service_windows=service_windows,
)
self.stations = dict(
(k, Station(v["name"], v["zone"])) for k, v in self.stations.items()
)
# -----------------------
# 5. Record trip stations
# -----------------------
with z.open("stop_times.txt", "r") as csvfile:
stop_times_reader = csv.DictReader(TextIOWrapper(csvfile))
for r in stop_times_reader:
stop_id = r["stop_id"]
train = self.trains[r["trip_id"]]
arrival_day, arrival = _resolve_time(r["arrival_time"])
departure_day, departure = _resolve_time(r["departure_time"])
train.stops[self.stations[stop_id]] = Stop(
arrival=arrival,
arrival_day=arrival_day,
departure=departure,
departure_day=departure_day,
stop_number=int(r["stop_sequence"]),
)
# For display
self.stations = dict(
("_".join(re.split("[^A-Za-z0-9]", v.name)).lower(), v)
for _, v in self.stations.items()
)
# For station lookup by string
self._unambiguous_stations = dict(
(k.replace("_", ""), v) for k, v in self.stations.items()
)
def get_station(self, name):
"""
Attempts to resolves a station name from a string into an
actual station. An UnknownStationError is thrown if no
Station can be derived
:param name: the name to resolve
:type name: str or unicode
:returns: the resolved Station object
"""
sanitized = _sanitize_name(name)
sanitized = _ALIAS_MAP.get(sanitized, sanitized)
station = self._unambiguous_stations.get(sanitized, None)
if station:
return station
else:
raise UnknownStationError(name)
def fare_between(self, a, b):
"""
Returns the fare to travel between stations a and b. Caltrain fare
is always dependent on the distance and not the train type.
:param a: the starting station
:type a: str or unicode or Station
:param b: the destination station
:type b: str or unicode or Station
:returns: tuple of the dollar and cents cost
"""
a = self.get_station(a) if not isinstance(a, Station) else a
b = self.get_station(b) if not isinstance(b, Station) else b
return self._fares[(a.zone, b.zone)]
def next_trips(self, a, b, after=None):
"""
Returns a list of possible trips to get from stations a to b
following the after date. These are ordered from soonest to
latest and terminate at the end of the Caltrain's 'service day'.
:param a: the starting station
:type a: str or unicode or Station
:param b: the destination station
:type b: str or unicode or Station
:param after: the time to find the next trips after
(default datetime.now())
:type after: datetime
:returns: a list of possible trips
"""
if after is None:
after = datetime.now()
a = self.get_station(a) if not isinstance(a, Station) else a
b = self.get_station(b) if not isinstance(b, Station) else b
possibilities = []
for name, train in self.trains.items():
should_skip = set()
for sw in train.service_windows:
in_time_window = (
sw.start <= after.date() <= sw.end and after.weekday() in sw.days
)
stops_at_stations = a in train.stops and b in train.stops
if not in_time_window or not stops_at_stations or sw.id in should_skip:
continue
if sw.removed:
should_skip.add(sw.id)
continue
stop_a = train.stops[a]
stop_b = train.stops[b]
# Check to make sure this train is headed in the right direction.
if stop_a.stop_number > stop_b.stop_number:
continue
# Check to make sure this train has not left yet.
if stop_a.departure < after.time():
continue
possibilities.append(
Trip(
departure=stop_a.departure,
arrival=stop_b.arrival,
duration=_resolve_duration(stop_a, stop_b),
train=train,
)
)
possibilities.sort(key=lambda x: x.departure)
return possibilities
|
python
|
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
raise Exception('this code should never execute')
|
python
|
skills = [
{
"id" : "0001",
"name" : "Liver of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumInebriety" : "+5",
},
},
{
"id" : "0002",
"name" : "Chronic Indigestion",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "0003",
"name" : "The Smile of Mr. A.",
"type" : "Buff",
"mpCost" : 5,
"isPermable" : False,
},
{
"id" : "0004",
"name" : "Arse Shoot",
"type" : "Buff",
"mpCost" : 5,
"isPermable" : False,
},
{
"id" : "0005",
"name" : "Stomach of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumFullness" : "+5",
},
},
{
"id" : "0006",
"name" : "Spleen of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumSpleen" : "+5",
},
},
{
"id" : "0010",
"name" : "Powers of Observatiogn",
"type" : "Passive",
"effects" :
{
"itemDrop" : "+10%",
},
},
{
"id" : "0011",
"name" : "Gnefarious Pickpocketing",
"type" : "Passive",
"effects" :
{
"meatDrop" : "+10%",
},
},
{
"id" : "0012",
"name" : "Torso Awaregness",
"type" : "Passive",
},
{
"id" : "0013",
"name" : "Gnomish Hardigness",
"type" : "Passive",
"effects" :
{
"maximumHP" : "+5%",
},
},
{
"id" : "0014",
"name" : "Cosmic Ugnderstanding",
"type" : "Passive",
"effects" :
{
"maximumMP" : "+5%",
},
},
{
"id" : "0015",
"name" : "CLEESH",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "0019",
"name" : "Transcendent Olfaction",
"type" : "Combat",
"mpCost" : 40,
"isAutomaticallyPermed" : True,
},
{
"id" : "0020",
"name" : "Really Expensive Jewelrycrafting",
"type" : "Passive",
"isPermable" : False,
},
{
"id" : "0021",
"name" : "Lust",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"combatInitiative" : "+50%",
"spellDamage" : "-5",
"meleeDamage" : "-5",
},
},
{
"id" : "0022",
"name" : "Gluttony",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"strengthensFood" : True,
"statsPerFight" : "-2",
},
},
{
"id" : "0023",
"name" : "Greed",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"meatDrop" : "+50%",
"itemDrop" : "-15%",
},
},
{
"id" : "0024",
"name" : "Sloth",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"damageReduction" : "+8",
"combatInitiative" : "-25%",
},
},
{
"id" : "0025",
"name" : "Wrath",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"spellDamage" : "+10",
"meleeDamage" : "+10",
"damageReduction" : "-4",
},
},
{
"id" : "0026",
"name" : "Envy",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"itemDrop" : "+30%",
"meatDrop" : "-25%",
},
},
{
"id" : "0027",
"name" : "Pride",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"statsPerFight" : "+4",
"weakensFood" : True,
},
},
{
"id" : "0028",
"name" : "Awesome Balls of Fire",
"type" : "Combat",
"mpCost" : 120,
},
{
"id" : "0029",
"name" : "Conjure Relaxing Campfire",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "0030",
"name" : "Snowclone",
"type" : "Combat",
"mpCost" : 120,
},
{
"id" : "0031",
"name" : "Maximum Chill",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "0032",
"name" : "Eggsplosion",
"type" : "Combat",
"mpCost" : 120,
},
{
"id" : "0033",
"name" : "Mudbath",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "0036",
"name" : "Grease Lightning",
"type" : "Combat",
"mpCost" : 120,
},
{
"id" : "0037",
"name" : "Inappropriate Backrub",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "0038",
"name" : "Natural Born Scrabbler",
"type" : "Passive",
"effects" :
{
"itemDrop" : "+5%",
},
},
{
"id" : "0039",
"name" : "Thrift and Grift",
"type" : "Passive",
"effects" :
{
"meatDrop" : "+10%",
},
},
{
"id" : "0040",
"name" : "Abs of Tin",
"type" : "Passive",
"effects" :
{
"maximumHP" : "+10%",
},
},
{
"id" : "0041",
"name" : "Marginally Insane",
"type" : "Passive",
"effects" :
{
"maximumMP" : "+10%",
},
},
{
"id" : "0042",
"name" : "Raise Backup Dancer",
"type" : "Combat",
"mpCost" : 120,
},
{
"id" : "0043",
"name" : "Creepy Lullaby",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "0044",
"name" : "Rainbow Gravitation",
"type" : "Noncombat",
"mpCost" : 30,
},
{
"id" : "1000",
"name" : "Seal Clubbing Frenzy",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "1003",
"name" : "Thrust-Smack",
"type" : "Combat",
"mpCost" : 3,
},
{
"id" : "1004",
"name" : "Lunge-Smack",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "1005",
"name" : "Lunging Thrust-Smack",
"type" : "Combat",
"mpCost" : 8,
},
{
"id" : "1006",
"name" : "Super-Advanced Meatsmithing",
"type" : "Passive",
},
{
"id" : "1007",
"name" : "Tongue of the Otter",
"type" : "Noncombat",
"mpCost" : 7,
},
{
"id" : "1008",
"name" : "Hide of the Otter",
"type" : "Passive",
},
{
"id" : "1009",
"name" : "Claws of the Otter",
"type" : "Passive",
},
{
"id" : "1010",
"name" : "Tongue of the Walrus",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "1011",
"name" : "Hide of the Walrus",
"type" : "Passive",
},
{
"id" : "1012",
"name" : "Claws of the Walrus",
"type" : "Passive",
},
{
"id" : "1014",
"name" : "Eye of the Stoat",
"type" : "Passive",
},
{
"id" : "1015",
"name" : "Rage of the Reindeer",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "1016",
"name" : "Pulverize",
"type" : "Passive",
},
{
"id" : "1017",
"name" : "Double-Fisted Skull Smashing",
"type" : "Passive",
},
{
"id" : "1018",
"name" : "Northern Exposure",
"type" : "Passive",
},
{
"id" : "1019",
"name" : "Musk of the Moose",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "1020",
"name" : "Snarl of the Timberwolf",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "2000",
"name" : "Patience of the Tortoise",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "2003",
"name" : "Headbutt",
"type" : "Combat",
"mpCost" : 3,
},
{
"id" : "2004",
"name" : "Skin of the Leatherback",
"type" : "Passive",
},
{
"id" : "2005",
"name" : "Shieldbutt",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "2006",
"name" : "Armorcraftiness",
"type" : "Passive",
},
{
"id" : "2007",
"name" : "Ghostly Shell",
"type" : "Buff",
"mpCost" : 6,
},
{
"id" : "2008",
"name" : "Reptilian Fortitude",
"type" : "Buff",
"mpCost" : 10,
},
{
"id" : "2009",
"name" : "Empathy of the Newt",
"type" : "Buff",
"mpCost" : 15,
},
{
"id" : "2010",
"name" : "Tenacity of the Snapper",
"type" : "Buff",
"mpCost" : 8,
},
{
"id" : "2011",
"name" : "Wisdom of the Elder Tortoises",
"type" : "Passive",
},
{
"id" : "2012",
"name" : "Astral Shell",
"type" : "Buff",
"mpCost" : 10,
},
{
"id" : "2014",
"name" : "Amphibian Sympathy",
"type" : "Passive",
},
{
"id" : "2015",
"name" : "Kneebutt",
"type" : "Combat",
"mpCost" : 4,
},
{
"id" : "2016",
"name" : "Cold-Blooded Fearlessness",
"type" : "Passive",
},
{
"id" : "2020",
"name" : "Hero of the Half-Shell",
"type" : "Passive",
},
{
"id" : "2021",
"name" : "Tao of the Terrapin",
"type" : "Passive",
},
{
"id" : "2022",
"name" : "Spectral Snapper",
"type" : "Combat",
"mpCost" : 20,
},
{
"id" : "2103",
"name" : "Head + Knee Combo",
"type" : "Combat",
"mpCost" : 8,
},
{
"id" : "2105",
"name" : "Head + Shield Combo",
"type" : "Combat",
"mpCost" : 9,
},
{
"id" : "2106",
"name" : "Knee + Shield Combo",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "2107",
"name" : "Head + Knee + Shield Combo",
"type" : "Combat",
"mpCost" : 13,
},
{
"id" : "3000",
"name" : "Manicotti Meditation",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "3003",
"name" : "Ravioli Shurikens",
"type" : "Combat",
"mpCost" : 4,
},
{
"id" : "3004",
"name" : "Entangling Noodles",
"type" : "Combat",
"mpCost" : 3,
},
{
"id" : "3005",
"name" : "Cannelloni Cannon",
"type" : "Combat",
"mpCost" : 7,
},
{
"id" : "3006",
"name" : "Pastamastery",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3007",
"name" : "Stuffed Mortar Shell",
"type" : "Combat",
"mpCost" : 19,
},
{
"id" : "3008",
"name" : "Weapon of the Pastalord",
"type" : "Combat",
"mpCost" : 35,
},
{
"id" : "3009",
"name" : "Lasagna Bandages",
"type" : "Combat / Noncombat",
"mpCost" : 6,
},
{
"id" : "3010",
"name" : "Leash of Linguini",
"type" : "Noncombat",
"mpCost" : 12,
},
{
"id" : "3011",
"name" : "Spirit of Rigatoni",
"type" : "Passive",
},
{
"id" : "3012",
"name" : "Cannelloni Cocoon",
"type" : "Noncombat",
"mpCost" : 20,
},
{
"id" : "3014",
"name" : "Spirit of Ravioli",
"type" : "Passive",
},
{
"id" : "3015",
"name" : "Springy Fusilli",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3016",
"name" : "Tolerance of the Kitchen",
"type" : "Passive",
},
{
"id" : "3017",
"name" : "Flavour of Magic",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3018",
"name" : "Transcendental Noodlecraft",
"type" : "Passive",
},
{
"id" : "3019",
"name" : "Fearful Fettucini",
"type" : "Combat",
"mpCost" : 35,
},
{
"id" : "3020",
"name" : "Spaghetti Spear",
"type" : "Combat",
"mpCost" : 1,
},
{
"id" : "3101",
"name" : "Spirit of Cayenne",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3102",
"name" : "Spirit of Peppermint",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3103",
"name" : "Spirit of Garlic",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3104",
"name" : "Spirit of Wormwood",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "3105",
"name" : "Spirit of Bacon Grease",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "4000",
"name" : "Sauce Contemplation",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "4003",
"name" : "Stream of Sauce",
"type" : "Combat",
"mpCost" : 3,
},
{
"id" : "4004",
"name" : "Expert Panhandling",
"type" : "Passive",
},
{
"id" : "4005",
"name" : "Saucestorm",
"type" : "Combat",
"mpCost" : 12,
},
{
"id" : "4006",
"name" : "Advanced Saucecrafting",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "4007",
"name" : "Elemental Saucesphere",
"type" : "Buff",
"mpCost" : 10,
},
{
"id" : "4008",
"name" : "Jalapeno Saucesphere",
"type" : "Buff",
"mpCost" : 5,
},
{
"id" : "4009",
"name" : "Wave of Sauce",
"type" : "Combat",
"mpCost" : 23,
},
{
"id" : "4010",
"name" : "Intrinsic Spiciness",
"type" : "Passive",
},
{
"id" : "4011",
"name" : "Jabanero Saucesphere",
"type" : "Buff",
"mpCost" : 10,
},
{
"id" : "4012",
"name" : "Saucegeyser",
"type" : "Combat",
"mpCost" : 40,
},
{
"id" : "4014",
"name" : "Saucy Salve",
"type" : "Combat",
"mpCost" : 4,
},
{
"id" : "4015",
"name" : "Impetuous Sauciness",
"type" : "Passive",
},
{
"id" : "4016",
"name" : "Diminished Gag Reflex",
"type" : "Passive",
},
{
"id" : "4017",
"name" : "Immaculate Seasoning",
"type" : "Passive",
},
{
"id" : "4018",
"name" : "The Way of Sauce",
"type" : "Passive",
},
{
"id" : "4019",
"name" : "Scarysauce",
"type" : "Buff",
"mpCost" : 10,
},
{
"id" : "4020",
"name" : "Salsaball",
"type" : "Combat",
"mpCost" : 1,
},
{
"id" : "5000",
"name" : "Disco Aerobics",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "5003",
"name" : "Disco Eye-Poke",
"type" : "Combat",
"mpCost" : 3,
},
{
"id" : "5004",
"name" : "Nimble Fingers",
"type" : "Passive",
},
{
"id" : "5005",
"name" : "Disco Dance of Doom",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "5006",
"name" : "Mad Looting Skillz",
"type" : "Passive",
},
{
"id" : "5007",
"name" : "Disco Nap",
"type" : "Noncombat",
"mpCost" : 8,
},
{
"id" : "5008",
"name" : "Disco Dance II: Electric Boogaloo",
"type" : "Combat",
"mpCost" : 7,
},
{
"id" : "5009",
"name" : "Disco Fever",
"type" : "Passive",
},
{
"id" : "5010",
"name" : "Overdeveloped Sense of Self Preservation",
"type" : "Passive",
},
{
"id" : "5011",
"name" : "Disco Power Nap",
"type" : "Noncombat",
"mpCost" : 12,
},
{
"id" : "5012",
"name" : "Disco Face Stab",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "5014",
"name" : "Advanced Cocktailcrafting",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "5015",
"name" : "Ambidextrous Funkslinging",
"type" : "Passive",
},
{
"id" : "5016",
"name" : "Heart of Polyester",
"type" : "Passive",
},
{
"id" : "5017",
"name" : "Smooth Movement",
"type" : "Noncombat",
"mpCost" : 10,
},
{
"id" : "5018",
"name" : "Superhuman Cocktailcrafting",
"type" : "Passive",
},
{
"id" : "5019",
"name" : "Tango of Terror",
"type" : "Combat",
"mpCost" : 8,
},
{
"id" : "6000",
"name" : "Moxie of the Mariachi",
"type" : "Noncombat",
"mpCost" : 1,
},
{
"id" : "6003",
"name" : "Aloysius' Antiphon of Aptitude",
"type" : "Buff",
"mpCost" : 40,
},
{
"id" : "6004",
"name" : "The Moxious Madrigal",
"type" : "Buff",
"mpCost" : 2,
},
{
"id" : "6005",
"name" : "Cletus's Canticle of Celerity",
"type" : "Buff",
"mpCost" : 4,
},
{
"id" : "6006",
"name" : "The Polka of Plenty",
"type" : "Buff",
"mpCost" : 7,
},
{
"id" : "6007",
"name" : "The Magical Mojomuscular Melody",
"type" : "Buff",
"mpCost" : 3,
},
{
"id" : "6008",
"name" : "The Power Ballad of the Arrowsmith",
"type" : "Buff",
"mpCost" : 5,
},
{
"id" : "6009",
"name" : "Brawnee's Anthem of Absorption",
"type" : "Buff",
"mpCost" : 13,
},
{
"id" : "6010",
"name" : "Fat Leon's Phat Loot Lyric",
"type" : "Buff",
"mpCost" : 11,
},
{
"id" : "6011",
"name" : "The Psalm of Pointiness",
"type" : "Buff",
"mpCost" : 15,
},
{
"id" : "6012",
"name" : "Jackasses' Symphony of Destruction",
"type" : "Buff",
"mpCost" : 9,
},
{
"id" : "6013",
"name" : "Stevedave's Shanty of Superiority",
"type" : "Buff",
"mpCost" : 30,
},
{
"id" : "6014",
"name" : "The Ode to Booze",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "6015",
"name" : "The Sonata of Sneakiness",
"type" : "Buff",
"mpCost" : 20,
},
{
"id" : "6016",
"name" : "Carlweather's Cantata of Confrontation",
"type" : "Buff",
"mpCost" : 20,
},
{
"id" : "6017",
"name" : "Ur-Kel's Aria of Annoyance",
"type" : "Buff",
"mpCost" : 30,
},
{
"id" : "6018",
"name" : "Dirge of Dreadfulness",
"type" : "Buff",
"mpCost" : 9,
},
{
"id" : "6020",
"name" : "The Ballad of Richie Thingfinder",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "6021",
"name" : "Benetton's Medley of Diversity",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "6022",
"name" : "Elron's Explosive Etude",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "6023",
"name" : "Chorale of Companionship",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "6024",
"name" : "Prelude of Precision",
"type" : "Buff",
"mpCost" : 50,
},
{
"id" : "7001",
"name" : "Give In To Your Vampiric Urges",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7002",
"name" : "Shake Hands",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7003",
"name" : "Hot Breath",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7004",
"name" : "Cold Breath",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7005",
"name" : "Spooky Breath",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7006",
"name" : "Stinky Breath",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7007",
"name" : "Sleazy Breath",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7008",
"name" : "Moxious Maneuver",
"type" : "Combat",
},
{
"id" : "7009",
"name" : "Magic Missile",
"type" : "Combat",
"mpCost" : 2,
},
{
"id" : "7010",
"name" : "Fire Red Bottle-Rocket",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7011",
"name" : "Fire Blue Bottle-Rocket",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7012",
"name" : "Fire Orange Bottle-Rocket",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7013",
"name" : "Fire Purple Bottle-Rocket",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7014",
"name" : "Fire Black Bottle-Rocket",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7015",
"name" : "Creepy Grin",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "7016",
"name" : "Start Trash Fire",
"type" : "Combat",
"mpCost" : 100,
},
{
"id" : "7017",
"name" : "Overload Discarded Refrigerator",
"type" : "Combat",
"mpCost" : 100,
},
{
"id" : "7018",
"name" : "Trashquake",
"type" : "Combat",
"mpCost" : 100,
},
{
"id" : "7019",
"name" : "Zombo's Visage",
"type" : "Combat",
"mpCost" : 100,
},
{
"id" : "7020",
"name" : "Hypnotize Hobo",
"type" : "Combat",
"mpCost" : 100,
},
{
"id" : "7021",
"name" : "Ask Richard for a Bandage",
"type" : "Combat",
},
{
"id" : "7022",
"name" : "Ask Richard for a Grenade",
"type" : "Combat",
},
{
"id" : "7023",
"name" : "Ask Richard to Rough the Hobo Up a Bit",
"type" : "Combat",
},
{
"id" : "7024",
"name" : "Summon Mayfly Swarm",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7025",
"name" : "Get a You-Eye View",
"type" : "Combat",
"mpCost" : 30,
},
{
"id" : "7038",
"name" : "Vicious Talon Slash",
"type" : "Combat",
"mpCost" : 5,
},
{
"id" : "7039",
"name" : "All-You-Can-Beat Wing Buffet",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7040",
"name" : "Tunnel Upwards",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7041",
"name" : "Tunnel Downwards",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7042",
"name" : "Rise From Your Ashes",
"type" : "Combat",
"mpCost" : 20,
},
{
"id" : "7043",
"name" : "Antarctic Flap",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7044",
"name" : "The Statue Treatment",
"type" : "Combat",
"mpCost" : 20,
},
{
"id" : "7045",
"name" : "Feast on Carrion",
"type" : "Combat",
"mpCost" : 20,
},
{
"id" : "7046",
"name" : "Give Your Opponent \"The Bird\"",
"type" : "Combat",
"mpCost" : 20,
},
{
"id" : "7047",
"name" : "Ask the hobo for a drink",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7048",
"name" : "Ask the hobo for something to eat",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7049",
"name" : "Ask the hobo for some violence",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7050",
"name" : "Ask the hobo to tell you a joke",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7051",
"name" : "Ask the hobo to dance for you",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7052",
"name" : "Summon hobo underling",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7053",
"name" : "Rouse Sapling",
"type" : "Combat",
"mpCost" : 15,
},
{
"id" : "7054",
"name" : "Spray Sap",
"type" : "Combat",
"mpCost" : 15,
},
{
"id" : "7055",
"name" : "Put Down Roots",
"type" : "Combat",
"mpCost" : 15,
},
{
"id" : "7056",
"name" : "Fire off a Roman Candle",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7061",
"name" : "Spring Raindrop Attack",
"type" : "Combat",
"mpCost" : 0,
},
{
"id" : "7062",
"name" : "Summer Siesta",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7063",
"name" : "Falling Leaf Whirlwind",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7064",
"name" : "Winter's Bite Technique",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "7065",
"name" : "The 17 Cuts",
"type" : "Combat",
"mpCost" : 10,
},
{
"id" : "8000",
"name" : "Summon Snowcones",
"type" : "Mystical Bookshelf",
"mpCost" : 5,
},
{
"id" : "8100",
"name" : "Summon Candy Heart",
"type" : "Mystical Bookshelf",
},
{
"id" : "8101",
"name" : "Summon Party Favor",
"type" : "Mystical Bookshelf",
},
{
"id" : "8200",
"name" : "Summon Hilarious Objects",
"type" : "Mystical Bookshelf",
"mpCost" : 5,
},
{
"id" : "8201",
"name" : "Summon \"Tasteful\" Gifts",
"type" : "Mystical Bookshelf",
"mpCost" : 5,
},
]
|
python
|
from netmiko import ConnectHandler, file_transfer
from getpass import getpass
ios_devices = {
"host": "cisco3.lasthop.io",
"username": "pyclass",
"password": "88newclass",
"device_type": "cisco_ios",
}
source_file = "testTofu.txt"
dest_file = "testTofuBack.txt"
direction = "get"
file_system = "bootflash:"
# Create the Netmiko SSH connection
ssh_conn = ConnectHandler(**ios_devices)
transfer_dict = file_transfer(
ssh_conn,
source_file=source_file,
dest_file=dest_file,
file_system=file_system,
direction=direction,
overwrite_file=True,
)
print(transfer_dict)
|
python
|
#!/usr/bin/env python3
# coding: utf-8
from threading import Thread
from queue import Queue
class TaskQueue(Queue):
def __init__(self, num_workers=1):
super().__init__()
self.num_workers = num_workers
self.start_workers()
def add_task(self, task, *args, **kwargs):
args = args or ()
kwargs = kwargs or {}
self.put((task, args, kwargs))
def start_workers(self):
for i in range(self.num_workers):
t = Thread(target=self.worker)
t.daemon = True
t.start()
def worker(self):
while True:
item, args, kwargs = self.get()
item(*args, **kwargs)
self.task_done()
|
python
|
#!/usr/bin/env python
import logging
import os
import shutil
import sys
import tempfile
from io import BytesIO
from itertools import groupby
from subprocess import Popen,PIPE, check_output
import requests
from KafNafParserPy import *
from lxml import etree
from lxml.etree import XMLSyntaxError
from .alpino_dependency import Calpino_dependency
from .convert_penn_to_kaf import convert_penn_to_knaf_with_numtokens
__version__ = "0.3"
this_name = 'Morphosyntactic parser based on Alpino'
last_modified = '2017-03-18'
###############################################
def set_up_alpino():
##Uncomment next line and point it to your local path to Alpino if you dont want to set the environment variable ALPINO_HOME
#os.environ['ALPINO_HOME'] = '/home/izquierdo/tools/Alpino'
if 'ALPINO_HOME' in os.environ:
os.environ['SP_CSETLEN'] = '212'
os.environ['SP_CTYPE'] = 'utf8'
return 'local', os.environ['ALPINO_HOME']
elif 'ALPINO_SERVER' in os.environ:
return 'server', os.environ['ALPINO_SERVER']
else:
raise Exception('ALPINO_HOME or ALPINO_SERVER variables not set.'
'Set ALPINO_HOME to point to your local path to Alpino. For instance:\n'
'export ALPINO_HOME=/home/your_user/your_tools/Alpino')
def tokenize_local(paras, alpino_home):
cmd = os.path.join(alpino_home, 'Tokenization', 'tok')
sentnr = 1
for parnr, para in enumerate(paras, start=1):
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE)
out, _err = p.communicate(para.encode("utf-8"))
for s in out.decode('utf-8').split("\n"):
if s.strip():
yield parnr, sentnr, s.strip()
sentnr += 1
def add_tokenized_to_naf(naf, sentences):
"""Add the tokenized sentences to naf, returning and [(token, id), ..] list"""
offset = 0
old_parnr = None
for parnr, sentnr, sentence in sentences:
if old_parnr is not None and parnr != old_parnr:
offset += 1 # character for line break
sent = []
for word in sentence.split():
length = len(word)
token = naf.create_wf(word, sentnr, offset=offset, length=length)
offset += len(word) + 1
token.set_para(str(parnr))
sent.append((word, token.get_id()))
yield sent
def tokenize(naf):
"""Tokenize the text in the NAF object and return [(token, id), ..] pairs
Assumes that single line breaks are not relevant, and double lines breaks mark paragraphs
"""
paras = [para.replace("\n", " ") for para in re.split(r"\n\s*\n", naf.get_raw())]
alpino_type, alpino_location = set_up_alpino()
if alpino_type == "local":
sentences = list(tokenize_local(paras, alpino_location))
else:
raise NotImplementedError("Tokenization via alpino-server is not implemented yet")
return list(add_tokenized_to_naf(naf, sentences))
def load_sentences(in_obj):
previous_sent = None
previous_para = None
current_sent = []
sentences = []
for token_obj in in_obj.get_tokens():
token = token_obj.get_text()
sent = token_obj.get_sent()
para = token_obj.get_para()
token_id = token_obj.get_id()
if ((previous_sent is not None and sent != previous_sent) or
(previous_para is not None and para != previous_para)):
sentences.append(current_sent)
current_sent = [(token,token_id)]
else:
current_sent.append((token,token_id))
previous_sent = sent
previous_para = para
if len(current_sent) !=0:
sentences.append(current_sent)
return sentences
def get_term_type(pos):
if pos in ['det','pron','prep','vg','conj' ]:
return 'close'
else:
return 'open'
def node_to_penn(node,map_token_begin_node):
children = node.getchildren()
if len(children) == 0:
word = node.get('word',None)
if word is not None:
#The attribute begin gives you the number of the token
word = word.replace('(','-LRB')
word = word.replace(')','-RRB-')
num_token = node.get('begin')
map_token_begin_node[num_token] = node
word = num_token+'#'+word
if node.get('rel') == 'hd':
head = '=H'
else:
head = ''
return '('+node.get('pos')+head+' '+word+')'
else:
return ''
else:
str = '('+node.get('cat')+' '
for n in children:
str+=node_to_penn(n,map_token_begin_node)
str+=')'
return str
def xml_to_penn(tree):
'''
Converts the xml from Alpino into penntreebank format
'''
##This is a mapping for the token begin (0,1,2,...) to the <node element
map_token_begin_node = {}
str = node_to_penn(tree.find('node'),map_token_begin_node)
return str, map_token_begin_node
def process_alpino_xml(xml_tree, dependencies, sentence,count_terms,knaf_obj,cnt_t,cnt_nt,cnt_edge):
penn_tree_str, map_token_begin_node = xml_to_penn(xml_tree)
##########################################
#Create the term layer
##########################################
term_ids = []
lemma_for_termid = {}
logging.info('Creating the term layer...')
for num_token, (token,token_id) in enumerate(sentence):
new_term_id = 't_'+str(count_terms)
count_terms+=1
term_ids.append(new_term_id)
alpino_node = map_token_begin_node[str(num_token)]
term_obj = Cterm(type=knaf_obj.get_type())
term_obj.set_id(new_term_id)
new_span = Cspan()
new_span.create_from_ids([token_id])
term_obj.set_span(new_span)
term_obj.set_lemma(alpino_node.get('lemma','unknown'))
lemma_for_termid[new_term_id] = alpino_node.get('lemma','unknown')
alppos = alpino_node.get('pos','unknown')
term_obj.set_pos(alppos)
term_obj.set_morphofeat(alpino_node.get('postag','unknown'))
termtype = get_term_type(alppos)
term_obj.set_type(termtype)
knaf_obj.add_term(term_obj)
##########################################
##########################################
##Constituency layer
logging.info('Creating the constituency layer...')
tree_obj,cnt_t,cnt_nt,cnt_edge = convert_penn_to_knaf_with_numtokens(penn_tree_str,term_ids,lemma_for_termid,cnt_t,cnt_nt,cnt_edge)
knaf_obj.add_constituency_tree(tree_obj)
##########################################
##########################################
# Dependency part
##########################################
for my_dep in dependencies:
if my_dep.is_ok():
deps = my_dep.generate_dependencies(term_ids)
for d in deps:
knaf_obj.add_dependency(d)
##########################################
# we return the counters for terms and consituent elements to keep generating following identifiers for next sentnces
return count_terms,cnt_t,cnt_nt,cnt_edge
def call_alpino(sentences, max_min_per_sent):
"""Call alpino and yield (sentence, xml_tree, dependencies) tuples"""
alpino_type, alpino_location = set_up_alpino()
if alpino_type == 'local':
return call_alpino_local(sentences, max_min_per_sent, alpino_location)
else:
return call_alpino_server(sentences, alpino_location)
def call_alpino_server(sentences, server):
## Under certain condition, there is know bug of Alpino, it sets the encoding in the XML
## to iso-8859-1, but the real encoding is UTF-8. So we need to force to use this encoding
parser = etree.XMLParser(encoding='UTF-8')
url = "{server}/parse".format(**locals())
text = "\n".join(sentences_from_naf(sentences))
r = requests.post(url, json=dict(output="treebank_triples", text=text))
r.raise_for_status()
for sid, results in r.json().items():
sentence = sentences[int(sid)-1]
tree = etree.fromstring(results['xml'].encode("utf-8"), parser)
dependencies = [Calpino_dependency(dep) for dep in results['triples']]
yield sentence, tree, dependencies
def sentences_from_naf(sentences):
for i, sentence in enumerate(sentences, 1):
sent = " ".join(token.replace('[', '\[').replace(']', '\]') for token, _token_id in sentence)
yield u"{i}|{sent}".format(**locals())
def call_alpino_local(sentences, max_min_per_sent, alpino_home):
## Under certain condition, there is know bug of Alpino, it sets the encoding in the XML
## to iso-8859-1, but the real encoding is UTF-8. So we need to force to use this encoding
parser = etree.XMLParser(encoding='UTF-8')
# Create temporary folder to store the XML of Alpino
out_folder_alp = tempfile.mkdtemp()
####################
# Call to Alpinoo and generate the XML files
cmd = os.path.join(alpino_home, 'bin', 'Alpino')
if max_min_per_sent is not None:
# max_min_per_sent is minutes
cmd += ' user_max=%d' % int(max_min_per_sent * 60 * 1000) # converted to milliseconds
cmd += ' end_hook=xml -flag treebank ' + out_folder_alp + ' -parse'
logging.info('Calling Alpino with {} sentences'.format(len(sentences)))
logging.debug("CMD: {}".format(cmd))
t1 = time.time()
alpino_pro = Popen(cmd, stdin=PIPE, shell=True)
for sentence in sentences_from_naf(sentences):
alpino_pro.stdin.write(sentence.encode("utf-8"))
alpino_pro.stdin.write(b'\n')
alpino_pro.stdin.close()
if alpino_pro.wait() != 0:
raise Exception("Call to alpino failed (see logs): %s" % cmd)
logging.debug("Alpino done in %1.3f seconds" % (time.time() - t1))
# Parse results, get dependencies, and yield sentence results
xml_files = [os.path.join(out_folder_alp, str(i+1)+'.xml') for i in range(len(sentences))]
missing_files = [xml_file for xml_file in xml_files if not os.path.exists(xml_file)]
if missing_files:
logging.warning('Not found the file {}'.format(missing_files))
t1 = time.time()
logging.info('Calling Alpino for dependencies')
alpino_bin = os.path.join(alpino_home, 'bin', 'Alpino')
cmd = [alpino_bin, '-treebank_triples'] + xml_files
logging.debug("CMD: {}".format(cmd))
output = check_output(cmd)
logging.debug("Alpino -treebank_triples done in %1.3f seconds" % (time.time() - t1))
def get_filename(output_line):
return output_line.decode("utf-8").split("|")[-1]
grouped_lines = {xml_file: list(lines) for xml_file, lines in groupby(output.splitlines(), get_filename)}
for i, xml_file in enumerate(xml_files):
lines = grouped_lines[xml_file]
sent = sentences[i]
dependencies = [Calpino_dependency(line.strip().decode('utf-8')) for line in lines]
tree = etree.parse(xml_file, parser)
# Yield sentence, parsed XML tree, and dependencies
yield sent, tree, dependencies
# Cleanup
shutil.rmtree(out_folder_alp)
def get_naf(input_file):
# We need to buffer the input since otherwise it will be lost if the parser fails
input = input_file.read()
try:
naf = KafNafParser(BytesIO(input))
except XMLSyntaxError:
input = input.decode("utf-8")
if "<NAF" in input and "</NAF>" in input:
# I'm guessing this should be a NAF file but something is wrong - let's raise it
logging.exception("Error parsing NAF file")
raise
naf = KafNafParser(type="NAF")
naf.set_version("3.0")
naf.set_language("nl")
naf.lang = "nl"
naf.raw = input
naf.set_raw(naf.raw)
return naf
def parse(input_file, max_min_per_sent=None):
if isinstance(input_file, KafNafParser):
in_obj = input_file
else:
in_obj = get_naf(input_file)
lang = in_obj.get_language()
if lang != 'nl':
logging.warning('ERROR! Language is {} and must be nl (Dutch)'.format(lang))
sys.exit(-1)
## Sentences is a list of lists containing pairs token, tokenid
# [[(This,id1),(is,id2)...],[('The',id10)...
if in_obj.text_layer is None:
sentences = tokenize(in_obj)
else:
sentences = load_sentences(in_obj)
####################
####################
# Process the XML files
count_terms = 0
cnt_t = cnt_nt = cnt_edge = 0
for sentence, tree, dependencies in call_alpino(sentences, max_min_per_sent):
count_terms,cnt_t,cnt_nt,cnt_edge = process_alpino_xml(tree, dependencies, sentence,count_terms,in_obj,cnt_t,cnt_nt,cnt_edge)
####################
##Add the linguistic processors
my_lp = Clp()
my_lp.set_name(this_name)
my_lp.set_version(__version__+'_'+last_modified)
my_lp.set_timestamp()
in_obj.add_linguistic_processor('terms',my_lp)
my_lp_const = Clp()
my_lp_const.set_name(this_name)
my_lp_const.set_version(__version__+'_'+last_modified)
my_lp_const.set_timestamp()
in_obj.add_linguistic_processor('constituents',my_lp_const)
my_lp_deps = Clp()
my_lp_deps.set_name(this_name)
my_lp_deps.set_version(__version__+'_'+last_modified)
my_lp_deps.set_timestamp()
in_obj.add_linguistic_processor('deps',my_lp_deps)
####################
return in_obj
|
python
|
import os
import pytest
from packaging import version
from unittest import TestCase
from unittest.mock import patch
from osbot_utils.utils.Dev import pprint
from osbot_utils.utils.Files import temp_folder, folder_files, folder_delete_all, folder_create, file_create_bytes, \
file_contents_as_bytes, file_contents, file_name, temp_file, file_sha256, path_combine, file_exists, folder_exists
from osbot_utils.utils.Http import POST, POST_json
from osbot_utils.utils.Json import json_to_str, str_to_json
from osbot_utils.utils.Misc import base64_to_str, base64_to_bytes, str_to_bytes, random_string, random_text, \
str_to_base64, bytes_to_str, bytes_to_base64, random_uuid
from osbot_utils.utils.Json import str_to_json, json_to_str, json_parse
from cdr_plugin_folder_to_folder.common_settings.Config import Config, DEFAULT_ENDPOINTS, DEFAULT_ENDPOINT_PORT
from cdr_plugin_folder_to_folder.metadata.Metadata import Metadata
from cdr_plugin_folder_to_folder.metadata.Metadata_Service import Metadata_Service
from cdr_plugin_folder_to_folder.metadata.Metadata_Utils import Metadata_Utils
from cdr_plugin_folder_to_folder.pre_processing.Pre_Processor import Pre_Processor
from cdr_plugin_folder_to_folder.processing.Endpoint_Service import Endpoint_Service
from cdr_plugin_folder_to_folder.processing.Events_Log import Events_Log
from cdr_plugin_folder_to_folder.processing.Events_Log_Elastic import Events_Log_Elastic
from cdr_plugin_folder_to_folder.processing.File_Processing import File_Processing
from cdr_plugin_folder_to_folder.storage.Storage import Storage
from cdr_plugin_folder_to_folder.utils.file_utils import FileService
from cdr_plugin_folder_to_folder.utils.testing.Temp_Config import Temp_Config
from cdr_plugin_folder_to_folder.utils.testing.Test_Data import Test_Data
from cdr_plugin_folder_to_folder.processing.Report_Elastic import Report_Elastic
from cdr_plugin_folder_to_folder.processing.Analysis_Json import Analysis_Json
from cdr_plugin_folder_to_folder.processing.Analysis_Elastic import Analysis_Elastic
from cdr_plugin_folder_to_folder.pre_processing.Status import FileStatus
from cdr_plugin_folder_to_folder.configure.Configure_Env import SDKEngineVersionKey, SDKAPIVersionKey, LowestEngineVersion, LowestAPIVersion
import traceback
import base64
class test_File_Processing(Temp_Config):
config = None
temp_root = None
# @classmethod
# def setUpClass(cls) -> None:
# super().setUpClass()
#
# #cls.temp_root = folder_create('/tmp/temp_root') # temp_folder()
# #cls.config.set_root_folder(root_folder=cls.temp_root)
def setUp(self) -> None:
self.sdk_server = self.config.test_sdk
self.sdk_port = DEFAULT_ENDPOINT_PORT
#self.temp_folder = temp_folder()
self.events_elastic = Events_Log_Elastic()
self.endpoint_service = Endpoint_Service()
self.report_elastic = Report_Elastic()
self.analysis_elastic = Analysis_Elastic()
self.storage = Storage()
self.meta_service = Metadata_Service()
self.test_file_path = self.add_test_files(count=1, execute_stage_1=True).pop() # Test_Data().create_test_pdf(text=random_text(prefix="some random text: "))
self.test_file_name = file_name(self.test_file_path)
self.test_file_hash = self.storage.hd2_data_file_hashes().pop()
self.test_file_metadata = Metadata(file_hash=self.test_file_hash).load()
self.events_log = self.test_file_metadata.events_log()
self.file_processing = File_Processing(events_log=self.events_log, events_elastic = self.events_elastic, report_elastic=self.report_elastic, analysis_elastic= self.analysis_elastic, meta_service=self.meta_service )
assert self.test_file_metadata.exists()
#assert self.test_file_metadata.get_original_file_paths() == [self.test_file_name]
def tearDown(self) -> None:
self.test_file_metadata.delete()
def test_do_rebuild_zip(self):
self.endpoint_service.endpoints = str_to_json(DEFAULT_ENDPOINTS)["Endpoints"]
endpoint = self.endpoint_service.get_endpoint_url()
metadata = self.test_file_metadata
folder_path = metadata.metadata_folder_path()
source_path = metadata.source_file_path()
kwargs = {"endpoint": endpoint,
"hash": self.test_file_hash,
"source_path": source_path,
"dir": folder_path}
assert self.file_processing.do_rebuild_zip(**kwargs)
metadata.load()
# assert metadata.data.get('xml_report_status' ) == 'Obtained'
# assert metadata.data.get('file_name' ) == self.test_file_name
assert metadata.data.get('rebuild_server' ) == endpoint
assert version.parse(metadata.data.get('skd_engine_version')) >= version.parse(LowestEngineVersion)
assert version.parse(metadata.data.get('sdk_api_version')) >= version.parse(LowestAPIVersion)
assert metadata.data.get('error' ) is None
assert metadata.data.get('original_hash' ) == self.test_file_hash
assert metadata.data.get('original_file_size' ) == 755
assert metadata.data.get('original_file_extension') == '.pdf'
assert metadata.data.get('rebuild_status' ) == 'Initial'
assert metadata.data.get('rebuild_file_extension' ) == 'pdf'
assert metadata.data.get('rebuild_file_size' ) == 1267
def test_do_rebuild(self):
self.endpoint_service.endpoints = str_to_json(DEFAULT_ENDPOINTS)["Endpoints"]
endpoint = self.endpoint_service.get_endpoint_url()
metadata = self.test_file_metadata
folder_path = metadata.metadata_folder_path()
source_path = metadata.source_file_path()
kwargs = {"endpoint" : endpoint ,
"hash" : self.test_file_hash ,
"source_path" : source_path ,
"dir" : folder_path }
assert self.file_processing.do_rebuild(**kwargs)
pprint(metadata.load())
# assert metadata.data.get('xml_report_status' ) == 'Obtained'
# assert metadata.data.get('file_name' ) == self.test_file_name
assert metadata.data.get('rebuild_server' ) == endpoint
assert version.parse(metadata.data.get('skd_engine_version')) >= version.parse(LowestEngineVersion)
assert version.parse(metadata.data.get('sdk_api_version')) >= version.parse(LowestAPIVersion)
assert metadata.data.get('error' ) is None
assert metadata.data.get('original_hash' ) == self.test_file_hash
assert metadata.data.get('original_file_size' ) == 755
assert metadata.data.get('original_file_extension') == '.pdf'
assert metadata.data.get('rebuild_status' ) == 'Initial'
# 'rebuild_file_extension' is obtained from the xml report.
# When accessing the SKD behind a loadbalancer, we do not always get the report
#assert metadata.data.get('rebuild_file_extension' ) == 'pdf'
assert metadata.data.get('rebuild_file_size' ) == 1267
def test_do_rebuild_with_exception(self):
self.endpoint_service.endpoints = str_to_json(DEFAULT_ENDPOINTS)["Endpoints"]
endpoint = self.endpoint_service.get_endpoint_url()
metadata = self.test_file_metadata
folder_path = metadata.metadata_folder_path()
source_path = metadata.source_file_path()
kwargs = {"endpoint" : endpoint ,
"hash" : self.test_file_hash ,
"source_path" : source_path ,
"dir" : folder_path }
with patch.object(FileService, 'base64decode', side_effect=Exception()):
assert self.file_processing.do_rebuild(**kwargs) is False
def test_processDirectory(self):
self.endpoint_service.endpoints = str_to_json(DEFAULT_ENDPOINTS)["Endpoints"]
endpoint = self.endpoint_service.get_endpoint_url()
metadata = self.test_file_metadata
folder_path = metadata.metadata_folder_path()
source_path = metadata.source_file_path()
kwargs = {"endpoint" : endpoint ,
"dir" : folder_path }
assert self.file_processing.processDirectory(**kwargs)
# def test_server_status(self,): # refactor into separate test file
# server = "84.16.229.232" # aws # 5.1 lowest response time
# #server = "192.168.0.249" # local # 3.9 lowest response time
# server = "34.254.193.225" # 0.5 lowest response time
# server = "CompliantK8sICAPLB-d6bf82358f9adc63.elb.eu-west-1.amazonaws.com"
# server = "34.243.13.180"
# url = f"http://{server}:8080/api/rebuild/base64"
# headers = { 'accept': 'application/json',
# 'Content-Type': 'application/json'}
# text = random_text("random text - ")
# test_pdf = Test_Data().create_test_pdf(text=text)
# original_bytes = file_contents_as_bytes(test_pdf)
#
# original_base64 = bytes_to_base64(original_bytes)
# post_data = {"Base64": original_base64}
# try:
# result = POST(url, data=post_data, headers=headers)
# rebuild_base64 = base64_to_bytes(result)
# pprint(rebuild_base64)
# except Exception as error:
# pprint(error)
# #`
def test_processBadFile(self):
bad_file = temp_file(contents=random_text())
metadata = self.meta_service.create_metadata(bad_file)
endpoint = f'http://{self.sdk_server}:{self.sdk_port}'
dir = metadata.metadata_folder_path()
try:
result = self.file_processing.processDirectory(endpoint=endpoint, dir=dir)
except Exception as e:
traceback.print_exc()
self.fail("Should not have thrown")
assert result == True
metadata.load()
assert metadata.data.get('rebuild_status') == FileStatus.NOT_SUPPORTED
def test_processBadFileWithoutSaveOriginal(self):
bad_file = temp_file(contents=random_text())
self.config.save_unsupported_file_types = False
metadata = self.meta_service.create_metadata(bad_file)
endpoint = f'http://{self.sdk_server}:{self.sdk_port}'
dir = metadata.metadata_folder_path()
try:
result = self.file_processing.processDirectory(endpoint=endpoint, dir=dir)
except Exception as e:
traceback.print_exc()
self.fail("Should not have thrown")
assert result == True
metadata.load()
assert metadata.data.get('rebuild_status') == FileStatus.NOT_SUPPORTED
def test_pdf_rebuild(self): # refactor into separate test file
server = self.config.test_sdk
url = f"http://{self.sdk_server}:{self.sdk_port}/api/rebuild/base64"
headers = { 'accept': 'application/json',
'Content-Type': 'application/json'}
text = random_text("random text - ")
test_pdf = Test_Data().create_test_pdf(text=text)
original_bytes = file_contents_as_bytes(test_pdf)
original_base64 = bytes_to_base64(original_bytes)
post_data = {"Base64": original_base64}
result = POST(url, data=post_data, headers=headers)
rebuild_base64 = base64_to_bytes(result)
assert str_to_bytes(text) in original_bytes
assert b'Glasswall' not in original_bytes
assert str_to_bytes(text) in rebuild_base64
assert b'Glasswall' in rebuild_base64
def test_processDirectory__bad_zip_file(self):
bad_file = temp_file(contents=random_text())
metadata = self.meta_service.create_metadata(bad_file)
endpoint = f'http://{self.sdk_server}:{self.sdk_port}'
dir = metadata.metadata_folder_path()
result = self.file_processing.processDirectory(endpoint=endpoint, dir=dir, use_rebuild_zip=True)
assert result == True
metadata.load()
assert metadata.data.get('rebuild_status') == FileStatus.NOT_SUPPORTED
assert metadata.data.get('error') == "400 Bad Request. See details in 'error.json'"
def test_processZipFileWithDualEP(self):
uuid = random_text()
path = '/tmp/'+uuid
zip_file = Test_Data().create_test_zip(path=path)
metadata = self.meta_service.create_metadata(zip_file)
endpoint = f'http://{self.sdk_server}:{self.sdk_port}'
dir = metadata.metadata_folder_path()
try:
result = self.file_processing.processDirectory(endpoint=endpoint, dir=dir, use_rebuild_zip=True)
except Exception as e:
traceback.print_exc()
self.fail("Should not have thrown")
#assert result == True
metadata.load()
assert metadata.data.get('rebuild_status') == FileStatus.NOT_SUPPORTED
def test_zbase64request_with_wrong_endpoint(self):
with pytest.raises(ValueError):
self.file_processing.base64request("no-endpoint","no-route","ABC")
def test_xmlreport_request_with_wrong_endpoint(self):
with pytest.raises(ValueError):
self.file_processing.xmlreport_request("no-endpoint","ABC")
def test_zconvert_xml_report_to_json_with_no_xmlreport(self):
with pytest.raises(ValueError):
self.file_processing.convert_xml_report_to_json("/", None)
def test_zconvert_xml_report_to_json_with_bad_xmlreport(self):
xmlreport = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> \
<note> \
<to>Tove</to> \
<from>Jani</from> \
<heading>Reminder</heading> \
<body>Don't forget me this weekend!</body> \
</note> \
"
assert self.file_processing.convert_xml_report_to_json("/", xmlreport) is False
def test_do_rebuild_with_bad_source_path(self):
metadata_file_path = self.test_file_metadata.metadata_file_path()
assert self.file_processing.do_rebuild('none','none','/',os.path.dirname(metadata_file_path)) is False
def test_do_rebuild_zip_with_bad_source_path(self):
metadata_file_path = self.test_file_metadata.metadata_file_path()
assert self.file_processing.do_rebuild_zip('none','none','/',os.path.dirname(metadata_file_path)) is False
@patch('cdr_plugin_folder_to_folder.processing.File_Processing.File_Processing.rebuild')
def test_do_rebuild_with_empty_response(self, mock_rebuild):
mock_rebuild.return_value.ok = True
mock_rebuild.return_value.text = ''
dir = os.path.dirname(self.test_file_metadata.metadata_file_path())
source = path_combine(dir,"source")
endpoint = 'http://127.0.0.1:8080'
assert self.file_processing.do_rebuild(endpoint,'ABC',source,dir) is False
def test_get_metadata_from_headers(self):
headers = {SDKEngineVersionKey: '1.0.0', SDKAPIVersionKey: '1.0.0'}
assert SDKEngineVersionKey in headers
assert SDKAPIVersionKey in headers
dir = os.path.dirname(self.test_file_metadata.metadata_file_path())
self.file_processing.get_metadata_from_headers(dir, headers)
server_version = self.file_processing.meta_service.metadata.get_server_version()
assert server_version == 'Engine:1.0.0 API:1.0.0'
headers = {}
assert not SDKEngineVersionKey in headers
assert not SDKAPIVersionKey in headers
self.file_processing.get_metadata_from_headers(dir, headers)
server_version = self.file_processing.meta_service.metadata.get_server_version()
assert server_version == 'Engine: API:'
|
python
|
# Generated by Django 3.1.4 on 2021-11-13 12:20
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import uuid
class Migration(migrations.Migration):
dependencies = [
('library_app', '0007_auto_20211113_1319'),
]
operations = [
migrations.AlterField(
model_name='bad_borrower',
name='ending_date',
field=models.DateField(default=datetime.datetime(2023, 10, 21, 12, 20, 20, 235484, tzinfo=utc), verbose_name='Date de fin'),
),
migrations.AlterField(
model_name='loan',
name='ending_date',
field=models.DateField(default=datetime.datetime(2021, 12, 13, 12, 20, 20, 235484, tzinfo=utc), verbose_name='Date de fin'),
),
migrations.AlterField(
model_name='ouvrageinstance',
name='id',
field=models.UUIDField(default=uuid.uuid4, help_text='Unique ID pour cette version dans toute la biliothèque', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='subscription',
name='ending_date',
field=models.DateField(default=datetime.datetime(2022, 11, 12, 12, 20, 20, 235484, tzinfo=utc), verbose_name='Date de fin'),
),
]
|
python
|
# Original script acquired from https://github.com/adafruit/Adafruit_Python_MCP3008
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import time
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
def readadc(channel):
if (channel==0): return mcp.read_adc(0)
elif (channel==1):
degrees = ((float(mcp.read_adc(1)))/1024)*100
return degrees
elif (channel==2):
volts = (mcp.read_adc(2)*3.3)/float(1023)
return volts
else :
print("Eish!")
|
python
|
"""
This component provides basic support for the Philips Hue system.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hue/
"""
import asyncio
import json
import ipaddress
import logging
import os
import async_timeout
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.discovery import SERVICE_HUE
from homeassistant.const import CONF_FILENAME, CONF_HOST
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import discovery, aiohttp_client
from homeassistant import config_entries
from homeassistant.util.json import save_json
REQUIREMENTS = ['aiohue==1.3.0']
_LOGGER = logging.getLogger(__name__)
DOMAIN = "hue"
SERVICE_HUE_SCENE = "hue_activate_scene"
API_NUPNP = 'https://www.meethue.com/api/nupnp'
CONF_BRIDGES = "bridges"
CONF_ALLOW_UNREACHABLE = 'allow_unreachable'
DEFAULT_ALLOW_UNREACHABLE = False
PHUE_CONFIG_FILE = 'phue.conf'
CONF_ALLOW_HUE_GROUPS = "allow_hue_groups"
DEFAULT_ALLOW_HUE_GROUPS = True
BRIDGE_CONFIG_SCHEMA = vol.Schema({
# Validate as IP address and then convert back to a string.
vol.Required(CONF_HOST): vol.All(ipaddress.ip_address, cv.string),
vol.Optional(CONF_FILENAME, default=PHUE_CONFIG_FILE): cv.string,
vol.Optional(CONF_ALLOW_UNREACHABLE,
default=DEFAULT_ALLOW_UNREACHABLE): cv.boolean,
vol.Optional(CONF_ALLOW_HUE_GROUPS,
default=DEFAULT_ALLOW_HUE_GROUPS): cv.boolean,
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_BRIDGES):
vol.All(cv.ensure_list, [BRIDGE_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
ATTR_GROUP_NAME = "group_name"
ATTR_SCENE_NAME = "scene_name"
SCENE_SCHEMA = vol.Schema({
vol.Required(ATTR_GROUP_NAME): cv.string,
vol.Required(ATTR_SCENE_NAME): cv.string,
})
CONFIG_INSTRUCTIONS = """
Press the button on the bridge to register Philips Hue with Home Assistant.

"""
async def async_setup(hass, config):
"""Set up the Hue platform."""
conf = config.get(DOMAIN)
if conf is None:
conf = {}
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
async def async_bridge_discovered(service, discovery_info):
"""Dispatcher for Hue discovery events."""
# Ignore emulated hue
if "HASS Bridge" in discovery_info.get('name', ''):
return
await async_setup_bridge(
hass, discovery_info['host'],
'phue-{}.conf'.format(discovery_info['serial']))
discovery.async_listen(hass, SERVICE_HUE, async_bridge_discovered)
# User has configured bridges
if CONF_BRIDGES in conf:
bridges = conf[CONF_BRIDGES]
# Component is part of config but no bridges specified, discover.
elif DOMAIN in config:
# discover from nupnp
websession = aiohttp_client.async_get_clientsession(hass)
async with websession.get(API_NUPNP) as req:
hosts = await req.json()
# Run through config schema to populate defaults
bridges = [BRIDGE_CONFIG_SCHEMA({
CONF_HOST: entry['internalipaddress'],
CONF_FILENAME: '.hue_{}.conf'.format(entry['id']),
}) for entry in hosts]
else:
# Component not specified in config, we're loaded via discovery
bridges = []
if not bridges:
return True
await asyncio.wait([
async_setup_bridge(
hass, bridge[CONF_HOST], bridge[CONF_FILENAME],
bridge[CONF_ALLOW_UNREACHABLE], bridge[CONF_ALLOW_HUE_GROUPS]
) for bridge in bridges
])
return True
async def async_setup_bridge(
hass, host, filename=None,
allow_unreachable=DEFAULT_ALLOW_UNREACHABLE,
allow_hue_groups=DEFAULT_ALLOW_HUE_GROUPS,
username=None):
"""Set up a given Hue bridge."""
assert filename or username, 'Need to pass at least a username or filename'
# Only register a device once
if host in hass.data[DOMAIN]:
return
if username is None:
username = await hass.async_add_job(
_find_username_from_config, hass, filename)
bridge = HueBridge(host, hass, filename, username, allow_unreachable,
allow_hue_groups)
await bridge.async_setup()
def _find_username_from_config(hass, filename):
"""Load username from config."""
path = hass.config.path(filename)
if not os.path.isfile(path):
return None
with open(path) as inp:
return list(json.load(inp).values())[0]['username']
class HueBridge(object):
"""Manages a single Hue bridge."""
def __init__(self, host, hass, filename, username,
allow_unreachable=False, allow_groups=True):
"""Initialize the system."""
self.host = host
self.hass = hass
self.filename = filename
self.username = username
self.allow_unreachable = allow_unreachable
self.allow_groups = allow_groups
self.available = True
self.config_request_id = None
self.api = None
async def async_setup(self):
"""Set up a phue bridge based on host parameter."""
import aiohue
api = aiohue.Bridge(
self.host,
username=self.username,
websession=aiohttp_client.async_get_clientsession(self.hass)
)
try:
with async_timeout.timeout(5):
# Initialize bridge and validate our username
if not self.username:
await api.create_user('home-assistant')
await api.initialize()
except (aiohue.LinkButtonNotPressed, aiohue.Unauthorized):
_LOGGER.warning("Connected to Hue at %s but not registered.",
self.host)
self.async_request_configuration()
return
except (asyncio.TimeoutError, aiohue.RequestError):
_LOGGER.error("Error connecting to the Hue bridge at %s",
self.host)
return
except aiohue.AiohueException:
_LOGGER.exception('Unknown Hue linking error occurred')
self.async_request_configuration()
return
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error connecting with Hue bridge at %s",
self.host)
return
self.hass.data[DOMAIN][self.host] = self
# If we came here and configuring this host, mark as done
if self.config_request_id:
request_id = self.config_request_id
self.config_request_id = None
self.hass.components.configurator.async_request_done(request_id)
self.username = api.username
# Save config file
await self.hass.async_add_job(
save_json, self.hass.config.path(self.filename),
{self.host: {'username': api.username}})
self.api = api
self.hass.async_add_job(discovery.async_load_platform(
self.hass, 'light', DOMAIN,
{'host': self.host}))
self.hass.services.async_register(
DOMAIN, SERVICE_HUE_SCENE, self.hue_activate_scene,
schema=SCENE_SCHEMA)
@callback
def async_request_configuration(self):
"""Request configuration steps from the user."""
configurator = self.hass.components.configurator
# We got an error if this method is called while we are configuring
if self.config_request_id:
configurator.async_notify_errors(
self.config_request_id,
"Failed to register, please try again.")
return
async def config_callback(data):
"""Callback for configurator data."""
await self.async_setup()
self.config_request_id = configurator.async_request_config(
"Philips Hue", config_callback,
description=CONFIG_INSTRUCTIONS,
entity_picture="/static/images/logo_philips_hue.png",
submit_caption="I have pressed the button"
)
async def hue_activate_scene(self, call, updated=False):
"""Service to call directly into bridge to set scenes."""
group_name = call.data[ATTR_GROUP_NAME]
scene_name = call.data[ATTR_SCENE_NAME]
group = next(
(group for group in self.api.groups.values()
if group.name == group_name), None)
scene_id = next(
(scene.id for scene in self.api.scenes.values()
if scene.name == scene_name), None)
# If we can't find it, fetch latest info.
if not updated and (group is None or scene_id is None):
await self.api.groups.update()
await self.api.scenes.update()
await self.hue_activate_scene(call, updated=True)
return
if group is None:
_LOGGER.warning('Unable to find group %s', group_name)
return
if scene_id is None:
_LOGGER.warning('Unable to find scene %s', scene_name)
return
await group.set_action(scene=scene_id)
@config_entries.HANDLERS.register(DOMAIN)
class HueFlowHandler(config_entries.ConfigFlowHandler):
"""Handle a Hue config flow."""
VERSION = 1
def __init__(self):
"""Initialize the Hue flow."""
self.host = None
@property
def _websession(self):
"""Return a websession.
Cannot assign in init because hass variable is not set yet.
"""
return aiohttp_client.async_get_clientsession(self.hass)
async def async_step_init(self, user_input=None):
"""Handle a flow start."""
from aiohue.discovery import discover_nupnp
if user_input is not None:
self.host = user_input['host']
return await self.async_step_link()
try:
with async_timeout.timeout(5):
bridges = await discover_nupnp(websession=self._websession)
except asyncio.TimeoutError:
return self.async_abort(
reason='discover_timeout'
)
if not bridges:
return self.async_abort(
reason='no_bridges'
)
# Find already configured hosts
configured_hosts = set(
entry.data['host'] for entry
in self.hass.config_entries.async_entries(DOMAIN))
hosts = [bridge.host for bridge in bridges
if bridge.host not in configured_hosts]
if not hosts:
return self.async_abort(
reason='all_configured'
)
elif len(hosts) == 1:
self.host = hosts[0]
return await self.async_step_link()
return self.async_show_form(
step_id='init',
data_schema=vol.Schema({
vol.Required('host'): vol.In(hosts)
})
)
async def async_step_link(self, user_input=None):
"""Attempt to link with the Hue bridge."""
import aiohue
errors = {}
if user_input is not None:
bridge = aiohue.Bridge(self.host, websession=self._websession)
try:
with async_timeout.timeout(5):
# Create auth token
await bridge.create_user('home-assistant')
# Fetches name and id
await bridge.initialize()
except (asyncio.TimeoutError, aiohue.RequestError,
aiohue.LinkButtonNotPressed):
errors['base'] = 'register_failed'
except aiohue.AiohueException:
errors['base'] = 'linking'
_LOGGER.exception('Unknown Hue linking error occurred')
else:
return self.async_create_entry(
title=bridge.config.name,
data={
'host': bridge.host,
'bridge_id': bridge.config.bridgeid,
'username': bridge.username,
}
)
return self.async_show_form(
step_id='link',
errors=errors,
)
async def async_setup_entry(hass, entry):
"""Set up a bridge for a config entry."""
await async_setup_bridge(hass, entry.data['host'],
username=entry.data['username'])
return True
|
python
|
import re
import sys
import boa3
from boa3 import neo
from boa3.constants import SIZE_OF_INT32, SIZE_OF_INT160, DEFAULT_UINT32
from boa3.neo import cryptography
from boa3.neo.utils.serializer import Serializer
from boa3.neo.vm.type.Integer import Integer
class NefFile:
"""
The object encapsulates the information of the NEO Executable Format (NEF)
:ivar compiler: the name of the compiler used to generate the file
:ivar version: the version of the compiler
:ivar script_hash: the smart contract hash
:ivar check_sum: the check sum of the file.
:ivar script: the script of the smart contract
"""
# Constants
__COMPILER_HEADER_SIZE = 32
__VERSION_NUMBER_OF_FIELDS = 4 # major.minor.patch-release
__VERSION_HEADER_SIZE = __VERSION_NUMBER_OF_FIELDS * SIZE_OF_INT32
def __init__(self, script_bytes: bytes):
"""
:param script_bytes: the script of the smart contract
"""
self.__magic: int = 0x3346454E # NEO Executable Format 3 (NEF3)
self.compiler: str = "neo3-boa" # Compiler Name
self.version: str = boa3.__version__ # Compiler Version
self.check_sum: int = 0
self.script: bytes = script_bytes # Smart Contract Script
self.script_hash: bytes = neo.to_script_hash(self.script) # Script Hash
self.check_sum = self.compute_check_sum() # Checksum
@property
def size(self) -> int:
"""
Get the size in bytes of the NEF file
:return: size of NEF File.
"""
# it is calculated with constants to be compatible with Neo code
# because Python sizeof differs from C# sizeof
return (
SIZE_OF_INT32 # size of magic
+ NefFile.__COMPILER_HEADER_SIZE # total size of compiler's name
+ NefFile.__VERSION_HEADER_SIZE # total size of compiler's version
+ SIZE_OF_INT160 # size of script hash
+ SIZE_OF_INT32 # size of check sum
+ len(self.script_len_in_bytes) # size used to store script size
+ len(self.script) # size of smart contract script
)
@property
def script_len_in_bytes(self) -> bytes:
"""
Get the size of the script in bytes to compute the size of the header
:return: size of the script in bytes.
"""
return Integer(len(self.script)).to_byte_array()
@property
def __header_size_before_check_sum(self) -> int:
"""
Get the size of the header of the NEF file before the checksum
:return: size of header.
"""
return (
SIZE_OF_INT32 # size of magic
+ NefFile.__COMPILER_HEADER_SIZE # total size of compiler's name
+ NefFile.__VERSION_HEADER_SIZE # total size of compiler's version
+ SIZE_OF_INT160 # size of script hash
)
@property
def __version_info(self) -> list:
"""
Returns the information about the compiler version
:return: a list of the fields of the version
"""
version_info = re.split('[.-]', self.version) # major.minor.patch-release
for index, field in enumerate(version_info):
try:
version_info[index] = int(field)
except ValueError:
# in python versions, the release field is a string
# the nef header needs int values in the version
version_info[index] = DEFAULT_UINT32
while len(version_info) < NefFile.__VERSION_NUMBER_OF_FIELDS:
version_info.append(DEFAULT_UINT32)
return version_info[0:NefFile.__VERSION_NUMBER_OF_FIELDS]
def serialize(self) -> bytes:
"""
Serialize the NefFile object
:return: bytes of the serialized object.
"""
nef_serializer = Serializer()
nef_serializer.write_integer(self.__magic)
nef_serializer.write_string(self.compiler, NefFile.__COMPILER_HEADER_SIZE)
for info in self.__version_info:
nef_serializer.write_integer(info)
nef_serializer.write_bytes(self.script_hash)
nef_serializer.write_integer(self.check_sum)
nef_serializer.write_value(self.script)
return nef_serializer.result
def compute_check_sum(self) -> int:
"""
Computes the checksum of the NEF file
:return: computed check sum.
"""
serialized = self.serialize()
size = self.__header_size_before_check_sum
check_sum = cryptography.sha256(serialized[0:size])
return int.from_bytes(check_sum[0:SIZE_OF_INT32], sys.byteorder, signed=False)
|
python
|
"""
@author: Skye Cui
@file: layers.py
@time: 2021/2/22 13:43
@description:
"""
import tensorflow as tf
class ConvAttention(tf.keras.layers.Layer):
def __init__(self, l, h, w, c, k):
super(ConvAttention, self).__init__()
self.reshape = tf.keras.layers.Reshape((l, w * h * c))
self.layer1 = tf.keras.layers.Dense(units=k, activation='tanh')
self.layer2 = tf.keras.layers.Dense(units=1)
def call(self, inputs, training=None):
outputs = self.layer2(self.layer1(self.reshape(inputs)))
outputs = tf.nn.softmax(outputs, axis=-2)
return outputs
class WeightedSumBlock(tf.keras.layers.Layer):
def __init__(self, l, h, w, c):
super(WeightedSumBlock, self).__init__()
self.l = l
self.add = tf.keras.layers.Add()
self.reshape1 = tf.keras.layers.Reshape((l, w * h * c))
self.reshape2 = tf.keras.layers.Reshape((h, w, c))
def call(self, inputs, training=None):
inputs, alpha = inputs
inputs = self.reshape1(inputs)
info = tf.multiply(alpha, inputs)
info = tf.keras.layers.Lambda(lambda x: tf.split(x, num_or_size_splits=self.l, axis=-2))(info)
outputs = tf.keras.layers.add(info)
outputs = self.reshape2(outputs)
return outputs
class ConvlstmMaxPoolBlock(tf.keras.layers.Layer):
def __init__(self, filters, kernel_size, pool_size, strides, t, h, w, c):
super(ConvlstmMaxPoolBlock, self).__init__()
self.convlstm = tf.keras.layers.ConvLSTM2D(filters=filters, kernel_size=kernel_size, padding='same',
return_sequences=True, return_state=True,
activation=tf.keras.layers.LeakyReLU())
self.max_pool = tf.keras.layers.MaxPool3D(pool_size=(1, pool_size, pool_size), strides=(1, strides, strides))
self.bn = tf.keras.layers.BatchNormalization()
self.alpha = ConvAttention(t, h, w, c, k=16)
self.get_feature_maps = WeightedSumBlock(t, h, w, c)
def call(self, inputs, skip_layer=None):
out, state_h, state_c = self.convlstm(inputs)
bn_out = self.bn(out)
alpha = self.alpha(bn_out)
skip_layer_feature_map = self.get_feature_maps([bn_out, alpha])
pool_out = self.max_pool(bn_out)
return pool_out, (state_h, state_c), skip_layer_feature_map
class ConvlstmTransBlock(tf.keras.layers.Layer):
def __init__(self, filters, kernel_size, up_size, strategy):
super(ConvlstmTransBlock, self).__init__()
self.strategy = strategy
self.deconvlstm = tf.keras.layers.ConvLSTM2D(filters=filters, kernel_size=kernel_size, padding='same',
return_sequences=True, activation=tf.keras.layers.LeakyReLU())
self.up_sampling3d = tf.keras.layers.UpSampling3D(size=(1, up_size, up_size))
self.bn = tf.keras.layers.TimeDistributed(tf.keras.layers.BatchNormalization())
def call(self, inputs, training=None):
inputs, hidden_state, map = inputs
T = tf.shape(inputs)[1]
skip_layer = tf.tile(tf.expand_dims(map, 1), [1, T, 1, 1, 1])
up_out = self.up_sampling3d(inputs)
deconv_out = self.deconvlstm(up_out, initial_state=hidden_state)
bn_out = self.bn(deconv_out)
out = tf.keras.layers.Concatenate()([skip_layer, bn_out])
return out
|
python
|
start_case_mutation = """\
mutation startCase($case: StartCaseInput!) {
startCase(input: $case) {
case {
id
}
}
}\
"""
intervalled_forms_query = """\
query allInterForms {
allForms (metaHasKey: "interval") {
pageInfo {
startCursor
endCursor
}
edges {
node {
meta
id
slug
documents {
edges {
node {
case {
closedAt
closedByUser
status
}
}
}
}
}
}
}
}\
"""
|
python
|
# -*- coding: utf-8 -*-
# pylint: disable=no-self-use, too-many-locals, too-many-arguments, too-many-statements, too-many-instance-attributes
"""Invite"""
import string
import time
import json
from configparser import ConfigParser
import requests
from flask import request
from library.couch_database import CouchDatabase
from library.couch_queries import Queries
from library.common import Common
from library.sha_security import ShaSecurity
from library.postgresql_queries import PostgreSQL
from library.emailer import Email
from library.config_parser import config_section_parser
from templates.invitation import Invitation
class Invite(Common, ShaSecurity):
"""Class for Invite"""
# INITIALIZE
def __init__(self):
"""The Constructor for Invite class"""
# INIT CONFIG
self.config = ConfigParser()
# CONFIG FILE
self.config.read("config/config.cfg")
self._couch_db = CouchDatabase()
self.couch_query = Queries()
self.postgres = PostgreSQL()
self.epoch_default = 26763
self.vpn_db_build = config_section_parser(self.config, "VPNDB")['build']
super(Invite, self).__init__()
if self.vpn_db_build.upper() == 'TRUE':
self.my_ip = config_section_parser(self.config, "IPS")['my']
self.my_protocol = config_section_parser(self.config, "IPS")['my_protocol']
self.user_vpn = config_section_parser(self.config, "IPS")['user_vpn']
self.user_protocol = config_section_parser(self.config, "IPS")['user_protocol']
self.vessel_vpn = config_section_parser(self.config, "IPS")['vessel_vpn']
self.vessel_protocol = config_section_parser(self.config, "IPS")['vessel_protocol']
self.vpn_token = '269c2c3706886d94aeefd6e7f7130ab08346590533d4c5b24ccaea9baa5211ec'
# GET VESSEL FUNCTION
def invitation(self):
"""
This API is for Sending invitation
---
tags:
- User
produces:
- application/json
parameters:
- name: token
in: header
description: Token
required: true
type: string
- name: userid
in: header
description: User ID
required: true
type: string
- name: query
in: body
description: Invite
required: true
schema:
id: Invite
properties:
first_name:
type: string
last_name:
type: string
middle_name:
type: string
url:
type: string
email:
type: string
companies:
types: array
example: []
roles:
types: array
example: []
vessels:
types: array
example: []
responses:
500:
description: Error
200:
description: Sending invitaion
"""
# INIT DATA
data = {}
# GET DATA
token = request.headers.get('token')
userid = request.headers.get('userid')
# GET JSON REQUEST
query_json = request.get_json(force=True)
# GET REQUEST PARAMS
email = query_json["email"]
url = query_json["url"]
vessels = query_json['vessels']
# CHECK TOKEN
token_validation = self.validate_token(token, userid)
if not token_validation:
data["alert"] = "Invalid Token"
data['status'] = 'Failed'
# RETURN ALERT
return self.return_data(data)
# INIT IMPORTANT KEYS
important_keys = {}
important_keys['companies'] = []
important_keys['roles'] = []
important_keys['email'] = "string"
important_keys['url'] = "string"
# CHECK IMPORTANT KEYS IN REQUEST JSON
if not self.check_request_json(query_json, important_keys):
data["alert"] = "Invalid query, Missing parameter!"
data['status'] = 'Failed'
# RETURN ALERT
return self.return_data(data)
# CHECK INVITATION
if self.check_invitaion(email):
data["alert"] = "Already invited!"
data['status'] = 'Failed'
# RETURN ALERT
return self.return_data(data)
password = self.generate_password()
# INSERT INVITATION
account_id = self.insert_invitation(password, query_json)
if not account_id:
data = {}
data['message'] = "Invalid email!"
data['status'] = "Failed"
return self.return_data(data)
if self.vpn_db_build.upper() == 'TRUE':
# FOR USER VPN
# JOB DATAS
callback_url = self.my_protocol + "://" + self.my_ip + "/vpn/update"
data_url = self.my_protocol + "://" + self.my_ip + "/vpn/data"
sql_str = "SELECT * FROM account_role where account_id='{0}' ".format(account_id)
sql_str += "AND role_id in (SELECT role_id FROM role "
sql_str += "WHERE role_name='super admin')"
super_admin = self.postgres.query_fetch_one(sql_str)
vpn_type = 'VCLIENT'
cvpn_type = 'CLIENT'
if super_admin:
vpn_type = 'VRH'
cvpn_type = 'RHADMIN'
# INSERT JOB
job_id = self.insert_job(callback_url,
data_url,
self.vpn_token,
account_id,
self.user_vpn,
cvpn_type)
# INIT PARAMS FOR CREATE VPN
vpn_params = {}
vpn_params['callback_url'] = callback_url
vpn_params['data_url'] = data_url
vpn_params['job_id'] = job_id
# CREATE VPN
self.create_vpn(vpn_params, self.vpn_token)
# FOR VESSEL VPN
if vessels or super_admin:
allow_access = False
for vessel in vessels:
if vessel['allow_access']:
allow_access = True
break
if allow_access or super_admin:
# INSERT JOB
job_id = self.insert_job(callback_url,
data_url,
self.vpn_token,
account_id,
self.vessel_vpn,
vpn_type)
# INIT PARAMS FOR CREATE VPN
vpn_params = {}
vpn_params['callback_url'] = callback_url
vpn_params['data_url'] = data_url
vpn_params['job_id'] = job_id
# CREATE VPN
self.create_vpn(vpn_params, self.vpn_token, True)
# SEND INVITATION
self.send_invitation(email, password, url)
data = {}
data['message'] = "Invitation successfully sent!"
data['status'] = "ok"
return self.return_data(data)
def check_invitaion(self, email):
"""Check Invitation"""
sql_str = "SELECT * FROM account WHERE "
sql_str += " email = '" + email + "'"
res = self.postgres.query_fetch_one(sql_str)
if res:
return res
return 0
def check_username(self, username):
"""Check Invitation"""
sql_str = "SELECT * FROM account WHERE "
sql_str += " username = '" + username + "'"
res = self.postgres.query_fetch_one(sql_str)
if res:
return res
return 0
def insert_invitation(self, password, query_json):
"""Insert Invitation"""
token = self.generate_token()
vessels = query_json['vessels']
companies = query_json['companies']
roles = query_json['roles']
data = query_json
data = self.remove_key(data, "companies")
data = self.remove_key(data, "roles")
data = self.remove_key(data, "vessels")
# username = query_json["email"].split("@")[0]
username = "no_username_{0}".format(int(time.time()))
if not self.check_username(username):
username += self.random_str_generator(5)
data['username'] = username
data['token'] = token
data['status'] = True
data['state'] = False
data['password'] = self.string_to_sha_plus(password)
data['created_on'] = time.time()
account_id = self.postgres.insert('account', data, 'id')
if not account_id:
return 0
for vessel in vessels:
ntwconf = self.couch_query.get_complete_values(
vessel['vessel_id'],
"NTWCONF"
)
# ACCOUNT VESSEL
temp = {}
temp['vessel_vpn_ip'] = ntwconf['NTWCONF']['tun1']['IP']
temp['account_id'] = account_id
temp['vessel_id'] = vessel['vessel_id']
temp['vessel_vpn_state'] = 'pending'
temp['allow_access'] = False
if 'allow_access' in vessel.keys():
temp['allow_access'] = vessel['allow_access']
self.postgres.insert('account_vessel', temp)
for company in companies:
# ACCOUNT COMPANY
temp = {}
temp['account_id'] = account_id
temp['company_id'] = company
self.postgres.insert('account_company', temp)
for role_id in roles:
# ACCOUNT COMPANY
temp = {}
temp['account_id'] = account_id
temp['role_id'] = role_id
self.postgres.insert('account_role', temp)
return account_id
def send_invitation(self, email, password, url):
"""Send Invitation"""
email_temp = Invitation()
emailer = Email()
message = email_temp.invitation_temp(password, url)
subject = "Invitation"
emailer.send_email(email, message, subject)
return 1
def generate_password(self):
"""Generate Password"""
char = string.ascii_uppercase
char += string.ascii_lowercase
char += string.digits
return self.random_str_generator(8, char)
def insert_job(self, callback_url, data_url, vpn_token, account_id, user_vpn, vpn_type):
"""Insert Job"""
update_on = time.time()
# INIT NEW JOB
temp = {}
temp['callback_url'] = callback_url
temp['vnp_server_ip'] = user_vpn
temp['data_url'] = data_url
temp['token'] = vpn_token
temp['status'] = 'pending'
temp['account_id'] = account_id
temp['vpn_type'] = vpn_type
temp['action'] = 'CREATE'
temp['account_os'] = 'WINDOWS' # LINUX
temp['update_on'] = update_on
temp['created_on'] = update_on
# INSERT NEW JOB
job_id = self.postgres.insert('job',
temp,
'job_id'
)
return job_id
def create_vpn(self, data, vpn_token, flag=False):
"""Create VPN"""
api_endpoint = self.user_protocol + "://" + self.user_vpn + "/ovpn"
if flag:
api_endpoint = self.vessel_protocol + "://" + self.vessel_vpn + "/ovpn"
headers = {'content-type': 'application/json', 'token': vpn_token}
req = requests.post(api_endpoint, data=json.dumps(data), headers=headers)
res = req.json()
return res
|
python
|
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import field
import boto3
from ..ec2api.vpcs import VPCs
from ..ec2common.ec2exceptions import *
# See vpc notes at the end of this file.
@dataclass
class VPCAttributes:
CidrBlock: str = None
DhcpOptionsId: str = None
State: str = None
VpcId: str = None
OwnerId: str = None
InstanceTenancy: str = None
# Tenancy defines how EC2 instances are distributed across physical hardware
# and affects pricing. There are three tenancy options available:
# - Shared (default) — Multiple AWS accounts may share the same physical hardware.
# - Dedicated Instance (dedicated) — Your instance runs on single-tenant hardware.
# - Dedicated Host (host) — Your instance runs on a physical server with EC2 instance capacity fully dedicated to your use, an isolated server with configurations that you can control.
Ipv6CidrBlockAssociationSet: object = field(default_factory=list)
CidrBlockAssociationSet: object = field(default_factory=list)
IsDefault: bool = None
Tags: object = field(default_factory=list)
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_vpc
class VPCManager:
def __init__(self):
self.vpcapi = VPCs()
def create_vpc(self, CidrBlock: str, arg_region):
vpcattributes = self.vpcapi.create_vpc_IPV4(
CidrBlock=CidrBlock, arg_region=arg_region
)
newvpc = VPC()
newvpc.attributes = VPCAttributes(**vpcattributes)
newvpc.region = arg_region
return newvpc
def get_vpc_in_region(self, VPCId, arg_region):
# Searches for the VPCId in a specific region
vpc_attributes = self.vpcapi.describe_vpc(VPCId, arg_region)
newvpc = VPC()
newvpc.attributes = VPCAttributes(**vpc_attributes)
return newvpc
def get_all_vpcs_in_region(self, arg_region):
# Gets all vpcs in a specified region
vpc_objects = []
response = self.vpcapi.describe_vpcs_in_region(arg_region)
vpcs = response["Vpcs"]
for vpc in vpcs:
newvpc = VPC()
newvpc.attributes = VPCAttributes(**vpc)
newvpc.region = arg_region
vpc_objects.append(newvpc)
return vpc_objects
def get_vpc(self, VPCId):
# Searches all regions for a vpc with ID vpcid
all_vpcs, result = self.does_vpc_exist(VPCId)
if not result:
raise VPCDoesNotExist(f"{VPCId} does not exist. ")
else:
vpc: VPC
for vpc in all_vpcs:
if vpc.attributes.VpcId == VPCId:
return vpc
def get_all_vpcs(self):
# Gets all vpcs accross all regions
vpc_objects_to_return = []
region_list = self.vpcapi.get_all_region_names()
vpc_object: VPC
for region in region_list:
vpc_objects = self.get_all_vpcs_in_region(region)
for vpc_object in vpc_objects:
vpc_object.region = region
vpc_objects_to_return.append(vpc_object)
return vpc_objects_to_return
def get_vpc_region(self, VPCid):
# For a given VPCid returns its region
all_vpcs, result = self.does_vpc_exist(VPCid)
if not result:
raise VPCDoesNotExist(f"{VPCid} does not exist. ")
else:
vpc: VPC
for vpc in all_vpcs:
if vpc.attributes.VpcId == VPCid:
return vpc.region
def does_vpc_exist(self, VPCid):
# To check if a vpc exists we need to build all the VPC objects.
# So, we mayaswell return the full list if it is needed also.
vpcs = self.get_all_vpcs()
vpc: VPC
for vpc in vpcs:
if vpc.attributes.VpcId == VPCid:
return vpcs, True
return vpcs, False
class VPC:
# Perhaps a vpc object should be able to...
# create subnets,
def __init__(self):
self.attributes = VPCAttributes()
self.region = None
def create_subnet(self, CidrBlock: str):
self.attributes.A
# VPC quick notes.
# https://www.youtube.com/watch?v=z07HTSzzp3o
# https://www.youtube.com/watch?v=bGDMeD6kOz0
#
# Available Private IPv4 IP addresses
# According to rfc1918 with CIDR notation.
#
# class C) 192.168.0.0/16
# class B) 172.16.0.0/12
# class A) 10.0.0.0/8
#
# https://www.freecodecamp.org/news/subnet-cheat-sheet-24-subnet-mask-30-26-27-29-and-other-ip-address-cidr-network-references/
#
#
#
# So according to the rfc1918 you should only stick to the above 3 blocks of IPs
# for your private networks.
#
# Amazon guide: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#vpc-subnet-basics
#
# Class A VPC must be /16 or smaller.
# Class B VPC must be /16 or smaller.
# Class C VPC must be /16 or smaller.
# /28 is the smalles netmask allowed by amazon.
# from the cheat sheet, /28 is 16 IP addresses.
# /16 is 65536 IP addresses.
# SUBNETTING
# OK.... lets say we create an amazon class A VPC with 65,536 IP addresses
# 10.0.0.0/16
#
# We have 65,536 IP addresses that we can subnet.
#
# First of all /16 blocks the first 16 bytes of an IP address
# Decimal Version: 255.255.0.0
# Binary Version: 11111111.11111111.00000000.00000000
#
# Which leaves:
# Decimal:
# 0.0.255.255 to play with, thats...
# 256*256 = 65,536 (including the 0) available IP addresses for your VPC
# and to be slices up in subnets.
#
# Binary:
# 0.0.11111111.11111111
# SUBNET MASK
# So viewed in binary it's easier to understand what a subnet mask is.
# 11111111.11111111.00000000.00000000 is a mask for our example.
# the first 11111111.11111111 just block out the area, not allowed to use.
# It's our network.
# Remember our network is class A so the first 16 bits under the mask is
# 00001010.00000000 = 10.0.
# the last 00000000.00000000 is called the 'wildcard mask', we can create
# as many combination of these binary numbers to create a complete IP on the
# network.
# e.g. 00000010.00000001 = 2.1
# which is 11111111.11111111.00000010.00000001 = 255.255.2.1
# but our example is a class A network, the first 16 bytes are actually
# 00001010.00000000 = 10.0.
# so our internal IP address is actually 10.0.2.1 for our example.
# Our range of available IPs for our private devices is.
# Start:
# 00001010.00000000.00000000.00000000 = 10.0.0.0
# End:
# 00001010.00000000.11111111.11111111 = 10.0.255.255
# So, whats a subnet?
# You can slice up the above private IP addresses in the PVC in to
# subnetworks. The slice sizes depend upon, and are contrained, by BINARY maths
# and also the imposed limit by amazon which is VPCs 16 or smaller as noted above.
#
# Okay, let do some subnetting.
#
# Our VPC: 10.0.0.0/16 with 65,534 IP Addresses
# Start: 00001010.00000000.00000000.00000000 = 10.0.0.0
# End: 00001010.00000000.11111111.11111111 = 10.0.255.255
#
# let make subnet of the smallest allowed size = 16 IP addresses, which is CIDR=/28
# 00001010.00000000.00000000.0000*0000 < 32-28 = 4
# The last 4 bits of the subnet must be kept zero, these represent the ip addresses
# that will be assigned to the computers in your subnet.
# How many IP addresses? 2^4= 16. Easy.
# So each subnet will have 16 IP addresses.
#
# And our binary restrictions are as follows, we can only define our subnet slices
# using the 0 below.
#
# XXXXXXXX.XXXXXXXX.00000000.0000XXXX
#
# So,
# XXXXXXXX.XXXXXXXX.00000001.0000XXXX is a valid subnet mask
# XXXXXXXX.XXXXXXXX.00000010.0000XXXX is a valid subnet mask
# XXXXXXXX.XXXXXXXX.11111111.0000XXXX is a valid subnet mask
#
# So we have the following valid subnets in CIDR format.
# 10.0.0.0/28
# 10.0.1.0/28
# ...
# 10.0.255.0/28
#
# Wait there is more. We can also use those other zeros too.
#
# XXXXXXXX.XXXXXXXX.00000000.0001XXXX is a valid subnet mask
# XXXXXXXX.XXXXXXXX.00000000.0010XXXX is a valid subnet mask
# XXXXXXXX.XXXXXXXX.00000000.0010XXXX is a valid subnet mask
#
# So we also have the following subnets available,
#
# 10.0.0.0/28
# 10.0.0.16/28
# 10.0.0.32/28
# 10.0.0.48/28
# 10.0.0.240/28
#
# and you can mix n match these digits so the following are valid subnets too....
#
# 10.0.1.16/28
# 10.0.1.32/28
# 10.0.1.48/28
# 10.0.2.16/28
#
# Each of these has space for 16 IP addresses.
#
# So subnetting... easy but tricky.
# INTERNET GATEWAY private to public(outside world)
# SECURITY GROUPS applied on per instance level, assined to vpc.
# Network Access Control List (NACL), subnet level - which traffic can enter subnet.
# ROUTING TABLE... route traffic differently, and assign public IP addresses.
# NAT GATEWAY ... Translates internal ips to public ones.
|
python
|
# coding=utf-8
from particles import Particle
class RectParticle(Particle):
def __init__(self, l):
Particle.__init__(self, l)
# super(RectParticle, self).__init__(l)
rectMode(CENTER)
self.rota = PI/3
def display(self):
stroke(0, self.lifespan)
fill(204, 53, 100, self.lifespan)
with pushMatrix():
translate(self.location.x, self.location.y)
rotate(self.rota)
rect(0, 0, 20, 20)
self.rota += random(0.02, .10)
|
python
|
import pytest
from detect_secrets.core.potential_secret import PotentialSecret
from testing.factories import potential_secret_factory
@pytest.mark.parametrize(
'a, b, is_equal',
[
(
potential_secret_factory(line_number=1),
potential_secret_factory(line_number=2),
True,
),
(
potential_secret_factory(type='A'),
potential_secret_factory(type='B'),
False,
),
(
potential_secret_factory(secret='A'),
potential_secret_factory(secret='B'),
False,
),
],
)
def test_equality(a, b, is_equal):
assert (a == b) is is_equal
# As a sanity check that it works both ways
assert (a != b) is not is_equal
def test_secret_storage():
secret = potential_secret_factory(secret='secret')
assert secret.secret_hash != 'secret'
def test_json():
secret = potential_secret_factory(secret='blah')
for value in secret.json().values():
assert value != 'blah'
@pytest.mark.parametrize(
'kwargs',
(
{
'line_number': 0,
},
{
'is_secret': True,
'is_verified': False,
},
),
)
def test_load_secret_from_dict(kwargs):
secret = potential_secret_factory(**kwargs)
new_secret = PotentialSecret.load_secret_from_dict(secret.json())
assert secret == new_secret
assert new_secret.secret_value is None
def test_stringify():
secret = potential_secret_factory(type='secret_type', secret='blah')
assert str(secret) == (
'Secret Type: secret_type\n'
'Location: filename:1\n'
)
|
python
|
"""
Basic shared function to read input data for each problem; the data file
must be in the subdirectory 'input' and with the name '<prog_name>.txt',
where '<prog_name>.py' is the name of the program being run
"""
import inspect
import pathlib
def get_input():
"""
Get input data for currently running program
If the name of the program is '<prog_name>.py', then the data file
must be 'input/<prog_name>.txt'
Returns data from file, stripped of last newline
"""
frame = inspect.stack()[1]
filename = pathlib.Path(frame[0].f_code.co_filename)
input_filename = pathlib.Path('input') / filename.with_suffix('.txt')
with open(input_filename) as fh:
input_data = fh.read().strip()
return input_data
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Holds fixtures for the smif package tests
"""
from __future__ import absolute_import, division, print_function
import json
import logging
import os
from copy import deepcopy
import numpy as np
import pandas as pd
from pytest import fixture
from smif.data_layer import Store
from smif.data_layer.data_array import DataArray
from smif.data_layer.file.file_config_store import _write_yaml_file as dump
from smif.data_layer.memory_interface import (MemoryConfigStore,
MemoryDataStore,
MemoryMetadataStore)
from smif.metadata import Spec
logging.basicConfig(filename='test_logs.log',
level=logging.DEBUG,
format='%(asctime)s %(name)-12s: %(levelname)-8s %(message)s',
filemode='w')
@fixture
def empty_store():
"""Store fixture
"""
# implement each part using the memory classes, simpler than mocking
# each other implementation of a part is tested fully by e.g. test_config_store.py
return Store(
config_store=MemoryConfigStore(),
metadata_store=MemoryMetadataStore(),
data_store=MemoryDataStore()
)
@fixture
def setup_empty_folder_structure(tmpdir_factory):
folder_list = ['models', 'results', 'config', 'data']
config_folders = [
'dimensions',
'model_runs',
'scenarios',
'sector_models',
'sos_models',
]
for folder in config_folders:
folder_list.append(os.path.join('config', folder))
data_folders = [
'coefficients',
'dimensions',
'initial_conditions',
'interventions',
'narratives',
'scenarios',
'strategies',
'parameters'
]
for folder in data_folders:
folder_list.append(os.path.join('data', folder))
test_folder = tmpdir_factory.mktemp("smif")
for folder in folder_list:
test_folder.mkdir(folder)
return test_folder
@fixture
def setup_folder_structure(setup_empty_folder_structure, oxford_region, remap_months,
initial_system, planned_interventions):
"""
Returns
-------
:class:`LocalPath`
Path to the temporary folder
"""
test_folder = setup_empty_folder_structure
region_file = test_folder.join('data', 'dimensions', 'test_region.geojson')
region_file.write(json.dumps(oxford_region))
intervals_file = test_folder.join('data', 'dimensions', 'annual.yml')
intervals_file.write("""\
- name: '1'
interval: [[P0Y, P1Y]]
""")
intervals_file = test_folder.join('data', 'dimensions', 'hourly.yml')
intervals_file.write("""\
- name: '1'
interval: [[PT0H, PT1H]]
""")
initial_conditions_dir = str(test_folder.join('data', 'initial_conditions'))
dump(initial_conditions_dir, 'init_system', initial_system)
interventions_dir = str(test_folder.join('data', 'interventions'))
dump(interventions_dir, 'planned_interventions', planned_interventions)
dimensions_dir = str(test_folder.join('data', 'dimensions'))
dump(dimensions_dir, 'remap', remap_months)
units_file = test_folder.join('data', 'user_units.txt')
with units_file.open(mode='w') as units_fh:
units_fh.write("blobbiness = m^3 * 10^6\n")
units_fh.write("people = [people]\n")
units_fh.write("mcm = 10^6 * m^3\n")
units_fh.write("GBP=[currency]\n")
return test_folder
@fixture
def interventions_index_file(setup_folder_structure):
data = {
'model_1': {'model_1_id_1': 'path1', 'model_1_id_2': 'path2'},
'model_2': {'model_2_id_1': 'path3', 'model_2_id_2': 'path4'}
}
test_folder = setup_folder_structure
models_dir = str(test_folder.join('config', 'sector_models'))
dump(models_dir, 'interventions_file_index', data)
@fixture
def initial_system():
"""Initial system (interventions with build_date)
"""
return [
{'name': 'water_asset_a', 'build_year': 2017},
{'name': 'water_asset_b', 'build_year': 2017},
{'name': 'water_asset_c', 'build_year': 2017},
]
@fixture
def parameters():
return [
{
'name': 'smart_meter_savings',
'description': 'The savings from smart meters',
'absolute_range': (0, 100),
'suggested_range': (3, 10),
'default_value': 3,
'unit': '%'
}
]
@fixture
def planned_interventions():
"""Return pre-specified planning intervention data
"""
return [
{
'name': 'water_asset_a',
'capacity': {'value': 6, 'unit': 'Ml'},
'description': 'Existing water treatment plants',
'location': {'lat': 51.74556, 'lon': -1.240528}
},
{
'name': 'water_asset_b',
'capacity': {'value': 6, 'unit': 'Ml'},
'description': 'Existing water treatment plants',
'location': {'lat': 51.74556, 'lon': -1.240528}
},
{
'name': 'water_asset_c',
'capacity': {'value': 6, 'unit': 'Ml'},
'description': 'Existing water treatment plants',
'location': {'lat': 51.74556, 'lon': -1.240528}
},
]
@fixture
def oxford_region():
data = {
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::27700"
}
},
"features": [
{
"type": "Feature",
"properties": {
"name": "oxford"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[448180, 209366],
[449500, 211092],
[450537, 211029],
[450873, 210673],
[451250, 210793],
[451642, 210023],
[453855, 208466],
[454585, 208468],
[456077, 207967],
[456146, 207738],
[456668, 207779],
[456708, 207444],
[456278, 207122],
[456149, 206615],
[455707, 206798],
[455749, 204521],
[456773, 204488],
[457014, 204184],
[456031, 203475],
[456444, 202854],
[456087, 202044],
[455369, 201799],
[454396, 202203],
[453843, 201634],
[452499, 203209],
[452052, 203566],
[451653, 203513],
[450645, 205137],
[449497, 205548],
[449051, 206042],
[448141, 208446],
[448180, 209366]
]
]
}
},
]
}
return data
@fixture
def initial_conditions():
return [{'name': 'solar_installation', 'build_year': 2017}]
@fixture
def interventions():
return {
'solar_installation': {
'name': 'solar_installation',
'capacity': 5,
'capacity_units': 'MW'
},
'wind_installation': {
'name': 'wind_installation',
'capacity': 4,
'capacity_units': 'MW'
}
}
@fixture
def water_interventions_abc():
return [
{
"name": "water_asset_a",
"location": "oxford",
"capital_cost": {
"units": "£",
"value": 1000
},
"economic_lifetime": {
"units": "years",
"value": 25
},
"operational_lifetime": {
"units": "years",
"value": 25
}
},
{
"name": "water_asset_b",
"location": "oxford",
"capital_cost": {
"units": "£",
"value": 1500
},
"economic_lifetime": {
"units": "years",
"value": 25
},
"operational_lifetime": {
"units": "years",
"value": 25
}
},
{
"name": "water_asset_c",
"location": "oxford",
"capital_cost": {
"units": "£",
"value": 3000
},
"economic_lifetime": {
"units": "years",
"value": 25
},
"operational_lifetime": {
"units": "years",
"value": 25
}
}
]
@fixture
def model_run():
"""Return sample model_run
"""
return {
'name': 'unique_model_run_name',
'description': 'a description of what the model run contains',
'stamp': '2017-09-20T12:53:23+00:00',
'timesteps': [
2015,
2020,
2025
],
'sos_model': 'energy',
'scenarios': {
'population': 'High Population (ONS)'
},
'strategies': [
{
'type': 'pre-specified-planning',
'name': 'energy_supply',
'description': 'description of the strategy',
'model_name': 'energy_supply',
}
],
'narratives': {
'technology': [
'Energy Demand - High Tech'
],
'governance': [
'Central Planning'
]
}
}
@fixture
def get_sos_model(sample_narratives):
"""Return sample sos_model
"""
return {
'name': 'energy',
'description': "A system of systems model which encapsulates "
"the future supply and demand of energy for the UK",
'scenarios': [
'population'
],
'narratives': sample_narratives,
'sector_models': [
'energy_demand',
'energy_supply'
],
'scenario_dependencies': [
{
'source': 'population',
'source_output': 'population_count',
'sink': 'energy_demand',
'sink_input': 'population'
}
],
'model_dependencies': [
{
'source': 'energy_demand',
'source_output': 'gas_demand',
'sink': 'energy_supply',
'sink_input': 'natural_gas_demand'
}
]
}
@fixture
def get_sector_model(annual, hourly, lad):
"""Return sample sector_model
"""
return {
'name': 'energy_demand',
'description': "Computes the energy demand of the"
"UK population for each timestep",
'classname': 'EnergyDemandWrapper',
'path': '../../models/energy_demand/run.py',
'inputs': [
{
'name': 'population',
'dtype': 'int',
'dims': ['lad', 'annual'],
'coords': {
'lad': lad,
'annual': annual
},
'absolute_range': [0, int(1e12)],
'expected_range': [0, 100000],
'unit': 'people'
}
],
'outputs': [
{
'name': 'gas_demand',
'dtype': 'float',
'dims': ['lad', 'hourly'],
'coords': {
'lad': lad,
'hourly': hourly
},
'absolute_range': [0, float('inf')],
'expected_range': [0.01, 10],
'unit': 'GWh'
}
],
'parameters': [
{
'name': 'smart_meter_savings',
'description': "Difference in floor area per person"
"in end year compared to base year",
'absolute_range': [0, float('inf')],
'expected_range': [0.5, 2],
'unit': '%',
'dtype': 'float'
},
{
'name': 'homogeneity_coefficient',
'description': "How homegenous the centralisation"
"process is",
'absolute_range': [0, 1],
'expected_range': [0, 1],
'unit': 'percentage',
'dtype': 'float'
}
],
'interventions': [],
'initial_conditions': []
}
@fixture
def energy_supply_sector_model(hourly):
"""Return sample sector_model
"""
return {
'name': 'energy_supply',
'description': "Supply system model",
'classname': 'EnergySupplyWrapper',
'path': '../../models/energy_supply/run.py',
'inputs': [
{
'name': 'natural_gas_demand',
'dims': ['lad', 'hourly'],
'coords': {
'lad': ['a', 'b'],
'hourly': hourly
},
'absolute_range': [0, float('inf')],
'expected_range': [0, 100],
'dtype': 'float',
'unit': 'GWh'
}
],
'outputs': [],
'parameters': [],
'interventions': [],
'initial_conditions': []
}
@fixture
def sample_gas_demand_results(lad, hourly):
spec = Spec.from_dict({
'name': 'gas_demand',
'dtype': 'float',
'dims': ['lad', 'hourly'],
'coords': {
'lad': lad,
'hourly': hourly
}
})
data = np.zeros(spec.shape, dtype=float)
return DataArray(spec, data)
@fixture
def water_supply_sector_model(hourly):
"""Return sample sector_model
"""
return {
'name': 'water_supply',
'description': "Supply system model",
'classname': 'WaterSupplyWrapper',
'path': '../../models/water_supply/run.py',
'inputs': [],
'outputs': [],
'parameters': [
{
'name': 'clever_water_meter_savings',
'description': "",
'absolute_range': [0, 1],
'expected_range': [0, 0.2],
'unit': 'percentage',
'dtype': 'float'
},
{
'name': 'per_capita_water_demand',
'description': "",
'absolute_range': [0, float('inf')],
'expected_range': [0, 0.05],
'unit': 'Ml/day',
'dtype': 'float'
}
],
'interventions': [],
'initial_conditions': []
}
@fixture
def get_sector_model_parameter_defaults(get_sector_model):
"""DataArray for each parameter default
"""
data = {
'smart_meter_savings': np.array(0.5),
'homogeneity_coefficient': np.array(0.1)
}
for param in get_sector_model['parameters']:
nda = data[param['name']]
spec = Spec.from_dict(param)
data[param['name']] = DataArray(spec, nda)
return data
@fixture
def get_multidimensional_param():
spec = Spec.from_dict({
'name': 'ss_t_base_heating',
'description': 'Industrial base temperature',
'default': '../energy_demand/parameters/ss_t_base_heating.csv',
'unit': '',
'dims': ['interpolation_params', 'end_yr'],
'coords': {
'interpolation_params': ['diffusion_choice', 'value_ey'],
'end_yr': [2030, 2050]
},
'dtype': 'float'
})
dataframe = pd.DataFrame([
{
'interpolation_params': 'diffusion_choice',
'end_yr': 2030,
'ss_t_base_heating': 0
},
{
'interpolation_params': 'diffusion_choice',
'end_yr': 2050,
'ss_t_base_heating': 0
},
{
'interpolation_params': 'value_ey',
'end_yr': 2030,
'ss_t_base_heating': 15.5
},
{
'interpolation_params': 'value_ey',
'end_yr': 2050,
'ss_t_base_heating': 15.5
},
]).set_index(['interpolation_params', 'end_yr'])
return DataArray.from_df(spec, dataframe)
@fixture
def get_sector_model_no_coords(get_sector_model):
model = deepcopy(get_sector_model)
for spec_group in ('inputs', 'outputs', 'parameters'):
for spec in model[spec_group]:
try:
del spec['coords']
except KeyError:
pass
return model
@fixture
def sample_scenarios():
"""Return sample scenario
"""
return [
{
'name': 'population',
'description': 'The annual change in UK population',
'provides': [
{
'name': "population_count",
'description': "The count of population",
'unit': 'people',
'dtype': 'int',
'dims': ['lad', 'annual']
},
],
'variants': [
{
'name': 'High Population (ONS)',
'description': 'The High ONS Forecast for UK population out to 2050',
'data': {
'population_count': 'population_high.csv'
}
},
{
'name': 'Low Population (ONS)',
'description': 'The Low ONS Forecast for UK population out to 2050',
'data': {
'population_count': 'population_low.csv'
}
},
],
},
]
@fixture
def sample_scenario_data(scenario_with_timestep, get_sector_model, energy_supply_sector_model,
water_supply_sector_model):
scenario_data = {}
for scenario in [scenario_with_timestep]:
for variant in scenario['variants']:
for data_key, data_value in variant['data'].items():
spec_dict = [
provides for provides in scenario['provides']
if provides['name'] == data_key
][0]
spec = Spec.from_dict(spec_dict)
nda = np.random.random(spec.shape)
da = DataArray(spec, nda)
key = (scenario['name'], variant['name'], data_key)
scenario_data[key] = da
return scenario_data
@fixture
def get_scenario():
"""Return sample scenario
"""
return {
"name": "Economy",
"description": "Economic projections for the UK",
"provides": [
{
'name': "gva",
'description': "GVA",
'dtype': "float",
'unit': "million GBP"
}
],
"variants": [
{
"name": "Central Economy (High)",
"data": {
"gva": 3,
}
}
]
}
@fixture(scope='function')
def get_narrative():
"""Return sample narrative
"""
return {
'name': 'technology',
'description': 'Describes the evolution of technology',
'provides': {
'energy_demand': ['smart_meter_savings']
},
'variants': [
{
'name': 'high_tech_dsm',
'description': 'High takeup of smart technology on the demand side',
'data': {
'smart_meter_savings': 'high_tech_dsm.csv'
}
}
]
}
@fixture
def sample_narratives(get_narrative):
"""Return sample narratives
"""
return [
get_narrative,
{
'name': 'governance',
'description': 'Defines the nature of governance and influence upon decisions',
'provides': {
'energy_demand': ['homogeneity_coefficient']
},
'variants': [
{
'name': 'Central Planning',
'description': 'Stronger role for central government in planning and ' +
'regulation, less emphasis on market-based solutions',
'data': {
'homogeneity_coefficient': 'homogeneity_coefficient.csv'
}
},
],
},
]
@fixture
def sample_narrative_data(sample_narratives, get_sector_model, energy_supply_sector_model,
water_supply_sector_model):
narrative_data = {}
sos_model_name = 'energy'
sector_models = {}
sector_models[get_sector_model['name']] = get_sector_model
sector_models[energy_supply_sector_model['name']] = energy_supply_sector_model
sector_models[water_supply_sector_model['name']] = water_supply_sector_model
for narrative in sample_narratives:
for sector_model_name, param_names in narrative['provides'].items():
sector_model = sector_models[sector_model_name]
for param_name in param_names:
param = _pick_from_list(sector_model['parameters'], param_name)
for variant in narrative['variants']:
spec = Spec.from_dict(param)
nda = np.random.random(spec.shape)
da = DataArray(spec, nda)
key = (sos_model_name, narrative['name'], variant['name'], param_name)
narrative_data[key] = da
return narrative_data
@fixture
def sample_results():
spec = Spec(name='energy_use', dtype='float')
data = np.array(1, dtype=float)
return DataArray(spec, data)
def _pick_from_list(list_, name):
for item in list_:
if item['name'] == name:
return item
assert False, '{} not found in {}'.format(name, list_)
@fixture
def sample_dimensions(remap_months, hourly, annual, lad):
"""Return sample dimensions
"""
return [
{
'name': 'lad',
'description': 'Local authority districts for the UK',
'elements': lad
},
{
'name': 'hourly',
'description': 'The 8760 hours in the year named by hour',
'elements': hourly
},
{
'name': 'annual',
'description': 'One annual timestep, used for aggregate yearly data',
'elements': annual,
},
{
'name': 'remap_months',
'description': 'Remapped months to four representative months',
'elements': remap_months,
},
{
'name': 'technology_type',
'description': 'Technology dimension for narrative fixture',
'elements': [
{'name': 'water_meter'},
{'name': 'electricity_meter'},
]
},
{
'name': 'county',
'elements': [
{'name': 'oxford'}
]
},
{
'name': 'season',
'elements': [
{'name': 'cold_month'},
{'name': 'spring_month'},
{'name': 'hot_month'},
{'name': 'fall_month'}
]
}
]
@fixture
def get_dimension():
return {
"name": "annual",
"description": "Single annual interval of 8760 hours",
"elements":
[
{
"id": 1,
"interval": [["PT0H", "PT8760H"]]
}
]
}
@fixture
def lad():
return [{'name': 'a'}, {'name': 'b'}]
@fixture
def hourly():
return [
{
'name': n,
'interval': [['PT{}H'.format(n), 'PT{}H'.format(n + 1)]]
}
for n in range(8) # should be 8760
]
@fixture
def annual():
return [
{
'name': 1,
'interval': [['PT0H', 'PT8760H']]
}
]
@fixture
def remap_months():
"""Remapping four representative months to months across the year
In this case we have a model which represents the seasons through
the year using one month for each season. We then map the four
model seasons 1, 2, 3 & 4 onto the months throughout the year that
they represent.
The data will be presented to the model using the four time intervals,
1, 2, 3 & 4. When converting to hours, the data will be replicated over
the year. When converting from hours to the model time intervals,
data will be averaged and aggregated.
"""
data = [
{'name': 'cold_month', 'interval': [['P0M', 'P1M'], ['P1M', 'P2M'], ['P11M', 'P12M']]},
{'name': 'spring_month', 'interval': [['P2M', 'P3M'], ['P3M', 'P4M'], ['P4M', 'P5M']]},
{'name': 'hot_month', 'interval': [['P5M', 'P6M'], ['P6M', 'P7M'], ['P7M', 'P8M']]},
{'name': 'fall_month', 'interval': [['P8M', 'P9M'], ['P9M', 'P10M'], ['P10M', 'P11M']]}
]
return data
@fixture
def minimal_model_run():
return {
'name': 'test_modelrun',
'timesteps': [2010, 2015, 2010],
'sos_model': 'energy'
}
@fixture
def strategies():
return [
{
'type': 'pre-specified-planning',
'description': 'a description',
'model_name': 'test_model',
'interventions': [
{'name': 'a', 'build_year': 2020},
{'name': 'b', 'build_year': 2025},
]
},
{
'type': 'rule-based',
'description': 'reduce emissions',
'path': 'planning/energyagent.py',
'classname': 'EnergyAgent'
}
]
@fixture
def unit_definitions():
return ['kg = kilograms']
@fixture
def dimension():
return {'name': 'category', 'elements': [{'name': 1}, {'name': 2}, {'name': 3}]}
@fixture
def conversion_source_spec():
return Spec(name='a', dtype='float', unit='ml')
@fixture
def conversion_sink_spec():
return Spec(name='b', dtype='float', unit='ml')
@fixture
def conversion_coefficients():
return np.array([[1]])
@fixture
def scenario(sample_dimensions):
return deepcopy({
'name': 'mortality',
'description': 'The annual mortality rate in UK population',
'provides': [
{
'name': 'mortality',
'dims': ['lad'],
'coords': {'lad': sample_dimensions[0]['elements']},
'dtype': 'float',
}
],
'variants': [
{
'name': 'low',
'description': 'Mortality (Low)',
'data': {
'mortality': 'mortality_low.csv',
},
}
]
})
@fixture
def scenario_2_variants(sample_dimensions):
return deepcopy({
'name': 'mortality_2_variants',
'description': 'The annual mortality rate in UK population',
'provides': [
{
'name': 'mortality',
'dims': ['lad'],
'coords': {'lad': sample_dimensions[0]['elements']},
'dtype': 'float',
}
],
'variants': [
{
'name': 'low',
'description': 'Mortality (Low)',
'data': {
'mortality': 'mortality_low.csv',
},
},
{
'name': 'high',
'description': 'Mortality (High)',
'data': {
'mortality': 'mortality_high.csv',
},
}
]
})
@fixture
def scenario_no_variant(sample_dimensions):
return deepcopy({
'name': 'mortality_no_variants',
'description': 'The annual mortality rate in UK population',
'provides': [
{
'name': 'mortality',
'dims': ['lad'],
'coords': {'lad': sample_dimensions[0]['elements']},
'dtype': 'float',
}
],
'variants': [
]
})
@fixture
def scenario_with_timestep(sample_dimensions):
"""This fixture should only be used if you need to write scenario variant data for the
purpose of a test. See, for instance, test_scenario_variant_data in the test_store.py.
In this case, the timestep dimension (that is always present for scenario variant data)
is explicitly provided for ease of writing out complete scenario variant data.
"""
return deepcopy({
'name': 'mortality',
'description': 'The annual mortality rate in UK population',
'provides': [
{
'name': 'mortality',
'dims': ['timestep', 'lad'],
'coords': {
'timestep': [2015, 2016],
'lad': sample_dimensions[0]['elements']
},
'dtype': 'float',
}
],
'variants': [
{
'name': 'low',
'description': 'Mortality (Low)',
'data': {
'mortality': 'mortality_low.csv',
},
}
]
})
@fixture
def scenario_no_coords(scenario):
scenario = deepcopy(scenario)
for spec in scenario['provides']:
try:
del spec['coords']
except KeyError:
pass
return scenario
@fixture
def narrative_no_coords(get_narrative):
get_narrative = deepcopy(get_narrative)
for spec in get_narrative['provides']:
try:
del spec['coords']
except KeyError:
pass
return get_narrative
@fixture
def state():
return [
{
'name': 'test_intervention',
'build_year': 1900
}
]
|
python
|
import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wheel')
os.system('python -m twine upload dist/*')
sys.exit()
setup()
|
python
|
#!/usr/bin/env python3
# Copyright (c) 2020-2022, NVIDIA CORPORATION. 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 the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (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 torch
import tinycudann as tcnn
net = tcnn.Network(
n_input_dims=3,
n_output_dims=3,
network_config={
"otype": "FullyFusedMLP",
"activation": "ReLU",
"output_activation": "None",
"n_neurons": 16,
"n_hidden_layers": 2,
},
).cuda()
x = torch.rand(256, 3, device='cuda')
y = net(x)
y.sum().backward() # OK
x2 = torch.rand(256, 3, device='cuda')
y = net(x)
y2 = net(x2)
(y + y2).sum().backward() # RuntimeError: Must call forward() before calling backward()
print("success!")
|
python
|
# Based on https://www.geeksforgeeks.org/get-post-requests-using-python/
# importing
import requests
import time
# defining the api-endpoint
API_ENDPOINT = "https://api.gfycat.com/v1/gfycats"
# your API key here
# API_KEY = "XXXXXXXXXXXXXXXXX"
# your source code here
external_url = input("Please input the external URL you want to create a gif of: ")
# data to be sent to api
data = {'fetchUrl':external_url}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
print(r.text)
gfyname = r.text
# Wait for the gif to process
done = False
while done is False:
time.sleep(5)
r = requests.post(url = "https://api.gfycat.com/v1/gfycats/fetch/status/"+gfyname, data = {})
print(r.text)
if r.json['task'] == 'complete':
done = True
print("Done!")
|
python
|
import unittest
from datetime import datetime
from models import *
class Test_UserModel(unittest.TestCase):
"""
Test the user model class
"""
def setUp(self):
self.model = User()
self.model.save()
def test_var_initialization(self):
self.assertTrue(hasattr(self.model, "email"))
self.assertTrue(hasattr(self.model, "password"))
self.assertTrue(hasattr(self.model, "first_name"))
self.assertTrue(hasattr(self.model, "last_name"))
self.assertEqual(self.model.email, "")
self.assertEqual(self.model.password, "")
self.assertEqual(self.model.first_name, "")
self.assertEqual(self.model.last_name, "")
if __name__ == "__main__":
unittest.main()
|
python
|
"""
Configuration file
"""
__author__ = 'V. Sudilovsky'
__maintainer__ = 'V. Sudilovsky'
__copyright__ = 'ADS Copyright 2014, 2015'
__version__ = '1.0'
__email__ = '[email protected]'
__status__ = 'Production'
__license__ = 'MIT'
SAMPLE_APPLICATION_PARAM = {
'message': 'config params should be prefixed with the application name',
'reason': 'this will allow easier integration if this app is incorporated'
' as a python module',
}
SAMPLE_APPLICATION_ADSWS_API_URL = 'https://api.adsabs.harvard.edu'
# Database for microservice
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
# These lines are necessary only if the app needs to be a client of the
# adsws-api
from client import Client
SAMPLE_APPLICATION_ADSWS_API_TOKEN = 'this is a secret api token!'
SAMPLE_APPLICATION_CLIENT = Client(
{'TOKEN': SAMPLE_APPLICATION_ADSWS_API_TOKEN}
)
|
python
|
import asyncio
class ClientServerProtocol(asyncio.Protocol):
metrics = {}
def __init__(self):
# self.metrics = {}
self.spliter = '_#_'
self.ok_message = 'ok\n'
self.error_message = 'error\nwrong command\n\n'
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
resp = self.process_data(data.decode())
self.transport.write(resp.encode())
def process_data(self, data):
if data.startswith('get'):
resp = self.get_metrics(data)
elif data.startswith('put'):
resp = self.put_metrics(data)
else:
resp = self.error_message
return resp
def get_metrics_list(self, resp_list, key=None):
if key == '*':
for i in ((k.split('_#_')[0], i, k.split('_#_')[1], '\n') for k, i in self.metrics.items()):
resp_list.append(' '.join(i))
else:
for i in ((k.split('_#_')[0], i, k.split('_#_')[1], '\n') for k, i in self.metrics.items() if k.split('_#_')[0] == key):
resp_list.append(' '.join(i))
return resp_list
def get_metrics(self, data):
resp_list = []
resp_list.append(self.ok_message)
try:
_, key = data.split()
self.get_metrics_list(resp_list, key)
resp_list.append('\n')
except:
resp_list = []
resp_list.append(self.error_message)
return ''.join(resp_list)
def put_metrics(self, data):
resp = self.ok_message + '\n'
try:
_, metric, value, timestamp = data.split()
key = metric + self.spliter + timestamp
self.metrics[key] = value
value = float(value)
timestamp = int(timestamp)
except:
resp = self.error_message
return resp
def run_server(host, port):
loop = asyncio.get_event_loop()
coro = loop.create_server(
ClientServerProtocol,
host, port
)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
if __name__ == "__main__":
run_server('127.0.0.1', 8181)
|
python
|
__author__ = 'Thomas Rueckstiess, [email protected]'
from scipy import random, asarray, zeros, dot
from pybrain.structure.modules.neuronlayer import NeuronLayer
from pybrain.tools.functions import expln, explnPrime
from pybrain.structure.parametercontainer import ParameterContainer
class StateDependentLayer(NeuronLayer, ParameterContainer):
def __init__(self, dim, module, name=None, onesigma=True):
NeuronLayer.__init__(self, dim, name)
self.exploration = zeros(dim, float)
self.state = None
self.onesigma = onesigma
if self.onesigma:
# one single parameter: sigma
ParameterContainer.__init__(self, 1)
else:
# sigmas for all parameters in the exploration module
ParameterContainer.__init__(self, module.paramdim)
# a module for the exploration
assert module.outdim == dim, (
"Passed module does not have right dimension")
self.module = module
self.autoalpha = False
self.enabled = True
def setState(self, state):
self.state = asarray(state)
self.exploration[:] = self.module.activate(self.state)
self.module.reset()
def drawRandomWeights(self):
self.module._setParameters(
random.normal(0, expln(self.params), self.module.paramdim))
def _forwardImplementation(self, inbuf, outbuf):
assert self.exploration != None
if not self.enabled:
outbuf[:] = inbuf
else:
outbuf[:] = inbuf + self.exploration
self.exploration = zeros(self.dim, float)
def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
if self.onesigma:
# algorithm for one global sigma for all mu's
expln_params = expln(self.params)
sumxsquared = dot(self.state, self.state)
self._derivs += (
sum((outbuf - inbuf) ** 2 - expln_params ** 2 * sumxsquared)
/ expln_params * explnPrime(self.params)
)
inerr[:] = (outbuf - inbuf)
if not self.autoalpha and sumxsquared != 0:
inerr /= expln_params ** 2 * sumxsquared
self._derivs /= expln_params ** 2 * sumxsquared
else:
# Algorithm for seperate sigma for each mu
expln_params = expln(self.params
).reshape(len(outbuf), len(self.state))
explnPrime_params = explnPrime(self.params
).reshape(len(outbuf), len(self.state))
idx = 0
for j in range(len(outbuf)):
sigma_subst2 = dot(self.state ** 2, expln_params[j, :]**2)
for i in range(len(self.state)):
self._derivs[idx] = ((outbuf[j] - inbuf[j]) ** 2 - sigma_subst2) / sigma_subst2 * \
self.state[i] ** 2 * expln_params[j, i] * explnPrime_params[j, i]
if self.autoalpha and sigma_subst2 != 0:
self._derivs[idx] /= sigma_subst2
idx += 1
inerr[j] = (outbuf[j] - inbuf[j])
if not self.autoalpha and sigma_subst2 != 0:
inerr[j] /= sigma_subst2
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.