repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
russorat/savage-leads
api/models/lead.py
1
2649
from elasticsearch import Elasticsearch,RequestsHttpConnection,NotFoundError from flask import url_for import config import json class Lead(object): es = Elasticsearch(config.ES_HOSTS,connection_class=RequestsHttpConnection) @staticmethod def create_lead(lead_data): try: results = Lead.es.create(index='leads', doc_type='leads', body=lead_data ) if results['created']: return { 'status': 'success', 'message': '', 'created_id': results['_id'] } else: return { 'status': 'failure', 'message': 'failed to create new lead.', 'created_id': '' } except Exception as e: print e return { 'status': 'failure', 'message': 'unknown error', 'created_id': '' } @staticmethod def delete_lead(lead_id): try : Lead.es.delete(index='leads', doc_type='leads', id=lead_id ) return { 'status': 'success', 'message': '' } except NotFoundError as e: return { 'status': 'failure', 'message': 'id not found' } except Exception as e: print e return { 'status': 'failure', 'message': 'unknown error' } @staticmethod def get_lead(lead_id): try: results = Lead.es.get( index='leads', doc_type='leads', id='%s'%(lead_id), ignore=404 ) if results and results['found'] : return {'status':'success','message':'','results':[Lead.from_es_hit(results)]} return {'status':'success','message':'','results':[]} except NotFoundError as e: return { 'status': 'failure', 'message': 'id not found', 'results': [] } except Exception as e: print e return { 'status': 'failure', 'message': 'unknown exception', 'results': [] } @staticmethod def get_leads(size,page,search): try: results = Lead.es.search( index='leads', doc_type='leads', size=size, q=search or "*", sort='last_name:ASC,first_name:ASC' ) retVal = [] if results and results['hits']['total'] > 0 : for hit in results['hits']['hits']: retVal.append(Lead.from_es_hit(hit)) return {'status':'success','message':'','results':retVal} except Exception as e: print e return {'status':'failure','message':'unknown error','results':[]} @staticmethod def from_es_hit(hit): lead = {} lead['id'] = hit['_id'] for key,val in hit['_source'].items(): lead[key] = val lead['uri'] = url_for('get_lead', lead_id=lead['id'], _external=True) return lead
apache-2.0
openstack/dragonflow
dragonflow/tests/unit/test_port_behind_port.py
1
2387
# 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. from testscenarios import load_tests_apply_scenarios as load_tests # noqa from dragonflow import conf as cfg from dragonflow.db.models import trunk as trunk_models from dragonflow.tests.unit import test_mech_driver class TestPortBehindPort(test_mech_driver.DFMechanismDriverTestCase): scenarios = [ ('ipvlan', {'segmentation_type': trunk_models.TYPE_IPVLAN}), ('macvlan', {'segmentation_type': trunk_models.TYPE_MACVLAN}), ] def setUp(self): cfg.CONF.set_override('auto_detect_port_behind_port', True, group='df') super(TestPortBehindPort, self).setUp() def test_detect_nested_port(self): with self.network() as n,\ self.subnet(network=n) as s,\ self.port(subnet=s) as p1,\ self.port(subnet=s) as p2: p1 = p1['port'] p2 = p2['port'] p2_ip = p2['fixed_ips'][0]['ip_address'] aap = {"ip_address": p2_ip} if self.segmentation_type == trunk_models.TYPE_MACVLAN: aap['mac_address'] = p2['mac_address'] data = {'port': {'allowed_address_pairs': [aap]}} self.nb_api.create.reset_mock() req = self.new_update_request( 'ports', data, p1['id']) req.get_response(self.api) cps_id = trunk_models.get_child_port_segmentation_id( p1['id'], p2['id']) model = trunk_models.ChildPortSegmentation( id=cps_id, topic=p1['project_id'], parent=p1['id'], port=p2['id'], segmentation_type=self.segmentation_type, ) self.nb_api.create.assert_called_once_with(model)
apache-2.0
tinkerthaler/odoo
openerp/addons/base/ir/ir_default.py
342
1883
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class ir_default(osv.osv): _name = 'ir.default' _columns = { 'field_tbl': fields.char('Object'), 'field_name': fields.char('Object Field'), 'value': fields.char('Default Value'), 'uid': fields.many2one('res.users', 'Users'), 'page': fields.char('View'), 'ref_table': fields.char('Table Ref.'), 'ref_id': fields.integer('ID Ref.',size=64), 'company_id': fields.many2one('res.company','Company') } def _get_company_id(self, cr, uid, context=None): res = self.pool.get('res.users').read(cr, uid, [uid], ['company_id'], context=context) if res and res[0]['company_id']: return res[0]['company_id'][0] return False _defaults = { 'company_id': _get_company_id, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
yosshy/nova
nova/scheduler/filters/image_props_filter.py
58
4622
# Copyright (c) 2011-2012 OpenStack Foundation # Copyright (c) 2012 Canonical Ltd # Copyright (c) 2012 SUSE LINUX Products GmbH # 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. from distutils import versionpredicate from oslo_log import log as logging from nova.compute import arch from nova.compute import hv_type from nova.compute import vm_mode from nova.scheduler import filters from nova import utils LOG = logging.getLogger(__name__) class ImagePropertiesFilter(filters.BaseHostFilter): """Filter compute nodes that satisfy instance image properties. The ImagePropertiesFilter filters compute nodes that satisfy any architecture, hypervisor type, or virtual machine mode properties specified on the instance's image properties. Image properties are contained in the image dictionary in the request_spec. """ # Image Properties and Compute Capabilities do not change within # a request run_filter_once_per_request = True def _instance_supported(self, host_state, image_props, hypervisor_version): img_arch = image_props.get('architecture', None) img_h_type = image_props.get('hypervisor_type', None) img_vm_mode = image_props.get('vm_mode', None) checked_img_props = ( arch.canonicalize(img_arch), hv_type.canonicalize(img_h_type), vm_mode.canonicalize(img_vm_mode) ) # Supported if no compute-related instance properties are specified if not any(checked_img_props): return True supp_instances = host_state.supported_instances # Not supported if an instance property is requested but nothing # advertised by the host. if not supp_instances: LOG.debug("Instance contains properties %(image_props)s, " "but no corresponding supported_instances are " "advertised by the compute node", {'image_props': image_props}) return False def _compare_props(props, other_props): for i in props: if i and i not in other_props: return False return True def _compare_product_version(hyper_version, image_props): version_required = image_props.get('hypervisor_version_requires') if not(hypervisor_version and version_required): return True img_prop_predicate = versionpredicate.VersionPredicate( 'image_prop (%s)' % version_required) hyper_ver_str = utils.convert_version_to_str(hyper_version) return img_prop_predicate.satisfied_by(hyper_ver_str) for supp_inst in supp_instances: if _compare_props(checked_img_props, supp_inst): if _compare_product_version(hypervisor_version, image_props): return True LOG.debug("Instance contains properties %(image_props)s " "that are not provided by the compute node " "supported_instances %(supp_instances)s or " "hypervisor version %(hypervisor_version)s do not match", {'image_props': image_props, 'supp_instances': supp_instances, 'hypervisor_version': hypervisor_version}) return False def host_passes(self, host_state, filter_properties): """Check if host passes specified image properties. Returns True for compute nodes that satisfy image properties contained in the request_spec. """ spec = filter_properties.get('request_spec', {}) image_props = spec.get('image', {}).get('properties', {}) if not self._instance_supported(host_state, image_props, host_state.hypervisor_version): LOG.debug("%(host_state)s does not support requested " "instance_properties", {'host_state': host_state}) return False return True
apache-2.0
cloudbau/nova
nova/tests/api/openstack/compute/contrib/test_evacuate.py
3
10062
# Copyright 2013 OpenStack Foundation # # 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 uuid from oslo.config import cfg import webob from nova.compute import api as compute_api from nova.compute import vm_states from nova import context from nova import exception from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes CONF = cfg.CONF CONF.import_opt('password_length', 'nova.utils') def fake_compute_api(*args, **kwargs): return True def fake_compute_api_get(self, context, instance_id): # BAD_UUID is something that does not exist if instance_id == 'BAD_UUID': raise exception.InstanceNotFound(instance_id=instance_id) else: return { 'id': 1, 'uuid': instance_id, 'vm_state': vm_states.ACTIVE, 'task_state': None, 'host': 'host1' } def fake_service_get_by_compute_host(self, context, host): if host == 'bad_host': raise exception.ComputeHostNotFound(host=host) else: return { 'host_name': host, 'service': 'compute', 'zone': 'nova' } class EvacuateTest(test.NoDBTestCase): _methods = ('resize', 'evacuate') def setUp(self): super(EvacuateTest, self).setUp() self.stubs.Set(compute_api.API, 'get', fake_compute_api_get) self.stubs.Set(compute_api.HostAPI, 'service_get_by_compute_host', fake_service_get_by_compute_host) self.UUID = uuid.uuid4() for _method in self._methods: self.stubs.Set(compute_api.API, _method, fake_compute_api) def test_evacuate_with_valid_instance(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'false', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' res = req.get_response(app) self.assertEqual(res.status_int, 200) def test_evacuate_with_invalid_instance(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % 'BAD_UUID') req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'false', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' res = req.get_response(app) self.assertEqual(res.status_int, 404) def test_evacuate_with_active_service(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.content_type = 'application/json' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'false', 'adminPass': 'MyNewPass' } }) def fake_evacuate(*args, **kwargs): raise exception.ComputeServiceInUse("Service still in use") self.stubs.Set(compute_api.API, 'evacuate', fake_evacuate) res = req.get_response(app) self.assertEqual(res.status_int, 400) def test_evacuate_instance_with_no_target(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'onSharedStorage': 'False', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' res = req.get_response(app) self.assertEqual(res.status_int, 400) def test_evacuate_instance_with_bad_target(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) req = webob.Request.blank('/v2/fake/servers/%s/action' % self.UUID) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'bad_host', 'onSharedStorage': 'false', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' res = req.get_response(app) self.assertEqual(res.status_int, 404) def test_evacuate_instance_with_target(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'false', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) resp = req.get_response(app) self.assertEqual(resp.status_int, 200) resp_json = jsonutils.loads(resp.body) self.assertEqual("MyNewPass", resp_json['adminPass']) def test_evacuate_shared_and_pass(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'True', 'adminPass': 'MyNewPass' } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) res = req.get_response(app) self.assertEqual(res.status_int, 400) def test_evacuate_not_shared_pass_generated(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'False', } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) resp = req.get_response(app) self.assertEqual(resp.status_int, 200) resp_json = jsonutils.loads(resp.body) self.assertEqual(CONF.password_length, len(resp_json['adminPass'])) def test_evacuate_shared(self): ctxt = context.get_admin_context() ctxt.user_id = 'fake' ctxt.project_id = 'fake' ctxt.is_admin = True app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'True', } }) req.content_type = 'application/json' def fake_update(inst, context, instance, task_state, expected_task_state): return None self.stubs.Set(compute_api.API, 'update', fake_update) res = req.get_response(app) self.assertEqual(res.status_int, 200) def test_not_admin(self): ctxt = context.RequestContext('fake', 'fake', is_admin=False) app = fakes.wsgi_app(fake_auth_context=ctxt) uuid1 = self.UUID req = webob.Request.blank('/v2/fake/servers/%s/action' % uuid1) req.method = 'POST' req.body = jsonutils.dumps({ 'evacuate': { 'host': 'my_host', 'onSharedStorage': 'True', } }) req.content_type = 'application/json' res = req.get_response(app) self.assertEqual(res.status_int, 403)
apache-2.0
woggle/mesos-old
frameworks/hadoop-0.20.2/src/contrib/hod/hodlib/HodRing/hodRing.py
64
32427
#Licensed to the Apache Software Foundation (ASF) under one #or more contributor license agreements. See the NOTICE file #distributed with this work for additional information #regarding copyright ownership. The ASF licenses this file #to you 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. #!/usr/bin/env python """hodring launches hadoop commands on work node and cleans up all the work dirs afterward """ # -*- python -*- import os, sys, time, shutil, getpass, xml.dom.minidom, xml.dom.pulldom import socket, sets, urllib, csv, signal, pprint, random, re, httplib from xml.dom import getDOMImplementation from pprint import pformat from optparse import OptionParser from urlparse import urlparse from hodlib.Common.util import local_fqdn, parseEquals, getMapredSystemDirectory, isProcessRunning from hodlib.Common.tcp import tcpSocket, tcpError binfile = sys.path[0] libdir = os.path.dirname(binfile) sys.path.append(libdir) import hodlib.Common.logger from hodlib.GridServices.service import * from hodlib.Common.util import * from hodlib.Common.socketServers import threadedHTTPServer from hodlib.Common.hodsvc import hodBaseService from hodlib.Common.threads import simpleCommand from hodlib.Common.xmlrpc import hodXRClient mswindows = (sys.platform == "win32") originalcwd = os.getcwd() reHdfsURI = re.compile("hdfs://(.*?:\d+)(.*)") class CommandDesc: """A class that represents the commands that are run by hodring""" def __init__(self, dict, log): self.log = log self.log.debug("In command desc") self.log.debug("Done in command desc") dict.setdefault('argv', []) dict.setdefault('version', None) dict.setdefault('envs', {}) dict.setdefault('workdirs', []) dict.setdefault('attrs', {}) dict.setdefault('final-attrs', {}) dict.setdefault('fg', False) dict.setdefault('ignorefailures', False) dict.setdefault('stdin', None) self.log.debug("Printing dict") self._checkRequired(dict) self.dict = dict def _checkRequired(self, dict): if 'name' not in dict: raise ValueError, "Command description lacks 'name'" if 'program' not in dict: raise ValueError, "Command description lacks 'program'" if 'pkgdirs' not in dict: raise ValueError, "Command description lacks 'pkgdirs'" def getName(self): return self.dict['name'] def getProgram(self): return self.dict['program'] def getArgv(self): return self.dict['argv'] def getVersion(self): return self.dict['version'] def getEnvs(self): return self.dict['envs'] def getPkgDirs(self): return self.dict['pkgdirs'] def getWorkDirs(self): return self.dict['workdirs'] def getAttrs(self): return self.dict['attrs'] def getfinalAttrs(self): return self.dict['final-attrs'] def isForeground(self): return self.dict['fg'] def isIgnoreFailures(self): return self.dict['ignorefailures'] def getStdin(self): return self.dict['stdin'] def parseDesc(str): dict = CommandDesc._parseMap(str) dict['argv'] = CommandDesc._parseList(dict['argv']) dict['envs'] = CommandDesc._parseMap(dict['envs']) dict['pkgdirs'] = CommandDesc._parseList(dict['pkgdirs'], ':') dict['workdirs'] = CommandDesc._parseList(dict['workdirs'], ':') dict['attrs'] = CommandDesc._parseMap(dict['attrs']) dict['final-attrs'] = CommandDesc._parseMap(dict['final-attrs']) return CommandDesc(dict) parseDesc = staticmethod(parseDesc) def _parseList(str, delim = ','): list = [] for row in csv.reader([str], delimiter=delim, escapechar='\\', quoting=csv.QUOTE_NONE, doublequote=False): list.extend(row) return list _parseList = staticmethod(_parseList) def _parseMap(str): """Parses key value pairs""" dict = {} for row in csv.reader([str], escapechar='\\', quoting=csv.QUOTE_NONE, doublequote=False): for f in row: [k, v] = f.split('=', 1) dict[k] = v return dict _parseMap = staticmethod(_parseMap) class MRSystemDirectoryManager: """Class that is responsible for managing the MapReduce system directory""" def __init__(self, jtPid, mrSysDir, fsName, hadoopPath, log, retries=120): self.__jtPid = jtPid self.__mrSysDir = mrSysDir self.__fsName = fsName self.__hadoopPath = hadoopPath self.__log = log self.__retries = retries def toCleanupArgs(self): return " --jt-pid %s --mr-sys-dir %s --fs-name %s --hadoop-path %s " \ % (self.__jtPid, self.__mrSysDir, self.__fsName, self.__hadoopPath) def removeMRSystemDirectory(self): jtActive = isProcessRunning(self.__jtPid) count = 0 # try for a max of a minute for the process to end while jtActive and (count<self.__retries): time.sleep(0.5) jtActive = isProcessRunning(self.__jtPid) count += 1 if count == self.__retries: self.__log.warn('Job Tracker did not exit even after a minute. Not going to try and cleanup the system directory') return self.__log.debug('jt is now inactive') cmd = "%s dfs -fs hdfs://%s -rmr %s" % (self.__hadoopPath, self.__fsName, \ self.__mrSysDir) self.__log.debug('Command to run to remove system directory: %s' % (cmd)) try: hadoopCommand = simpleCommand('mr-sys-dir-cleaner', cmd) hadoopCommand.start() hadoopCommand.wait() hadoopCommand.join() ret = hadoopCommand.exit_code() if ret != 0: self.__log.warn("Error in removing MapReduce system directory '%s' from '%s' using path '%s'" \ % (self.__mrSysDir, self.__fsName, self.__hadoopPath)) self.__log.warn(pprint.pformat(hadoopCommand.output())) else: self.__log.info("Removed MapReduce system directory successfully.") except: self.__log.error('Exception while cleaning up MapReduce system directory. May not be cleaned up. %s', \ get_exception_error_string()) self.__log.debug(get_exception_string()) def createMRSystemDirectoryManager(dict, log): keys = [ 'jt-pid', 'mr-sys-dir', 'fs-name', 'hadoop-path' ] for key in keys: if (not dict.has_key(key)) or (dict[key] is None): return None mrSysDirManager = MRSystemDirectoryManager(int(dict['jt-pid']), dict['mr-sys-dir'], \ dict['fs-name'], dict['hadoop-path'], log) return mrSysDirManager class HadoopCommand: """Runs a single hadoop command""" def __init__(self, id, desc, tempdir, tardir, log, javahome, mrSysDir, restart=False): self.desc = desc self.log = log self.javahome = javahome self.__mrSysDir = mrSysDir self.program = desc.getProgram() self.name = desc.getName() self.workdirs = desc.getWorkDirs() self.hadoopdir = tempdir self.confdir = os.path.join(self.hadoopdir, '%d-%s' % (id, self.name), "confdir") self.logdir = os.path.join(self.hadoopdir, '%d-%s' % (id, self.name), "logdir") self.out = os.path.join(self.logdir, '%s.out' % self.name) self.err = os.path.join(self.logdir, '%s.err' % self.name) self.child = None self.restart = restart self.filledInKeyVals = [] self._createWorkDirs() self._createHadoopSiteXml() self._createHadoopLogDir() self.__hadoopThread = None self.stdErrContents = "" # store list of contents for returning to user def _createWorkDirs(self): for dir in self.workdirs: if os.path.exists(dir): if not os.access(dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK): raise ValueError, "Workdir %s does not allow rwx permission." % (dir) continue try: os.makedirs(dir) except: pass def getFilledInKeyValues(self): return self.filledInKeyVals def createXML(self, doc, attr, topElement, final): for k,v in attr.iteritems(): self.log.debug('_createHadoopSiteXml: ' + str(k) + " " + str(v)) if ( v == "fillinport" ): v = "%d" % (ServiceUtil.getUniqRandomPort(low=50000, log=self.log)) keyvalpair = '' if isinstance(v, (tuple, list)): for item in v: keyvalpair = "%s%s=%s," % (keyvalpair, k, item) keyvalpair = keyvalpair[:-1] else: keyvalpair = k + '=' + v self.filledInKeyVals.append(keyvalpair) if(k == "mapred.job.tracker"): # total hack for time's sake keyvalpair = k + "=" + v self.filledInKeyVals.append(keyvalpair) if ( v == "fillinhostport"): port = "%d" % (ServiceUtil.getUniqRandomPort(low=50000, log=self.log)) self.log.debug('Setting hostname to: %s' % local_fqdn()) v = local_fqdn() + ':' + port keyvalpair = '' if isinstance(v, (tuple, list)): for item in v: keyvalpair = "%s%s=%s," % (keyvalpair, k, item) keyvalpair = keyvalpair[:-1] else: keyvalpair = k + '=' + v self.filledInKeyVals.append(keyvalpair) if ( v == "fillindir"): v = self.__mrSysDir pass prop = None if isinstance(v, (tuple, list)): for item in v: prop = self._createXmlElement(doc, k, item, "No description", final) topElement.appendChild(prop) else: if k == 'fs.default.name': prop = self._createXmlElement(doc, k, "hdfs://" + v, "No description", final) else: prop = self._createXmlElement(doc, k, v, "No description", final) topElement.appendChild(prop) def _createHadoopSiteXml(self): if self.restart: if not os.path.exists(self.confdir): os.makedirs(self.confdir) else: assert os.path.exists(self.confdir) == False os.makedirs(self.confdir) implementation = getDOMImplementation() doc = implementation.createDocument('', 'configuration', None) comment = doc.createComment("This is an auto generated hadoop-site.xml, do not modify") topElement = doc.documentElement topElement.appendChild(comment) finalAttr = self.desc.getfinalAttrs() self.createXML(doc, finalAttr, topElement, True) attr = {} attr1 = self.desc.getAttrs() for k,v in attr1.iteritems(): if not finalAttr.has_key(k): attr[k] = v self.createXML(doc, attr, topElement, False) siteName = os.path.join(self.confdir, "hadoop-site.xml") sitefile = file(siteName, 'w') print >> sitefile, topElement.toxml() sitefile.close() self.log.debug('created %s' % (siteName)) def _createHadoopLogDir(self): if self.restart: if not os.path.exists(self.logdir): os.makedirs(self.logdir) else: assert os.path.exists(self.logdir) == False os.makedirs(self.logdir) def _createXmlElement(self, doc, name, value, description, final): prop = doc.createElement("property") nameP = doc.createElement("name") string = doc.createTextNode(name) nameP.appendChild(string) valueP = doc.createElement("value") string = doc.createTextNode(value) valueP.appendChild(string) desc = doc.createElement("description") string = doc.createTextNode(description) desc.appendChild(string) prop.appendChild(nameP) prop.appendChild(valueP) prop.appendChild(desc) if (final): felement = doc.createElement("final") string = doc.createTextNode("true") felement.appendChild(string) prop.appendChild(felement) pass return prop def getMRSystemDirectoryManager(self): return MRSystemDirectoryManager(self.__hadoopThread.getPid(), self.__mrSysDir, \ self.desc.getfinalAttrs()['fs.default.name'], \ self.path, self.log) def run(self, dir): status = True args = [] desc = self.desc self.log.debug(pprint.pformat(desc.dict)) self.log.debug("Got package dir of %s" % dir) self.path = os.path.join(dir, self.program) self.log.debug("path: %s" % self.path) args.append(self.path) args.extend(desc.getArgv()) envs = desc.getEnvs() fenvs = os.environ for k, v in envs.iteritems(): fenvs[k] = v if envs.has_key('HADOOP_OPTS'): fenvs['HADOOP_OPTS'] = envs['HADOOP_OPTS'] self.log.debug("HADOOP_OPTS : %s" % fenvs['HADOOP_OPTS']) fenvs['JAVA_HOME'] = self.javahome fenvs['HADOOP_CONF_DIR'] = self.confdir fenvs['HADOOP_LOG_DIR'] = self.logdir self.log.info(pprint.pformat(fenvs)) hadoopCommand = '' for item in args: hadoopCommand = "%s%s " % (hadoopCommand, item) # Redirecting output and error to self.out and self.err hadoopCommand = hadoopCommand + ' 1>%s 2>%s ' % (self.out, self.err) self.log.debug('running command: %s' % (hadoopCommand)) self.log.debug('hadoop env: %s' % fenvs) self.log.debug('Command stdout will be redirected to %s ' % self.out + \ 'and command stderr to %s' % self.err) self.__hadoopThread = simpleCommand('hadoop', hadoopCommand, env=fenvs) self.__hadoopThread.start() while self.__hadoopThread.stdin == None: time.sleep(.2) self.log.debug("hadoopThread still == None ...") input = desc.getStdin() self.log.debug("hadoop input: %s" % input) if input: if self.__hadoopThread.is_running(): print >>self.__hadoopThread.stdin, input else: self.log.error("hadoop command failed to start") self.__hadoopThread.stdin.close() self.log.debug("isForground: %s" % desc.isForeground()) if desc.isForeground(): self.log.debug("Waiting on hadoop to finish...") self.__hadoopThread.wait() self.log.debug("Joining hadoop thread...") self.__hadoopThread.join() if self.__hadoopThread.exit_code() != 0: status = False else: status = self.getCommandStatus() self.log.debug("hadoop run status: %s" % status) if status == False: self.handleFailedCommand() if (status == True) or (not desc.isIgnoreFailures()): return status else: self.log.error("Ignoring Failure") return True def kill(self): self.__hadoopThread.kill() if self.__hadoopThread: self.__hadoopThread.join() def addCleanup(self, list): list.extend(self.workdirs) list.append(self.confdir) def getCommandStatus(self): status = True ec = self.__hadoopThread.exit_code() if (ec != 0) and (ec != None): status = False return status def handleFailedCommand(self): self.log.error('hadoop error: %s' % ( self.__hadoopThread.exit_status_string())) # read the contents of redirected stderr to print information back to user if os.path.exists(self.err): f = None try: f = open(self.err) lines = f.readlines() # format for line in lines: self.stdErrContents = "%s%s" % (self.stdErrContents, line) finally: if f is not None: f.close() self.log.error('See %s.out and/or %s.err for details. They are ' % \ (self.name, self.name) + \ 'located at subdirectories under either ' + \ 'hodring.work-dirs or hodring.log-destination-uri.') class HodRing(hodBaseService): """The main class for hodring that polls the commands it runs""" def __init__(self, config): hodBaseService.__init__(self, 'hodring', config['hodring']) self.log = self.logs['main'] self._http = None self.__pkg = None self.__pkgDir = None self.__tempDir = None self.__running = {} self.__hadoopLogDirs = [] self.__init_temp_dir() def __init_temp_dir(self): self.__tempDir = os.path.join(self._cfg['temp-dir'], "%s.%s.hodring" % (self._cfg['userid'], self._cfg['service-id'])) if not os.path.exists(self.__tempDir): os.makedirs(self.__tempDir) os.chdir(self.__tempDir) def __fetch(self, url, spath): retry = 3 success = False while (retry != 0 and success != True): try: input = urllib.urlopen(url) bufsz = 81920 buf = input.read(bufsz) out = open(spath, 'w') while len(buf) > 0: out.write(buf) buf = input.read(bufsz) input.close() out.close() success = True except: self.log.debug("Failed to copy file") retry = retry - 1 if (retry == 0 and success != True): raise IOError, "Failed to copy the files" def __get_name(self, addr): parsedUrl = urlparse(addr) path = parsedUrl[2] split = path.split('/', 1) return split[1] def __get_dir(self, name): """Return the root directory inside the tarball specified by name. Assumes that the tarball begins with a root directory.""" import tarfile myTarFile = tarfile.open(name) hadoopPackage = myTarFile.getnames()[0] self.log.debug("tarball name : %s hadoop package name : %s" %(name,hadoopPackage)) return hadoopPackage def getRunningValues(self): return self.__running.values() def getTempDir(self): return self.__tempDir def getHadoopLogDirs(self): return self.__hadoopLogDirs def __download_package(self, ringClient): self.log.debug("Found download address: %s" % self._cfg['download-addr']) try: addr = 'none' downloadTime = self._cfg['tarball-retry-initial-time'] # download time depends on tarball size and network bandwidth increment = 0 addr = ringClient.getTarList(self.hostname) while(addr == 'none'): rand = self._cfg['tarball-retry-initial-time'] + increment + \ random.uniform(0,self._cfg['tarball-retry-interval']) increment = increment + 1 self.log.debug("got no tarball. Retrying again in %s seconds." % rand) time.sleep(rand) addr = ringClient.getTarList(self.hostname) self.log.debug("got this address %s" % addr) tarName = self.__get_name(addr) self.log.debug("tar package name: %s" % tarName) fetchPath = os.path.join(os.getcwd(), tarName) self.log.debug("fetch path: %s" % fetchPath) self.__fetch(addr, fetchPath) self.log.debug("done fetching") tarUrl = "http://%s:%d/%s" % (self._http.server_address[0], self._http.server_address[1], tarName) try: ringClient.registerTarSource(self.hostname, tarUrl,addr) #ringClient.tarDone(addr) except KeyError, e: self.log.error("registerTarSource and tarDone failed: ", e) raise KeyError(e) check = untar(fetchPath, os.getcwd()) if (check == False): raise IOError, "Untarring failed." self.__pkg = self.__get_dir(tarName) self.__pkgDir = os.path.join(os.getcwd(), self.__pkg) except Exception, e: self.log.error("Failed download tar package: %s" % get_exception_error_string()) raise Exception(e) def __run_hadoop_commands(self, restart=True): id = 0 for desc in self._cfg['commanddesc']: self.log.debug(pprint.pformat(desc.dict)) mrSysDir = getMapredSystemDirectory(self._cfg['mapred-system-dir-root'], self._cfg['userid'], self._cfg['service-id']) self.log.debug('mrsysdir is %s' % mrSysDir) cmd = HadoopCommand(id, desc, self.__tempDir, self.__pkgDir, self.log, self._cfg['java-home'], mrSysDir, restart) self.__hadoopLogDirs.append(cmd.logdir) self.log.debug("hadoop log directory: %s" % self.__hadoopLogDirs) try: # if the tarball isn't there, we use the pkgs dir given. if self.__pkgDir == None: pkgdir = desc.getPkgDirs() else: pkgdir = self.__pkgDir self.log.debug('This is the packcage dir %s ' % (pkgdir)) if not cmd.run(pkgdir): addnInfo = "" if cmd.stdErrContents is not "": addnInfo = " Information from stderr of the command:\n%s" % (cmd.stdErrContents) raise Exception("Could not launch the %s using %s/bin/hadoop.%s" % (desc.getName(), pkgdir, addnInfo)) except Exception, e: self.log.debug("Exception running hadoop command: %s\n%s" % (get_exception_error_string(), get_exception_string())) self.__running[id] = cmd raise Exception(e) id += 1 if desc.isForeground(): continue self.__running[id-1] = cmd # ok.. now command is running. If this HodRing got jobtracker, # Check if it is ready for accepting jobs, and then only return self.__check_jobtracker(desc, id-1, pkgdir) def __check_jobtracker(self, desc, id, pkgdir): # Check jobtracker status. Return properly if it is ready to accept jobs. # Currently Checks for Jetty to come up, the last thing that can be checked # before JT completes initialisation. To be perfectly reliable, we need # hadoop support name = desc.getName() if name == 'jobtracker': # Yes I am the Jobtracker self.log.debug("Waiting for jobtracker to initialise") version = desc.getVersion() self.log.debug("jobtracker version : %s" % version) hadoopCmd = self.getRunningValues()[id] attrs = hadoopCmd.getFilledInKeyValues() attrs = parseEquals(attrs) jobTrackerAddr = attrs['mapred.job.tracker'] self.log.debug("jobtracker rpc server : %s" % jobTrackerAddr) if version < 16: jettyAddr = jobTrackerAddr.split(':')[0] + ':' + \ attrs['mapred.job.tracker.info.port'] else: jettyAddr = attrs['mapred.job.tracker.http.address'] self.log.debug("Jobtracker jetty : %s" % jettyAddr) # Check for Jetty to come up # For this do a http head, and then look at the status defaultTimeout = socket.getdefaulttimeout() # socket timeout isn`t exposed at httplib level. Setting explicitly. socket.setdefaulttimeout(1) sleepTime = 0.5 jettyStatus = False jettyStatusmsg = "" while sleepTime <= 32: # There is a possibility that the command might fail after a while. # This code will check if the command failed so that a better # error message can be returned to the user. if not hadoopCmd.getCommandStatus(): self.log.critical('Hadoop command found to have failed when ' \ 'checking for jobtracker status') hadoopCmd.handleFailedCommand() addnInfo = "" if hadoopCmd.stdErrContents is not "": addnInfo = " Information from stderr of the command:\n%s" \ % (hadoopCmd.stdErrContents) raise Exception("Could not launch the %s using %s/bin/hadoop.%s" \ % (desc.getName(), pkgdir, addnInfo)) try: jettyConn = httplib.HTTPConnection(jettyAddr) jettyConn.request("HEAD", "/jobtracker.jsp") # httplib inherently retries the following till socket timeout resp = jettyConn.getresponse() if resp.status != 200: # Some problem? jettyStatus = False jettyStatusmsg = "Jetty gave a non-200 response to a HTTP-HEAD" +\ " request. HTTP Status (Code, Msg): (%s, %s)" % \ ( resp.status, resp.reason ) break else: self.log.info("Jetty returned a 200 status (%s)" % resp.reason) self.log.info("JobTracker successfully initialised") return except socket.error: self.log.debug("Jetty gave a socket error. Sleeping for %s" \ % sleepTime) time.sleep(sleepTime) sleepTime = sleepTime * 2 except Exception, e: jettyStatus = False jettyStatusmsg = ("Process(possibly other than jetty) running on" + \ " port assigned to jetty is returning invalid http response") break socket.setdefaulttimeout(defaultTimeout) if not jettyStatus: self.log.critical("Jobtracker failed to initialise.") if jettyStatusmsg: self.log.critical( "Reason: %s" % jettyStatusmsg ) else: self.log.critical( "Reason: Jetty failed to give response") raise Exception("JobTracker failed to initialise") def stop(self): self.log.debug("Entered hodring stop.") if self._http: self.log.debug("stopping http server...") self._http.stop() self.log.debug("call hodsvcrgy stop...") hodBaseService.stop(self) def _xr_method_clusterStart(self, initialize=True): return self.clusterStart(initialize) def _xr_method_clusterStop(self): return self.clusterStop() def start(self): """Run and maintain hodring commands""" try: if self._cfg.has_key('download-addr'): self._http = threadedHTTPServer('', self._cfg['http-port-range']) self.log.info("Starting http server...") self._http.serve_forever() self.log.debug("http://%s:%d" % (self._http.server_address[0], self._http.server_address[1])) hodBaseService.start(self) ringXRAddress = None if self._cfg.has_key('ringmaster-xrs-addr'): ringXRAddress = "http://%s:%s/" % (self._cfg['ringmaster-xrs-addr'][0], self._cfg['ringmaster-xrs-addr'][1]) self.log.debug("Ringmaster at %s" % ringXRAddress) self.log.debug("Creating service registry XML-RPC client.") serviceClient = hodXRClient(to_http_url( self._cfg['svcrgy-addr'])) if ringXRAddress == None: self.log.info("Did not get ringmaster XML-RPC address. Fetching information from service registry.") ringList = serviceClient.getServiceInfo(self._cfg['userid'], self._cfg['service-id'], 'ringmaster', 'hod') self.log.debug(pprint.pformat(ringList)) if len(ringList): if isinstance(ringList, list): ringXRAddress = ringList[0]['xrs'] count = 0 while (ringXRAddress == None and count < 3000): ringList = serviceClient.getServiceInfo(self._cfg['userid'], self._cfg['service-id'], 'ringmaster', 'hod') if len(ringList): if isinstance(ringList, list): ringXRAddress = ringList[0]['xrs'] count = count + 1 time.sleep(.2) if ringXRAddress == None: raise Exception("Could not get ringmaster XML-RPC server address.") self.log.debug("Creating ringmaster XML-RPC client.") ringClient = hodXRClient(ringXRAddress) id = self.hostname + "_" + str(os.getpid()) if 'download-addr' in self._cfg: self.__download_package(ringClient) else: self.log.debug("Did not find a download address.") cmdlist = [] firstTime = True increment = 0 hadoopStartupTime = 2 cmdlist = ringClient.getCommand(id) while (cmdlist == []): if firstTime: sleepTime = increment + self._cfg['cmd-retry-initial-time'] + hadoopStartupTime\ + random.uniform(0,self._cfg['cmd-retry-interval']) firstTime = False else: sleepTime = increment + self._cfg['cmd-retry-initial-time'] + \ + random.uniform(0,self._cfg['cmd-retry-interval']) self.log.debug("Did not get command list. Waiting for %s seconds." % (sleepTime)) time.sleep(sleepTime) increment = increment + 1 cmdlist = ringClient.getCommand(id) self.log.debug(pformat(cmdlist)) cmdDescs = [] for cmds in cmdlist: cmdDescs.append(CommandDesc(cmds['dict'], self.log)) self._cfg['commanddesc'] = cmdDescs self.log.info("Running hadoop commands...") self.__run_hadoop_commands(False) masterParams = [] for k, cmd in self.__running.iteritems(): masterParams.extend(cmd.filledInKeyVals) self.log.debug("printing getparams") self.log.debug(pformat(id)) self.log.debug(pformat(masterParams)) # when this is on a required host, the ringMaster already has our masterParams if(len(masterParams) > 0): ringClient.addMasterParams(id, masterParams) except Exception, e: raise Exception(e) def clusterStart(self, initialize=True): """Start a stopped mapreduce/dfs cluster""" if initialize: self.log.debug('clusterStart Method Invoked - Initialize') else: self.log.debug('clusterStart Method Invoked - No Initialize') try: self.log.debug("Creating service registry XML-RPC client.") serviceClient = hodXRClient(to_http_url(self._cfg['svcrgy-addr']), None, None, 0, 0, 0) self.log.info("Fetching ringmaster information from service registry.") count = 0 ringXRAddress = None while (ringXRAddress == None and count < 3000): ringList = serviceClient.getServiceInfo(self._cfg['userid'], self._cfg['service-id'], 'ringmaster', 'hod') if len(ringList): if isinstance(ringList, list): ringXRAddress = ringList[0]['xrs'] count = count + 1 if ringXRAddress == None: raise Exception("Could not get ringmaster XML-RPC server address.") self.log.debug("Creating ringmaster XML-RPC client.") ringClient = hodXRClient(ringXRAddress, None, None, 0, 0, 0) id = self.hostname + "_" + str(os.getpid()) cmdlist = [] if initialize: if 'download-addr' in self._cfg: self.__download_package(ringClient) else: self.log.debug("Did not find a download address.") while (cmdlist == []): cmdlist = ringClient.getCommand(id) else: while (cmdlist == []): cmdlist = ringClient.getAdminCommand(id) self.log.debug(pformat(cmdlist)) cmdDescs = [] for cmds in cmdlist: cmdDescs.append(CommandDesc(cmds['dict'], self.log)) self._cfg['commanddesc'] = cmdDescs if initialize: self.log.info("Running hadoop commands again... - Initialize") self.__run_hadoop_commands() masterParams = [] for k, cmd in self.__running.iteritems(): self.log.debug(cmd) masterParams.extend(cmd.filledInKeyVals) self.log.debug("printing getparams") self.log.debug(pformat(id)) self.log.debug(pformat(masterParams)) # when this is on a required host, the ringMaster already has our masterParams if(len(masterParams) > 0): ringClient.addMasterParams(id, masterParams) else: self.log.info("Running hadoop commands again... - No Initialize") self.__run_hadoop_commands() except: self.log.error(get_exception_string()) return True def clusterStop(self): """Stop a running mapreduce/dfs cluster without stopping the hodring""" self.log.debug('clusterStop Method Invoked') try: for cmd in self.__running.values(): cmd.kill() self.__running = {} except: self.log.error(get_exception_string()) return True
apache-2.0
pombredanne/http-repo.gem5.org-gem5-
src/arch/arm/kvm/ArmV8KvmCPU.py
38
2269
# Copyright (c) 2015 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andreas Sandberg from m5.params import * from BaseArmKvmCPU import BaseArmKvmCPU class ArmV8KvmCPU(BaseArmKvmCPU): type = 'ArmV8KvmCPU' cxx_header = "arch/arm/kvm/armv8_cpu.hh"
bsd-3-clause
okwow123/djangol2
example/env/lib/python2.7/site-packages/django/contrib/gis/gdal/__init__.py
52
2169
""" This module houses ctypes interfaces for GDAL objects. The following GDAL objects are supported: CoordTransform: Used for coordinate transformations from one spatial reference system to another. Driver: Wraps an OGR data source driver. DataSource: Wrapper for the OGR data source object, supports OGR-supported data sources. Envelope: A ctypes structure for bounding boxes (GDAL library not required). OGRGeometry: Object for accessing OGR Geometry functionality. OGRGeomType: A class for representing the different OGR Geometry types (GDAL library not required). SpatialReference: Represents OSR Spatial Reference objects. The GDAL library will be imported from the system path using the default library name for the current OS. The default library path may be overridden by setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C library on your system. """ from django.contrib.gis.gdal.envelope import Envelope from django.contrib.gis.gdal.error import ( # NOQA GDALException, OGRException, OGRIndexError, SRSException, check_err, ) from django.contrib.gis.gdal.geomtype import OGRGeomType # NOQA __all__ = [ 'check_err', 'Envelope', 'GDALException', 'OGRException', 'OGRIndexError', 'SRSException', 'OGRGeomType', 'HAS_GDAL', ] # Attempting to import objects that depend on the GDAL library. The # HAS_GDAL flag will be set to True if the library is present on # the system. try: from django.contrib.gis.gdal.driver import Driver # NOQA from django.contrib.gis.gdal.datasource import DataSource # NOQA from django.contrib.gis.gdal.libgdal import gdal_version, gdal_full_version, GDAL_VERSION # NOQA from django.contrib.gis.gdal.raster.source import GDALRaster # NOQA from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform # NOQA from django.contrib.gis.gdal.geometries import OGRGeometry # NOQA HAS_GDAL = True __all__ += [ 'Driver', 'DataSource', 'gdal_version', 'gdal_full_version', 'GDALRaster', 'GDAL_VERSION', 'SpatialReference', 'CoordTransform', 'OGRGeometry', ] except GDALException: HAS_GDAL = False
mit
yaroslavvb/tensorflow
tensorflow/python/kernel_tests/random_poisson_test.py
49
7153
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.random_ops.random_poisson.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging class RandomPoissonTest(test.TestCase): """This is a large test due to the moments computation taking some time.""" def _Sampler(self, num, lam, dtype, use_gpu, seed=None): def func(): with self.test_session(use_gpu=use_gpu, graph=ops.Graph()) as sess: rng = random_ops.random_poisson(lam, [num], dtype=dtype, seed=seed) ret = np.empty([10, num]) for i in xrange(10): ret[i, :] = sess.run(rng) return ret return func # TODO(srvasude): Factor this out along with the corresponding moment testing # method in random_gamma_test into a single library. def testMoments(self): try: from scipy import stats # pylint: disable=g-import-not-at-top except ImportError as e: tf_logging.warn("Cannot test moments: %s", e) return # The moments test is a z-value test. This is the largest z-value # we want to tolerate. Since the z-test approximates a unit normal # distribution, it should almost definitely never exceed 6. z_limit = 6.0 for dt in dtypes.float16, dtypes.float32, dtypes.float64: # Test when lam < 10 and when lam >= 10 for stride in 0, 4, 10: for lam in (3., 20): max_moment = 5 sampler = self._Sampler(10000, lam, dt, use_gpu=False, seed=12345) moments = [0] * (max_moment + 1) moments_sample_count = [0] * (max_moment + 1) x = np.array(sampler().flat) # sampler does 10x samples for k in range(len(x)): moment = 1. for i in range(max_moment + 1): index = k + i * stride if index >= len(x): break moments[i] += moment moments_sample_count[i] += 1 moment *= x[index] for i in range(max_moment + 1): moments[i] /= moments_sample_count[i] for i in range(1, max_moment + 1): g = stats.poisson(lam) if stride == 0: moments_i_mean = g.moment(i) moments_i_squared = g.moment(2 * i) else: moments_i_mean = pow(g.moment(1), i) moments_i_squared = pow(g.moment(2), i) moments_i_var = ( moments_i_squared - moments_i_mean * moments_i_mean) # Assume every operation has a small numerical error. # It takes i multiplications to calculate one i-th moment. error_per_moment = i * 1e-6 total_variance = ( moments_i_var / moments_sample_count[i] + error_per_moment) if not total_variance: total_variance = 1e-10 # z_test is approximately a unit normal distribution. z_test = abs( (moments[i] - moments_i_mean) / np.sqrt(total_variance)) self.assertLess(z_test, z_limit) # Checks that the CPU and GPU implementation returns the same results, # given the same random seed def testCPUGPUMatch(self): for dt in dtypes.float16, dtypes.float32, dtypes.float64: results = {} for use_gpu in [False, True]: sampler = self._Sampler(1000, 1.0, dt, use_gpu=use_gpu, seed=12345) results[use_gpu] = sampler() if dt == dtypes.float16: self.assertAllClose(results[False], results[True], rtol=1e-3, atol=1e-3) else: self.assertAllClose(results[False], results[True], rtol=1e-6, atol=1e-6) def testSeed(self): for dt in dtypes.float16, dtypes.float32, dtypes.float64: sx = self._Sampler(1000, 1.0, dt, use_gpu=True, seed=345) sy = self._Sampler(1000, 1.0, dt, use_gpu=True, seed=345) self.assertAllEqual(sx(), sy()) def testNoCSE(self): """CSE = constant subexpression eliminator. SetIsStateful() should prevent two identical random ops from getting merged. """ for dtype in dtypes.float16, dtypes.float32, dtypes.float64: with self.test_session(use_gpu=True): rnd1 = random_ops.random_poisson(2.0, [24], dtype=dtype) rnd2 = random_ops.random_poisson(2.0, [24], dtype=dtype) diff = rnd2 - rnd1 # Since these are all positive integers, the norm will # be at least 1 if they are different. self.assertGreaterEqual(np.linalg.norm(diff.eval()), 1) def testShape(self): # Fully known shape. rnd = random_ops.random_poisson(2.0, [150], seed=12345) self.assertEqual([150], rnd.get_shape().as_list()) rnd = random_ops.random_poisson( lam=array_ops.ones([1, 2, 3]), shape=[150], seed=12345) self.assertEqual([150, 1, 2, 3], rnd.get_shape().as_list()) rnd = random_ops.random_poisson( lam=array_ops.ones([1, 2, 3]), shape=[20, 30], seed=12345) self.assertEqual([20, 30, 1, 2, 3], rnd.get_shape().as_list()) rnd = random_ops.random_poisson( lam=array_ops.placeholder(dtypes.float32, shape=(2,)), shape=[12], seed=12345) self.assertEqual([12, 2], rnd.get_shape().as_list()) # Partially known shape. rnd = random_ops.random_poisson( lam=array_ops.ones([7, 3]), shape=array_ops.placeholder(dtypes.int32, shape=(1,)), seed=12345) self.assertEqual([None, 7, 3], rnd.get_shape().as_list()) rnd = random_ops.random_poisson( lam=array_ops.ones([9, 6]), shape=array_ops.placeholder(dtypes.int32, shape=(3,)), seed=12345) self.assertEqual([None, None, None, 9, 6], rnd.get_shape().as_list()) # Unknown shape. rnd = random_ops.random_poisson( lam=array_ops.placeholder(dtypes.float32), shape=array_ops.placeholder(dtypes.int32), seed=12345) self.assertIs(None, rnd.get_shape().ndims) rnd = random_ops.random_poisson( lam=array_ops.placeholder(dtypes.float32), shape=[50], seed=12345) self.assertIs(None, rnd.get_shape().ndims) if __name__ == "__main__": test.main()
apache-2.0
uranusjr/django
tests/migrations/test_autodetector.py
3
114892
import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import TestCase, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return ( self.__module__ + '.' + self.__class__.__name__, self.args, self.kwargs ) class AutodetectorTests(TestCase): """ Tests the migration autodetector. """ author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_name = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) author_name_null = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ]) author_name_longer = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ]) author_name_renamed = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ]) author_name_default = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default='Ada Lovelace')), ]) author_dates_of_birth_auto_now = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ]) author_dates_of_birth_auto_now_add = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ]) author_name_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_4 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_list_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 999])), ]) author_name_deconstructible_tuple_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 999))), ]) author_name_deconstructible_dict_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 999 })), ]) author_name_nested_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2-changed'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_extra_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), None, a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c-changed')), ))), ]) author_name_nested_deconstructible_extra_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), c=None, ))), ]) author_custom_pk = ModelState("testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))]) author_with_biography_non_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ]) author_with_biography_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ]) author_with_book = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_book_order_wrt = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}) author_renamed_with_book = ModelState("testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_publisher_string = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ]) author_with_publisher = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) author_with_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ]) author_with_custom_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ]) author_proxy = ModelState("testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",)) author_proxy_options = ModelState("testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author", )) author_proxy_notproxy = ModelState("testapp", "AuthorProxy", [], {}, ("testapp.author", )) author_proxy_third = ModelState("thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author", )) author_proxy_third_notproxy = ModelState("thirdapp", "AuthorProxy", [], {}, ("testapp.author", )) author_proxy_proxy = ModelState("testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy", )) author_unmanaged = ModelState("testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author", )) author_unmanaged_managed = ModelState("testapp", "AuthorUnmanaged", [], {}, ("testapp.author", )) author_unmanaged_default_pk = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_unmanaged_custom_pk = ModelState("testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ]) author_with_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ]) author_with_m2m_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ]) author_with_m2m_through = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract")), ]) author_with_renamed_m2m_through = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal")), ]) author_with_former_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ]) author_with_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) author_with_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_with_new_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}) author_renamed_with_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_renamed_with_new_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}) contract = ModelState("testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) contract_renamed = ModelState("testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) publisher = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ]) publisher_with_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_aardvark_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_book = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) other_pony = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ]) other_pony_food = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ('food_qs', FoodQuerySet.as_manager()), ('food_mgr', FoodManager('a', 'b')), ('food_mgr_kwargs', FoodManager('x', 'y', 3, 4)), ]) other_stable = ModelState("otherapp", "Stable", [("id", models.AutoField(primary_key=True))]) third_thing = ModelState("thirdapp", "Thing", [("id", models.AutoField(primary_key=True))]) book = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_proxy_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_proxy_proxy_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ]) book_migrations_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_no_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ]) book_with_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_field_and_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors_through_attribution = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author", through="otherapp.Attribution")), ("title", models.CharField(max_length=200)), ]) book_indexes = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [models.Index(fields=["author", "title"], name="book_title_author_idx")], }) book_unordered_indexes = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [models.Index(fields=["title", "author"], name="book_author_title_idx")], }) book_foo_together = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, "unique_together": {("author", "title")}, }) book_foo_together_2 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) book_foo_together_3 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, "unique_together": {("title", "newfield")}, }) book_foo_together_4 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, "unique_together": {("title", "newfield2")}, }) attribution = ModelState("otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) edition = ModelState("thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) custom_user = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser, )) custom_user_no_inherit = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ]) aardvark = ModelState("thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_testapp = ModelState("testapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_based_on_author = ModelState("testapp", "Aardvark", [], bases=("testapp.Author", )) aardvark_pk_fk_author = ModelState("testapp", "Aardvark", [ ("id", models.OneToOneField("testapp.Author", models.CASCADE, primary_key=True)), ]) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState("eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], { "unique_together": {("parent", "knight")}, "indexes": [models.Index(fields=["parent", "knight"], name='rabbit_circular_fk_index')], }) def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail("Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), )) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail("Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), )) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] real_types = [operation.__class__.__name__ for operation in migration.operations] if types != real_types: self.fail("Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), )) def assertOperationAttributes(self, changes, app_label, position, operation_position, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail("Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), )) def assertOperationFieldAttributes(self, changes, app_label, position, operation_position, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_position] if not hasattr(operation, 'field'): self.fail("No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, )) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail("Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), )) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): return MigrationAutodetector( self.make_project_state(before_states), self.make_project_state(after_states), questioner, )._detect_changes() def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, "0002_pony_stable") self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_trim_apps(self): """ Trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable, self.third_thing]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_initial": True})) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = 'custom_name' changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_new_model(self): """Tests autodetection of new models.""" changes = self.get_changes([], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) def test_old_model(self): """Tests deletion of old models.""" changes = self.get_changes([self.author_empty], []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_empty], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_date_fields_with_auto_now_not_asking_for_default(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now=True) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_date_fields_with_auto_now_add_not_asking_for_null_addition(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now_add]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_auto_now_add_addition') def test_add_date_fields_with_auto_now_add_asking_for_default(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now_add]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) self.assertEqual(mocked_ask_method.call_count, 3) def test_remove_field(self): """Tests autodetection of removed fields.""" changes = self.get_changes([self.author_name], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_name], [self.author_name_longer]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) def test_supports_functools_partial(self): def _content_file_name(instance, filename, key, **kwargs): return '{}/{}'.format(instance, filename) def content_file_name(key, **kwargs): return functools.partial(_content_file_name, key, **kwargs) # An unchanged partial reference. before = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file'))), ])] after = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file'))), ])] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, 'testapp', 0) # A changed partial reference. args_changed = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('other-file'))), ])] changes = self.get_changes(before, args_changed) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['AlterField']) # Can't use assertOperationFieldAttributes because we need the # deconstructed version, i.e., the exploded func/args/keywords rather # than the partial: we don't care if it's not the same instance of the # partial, only if it's the same source function, args, and keywords. value = changes['testapp'][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ('other-file',), {}), (value.func, value.args, value.keywords) ) kwargs_changed = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file', spam='eggs'))), ])] changes = self.get_changes(before, kwargs_changed) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['AlterField']) value = changes['testapp'][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ('file',), {'spam': 'eggs'}), (value.func, value.args, value.keywords) ) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', side_effect=AssertionError("Should not have prompted for not null addition")) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default='Ada Lovelace') @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value=models.NOT_PROVIDED) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default=models.NOT_PROVIDED) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value='Some Name') def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=False) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default="Some Name") def test_rename_field(self): """Tests autodetection of renamed fields.""" changes = self.get_changes( [self.author_name], [self.author_name_renamed], MigrationQuestioner({"ask_rename": True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="name", new_name="names") def test_rename_model(self): """Tests autodetection of renamed models.""" changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_author_renamed], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, 'otherapp', 0) def test_rename_m2m_through_model(self): """ Tests autodetection of renamed models that are used in M2M relations as through models. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [self.author_with_renamed_m2m_through, self.publisher, self.contract_renamed], MigrationQuestioner({'ask_rename_model': True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['RenameModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name='Contract', new_name='Deal') def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_field_and_author_renamed], MigrationQuestioner({"ask_rename": True, "ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, old_name="author", new_name="writer") def test_rename_model_with_fks_in_different_position(self): """ #24537 - The order of fields in a model does not influence the RenameModel detection. """ before = [ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ]), ] after = [ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({"ask_rename_model": True})) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB") def test_rename_model_reverse_relation_dependencies(self): """ The migration to rename a model pointed to by a foreign key in another app must run after the other app's migration that adds the foreign key with model's original name. Therefore, the renaming migration has a dependency on that other migration. """ before = [ ModelState('testapp', 'EntityA', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('otherapp', 'EntityB', [ ('id', models.AutoField(primary_key=True)), ('entity_a', models.ForeignKey('testapp.EntityA', models.CASCADE)), ]), ] after = [ ModelState('testapp', 'RenamedEntityA', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('otherapp', 'EntityB', [ ('id', models.AutoField(primary_key=True)), ('entity_a', models.ForeignKey('testapp.RenamedEntityA', models.CASCADE)), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename_model': True})) self.assertNumberMigrations(changes, 'testapp', 1) self.assertMigrationDependencies(changes, 'testapp', 0, [('otherapp', '__first__')]) self.assertOperationTypes(changes, 'testapp', 0, ['RenameModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name='EntityA', new_name='RenamedEntityA') def test_fk_dependency(self): """Having a ForeignKey automatically adds a dependency.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) changes = self.get_changes([], [self.author_name, self.book, self.edition]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("testapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="Edition") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("otherapp", "auto_1")]) def test_proxy_fk_dependency(self): """FK dependencies still work on proxy models.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) changes = self.get_changes([], [self.author_empty, self.author_proxy_third, self.book_proxy_fk]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("thirdapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="AuthorProxy") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("testapp", "auto_1")]) def test_same_app_no_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_circular_fk_dependency(self): """ Having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ changes = self.get_changes([], [self.author_with_book, self.book, self.publisher_with_book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 2) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'otherapp', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'otherapp', 0, []) self.assertMigrationDependencies(changes, 'otherapp', 1, [("otherapp", "auto_1"), ("testapp", "auto_1")]) # both split migrations should be `initial` self.assertTrue(changes['otherapp'][0].initial) self.assertTrue(changes['otherapp'][1].initial) def test_same_app_circular_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher_with_author]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_same_app_circular_fk_dependency_with_unique_together_and_indexes(self): """ #22275 - A migration with circular FK dependency does not try to create unique together constraint and indexes before creating all required fields first. """ changes = self.get_changes([], [self.knight, self.rabbit]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'eggs', 1) self.assertOperationTypes( changes, 'eggs', 0, ["CreateModel", "CreateModel", "AddIndex", "AlterUniqueTogether"] ) self.assertNotIn("unique_together", changes['eggs'][0].operations[0].options) self.assertNotIn("unique_together", changes['eggs'][0].operations[1].options) self.assertMigrationDependencies(changes, 'eggs', 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" changes = self.get_changes([self.author_empty], [self.author_with_db_table_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_one") def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" changes = self.get_changes([self.author_with_db_table_options], [self.author_with_new_db_table_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_two") def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" changes = self.get_changes([self.author_with_db_table_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table=None) def test_alter_db_table_no_changes(self): """ Alter_db_table doesn't generate a migration if no changes have been made. """ changes = self.get_changes([self.author_with_db_table_options], [self.author_with_db_table_options]) # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_new_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel", "AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") self.assertOperationAttributes(changes, "testapp", 0, 1, name="newauthor", table="author_three") def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[-a-zA-Z0-9_]+\\Z'), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) changes = self.get_changes([from_state], [to_state]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[a-z]+\\Z', 32), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_foo_together(self): """ #23452 - Empty unique/index_together shouldn't generate a migration. """ # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState("a", "model", [("id", models.AutoField(primary_key=True))]) # Explicitly testing for None, since this was the issue in #23452 after # an AlterFooTogether operation with e.g. () as value model_state_none = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": None, "unique_together": None, }) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": set(), "unique_together": set(), }) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations) self.fail('Created operation(s) %s from %s' % (ops, msg)) tests = ( (model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"'), (model_state_not_specified, model_state_none, '"not specified" to "None"'), (model_state_not_specified, model_state_empty, '"not specified" to "empty"'), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), (model_state_empty, model_state_not_specified, '"empty" to "not specified"'), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_create_model_with_indexes(self): """Test creation of new model with indexes already defined.""" author = ModelState('otherapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]}) changes = self.get_changes([], [author]) added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx') # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author') self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) def test_add_indexes(self): """Test change detection of new indexes.""" changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_indexes]) self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AddIndex']) added_index = models.Index(fields=['author', 'title'], name='book_title_author_idx') self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', index=added_index) def test_remove_indexes(self): """Test change detection of removed indexes.""" changes = self.get_changes([self.author_empty, self.book_indexes], [self.author_empty, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', name='book_title_author_idx') def test_order_fields_indexes(self): """Test change detection of reordering of fields in indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes] ) self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveIndex', 'AddIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', name='book_title_author_idx') added_index = models.Index(fields=['title', 'author'], name='book_author_title_idx') self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='book', index=added_index) def test_add_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_foo_together]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together={("author", "title")}) def test_remove_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes([self.author_empty, self.book_foo_together], [self.author_empty, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) def test_foo_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_with_no_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", "RemoveField" ]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 2, model_name="book", name="author") def test_foo_together_no_changes(self): """ index/unique_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_foo_together_ordering(self): """ index/unique_together also triggers on ordering changes. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together_2] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together={("title", "author")}) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together={("title", "author")}) def test_add_field_and_foo_together(self): """ Added fields will be created before using them in index/unique_together. """ changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_foo_together_3]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield")}) def test_create_model_and_unique_together(self): author = ModelState("otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) book_with_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) changes = self.get_changes([self.book_with_no_author], [author, book_with_author]) # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 4) # Right actions order? self.assertOperationTypes( changes, 'otherapp', 0, ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether'] ) def test_remove_field_and_foo_together(self): """ Removed fields will be removed after updating index/unique_together. """ changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, model_name="book", name="newfield") self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={("author", "title")}) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("author", "title")}) def test_rename_field_and_foo_together(self): """ Removed fields will be removed after updating index/unique_together. """ changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together_4], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={ ("title", "newfield2") }) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield2")}) def test_proxy(self): """The autodetector correctly deals with proxy models.""" # First, we test adding a proxy model changes = self.get_changes([self.author_empty], [self.author_empty, self.author_proxy]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": []} ) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one changes = self.get_changes( [self.author_empty, self.author_proxy], [self.author_empty, self.author_proxy_notproxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy", options={}) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_empty, self.author_proxy_third, self.book_proxy_fk]) # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'id') # Now, we test the custom pk field name changes = self.get_changes([], [self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk]) # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'pk_field') def test_proxy_to_mti_with_fk_to_proxy(self): # First, test the pk table and field name. changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk], ) self.assertEqual( changes['otherapp'][0].operations[0].fields[2][1].remote_field.model._meta.db_table, 'testapp_author', ) self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'id') # Change AuthorProxy to use MTI. changes = self.get_changes( [self.author_empty, self.author_proxy_third, self.book_proxy_fk], [self.author_empty, self.author_proxy_third_notproxy, self.book_proxy_fk], ) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ['DeleteModel', 'CreateModel']) # Right number/type of migrations for the Book model with a FK to # AuthorProxy? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AlterField']) # otherapp should depend on thirdapp. self.assertMigrationDependencies(changes, 'otherapp', 0, [('thirdapp', 'auto_1')]) # Now, test the pk table and field name. self.assertEqual( changes['otherapp'][0].operations[0].field.remote_field.model._meta.db_table, 'thirdapp_authorproxy', ) self.assertEqual(changes['otherapp'][0].operations[0].field.remote_field.field_name, 'author_ptr') def test_proxy_to_mti_with_fk_to_proxy_proxy(self): # First, test the pk table and field name. changes = self.get_changes( [], [self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk], ) self.assertEqual( changes['otherapp'][0].operations[0].fields[1][1].remote_field.model._meta.db_table, 'testapp_author', ) self.assertEqual(changes['otherapp'][0].operations[0].fields[1][1].remote_field.field_name, 'id') # Change AuthorProxy to use MTI. FK still points to AAuthorProxyProxy, # a proxy of AuthorProxy. changes = self.get_changes( [self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk], [self.author_empty, self.author_proxy_notproxy, self.author_proxy_proxy, self.book_proxy_proxy_fk], ) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['DeleteModel', 'CreateModel']) # Right number/type of migrations for the Book model with a FK to # AAuthorProxyProxy? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AlterField']) # otherapp should depend on testapp. self.assertMigrationDependencies(changes, 'otherapp', 0, [('testapp', 'auto_1')]) # Now, test the pk table and field name. self.assertEqual( changes['otherapp'][0].operations[0].field.remote_field.model._meta.db_table, 'testapp_authorproxy', ) self.assertEqual(changes['otherapp'][0].operations[0].field.remote_field.field_name, 'author_ptr') def test_unmanaged_create(self): """The autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model changes = self.get_changes([self.author_empty], [self.author_empty, self.author_unmanaged]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="AuthorUnmanaged", options={"managed": False}) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty, self.author_unmanaged_managed] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="authorunmanaged", options={}) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. changes = self.get_changes( [self.author_empty, self.author_unmanaged_managed], [self.author_empty, self.author_unmanaged] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False}) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_unmanaged_default_pk, self.book]) # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'id') # Now, we test the custom pk field name changes = self.get_changes([], [self.author_unmanaged_custom_pk, self.book]) # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'pk_field') @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([self.custom_user], [self.custom_user, self.author_with_custom_user]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, [("__setting__", "AUTH_USER_MODEL")]) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state([self.custom_user, self.author_with_custom_user]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name='user') fk_field = changes['testapp'][0].operations[0].field to_model = '%s.%s' % ( fk_field.remote_field.model._meta.app_label, fk_field.remote_field.model._meta.object_name, ) self.assertEqual(to_model, 'thirdapp.CustomUser') def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" changes = self.get_changes([self.author_empty], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ changes = self.get_changes([self.author_name_deconstructible_1], [self.author_name_deconstructible_2]) # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" changes = self.get_changes([self.author_name_deconstructible_3], [self.author_name_deconstructible_4]) self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_3] ) self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_3] ) self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_3] ) self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_2] ) self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_arg] ) self.assertEqual(len(changes), 1) # Additional args should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_arg] ) self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_kwarg] ) self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_kwarg] ) self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, )) ], ) changes = self.get_changes([], [author]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ changes = self.get_changes([self.author_with_publisher_string], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publisher_name") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ changes = self.get_changes( [self.author_with_publisher, self.publisher], [self.author_name] ) # removes both the model and FK # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Publisher") @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" changes = self.get_changes([self.author_empty, self.publisher], [self.author_with_m2m, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_alter_many_to_many(self): changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_m2m_blank, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ changes = self.get_changes([], [self.author_with_m2m_through, self.publisher, self.contract]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ "CreateModel", "CreateModel", "CreateModel", "AddField", "AddField" ]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Contract") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="Publisher") self.assertOperationAttributes(changes, 'testapp', 0, 3, model_name='contract', name='publisher') self.assertOperationAttributes(changes, 'testapp', 0, 4, model_name='author', name='publishers') def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution], [self.book_with_no_author, self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveField", "RemoveField", "RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="author", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name="book", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 2, name="authors", model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 3, name='Attribution') def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution], [self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, [ "RemoveField", "RemoveField", "RemoveField", "DeleteModel", "DeleteModel" ]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="author", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name="book", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 2, name="authors", model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 3, name='Attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 4, name='Book') def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ changes = self.get_changes([self.author_with_m2m_through, self.publisher, self.contract], [self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ "RemoveField", "RemoveField", "RemoveField", "DeleteModel", "DeleteModel" ]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers", model_name='author') self.assertOperationAttributes(changes, "testapp", 0, 1, name="author", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 3, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 4, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ changes = self.get_changes([self.author_with_former_m2m], [self.author_with_m2m, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Publisher') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publishers", model_name='author') def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ changes = self.get_changes([self.author_with_m2m, self.publisher], [self.author_with_former_m2m]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "AddField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name='Publisher') self.assertOperationFieldAttributes(changes, 'testapp', 0, 1, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ changes = self.get_changes([self.author_with_publisher, self.publisher_with_author], []) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "RemoveField", "DeleteModel", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publisher", model_name='author') self.assertOperationAttributes(changes, "testapp", 0, 1, name="author", model_name='publisher') self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" changes = self.get_changes([self.author_empty], [self.author_with_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, options={ "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) # Changing them back to empty should also make a change changes = self.get_changes([self.author_with_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", options={}) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" changes = self.get_changes( [self.author_proxy, self.author_empty], [self.author_proxy_options, self.author_empty] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorproxy", options={ "verbose_name": "Super Author" }) def test_set_alter_order_with_respect_to(self): """Setting order_with_respect_to adds a field.""" changes = self.get_changes([self.book, self.author_with_book], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to="book") def test_add_alter_order_with_respect_to(self): """ Setting order_with_respect_to when adding the FK too does things in the right order. """ changes = self.get_changes([self.author_name], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name="book") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author", order_with_respect_to="book") def test_remove_alter_order_with_respect_to(self): """ Removing order_with_respect_to when removing the FK too does things in the right order. """ changes = self.get_changes([self.book, self.author_with_book_order_wrt], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo", "RemoveField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to=None) self.assertOperationAttributes(changes, 'testapp', 0, 1, model_name="author", name="book") def test_add_model_order_with_respect_to(self): """ Setting order_with_respect_to when adding the whole model does things in the right order. """ changes = self.get_changes([], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author", order_with_respect_to="book") self.assertNotIn("_order", [name for name, field in changes['testapp'][0].operations[0].fields]) def test_alter_model_managers(self): """ Changing the model managers adds a new operation. """ changes = self.get_changes([self.other_pony], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) self.assertEqual(changes['otherapp'][0].operations[0].managers[1][1].args, ('a', 'b', 1, 2)) self.assertEqual(changes['otherapp'][0].operations[0].managers[2][1].args, ('x', 'y', 3, 4)) def test_swappable_first_inheritance(self): """Swappable models get their CreateModel first.""" changes = self.get_changes([], [self.custom_user, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [self.custom_user_no_inherit, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") def test_bases_first(self): """Bases of other models come first.""" changes = self.get_changes([], [self.aardvark_based_on_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_multiple_bases(self): """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations.""" A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) changes = self.get_changes([], [A, B, C, D, E]) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, [ "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel" ]) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Bases of proxies come first.""" changes = self.get_changes([], [self.author_empty, self.author_proxy, self.author_proxy_proxy]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="AuthorProxy") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="AAuthorProxyProxy") def test_pk_fk_included(self): """ A relation used as the primary key is kept as part of CreateModel. """ changes = self.get_changes([], [self.aardvark_pk_fk_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_first_dependency(self): """ A dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = ["migrations"] autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "__first__")]) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ A dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = ["migrations"] autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "0002_second")]) def test_alter_fk_before_model_deletion(self): """ ForeignKeys are altered _before_ the model they used to refer to are deleted. """ changes = self.get_changes( [self.author_name, self.publisher_with_author], [self.aardvark_testapp, self.publisher_with_aardvark_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "AlterField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Aardvark") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - ForeignKeys correctly depend on other apps' models. """ changes = self.get_changes([self.author_name, self.book], [self.author_with_book, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="book") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "__first__")]) def test_circular_dependency_mixed_addcreate(self): """ #23315 - The dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ]) person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ]) apackage = ModelState("b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ]) country = ModelState("b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ]) changes = self.get_changes([], [address, person, apackage, country]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertOperationTypes(changes, 'b', 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState("a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE))], bases=(AbstractBaseUser, ) ) address = ModelState("b", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('a', 'auto_1'), ('b', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('__setting__', 'AUTH_USER_MODEL')]) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) tenant = ModelState("b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE))], bases=(AbstractBaseUser, ) ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ("parent1", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='children')) ]) changes = self.get_changes([], [person]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'a', 0, []) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ changes = self.get_changes([self.author_empty], [self.author_with_biography_blank]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition') def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ changes = self.get_changes([self.author_empty], [self.author_with_biography_non_blank]) self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0)
bsd-3-clause
BeATz-UnKNoWN/python-for-android
python3-alpha/python3-src/Lib/idlelib/IOBinding.py
46
19385
import os import types import sys import codecs import tempfile import tkinter.filedialog as tkFileDialog import tkinter.messagebox as tkMessageBox import re from tkinter import * from tkinter.simpledialog import askstring from idlelib.configHandler import idleConf from codecs import BOM_UTF8 # Try setting the locale, so that we can find out # what encoding to use try: import locale locale.setlocale(locale.LC_CTYPE, "") except (ImportError, locale.Error): pass # Encoding for file names filesystemencoding = sys.getfilesystemencoding() ### currently unused locale_encoding = 'ascii' if sys.platform == 'win32': # On Windows, we could use "mbcs". However, to give the user # a portable encoding name, we need to find the code page try: locale_encoding = locale.getdefaultlocale()[1] codecs.lookup(locale_encoding) except LookupError: pass else: try: # Different things can fail here: the locale module may not be # loaded, it may not offer nl_langinfo, or CODESET, or the # resulting codeset may be unknown to Python. We ignore all # these problems, falling back to ASCII locale_encoding = locale.nl_langinfo(locale.CODESET) if locale_encoding is None or locale_encoding is '': # situation occurs on Mac OS X locale_encoding = 'ascii' codecs.lookup(locale_encoding) except (NameError, AttributeError, LookupError): # Try getdefaultlocale: it parses environment variables, # which may give a clue. Unfortunately, getdefaultlocale has # bugs that can cause ValueError. try: locale_encoding = locale.getdefaultlocale()[1] if locale_encoding is None or locale_encoding is '': # situation occurs on Mac OS X locale_encoding = 'ascii' codecs.lookup(locale_encoding) except (ValueError, LookupError): pass locale_encoding = locale_encoding.lower() encoding = locale_encoding ### KBK 07Sep07 This is used all over IDLE, check! ### 'encoding' is used below in encode(), check! coding_re = re.compile("coding[:=]\s*([-\w_.]+)") def coding_spec(data): """Return the encoding declaration according to PEP 263. When checking encoded data, only the first two lines should be passed in to avoid a UnicodeDecodeError if the rest of the data is not unicode. The first two lines would contain the encoding specification. Raise a LookupError if the encoding is declared but unknown. """ if isinstance(data, bytes): # This encoding might be wrong. However, the coding # spec must be ASCII-only, so any non-ASCII characters # around here will be ignored. Decoding to Latin-1 should # never fail (except for memory outage) lines = data.decode('iso-8859-1') else: lines = data # consider only the first two lines if '\n' in lines: lst = lines.split('\n')[:2] elif '\r' in lines: lst = lines.split('\r')[:2] else: lst = list(lines) str = '\n'.join(lst) match = coding_re.search(str) if not match: return None name = match.group(1) try: codecs.lookup(name) except LookupError: # The standard encoding error does not indicate the encoding raise LookupError("Unknown encoding: "+name) return name class IOBinding: def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.__id_open = self.text.bind("<<open-window-from-file>>", self.open) self.__id_save = self.text.bind("<<save-window>>", self.save) self.__id_saveas = self.text.bind("<<save-window-as-file>>", self.save_as) self.__id_savecopy = self.text.bind("<<save-copy-of-window-as-file>>", self.save_a_copy) self.fileencoding = None self.__id_print = self.text.bind("<<print-window>>", self.print_window) def close(self): # Undo command bindings self.text.unbind("<<open-window-from-file>>", self.__id_open) self.text.unbind("<<save-window>>", self.__id_save) self.text.unbind("<<save-window-as-file>>",self.__id_saveas) self.text.unbind("<<save-copy-of-window-as-file>>", self.__id_savecopy) self.text.unbind("<<print-window>>", self.__id_print) # Break cycles self.editwin = None self.text = None self.filename_change_hook = None def get_saved(self): return self.editwin.get_saved() def set_saved(self, flag): self.editwin.set_saved(flag) def reset_undo(self): self.editwin.reset_undo() filename_change_hook = None def set_filename_change_hook(self, hook): self.filename_change_hook = hook filename = None dirname = None def set_filename(self, filename): if filename and os.path.isdir(filename): self.filename = None self.dirname = filename else: self.filename = filename self.dirname = None self.set_saved(1) if self.filename_change_hook: self.filename_change_hook() def open(self, event=None, editFile=None): if self.editwin.flist: if not editFile: filename = self.askopenfile() else: filename=editFile if filename: # If the current window has no filename and hasn't been # modified, we replace its contents (no loss). Otherwise # we open a new window. But we won't replace the # shell window (which has an interp(reter) attribute), which # gets set to "not modified" at every new prompt. try: interp = self.editwin.interp except AttributeError: interp = None if not self.filename and self.get_saved() and not interp: self.editwin.flist.open(filename, self.loadfile) else: self.editwin.flist.open(filename) else: self.text.focus_set() return "break" # # Code for use outside IDLE: if self.get_saved(): reply = self.maybesave() if reply == "cancel": self.text.focus_set() return "break" if not editFile: filename = self.askopenfile() else: filename=editFile if filename: self.loadfile(filename) else: self.text.focus_set() return "break" eol = r"(\r\n)|\n|\r" # \r\n (Windows), \n (UNIX), or \r (Mac) eol_re = re.compile(eol) eol_convention = os.linesep # default def loadfile(self, filename): try: # open the file in binary mode so that we can handle # end-of-line convention ourselves. f = open(filename,'rb') two_lines = f.readline() + f.readline() f.seek(0) bytes = f.read() f.close() except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False chars, converted = self._decode(two_lines, bytes) if chars is None: tkMessageBox.showerror("Decoding Error", "File %s\nFailed to Decode" % filename, parent=self.text) return False # We now convert all end-of-lines to '\n's firsteol = self.eol_re.search(chars) if firsteol: self.eol_convention = firsteol.group(0) chars = self.eol_re.sub(r"\n", chars) self.text.delete("1.0", "end") self.set_filename(None) self.text.insert("1.0", chars) self.reset_undo() self.set_filename(filename) if converted: # We need to save the conversion results first # before being able to execute the code self.set_saved(False) self.text.mark_set("insert", "1.0") self.text.yview("insert") self.updaterecentfileslist(filename) return True def _decode(self, two_lines, bytes): "Create a Unicode string." chars = None # Check presence of a UTF-8 signature first if bytes.startswith(BOM_UTF8): try: chars = bytes[3:].decode("utf-8") except UnicodeDecodeError: # has UTF-8 signature, but fails to decode... return None, False else: # Indicates that this file originally had a BOM self.fileencoding = 'BOM' return chars, False # Next look for coding specification try: enc = coding_spec(two_lines) except LookupError as name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ "installation. The file may not display correctly" % name, master = self.text) enc = None except UnicodeDecodeError: return None, False if enc: try: chars = str(bytes, enc) self.fileencoding = enc return chars, False except UnicodeDecodeError: pass # Try ascii: try: chars = str(bytes, 'ascii') self.fileencoding = None return chars, False except UnicodeDecodeError: pass # Try utf-8: try: chars = str(bytes, 'utf-8') self.fileencoding = 'utf-8' return chars, False except UnicodeDecodeError: pass # Finally, try the locale's encoding. This is deprecated; # the user should declare a non-ASCII encoding try: # Wait for the editor window to appear self.editwin.text.update() enc = askstring( "Specify file encoding", "The file's encoding is invalid for Python 3.x.\n" "IDLE will convert it to UTF-8.\n" "What is the current encoding of the file?", initialvalue = locale_encoding, parent = self.editwin.text) if enc: chars = str(bytes, enc) self.fileencoding = None return chars, True except (UnicodeDecodeError, LookupError): pass return None, False # None on failure def maybesave(self): if self.get_saved(): return "yes" message = "Do you want to save %s before closing?" % ( self.filename or "this untitled document") confirm = tkMessageBox.askyesnocancel( title="Save On Close", message=message, default=tkMessageBox.YES, master=self.text) if confirm: reply = "yes" self.save(None) if not self.get_saved(): reply = "cancel" elif confirm is None: reply = "cancel" else: reply = "no" self.text.focus_set() return reply def save(self, event): if not self.filename: self.save_as(event) else: if self.writefile(self.filename): self.set_saved(True) try: self.editwin.store_file_breaks() except AttributeError: # may be a PyShell pass self.text.focus_set() return "break" def save_as(self, event): filename = self.asksavefile() if filename: if self.writefile(filename): self.set_filename(filename) self.set_saved(1) try: self.editwin.store_file_breaks() except AttributeError: pass self.text.focus_set() self.updaterecentfileslist(filename) return "break" def save_a_copy(self, event): filename = self.asksavefile() if filename: self.writefile(filename) self.text.focus_set() self.updaterecentfileslist(filename) return "break" def writefile(self, filename): self.fixlastline() text = self.text.get("1.0", "end-1c") if self.eol_convention != "\n": text = text.replace("\n", self.eol_convention) chars = self.encode(text) try: f = open(filename, "wb") f.write(chars) f.flush() f.close() return True except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False def encode(self, chars): if isinstance(chars, bytes): # This is either plain ASCII, or Tk was returning mixed-encoding # text to us. Don't try to guess further. return chars # Preserve a BOM that might have been present on opening if self.fileencoding == 'BOM': return BOM_UTF8 + chars.encode("utf-8") # See whether there is anything non-ASCII in it. # If not, no need to figure out the encoding. try: return chars.encode('ascii') except UnicodeError: pass # Check if there is an encoding declared try: # a string, let coding_spec slice it to the first two lines enc = coding_spec(chars) failed = None except LookupError as msg: failed = msg enc = None else: if not enc: # PEP 3120: default source encoding is UTF-8 enc = 'utf-8' if enc: try: return chars.encode(enc) except UnicodeError: failed = "Invalid encoding '%s'" % enc tkMessageBox.showerror( "I/O Error", "%s.\nSaving as UTF-8" % failed, master = self.text) # Fallback: save as UTF-8, with BOM - ignoring the incorrect # declared encoding return BOM_UTF8 + chars.encode("utf-8") def fixlastline(self): c = self.text.get("end-2c") if c != '\n': self.text.insert("end-1c", "\n") def print_window(self, event): confirm = tkMessageBox.askokcancel( title="Print", message="Print to Default Printer", default=tkMessageBox.OK, master=self.text) if not confirm: self.text.focus_set() return "break" tempfilename = None saved = self.get_saved() if saved: filename = self.filename # shell undo is reset after every prompt, looks saved, probably isn't if not saved or filename is None: (tfd, tempfilename) = tempfile.mkstemp(prefix='IDLE_tmp_') filename = tempfilename os.close(tfd) if not self.writefile(tempfilename): os.unlink(tempfilename) return "break" platform = os.name printPlatform = True if platform == 'posix': #posix platform command = idleConf.GetOption('main','General', 'print-command-posix') command = command + " 2>&1" elif platform == 'nt': #win32 platform command = idleConf.GetOption('main','General','print-command-win') else: #no printing for this platform printPlatform = False if printPlatform: #we can try to print for this platform command = command % filename pipe = os.popen(command, "r") # things can get ugly on NT if there is no printer available. output = pipe.read().strip() status = pipe.close() if status: output = "Printing failed (exit status 0x%x)\n" % \ status + output if output: output = "Printing command: %s\n" % repr(command) + output tkMessageBox.showerror("Print status", output, master=self.text) else: #no printing for this platform message = "Printing is not enabled for this platform: %s" % platform tkMessageBox.showinfo("Print status", message, master=self.text) if tempfilename: os.unlink(tempfilename) return "break" opendialog = None savedialog = None filetypes = [ ("Python files", "*.py *.pyw", "TEXT"), ("Text files", "*.txt", "TEXT"), ("All files", "*"), ] def askopenfile(self): dir, base = self.defaultfilename("open") if not self.opendialog: self.opendialog = tkFileDialog.Open(master=self.text, filetypes=self.filetypes) filename = self.opendialog.show(initialdir=dir, initialfile=base) return filename def defaultfilename(self, mode="open"): if self.filename: return os.path.split(self.filename) elif self.dirname: return self.dirname, "" else: try: pwd = os.getcwd() except os.error: pwd = "" return pwd, "" def asksavefile(self): dir, base = self.defaultfilename("save") if not self.savedialog: self.savedialog = tkFileDialog.SaveAs(master=self.text, filetypes=self.filetypes) filename = self.savedialog.show(initialdir=dir, initialfile=base) return filename def updaterecentfileslist(self,filename): "Update recent file list on all editor windows" if self.editwin.flist: self.editwin.update_recent_files_list(filename) def test(): root = Tk() class MyEditWin: def __init__(self, text): self.text = text self.flist = None self.text.bind("<Control-o>", self.open) self.text.bind("<Control-s>", self.save) self.text.bind("<Alt-s>", self.save_as) self.text.bind("<Alt-z>", self.save_a_copy) def get_saved(self): return 0 def set_saved(self, flag): pass def reset_undo(self): pass def open(self, event): self.text.event_generate("<<open-window-from-file>>") def save(self, event): self.text.event_generate("<<save-window>>") def save_as(self, event): self.text.event_generate("<<save-window-as-file>>") def save_a_copy(self, event): self.text.event_generate("<<save-copy-of-window-as-file>>") text = Text(root) text.pack() text.focus_set() editwin = MyEditWin(text) io = IOBinding(editwin) root.mainloop() if __name__ == "__main__": test()
apache-2.0
alexgleith/Quantum-GIS
python/pyplugin_installer/qgsplugininstallerfetchingdialog.py
9
3223
# -*- coding:utf-8 -*- """ /*************************************************************************** qgsplugininstallerfetchingdialog.py Plugin Installer module ------------------- Date : June 2013 Copyright : (C) 2013 by Borys Jurgiel Email : info at borysjurgiel dot pl This module is based on former plugin_installer plugin: Copyright (C) 2007-2008 Matthew Perry Copyright (C) 2008-2013 Borys Jurgiel ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ import sys import time from PyQt4.QtGui import * from ui_qgsplugininstallerfetchingbase import Ui_QgsPluginInstallerFetchingDialogBase from installer_data import * class QgsPluginInstallerFetchingDialog(QDialog, Ui_QgsPluginInstallerFetchingDialogBase): # ----------------------------------------- # def __init__(self, parent): QDialog.__init__(self, parent) self.setupUi(self) self.progressBar.setRange(0,len(repositories.allEnabled())*100) self.itemProgress = {} self.item = {} for key in repositories.allEnabled(): self.item[key] = QTreeWidgetItem(self.treeWidget) self.item[key].setText(0,key) if repositories.all()[key]["state"] > 1: self.itemProgress[key] = 100 self.displayState(key,0) else: self.itemProgress[key] = 0 self.displayState(key,2) self.treeWidget.resizeColumnToContents(0) repositories.repositoryFetched.connect(self.repositoryFetched) repositories.anythingChanged.connect(self.displayState) # ----------------------------------------- # def displayState(self,key,state,state2=None): messages=[self.tr("Success"),self.tr("Resolving host name..."),self.tr("Connecting..."),self.tr("Host connected. Sending request..."),self.tr("Downloading data..."),self.tr("Idle"),self.tr("Closing connection..."),self.tr("Error")] message = messages[state] if state2: message += " (%s%%)" % state2 self.item[key].setText(1,message) if state == 4 and state2: self.itemProgress[key] = state2 totalProgress = sum(self.itemProgress.values()) self.progressBar.setValue(totalProgress) # ----------------------------------------- # def repositoryFetched(self, repoName): self.itemProgress[repoName] = 100 if repositories.all()[repoName]["state"] == 2: self.displayState(repoName,0) else: self.displayState(repoName,7) if not repositories.fetchingInProgress(): self.close()
gpl-2.0
KaranToor/MA450
google-cloud-sdk/lib/googlecloudsdk/third_party/apis/runtimeconfig/v1beta1/runtimeconfig_v1beta1_client.py
2
29576
"""Generated client library for runtimeconfig version v1beta1.""" # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.py import base_api from googlecloudsdk.third_party.apis.runtimeconfig.v1beta1 import runtimeconfig_v1beta1_messages as messages class RuntimeconfigV1beta1(base_api.BaseApiClient): """Generated client library for service runtimeconfig version v1beta1.""" MESSAGES_MODULE = messages BASE_URL = u'https://runtimeconfig.googleapis.com/' _PACKAGE = u'runtimeconfig' _SCOPES = [u'https://www.googleapis.com/auth/cloud-platform', u'https://www.googleapis.com/auth/cloudruntimeconfig'] _VERSION = u'v1beta1' _CLIENT_ID = '1042881264118.apps.googleusercontent.com' _CLIENT_SECRET = 'x_Tw5K8nnjoRAqULM9PFAC2b' _USER_AGENT = 'x_Tw5K8nnjoRAqULM9PFAC2b' _CLIENT_CLASS_NAME = u'RuntimeconfigV1beta1' _URL_VERSION = u'v1beta1' _API_KEY = None def __init__(self, url='', credentials=None, get_credentials=True, http=None, model=None, log_request=False, log_response=False, credentials_args=None, default_global_params=None, additional_http_headers=None): """Create a new runtimeconfig handle.""" url = url or self.BASE_URL super(RuntimeconfigV1beta1, self).__init__( url, credentials=credentials, get_credentials=get_credentials, http=http, model=model, log_request=log_request, log_response=log_response, credentials_args=credentials_args, default_global_params=default_global_params, additional_http_headers=additional_http_headers) self.projects_configs_operations = self.ProjectsConfigsOperationsService(self) self.projects_configs_variables = self.ProjectsConfigsVariablesService(self) self.projects_configs_waiters = self.ProjectsConfigsWaitersService(self) self.projects_configs = self.ProjectsConfigsService(self) self.projects = self.ProjectsService(self) class ProjectsConfigsOperationsService(base_api.BaseApiService): """Service class for the projects_configs_operations resource.""" _NAME = u'projects_configs_operations' def __init__(self, client): super(RuntimeconfigV1beta1.ProjectsConfigsOperationsService, self).__init__(client) self._upload_configs = { } def Get(self, request, global_params=None): """Gets the latest state of a long-running operation. Clients can use this. method to poll the operation result at intervals as recommended by the API service. Args: request: (RuntimeconfigProjectsConfigsOperationsGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Operation) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/operations/{operationsId}', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.operations.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsOperationsGetRequest', response_type_name=u'Operation', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Args: request: (RuntimeconfigProjectsConfigsOperationsTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/operations/{operationsId}:testIamPermissions', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.operations.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[u'permissions'], relative_path=u'v1beta1/{+resource}:testIamPermissions', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsOperationsTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) class ProjectsConfigsVariablesService(base_api.BaseApiService): """Service class for the projects_configs_variables resource.""" _NAME = u'projects_configs_variables' def __init__(self, client): super(RuntimeconfigV1beta1.ProjectsConfigsVariablesService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a variable within the given configuration. You cannot create. a variable with a name that is a prefix of an existing variable name, or a name that has an existing variable name as a prefix. To learn more about creating a variable, read the [Setting and Getting Data](/deployment-manager/runtime-configurator/set-and-get-variables) documentation. Args: request: (RuntimeconfigProjectsConfigsVariablesCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Variable) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.variables.create', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'requestId'], relative_path=u'v1beta1/{+parent}/variables', request_field=u'variable', request_type_name=u'RuntimeconfigProjectsConfigsVariablesCreateRequest', response_type_name=u'Variable', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes a variable or multiple variables. If you specify a variable name, then that variable is deleted. If you specify a prefix and `recursive` is true, then all variables with that prefix are deleted. You must set a `recursive` to true if you delete variables by prefix. Args: request: (RuntimeconfigProjectsConfigsVariablesDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables/{variablesId}', http_method=u'DELETE', method_id=u'runtimeconfig.projects.configs.variables.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'recursive'], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsVariablesDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Gets information about a single variable. Args: request: (RuntimeconfigProjectsConfigsVariablesGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Variable) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables/{variablesId}', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.variables.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsVariablesGetRequest', response_type_name=u'Variable', supports_download=False, ) def List(self, request, global_params=None): """Lists variables within given a configuration, matching any provided filters. This only lists variable names, not the values. Args: request: (RuntimeconfigProjectsConfigsVariablesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListVariablesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.variables.list', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'filter', u'pageSize', u'pageToken'], relative_path=u'v1beta1/{+parent}/variables', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsVariablesListRequest', response_type_name=u'ListVariablesResponse', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Args: request: (RuntimeconfigProjectsConfigsVariablesTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables/{variablesId}:testIamPermissions', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.variables.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[u'permissions'], relative_path=u'v1beta1/{+resource}:testIamPermissions', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsVariablesTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) def Update(self, request, global_params=None): """Updates an existing variable with a new value. Args: request: (Variable) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Variable) The response message. """ config = self.GetMethodConfig('Update') return self._RunMethod( config, request, global_params=global_params) Update.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables/{variablesId}', http_method=u'PUT', method_id=u'runtimeconfig.projects.configs.variables.update', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='<request>', request_type_name=u'Variable', response_type_name=u'Variable', supports_download=False, ) def Watch(self, request, global_params=None): """Watches a specific variable and waits for a change in the variable's value. When there is a change, this method returns the new value or times out. If a variable is deleted while being watched, the `variableState` state is set to `DELETED` and the method returns the last known variable `value`. If you set the deadline for watching to a larger value than internal timeout (60 seconds), the current variable value is returned and the `variableState` will be `VARIABLE_STATE_UNSPECIFIED`. To learn more about creating a watcher, read the [Watching a Variable for Changes](/deployment-manager/runtime-configurator/watching-a-variable) documentation. Args: request: (RuntimeconfigProjectsConfigsVariablesWatchRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Variable) The response message. """ config = self.GetMethodConfig('Watch') return self._RunMethod( config, request, global_params=global_params) Watch.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/variables/{variablesId}:watch', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.variables.watch', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}:watch', request_field=u'watchVariableRequest', request_type_name=u'RuntimeconfigProjectsConfigsVariablesWatchRequest', response_type_name=u'Variable', supports_download=False, ) class ProjectsConfigsWaitersService(base_api.BaseApiService): """Service class for the projects_configs_waiters resource.""" _NAME = u'projects_configs_waiters' def __init__(self, client): super(RuntimeconfigV1beta1.ProjectsConfigsWaitersService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a Waiter resource. This operation returns a long-running Operation. resource which can be polled for completion. However, a waiter with the given name will exist (and can be retrieved) prior to the operation completing. If the operation fails, the failed Waiter resource will still exist and must be deleted prior to subsequent creation attempts. Args: request: (RuntimeconfigProjectsConfigsWaitersCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Operation) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/waiters', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.waiters.create', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'requestId'], relative_path=u'v1beta1/{+parent}/waiters', request_field=u'waiter', request_type_name=u'RuntimeconfigProjectsConfigsWaitersCreateRequest', response_type_name=u'Operation', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes the waiter with the specified name. Args: request: (RuntimeconfigProjectsConfigsWaitersDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/waiters/{waitersId}', http_method=u'DELETE', method_id=u'runtimeconfig.projects.configs.waiters.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsWaitersDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Gets information about a single waiter. Args: request: (RuntimeconfigProjectsConfigsWaitersGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Waiter) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/waiters/{waitersId}', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.waiters.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsWaitersGetRequest', response_type_name=u'Waiter', supports_download=False, ) def List(self, request, global_params=None): """List waiters within the given configuration. Args: request: (RuntimeconfigProjectsConfigsWaitersListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListWaitersResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/waiters', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.waiters.list', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'pageSize', u'pageToken'], relative_path=u'v1beta1/{+parent}/waiters', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsWaitersListRequest', response_type_name=u'ListWaitersResponse', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Args: request: (RuntimeconfigProjectsConfigsWaitersTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/waiters/{waitersId}:testIamPermissions', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.waiters.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[u'permissions'], relative_path=u'v1beta1/{+resource}:testIamPermissions', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsWaitersTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) class ProjectsConfigsService(base_api.BaseApiService): """Service class for the projects_configs resource.""" _NAME = u'projects_configs' def __init__(self, client): super(RuntimeconfigV1beta1.ProjectsConfigsService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a new RuntimeConfig resource. The configuration name must be. unique within project. Args: request: (RuntimeconfigProjectsConfigsCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (RuntimeConfig) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.create', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'requestId'], relative_path=u'v1beta1/{+parent}/configs', request_field=u'runtimeConfig', request_type_name=u'RuntimeconfigProjectsConfigsCreateRequest', response_type_name=u'RuntimeConfig', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes a RuntimeConfig resource. Args: request: (RuntimeconfigProjectsConfigsDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}', http_method=u'DELETE', method_id=u'runtimeconfig.projects.configs.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Gets information about a RuntimeConfig resource. Args: request: (RuntimeconfigProjectsConfigsGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (RuntimeConfig) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsGetRequest', response_type_name=u'RuntimeConfig', supports_download=False, ) def GetIamPolicy(self, request, global_params=None): """Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set. Args: request: (RuntimeconfigProjectsConfigsGetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('GetIamPolicy') return self._RunMethod( config, request, global_params=global_params) GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}:getIamPolicy', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.getIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1beta1/{+resource}:getIamPolicy', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsGetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def List(self, request, global_params=None): """Lists all the RuntimeConfig resources within project. Args: request: (RuntimeconfigProjectsConfigsListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListConfigsResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs', http_method=u'GET', method_id=u'runtimeconfig.projects.configs.list', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'pageSize', u'pageToken'], relative_path=u'v1beta1/{+parent}/configs', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsListRequest', response_type_name=u'ListConfigsResponse', supports_download=False, ) def SetIamPolicy(self, request, global_params=None): """Sets the access control policy on the specified resource. Replaces any. existing policy. Args: request: (RuntimeconfigProjectsConfigsSetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('SetIamPolicy') return self._RunMethod( config, request, global_params=global_params) SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}:setIamPolicy', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.setIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1beta1/{+resource}:setIamPolicy', request_field=u'setIamPolicyRequest', request_type_name=u'RuntimeconfigProjectsConfigsSetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Args: request: (RuntimeconfigProjectsConfigsTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}:testIamPermissions', http_method=u'POST', method_id=u'runtimeconfig.projects.configs.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1beta1/{+resource}:testIamPermissions', request_field=u'testIamPermissionsRequest', request_type_name=u'RuntimeconfigProjectsConfigsTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) def Update(self, request, global_params=None): """Updates a RuntimeConfig resource. The configuration must exist beforehand. Args: request: (RuntimeConfig) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (RuntimeConfig) The response message. """ config = self.GetMethodConfig('Update') return self._RunMethod( config, request, global_params=global_params) Update.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1beta1/projects/{projectsId}/configs/{configsId}', http_method=u'PUT', method_id=u'runtimeconfig.projects.configs.update', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1beta1/{+name}', request_field='<request>', request_type_name=u'RuntimeConfig', response_type_name=u'RuntimeConfig', supports_download=False, ) class ProjectsService(base_api.BaseApiService): """Service class for the projects resource.""" _NAME = u'projects' def __init__(self, client): super(RuntimeconfigV1beta1.ProjectsService, self).__init__(client) self._upload_configs = { }
apache-2.0
citrix-openstack-build/nova
nova/openstack/common/notifier/rpc_notifier.py
14
1694
# Copyright 2011 OpenStack Foundation. # 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. from oslo.config import cfg from nova.openstack.common import context as req_context from nova.openstack.common.gettextutils import _ # noqa from nova.openstack.common import log as logging from nova.openstack.common import rpc LOG = logging.getLogger(__name__) notification_topic_opt = cfg.ListOpt( 'notification_topics', default=['notifications', ], help='AMQP topic used for OpenStack notifications') CONF = cfg.CONF CONF.register_opt(notification_topic_opt) def notify(context, message): """Sends a notification via RPC.""" if not context: context = req_context.get_admin_context() priority = message.get('priority', CONF.default_notification_level) priority = priority.lower() for topic in CONF.notification_topics: topic = '%s.%s' % (topic, priority) try: rpc.notify(context, topic, message) except Exception: LOG.exception(_("Could not send notification to %(topic)s. " "Payload=%(message)s"), locals())
apache-2.0
Etwigg/Examples
Group Project Website/venv/Lib/site-packages/werkzeug/routing.py
87
66746
# -*- coding: utf-8 -*- """ werkzeug.routing ~~~~~~~~~~~~~~~~ When it comes to combining multiple controller or view functions (however you want to call them) you need a dispatcher. A simple way would be applying regular expression tests on the ``PATH_INFO`` and calling registered callback functions that return the value then. This module implements a much more powerful system than simple regular expression matching because it can also convert values in the URLs and build URLs. Here a simple example that creates an URL map for an application with two subdomains (www and kb) and some URL rules: >>> m = Map([ ... # Static URLs ... Rule('/', endpoint='static/index'), ... Rule('/about', endpoint='static/about'), ... Rule('/help', endpoint='static/help'), ... # Knowledge Base ... Subdomain('kb', [ ... Rule('/', endpoint='kb/index'), ... Rule('/browse/', endpoint='kb/browse'), ... Rule('/browse/<int:id>/', endpoint='kb/browse'), ... Rule('/browse/<int:id>/<int:page>', endpoint='kb/browse') ... ]) ... ], default_subdomain='www') If the application doesn't use subdomains it's perfectly fine to not set the default subdomain and not use the `Subdomain` rule factory. The endpoint in the rules can be anything, for example import paths or unique identifiers. The WSGI application can use those endpoints to get the handler for that URL. It doesn't have to be a string at all but it's recommended. Now it's possible to create a URL adapter for one of the subdomains and build URLs: >>> c = m.bind('example.com') >>> c.build("kb/browse", dict(id=42)) 'http://kb.example.com/browse/42/' >>> c.build("kb/browse", dict()) 'http://kb.example.com/browse/' >>> c.build("kb/browse", dict(id=42, page=3)) 'http://kb.example.com/browse/42/3' >>> c.build("static/about") '/about' >>> c.build("static/index", force_external=True) 'http://www.example.com/' >>> c = m.bind('example.com', subdomain='kb') >>> c.build("static/about") 'http://www.example.com/about' The first argument to bind is the server name *without* the subdomain. Per default it will assume that the script is mounted on the root, but often that's not the case so you can provide the real mount point as second argument: >>> c = m.bind('example.com', '/applications/example') The third argument can be the subdomain, if not given the default subdomain is used. For more details about binding have a look at the documentation of the `MapAdapter`. And here is how you can match URLs: >>> c = m.bind('example.com') >>> c.match("/") ('static/index', {}) >>> c.match("/about") ('static/about', {}) >>> c = m.bind('example.com', '/', 'kb') >>> c.match("/") ('kb/index', {}) >>> c.match("/browse/42/23") ('kb/browse', {'id': 42, 'page': 23}) If matching fails you get a `NotFound` exception, if the rule thinks it's a good idea to redirect (for example because the URL was defined to have a slash at the end but the request was missing that slash) it will raise a `RequestRedirect` exception. Both are subclasses of the `HTTPException` so you can use those errors as responses in the application. If matching succeeded but the URL rule was incompatible to the given method (for example there were only rules for `GET` and `HEAD` and routing system tried to match a `POST` request) a `MethodNotAllowed` exception is raised. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import difflib import re import uuid import posixpath from pprint import pformat from threading import Lock from werkzeug.urls import url_encode, url_quote, url_join from werkzeug.utils import redirect, format_string from werkzeug.exceptions import HTTPException, NotFound, MethodNotAllowed, \ BadHost from werkzeug._internal import _get_environ, _encode_idna from werkzeug._compat import itervalues, iteritems, to_unicode, to_bytes, \ text_type, string_types, native_string_result, \ implements_to_string, wsgi_decoding_dance from werkzeug.datastructures import ImmutableDict, MultiDict from werkzeug.utils import cached_property _rule_re = re.compile(r''' (?P<static>[^<]*) # static rule data < (?: (?P<converter>[a-zA-Z_][a-zA-Z0-9_]*) # converter name (?:\((?P<args>.*?)\))? # converter arguments \: # variable delimiter )? (?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name > ''', re.VERBOSE) _simple_rule_re = re.compile(r'<([^>]+)>') _converter_args_re = re.compile(r''' ((?P<name>\w+)\s*=\s*)? (?P<value> True|False| \d+.\d+| \d+.| \d+| \w+| [urUR]?(?P<stringval>"[^"]*?"|'[^']*') )\s*, ''', re.VERBOSE | re.UNICODE) _PYTHON_CONSTANTS = { 'None': None, 'True': True, 'False': False } def _pythonize(value): if value in _PYTHON_CONSTANTS: return _PYTHON_CONSTANTS[value] for convert in int, float: try: return convert(value) except ValueError: pass if value[:1] == value[-1:] and value[0] in '"\'': value = value[1:-1] return text_type(value) def parse_converter_args(argstr): argstr += ',' args = [] kwargs = {} for item in _converter_args_re.finditer(argstr): value = item.group('stringval') if value is None: value = item.group('value') value = _pythonize(value) if not item.group('name'): args.append(value) else: name = item.group('name') kwargs[name] = value return tuple(args), kwargs def parse_rule(rule): """Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal: """ pos = 0 end = len(rule) do_match = _rule_re.match used_names = set() while pos < end: m = do_match(rule, pos) if m is None: break data = m.groupdict() if data['static']: yield None, None, data['static'] variable = data['variable'] converter = data['converter'] or 'default' if variable in used_names: raise ValueError('variable name %r used twice.' % variable) used_names.add(variable) yield converter, data['args'] or None, variable pos = m.end() if pos < end: remaining = rule[pos:] if '>' in remaining or '<' in remaining: raise ValueError('malformed url rule: %r' % rule) yield None, None, remaining class RoutingException(Exception): """Special exceptions that require the application to redirect, notifying about missing urls, etc. :internal: """ class RequestRedirect(HTTPException, RoutingException): """Raise if the map requests a redirect. This is for example the case if `strict_slashes` are activated and an url that requires a trailing slash. The attribute `new_url` contains the absolute destination url. """ code = 301 def __init__(self, new_url): RoutingException.__init__(self, new_url) self.new_url = new_url def get_response(self, environ): return redirect(self.new_url, self.code) class RequestSlash(RoutingException): """Internal exception.""" class RequestAliasRedirect(RoutingException): """This rule is an alias and wants to redirect to the canonical URL.""" def __init__(self, matched_values): self.matched_values = matched_values @implements_to_string class BuildError(RoutingException, LookupError): """Raised if the build system cannot find a URL for an endpoint with the values provided. """ def __init__(self, endpoint, values, method, adapter=None): LookupError.__init__(self, endpoint, values, method) self.endpoint = endpoint self.values = values self.method = method self.adapter = adapter @cached_property def suggested(self): return self.closest_rule(self.adapter) def closest_rule(self, adapter): def _score_rule(rule): return sum([ 0.98 * difflib.SequenceMatcher( None, rule.endpoint, self.endpoint ).ratio(), 0.01 * bool(set(self.values or ()).issubset(rule.arguments)), 0.01 * bool(rule.methods and self.method in rule.methods) ]) if adapter and adapter.map._rules: return max(adapter.map._rules, key=_score_rule) def __str__(self): message = [] message.append('Could not build url for endpoint %r' % self.endpoint) if self.method: message.append(' (%r)' % self.method) if self.values: message.append(' with values %r' % sorted(self.values.keys())) message.append('.') if self.suggested: if self.endpoint == self.suggested.endpoint: if self.method and self.method not in self.suggested.methods: message.append(' Did you mean to use methods %r?' % sorted( self.suggested.methods )) missing_values = self.suggested.arguments.union( set(self.suggested.defaults or ()) ) - set(self.values.keys()) if missing_values: message.append( ' Did you forget to specify values %r?' % sorted(missing_values) ) else: message.append( ' Did you mean %r instead?' % self.suggested.endpoint ) return u''.join(message) class ValidationError(ValueError): """Validation error. If a rule converter raises this exception the rule does not match the current URL and the next URL is tried. """ class RuleFactory(object): """As soon as you have more complex URL setups it's a good idea to use rule factories to avoid repetitive tasks. Some of them are builtin, others can be added by subclassing `RuleFactory` and overriding `get_rules`. """ def get_rules(self, map): """Subclasses of `RuleFactory` have to override this method and return an iterable of rules.""" raise NotImplementedError() class Subdomain(RuleFactory): """All URLs provided by this factory have the subdomain set to a specific domain. For example if you want to use the subdomain for the current language this can be a good setup:: url_map = Map([ Rule('/', endpoint='#select_language'), Subdomain('<string(length=2):lang_code>', [ Rule('/', endpoint='index'), Rule('/about', endpoint='about'), Rule('/help', endpoint='help') ]) ]) All the rules except for the ``'#select_language'`` endpoint will now listen on a two letter long subdomain that holds the language code for the current request. """ def __init__(self, subdomain, rules): self.subdomain = subdomain self.rules = rules def get_rules(self, map): for rulefactory in self.rules: for rule in rulefactory.get_rules(map): rule = rule.empty() rule.subdomain = self.subdomain yield rule class Submount(RuleFactory): """Like `Subdomain` but prefixes the URL rule with a given string:: url_map = Map([ Rule('/', endpoint='index'), Submount('/blog', [ Rule('/', endpoint='blog/index'), Rule('/entry/<entry_slug>', endpoint='blog/show') ]) ]) Now the rule ``'blog/show'`` matches ``/blog/entry/<entry_slug>``. """ def __init__(self, path, rules): self.path = path.rstrip('/') self.rules = rules def get_rules(self, map): for rulefactory in self.rules: for rule in rulefactory.get_rules(map): rule = rule.empty() rule.rule = self.path + rule.rule yield rule class EndpointPrefix(RuleFactory): """Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications:: url_map = Map([ Rule('/', endpoint='index'), EndpointPrefix('blog/', [Submount('/blog', [ Rule('/', endpoint='index'), Rule('/entry/<entry_slug>', endpoint='show') ])]) ]) """ def __init__(self, prefix, rules): self.prefix = prefix self.rules = rules def get_rules(self, map): for rulefactory in self.rules: for rule in rulefactory.get_rules(map): rule = rule.empty() rule.endpoint = self.prefix + rule.endpoint yield rule class RuleTemplate(object): """Returns copies of the rules wrapped and expands string templates in the endpoint, rule, defaults or subdomain sections. Here a small example for such a rule template:: from werkzeug.routing import Map, Rule, RuleTemplate resource = RuleTemplate([ Rule('/$name/', endpoint='$name.list'), Rule('/$name/<int:id>', endpoint='$name.show') ]) url_map = Map([resource(name='user'), resource(name='page')]) When a rule template is called the keyword arguments are used to replace the placeholders in all the string parameters. """ def __init__(self, rules): self.rules = list(rules) def __call__(self, *args, **kwargs): return RuleTemplateFactory(self.rules, dict(*args, **kwargs)) class RuleTemplateFactory(RuleFactory): """A factory that fills in template variables into rules. Used by `RuleTemplate` internally. :internal: """ def __init__(self, rules, context): self.rules = rules self.context = context def get_rules(self, map): for rulefactory in self.rules: for rule in rulefactory.get_rules(map): new_defaults = subdomain = None if rule.defaults: new_defaults = {} for key, value in iteritems(rule.defaults): if isinstance(value, string_types): value = format_string(value, self.context) new_defaults[key] = value if rule.subdomain is not None: subdomain = format_string(rule.subdomain, self.context) new_endpoint = rule.endpoint if isinstance(new_endpoint, string_types): new_endpoint = format_string(new_endpoint, self.context) yield Rule( format_string(rule.rule, self.context), new_defaults, subdomain, rule.methods, rule.build_only, new_endpoint, rule.strict_slashes ) @implements_to_string class Rule(RuleFactory): """A Rule represents one URL pattern. There are some options for `Rule` that change the way it behaves and are passed to the `Rule` constructor. Note that besides the rule-string all arguments *must* be keyword arguments in order to not break the application on Werkzeug upgrades. `string` Rule strings basically are just normal URL paths with placeholders in the format ``<converter(arguments):name>`` where the converter and the arguments are optional. If no converter is defined the `default` converter is used which means `string` in the normal configuration. URL rules that end with a slash are branch URLs, others are leaves. If you have `strict_slashes` enabled (which is the default), all branch URLs that are matched without a trailing slash will trigger a redirect to the same URL with the missing slash appended. The converters are defined on the `Map`. `endpoint` The endpoint for this rule. This can be anything. A reference to a function, a string, a number etc. The preferred way is using a string because the endpoint is used for URL generation. `defaults` An optional dict with defaults for other rules with the same endpoint. This is a bit tricky but useful if you want to have unique URLs:: url_map = Map([ Rule('/all/', defaults={'page': 1}, endpoint='all_entries'), Rule('/all/page/<int:page>', endpoint='all_entries') ]) If a user now visits ``http://example.com/all/page/1`` he will be redirected to ``http://example.com/all/``. If `redirect_defaults` is disabled on the `Map` instance this will only affect the URL generation. `subdomain` The subdomain rule string for this rule. If not specified the rule only matches for the `default_subdomain` of the map. If the map is not bound to a subdomain this feature is disabled. Can be useful if you want to have user profiles on different subdomains and all subdomains are forwarded to your application:: url_map = Map([ Rule('/', subdomain='<username>', endpoint='user/homepage'), Rule('/stats', subdomain='<username>', endpoint='user/stats') ]) `methods` A sequence of http methods this rule applies to. If not specified, all methods are allowed. For example this can be useful if you want different endpoints for `POST` and `GET`. If methods are defined and the path matches but the method matched against is not in this list or in the list of another rule for that path the error raised is of the type `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the list of methods and `HEAD` is not, `HEAD` is added automatically. .. versionchanged:: 0.6.1 `HEAD` is now automatically added to the methods if `GET` is present. The reason for this is that existing code often did not work properly in servers not rewriting `HEAD` to `GET` automatically and it was not documented how `HEAD` should be treated. This was considered a bug in Werkzeug because of that. `strict_slashes` Override the `Map` setting for `strict_slashes` only for this rule. If not specified the `Map` setting is used. `build_only` Set this to True and the rule will never match but will create a URL that can be build. This is useful if you have resources on a subdomain or folder that are not handled by the WSGI application (like static data) `redirect_to` If given this must be either a string or callable. In case of a callable it's called with the url adapter that triggered the match and the values of the URL as keyword arguments and has to return the target for the redirect, otherwise it has to be a string with placeholders in rule syntax:: def foo_with_slug(adapter, id): # ask the database for the slug for the old id. this of # course has nothing to do with werkzeug. return 'foo/' + Foo.get_slug_for_id(id) url_map = Map([ Rule('/foo/<slug>', endpoint='foo'), Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'), Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug) ]) When the rule is matched the routing system will raise a `RequestRedirect` exception with the target for the redirect. Keep in mind that the URL will be joined against the URL root of the script so don't use a leading slash on the target URL unless you really mean root of that domain. `alias` If enabled this rule serves as an alias for another rule with the same endpoint and arguments. `host` If provided and the URL map has host matching enabled this can be used to provide a match rule for the whole host. This also means that the subdomain feature is disabled. .. versionadded:: 0.7 The `alias` and `host` parameters were added. """ def __init__(self, string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, redirect_to=None, alias=False, host=None): if not string.startswith('/'): raise ValueError('urls must start with a leading slash') self.rule = string self.is_leaf = not string.endswith('/') self.map = None self.strict_slashes = strict_slashes self.subdomain = subdomain self.host = host self.defaults = defaults self.build_only = build_only self.alias = alias if methods is None: self.methods = None else: if isinstance(methods, str): raise TypeError('param `methods` should be `Iterable[str]`, not `str`') self.methods = set([x.upper() for x in methods]) if 'HEAD' not in self.methods and 'GET' in self.methods: self.methods.add('HEAD') self.endpoint = endpoint self.redirect_to = redirect_to if defaults: self.arguments = set(map(str, defaults)) else: self.arguments = set() self._trace = self._converters = self._regex = self._weights = None def empty(self): """ Return an unbound copy of this rule. This can be useful if want to reuse an already bound URL for another map. See ``get_empty_kwargs`` to override what keyword arguments are provided to the new copy. """ return type(self)(self.rule, **self.get_empty_kwargs()) def get_empty_kwargs(self): """ Provides kwargs for instantiating empty copy with empty() Use this method to provide custom keyword arguments to the subclass of ``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass has custom keyword arguments that are needed at instantiation. Must return a ``dict`` that will be provided as kwargs to the new instance of ``Rule``, following the initial ``self.rule`` value which is always provided as the first, required positional argument. """ defaults = None if self.defaults: defaults = dict(self.defaults) return dict(defaults=defaults, subdomain=self.subdomain, methods=self.methods, build_only=self.build_only, endpoint=self.endpoint, strict_slashes=self.strict_slashes, redirect_to=self.redirect_to, alias=self.alias, host=self.host) def get_rules(self, map): yield self def refresh(self): """Rebinds and refreshes the URL. Call this if you modified the rule in place. :internal: """ self.bind(self.map, rebind=True) def bind(self, map, rebind=False): """Bind the url to a map and create a regular expression based on the information from the rule itself and the defaults from the map. :internal: """ if self.map is not None and not rebind: raise RuntimeError('url rule %r already bound to map %r' % (self, self.map)) self.map = map if self.strict_slashes is None: self.strict_slashes = map.strict_slashes if self.subdomain is None: self.subdomain = map.default_subdomain self.compile() def get_converter(self, variable_name, converter_name, args, kwargs): """Looks up the converter for the given parameter. .. versionadded:: 0.9 """ if converter_name not in self.map.converters: raise LookupError('the converter %r does not exist' % converter_name) return self.map.converters[converter_name](self.map, *args, **kwargs) def compile(self): """Compiles the regular expression and stores it.""" assert self.map is not None, 'rule not bound' if self.map.host_matching: domain_rule = self.host or '' else: domain_rule = self.subdomain or '' self._trace = [] self._converters = {} self._weights = [] regex_parts = [] def _build_regex(rule): for converter, arguments, variable in parse_rule(rule): if converter is None: regex_parts.append(re.escape(variable)) self._trace.append((False, variable)) for part in variable.split('/'): if part: self._weights.append((0, -len(part))) else: if arguments: c_args, c_kwargs = parse_converter_args(arguments) else: c_args = () c_kwargs = {} convobj = self.get_converter( variable, converter, c_args, c_kwargs) regex_parts.append('(?P<%s>%s)' % (variable, convobj.regex)) self._converters[variable] = convobj self._trace.append((True, variable)) self._weights.append((1, convobj.weight)) self.arguments.add(str(variable)) _build_regex(domain_rule) regex_parts.append('\\|') self._trace.append((False, '|')) _build_regex(self.is_leaf and self.rule or self.rule.rstrip('/')) if not self.is_leaf: self._trace.append((False, '/')) if self.build_only: return regex = r'^%s%s$' % ( u''.join(regex_parts), (not self.is_leaf or not self.strict_slashes) and '(?<!/)(?P<__suffix__>/?)' or '' ) self._regex = re.compile(regex, re.UNICODE) def match(self, path, method=None): """Check if the rule matches a given path. Path is a string in the form ``"subdomain|/path"`` and is assembled by the map. If the map is doing host matching the subdomain part will be the host instead. If the rule matches a dict with the converted values is returned, otherwise the return value is `None`. :internal: """ if not self.build_only: m = self._regex.search(path) if m is not None: groups = m.groupdict() # we have a folder like part of the url without a trailing # slash and strict slashes enabled. raise an exception that # tells the map to redirect to the same url but with a # trailing slash if self.strict_slashes and not self.is_leaf and \ not groups.pop('__suffix__') and \ (method is None or self.methods is None or method in self.methods): raise RequestSlash() # if we are not in strict slashes mode we have to remove # a __suffix__ elif not self.strict_slashes: del groups['__suffix__'] result = {} for name, value in iteritems(groups): try: value = self._converters[name].to_python(value) except ValidationError: return result[str(name)] = value if self.defaults: result.update(self.defaults) if self.alias and self.map.redirect_defaults: raise RequestAliasRedirect(result) return result def build(self, values, append_unknown=True): """Assembles the relative url for that rule and the subdomain. If building doesn't work for some reasons `None` is returned. :internal: """ tmp = [] add = tmp.append processed = set(self.arguments) for is_dynamic, data in self._trace: if is_dynamic: try: add(self._converters[data].to_url(values[data])) except ValidationError: return processed.add(data) else: add(url_quote(to_bytes(data, self.map.charset), safe='/:|+')) domain_part, url = (u''.join(tmp)).split(u'|', 1) if append_unknown: query_vars = MultiDict(values) for key in processed: if key in query_vars: del query_vars[key] if query_vars: url += u'?' + url_encode(query_vars, charset=self.map.charset, sort=self.map.sort_parameters, key=self.map.sort_key) return domain_part, url def provides_defaults_for(self, rule): """Check if this rule has defaults for a given rule. :internal: """ return not self.build_only and self.defaults and \ self.endpoint == rule.endpoint and self != rule and \ self.arguments == rule.arguments def suitable_for(self, values, method=None): """Check if the dict of values has enough data for url generation. :internal: """ # if a method was given explicitly and that method is not supported # by this rule, this rule is not suitable. if method is not None and self.methods is not None \ and method not in self.methods: return False defaults = self.defaults or () # all arguments required must be either in the defaults dict or # the value dictionary otherwise it's not suitable for key in self.arguments: if key not in defaults and key not in values: return False # in case defaults are given we ensure taht either the value was # skipped or the value is the same as the default value. if defaults: for key, value in iteritems(defaults): if key in values and value != values[key]: return False return True def match_compare_key(self): """The match compare key for sorting. Current implementation: 1. rules without any arguments come first for performance reasons only as we expect them to match faster and some common ones usually don't have any arguments (index pages etc.) 2. The more complex rules come first so the second argument is the negative length of the number of weights. 3. lastly we order by the actual weights. :internal: """ return bool(self.arguments), -len(self._weights), self._weights def build_compare_key(self): """The build compare key for sorting. :internal: """ return self.alias and 1 or 0, -len(self.arguments), \ -len(self.defaults or ()) def __eq__(self, other): return self.__class__ is other.__class__ and \ self._trace == other._trace __hash__ = None def __ne__(self, other): return not self.__eq__(other) def __str__(self): return self.rule @native_string_result def __repr__(self): if self.map is None: return u'<%s (unbound)>' % self.__class__.__name__ tmp = [] for is_dynamic, data in self._trace: if is_dynamic: tmp.append(u'<%s>' % data) else: tmp.append(data) return u'<%s %s%s -> %s>' % ( self.__class__.__name__, repr((u''.join(tmp)).lstrip(u'|')).lstrip(u'u'), self.methods is not None and u' (%s)' % u', '.join(self.methods) or u'', self.endpoint ) class BaseConverter(object): """Base class for all converters.""" regex = '[^/]+' weight = 100 def __init__(self, map): self.map = map def to_python(self, value): return value def to_url(self, value): return url_quote(value, charset=self.map.charset) class UnicodeConverter(BaseConverter): """This converter is the default converter and accepts any string but only one path segment. Thus the string can not include a slash. This is the default validator. Example:: Rule('/pages/<page>'), Rule('/<string(length=2):lang_code>') :param map: the :class:`Map`. :param minlength: the minimum length of the string. Must be greater or equal 1. :param maxlength: the maximum length of the string. :param length: the exact length of the string. """ def __init__(self, map, minlength=1, maxlength=None, length=None): BaseConverter.__init__(self, map) if length is not None: length = '{%d}' % int(length) else: if maxlength is None: maxlength = '' else: maxlength = int(maxlength) length = '{%s,%s}' % ( int(minlength), maxlength ) self.regex = '[^/]' + length class AnyConverter(BaseConverter): """Matches one of the items provided. Items can either be Python identifiers or strings:: Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>') :param map: the :class:`Map`. :param items: this function accepts the possible items as positional arguments. """ def __init__(self, map, *items): BaseConverter.__init__(self, map) self.regex = '(?:%s)' % '|'.join([re.escape(x) for x in items]) class PathConverter(BaseConverter): """Like the default :class:`UnicodeConverter`, but it also matches slashes. This is useful for wikis and similar applications:: Rule('/<path:wikipage>') Rule('/<path:wikipage>/edit') :param map: the :class:`Map`. """ regex = '[^/].*?' weight = 200 class NumberConverter(BaseConverter): """Baseclass for `IntegerConverter` and `FloatConverter`. :internal: """ weight = 50 def __init__(self, map, fixed_digits=0, min=None, max=None): BaseConverter.__init__(self, map) self.fixed_digits = fixed_digits self.min = min self.max = max def to_python(self, value): if (self.fixed_digits and len(value) != self.fixed_digits): raise ValidationError() value = self.num_convert(value) if (self.min is not None and value < self.min) or \ (self.max is not None and value > self.max): raise ValidationError() return value def to_url(self, value): value = self.num_convert(value) if self.fixed_digits: value = ('%%0%sd' % self.fixed_digits) % value return str(value) class IntegerConverter(NumberConverter): """This converter only accepts integer values:: Rule('/page/<int:page>') This converter does not support negative values. :param map: the :class:`Map`. :param fixed_digits: the number of fixed digits in the URL. If you set this to ``4`` for example, the application will only match if the url looks like ``/0001/``. The default is variable length. :param min: the minimal value. :param max: the maximal value. """ regex = r'\d+' num_convert = int class FloatConverter(NumberConverter): """This converter only accepts floating point values:: Rule('/probability/<float:probability>') This converter does not support negative values. :param map: the :class:`Map`. :param min: the minimal value. :param max: the maximal value. """ regex = r'\d+\.\d+' num_convert = float def __init__(self, map, min=None, max=None): NumberConverter.__init__(self, map, 0, min, max) class UUIDConverter(BaseConverter): """This converter only accepts UUID strings:: Rule('/object/<uuid:identifier>') .. versionadded:: 0.10 :param map: the :class:`Map`. """ regex = r'[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-' \ r'[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}' def to_python(self, value): return uuid.UUID(value) def to_url(self, value): return str(value) #: the default converter mapping for the map. DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, } class Map(object): """The map class stores all the URL rules and some configuration parameters. Some of the configuration values are only stored on the `Map` instance since those affect all rules, others are just defaults and can be overridden for each rule. Note that you have to specify all arguments besides the `rules` as keyword arguments! :param rules: sequence of url rules for this map. :param default_subdomain: The default subdomain for rules without a subdomain defined. :param charset: charset of the url. defaults to ``"utf-8"`` :param strict_slashes: Take care of trailing slashes. :param redirect_defaults: This will redirect to the default rule if it wasn't visited that way. This helps creating unique URLs. :param converters: A dict of converters that adds additional converters to the list of converters. If you redefine one converter this will override the original one. :param sort_parameters: If set to `True` the url parameters are sorted. See `url_encode` for more details. :param sort_key: The sort key function for `url_encode`. :param encoding_errors: the error method to use for decoding :param host_matching: if set to `True` it enables the host matching feature and disables the subdomain one. If enabled the `host` parameter to rules is used instead of the `subdomain` one. .. versionadded:: 0.5 `sort_parameters` and `sort_key` was added. .. versionadded:: 0.7 `encoding_errors` and `host_matching` was added. """ #: .. versionadded:: 0.6 #: a dict of default converters to be used. default_converters = ImmutableDict(DEFAULT_CONVERTERS) def __init__(self, rules=None, default_subdomain='', charset='utf-8', strict_slashes=True, redirect_defaults=True, converters=None, sort_parameters=False, sort_key=None, encoding_errors='replace', host_matching=False): self._rules = [] self._rules_by_endpoint = {} self._remap = True self._remap_lock = Lock() self.default_subdomain = default_subdomain self.charset = charset self.encoding_errors = encoding_errors self.strict_slashes = strict_slashes self.redirect_defaults = redirect_defaults self.host_matching = host_matching self.converters = self.default_converters.copy() if converters: self.converters.update(converters) self.sort_parameters = sort_parameters self.sort_key = sort_key for rulefactory in rules or (): self.add(rulefactory) def is_endpoint_expecting(self, endpoint, *arguments): """Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. :param endpoint: the endpoint to check. :param arguments: this function accepts one or more arguments as positional arguments. Each one of them is checked. """ self.update() arguments = set(arguments) for rule in self._rules_by_endpoint[endpoint]: if arguments.issubset(rule.arguments): return True return False def iter_rules(self, endpoint=None): """Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator """ self.update() if endpoint is not None: return iter(self._rules_by_endpoint[endpoint]) return iter(self._rules) def add(self, rulefactory): """Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. :param rulefactory: a :class:`Rule` or :class:`RuleFactory` """ for rule in rulefactory.get_rules(self): rule.bind(self) self._rules.append(rule) self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule) self._remap = True def bind(self, server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None): """Return a new :class:`MapAdapter` with the details specified to the call. Note that `script_name` will default to ``'/'`` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path_info is passed to :meth:`match` it will use the default path info passed to bind. While this doesn't really make sense for manual bind calls, it's useful if you bind a map to a WSGI environment which already contains the path info. `subdomain` will default to the `default_subdomain` for this map if no defined. If there is no `default_subdomain` you cannot use the subdomain feature. .. versionadded:: 0.7 `query_args` added .. versionadded:: 0.8 `query_args` can now also be a string. """ server_name = server_name.lower() if self.host_matching: if subdomain is not None: raise RuntimeError('host matching enabled and a ' 'subdomain was provided') elif subdomain is None: subdomain = self.default_subdomain if script_name is None: script_name = '/' try: server_name = _encode_idna(server_name) except UnicodeError: raise BadHost() return MapAdapter(self, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args) def bind_to_environ(self, environ, server_name=None, subdomain=None): """Like :meth:`bind` but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don't provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or `HTTP_HOST` if provided) as used `server_name` with disabled subdomain feature. If `subdomain` is `None` but an environment and a server name is provided it will calculate the current subdomain automatically. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME` in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated subdomain will be ``'staging.dev'``. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally `PATH_INFO` added as a default of the :class:`MapAdapter` so that you don't have to pass the path info to the match method. .. versionchanged:: 0.5 previously this method accepted a bogus `calculate_subdomain` parameter that did not have any effect. It was removed because of that. .. versionchanged:: 0.8 This will no longer raise a ValueError when an unexpected server name was passed. :param environ: a WSGI environment. :param server_name: an optional server name hint (see above). :param subdomain: optionally the current subdomain (see above). """ environ = _get_environ(environ) if 'HTTP_HOST' in environ: wsgi_server_name = environ['HTTP_HOST'] if environ['wsgi.url_scheme'] == 'http' \ and wsgi_server_name.endswith(':80'): wsgi_server_name = wsgi_server_name[:-3] elif environ['wsgi.url_scheme'] == 'https' \ and wsgi_server_name.endswith(':443'): wsgi_server_name = wsgi_server_name[:-4] else: wsgi_server_name = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \ in (('https', '443'), ('http', '80')): wsgi_server_name += ':' + environ['SERVER_PORT'] wsgi_server_name = wsgi_server_name.lower() if server_name is None: server_name = wsgi_server_name else: server_name = server_name.lower() if subdomain is None and not self.host_matching: cur_server_name = wsgi_server_name.split('.') real_server_name = server_name.split('.') offset = -len(real_server_name) if cur_server_name[offset:] != real_server_name: # This can happen even with valid configs if the server was # accesssed directly by IP address under some situations. # Instead of raising an exception like in Werkzeug 0.7 or # earlier we go by an invalid subdomain which will result # in a 404 error on matching. subdomain = '<invalid>' else: subdomain = '.'.join(filter(None, cur_server_name[:offset])) def _get_wsgi_string(name): val = environ.get(name) if val is not None: return wsgi_decoding_dance(val, self.charset) script_name = _get_wsgi_string('SCRIPT_NAME') path_info = _get_wsgi_string('PATH_INFO') query_args = _get_wsgi_string('QUERY_STRING') return Map.bind(self, server_name, script_name, subdomain, environ['wsgi.url_scheme'], environ['REQUEST_METHOD'], path_info, query_args=query_args) def update(self): """Called before matching and building to keep the compiled rules in the correct order after things changed. """ if not self._remap: return with self._remap_lock: if not self._remap: return self._rules.sort(key=lambda x: x.match_compare_key()) for rules in itervalues(self._rules_by_endpoint): rules.sort(key=lambda x: x.build_compare_key()) self._remap = False def __repr__(self): rules = self.iter_rules() return '%s(%s)' % (self.__class__.__name__, pformat(list(rules))) class MapAdapter(object): """Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does the URL matching and building based on runtime information. """ def __init__(self, map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args=None): self.map = map self.server_name = to_unicode(server_name) script_name = to_unicode(script_name) if not script_name.endswith(u'/'): script_name += u'/' self.script_name = script_name self.subdomain = to_unicode(subdomain) self.url_scheme = to_unicode(url_scheme) self.path_info = to_unicode(path_info) self.default_method = to_unicode(default_method) self.query_args = query_args def dispatch(self, view_func, path_info=None, method=None, catch_http_exceptions=False): """Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it ``catch_http_exceptions=True`` and it will catch the http exceptions. Here a small example for the dispatch usage:: from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) Keep in mind that this method might return exception objects, too, so use :class:`Response.force_type` to get a response object. :param view_func: a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above) :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param catch_http_exceptions: set to `True` to catch any of the werkzeug :class:`HTTPException`\s. """ try: try: endpoint, args = self.match(path_info, method) except RequestRedirect as e: return e return view_func(endpoint, args) except HTTPException as e: if catch_http_exceptions: return e raise def match(self, path_info=None, method=None, return_rule=False, query_args=None): """The usage is simple: you just pass the match method the current path info as well as the method (which defaults to `GET`). The following things can then happen: - you receive a `NotFound` exception that indicates that no URL is matching. A `NotFound` exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as `werkzeug.exceptions.NotFound`) - you receive a `MethodNotAllowed` exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. - you receive a `RequestRedirect` exception with a `new_url` attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request ``/foo`` although the correct URL is ``/foo/`` You can use the `RequestRedirect` instance as response-like object similar to all other subclasses of `HTTPException`. - you get a tuple in the form ``(endpoint, arguments)`` if there is a match (unless `return_rule` is True, in which case you get a tuple in the form ``(rule, arguments)``) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of `HTTPException` so they can be used as WSGI responses. The will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) And here is what happens on redirect and missing URLs: >>> urls.match("/downloads") Traceback (most recent call last): ... RequestRedirect: http://example.com/downloads/ >>> urls.match("/missing") Traceback (most recent call last): ... NotFound: 404 Not Found :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param return_rule: return the rule that matched instead of just the endpoint (defaults to `False`). :param query_args: optional query arguments that are used for automatic redirects as string or dictionary. It's currently not possible to use the query arguments for URL matching. .. versionadded:: 0.6 `return_rule` was added. .. versionadded:: 0.7 `query_args` was added. .. versionchanged:: 0.8 `query_args` can now also be a string. """ self.map.update() if path_info is None: path_info = self.path_info else: path_info = to_unicode(path_info, self.map.charset) if query_args is None: query_args = self.query_args method = (method or self.default_method).upper() path = u'%s|%s' % ( self.map.host_matching and self.server_name or self.subdomain, path_info and '/%s' % path_info.lstrip('/') ) have_match_for = set() for rule in self.map._rules: try: rv = rule.match(path, method) except RequestSlash: raise RequestRedirect(self.make_redirect_url( url_quote(path_info, self.map.charset, safe='/:|+') + '/', query_args)) except RequestAliasRedirect as e: raise RequestRedirect(self.make_alias_redirect_url( path, rule.endpoint, e.matched_values, method, query_args)) if rv is None: continue if rule.methods is not None and method not in rule.methods: have_match_for.update(rule.methods) continue if self.map.redirect_defaults: redirect_url = self.get_default_redirect(rule, method, rv, query_args) if redirect_url is not None: raise RequestRedirect(redirect_url) if rule.redirect_to is not None: if isinstance(rule.redirect_to, string_types): def _handle_match(match): value = rv[match.group(1)] return rule._converters[match.group(1)].to_url(value) redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to) else: redirect_url = rule.redirect_to(self, **rv) raise RequestRedirect(str(url_join('%s://%s%s%s' % ( self.url_scheme or 'http', self.subdomain and self.subdomain + '.' or '', self.server_name, self.script_name ), redirect_url))) if return_rule: return rule, rv else: return rule.endpoint, rv if have_match_for: raise MethodNotAllowed(valid_methods=list(have_match_for)) raise NotFound() def test(self, path_info=None, method=None): """Test if a rule would match. Works like `match` but returns `True` if the URL matches, or `False` if it does not exist. :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. """ try: self.match(path_info, method) except RequestRedirect: pass except HTTPException: return False return True def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return [] def get_host(self, domain_part): """Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. """ if self.map.host_matching: if domain_part is None: return self.server_name return to_unicode(domain_part, 'ascii') subdomain = domain_part if subdomain is None: subdomain = self.subdomain else: subdomain = to_unicode(subdomain, 'ascii') return (subdomain and subdomain + u'.' or u'') + self.server_name def get_default_redirect(self, rule, method, values, query_args): """A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only. :internal: """ assert self.map.redirect_defaults for r in self.map._rules_by_endpoint[rule.endpoint]: # every rule that comes after this one, including ourself # has a lower priority for the defaults. We order the ones # with the highest priority up for building. if r is rule: break if r.provides_defaults_for(rule) and \ r.suitable_for(values, method): values.update(r.defaults) domain_part, path = r.build(values) return self.make_redirect_url( path, query_args, domain_part=domain_part) def encode_query_args(self, query_args): if not isinstance(query_args, string_types): query_args = url_encode(query_args, self.map.charset) return query_args def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = '' if query_args: suffix = '?' + self.encode_query_args(query_args) return str('%s://%s/%s%s' % ( self.url_scheme or 'http', self.get_host(domain_part), posixpath.join(self.script_name[:-1].lstrip('/'), path_info.lstrip('/')), suffix )) def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build(endpoint, values, method, append_unknown=False, force_external=True) if query_args: url += '?' + self.encode_query_args(query_args) assert url != path, 'detected invalid alias setting. No canonical ' \ 'URL found' return url def _partial_build(self, endpoint, values, method, append_unknown): """Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpoint, values and method. :internal: """ # in case the method is none, try with the default method first if method is None: rv = self._partial_build(endpoint, values, self.default_method, append_unknown) if rv is not None: return rv # default method did not match or a specific method is passed, # check all and go with first result. for rule in self.map._rules_by_endpoint.get(endpoint, ()): if rule.suitable_for(values, method): rv = rule.build(values, append_unknown) if rv is not None: return rv def build(self, endpoint, values=None, method=None, force_external=False, append_unknown=True): """Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.build("index", {}) '/' >>> urls.build("downloads/show", {'id': 42}) '/downloads/42' >>> urls.build("downloads/show", {'id': 42}, force_external=True) 'http://example.com/downloads/42' Because URLs cannot contain non ASCII data you will always get bytestrings back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to unicode and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'}) '/?q=My+Searchstring' When processing those additional values, lists are furthermore interpreted as multiple values (as per :py:class:`werkzeug.datastructures.MultiDict`): >>> urls.build("index", {'q': ['a', 'b', 'c']}) '/?q=a&q=b&q=c' If a rule does not exist when building a `BuildError` exception is raised. The build method accepts an argument called `method` which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. .. versionadded:: 0.6 the `append_unknown` parameter was added. :param endpoint: the endpoint of the URL to build. :param values: the values for the URL to build. Unhandled values are appended to the URL as query parameters. :param method: the HTTP method for the rule if there are different URLs for different methods on the same endpoint. :param force_external: enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL. :param append_unknown: unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those. """ self.map.update() if values: if isinstance(values, MultiDict): valueiter = iteritems(values, multi=True) else: valueiter = iteritems(values) values = dict((k, v) for k, v in valueiter if v is not None) else: values = {} rv = self._partial_build(endpoint, values, method, append_unknown) if rv is None: raise BuildError(endpoint, values, method, self) domain_part, path = rv host = self.get_host(domain_part) # shortcut this. if not force_external and ( (self.map.host_matching and host == self.server_name) or (not self.map.host_matching and domain_part == self.subdomain) ): return str(url_join(self.script_name, './' + path.lstrip('/'))) return str('%s//%s%s/%s' % ( self.url_scheme + ':' if self.url_scheme else '', host, self.script_name[:-1], path.lstrip('/') ))
mit
LacusCon/hugula
Client/tools/site-packages/PIL/ImageFileIO.py
14
1233
# # The Python Imaging Library. # $Id: ImageFileIO.py 2134 2004-10-06 08:55:20Z fredrik $ # # kludge to get basic ImageFileIO functionality # # History: # 1998-08-06 fl Recreated # # Copyright (c) Secret Labs AB 1998-2002. # # See the README file for information on usage and redistribution. # from StringIO import StringIO ## # The <b>ImageFileIO</b> module can be used to read an image from a # socket, or any other stream device. # <p> # This module is deprecated. New code should use the <b>Parser</b> # class in the <a href="imagefile">ImageFile</a> module instead. # # @see ImageFile#Parser class ImageFileIO(StringIO): ## # Adds buffering to a stream file object, in order to # provide <b>seek</b> and <b>tell</b> methods required # by the <b>Image.open</b> method. The stream object must # implement <b>read</b> and <b>close</b> methods. # # @param fp Stream file handle. # @see Image#open def __init__(self, fp): data = fp.read() StringIO.__init__(self, data) if __name__ == "__main__": import Image fp = open("/images/clenna.im", "rb") im = Image.open(ImageFileIO(fp)) im.load() # make sure we can read the raster data print im.mode, im.size
mit
jaantollander/CrowdDynamics
crowddynamics/core/tests/test_interactions_benchmark.py
1
1239
import numpy as np import pytest from crowddynamics.core.interactions import agent_agent_block_list from crowddynamics.core.vector2D import unit_vector from crowddynamics.simulation.agents import Agents, Circular, ThreeCircle, \ AgentGroup def attributes(): orientation = np.random.uniform(-np.pi, np.pi) return dict(body_type='adult', orientation=orientation, velocity=np.random.uniform(0.0, 1.3, 2), angular_velocity=np.random.uniform(-1.0, 1.0), target_direction=unit_vector(orientation), target_orientation=orientation) @pytest.mark.parametrize('size', (200, 500, 1000)) @pytest.mark.parametrize('agent_type', (Circular, ThreeCircle)) def test_agent_agent_block_list(benchmark, size, agent_type, algorithm): # Grow the area with size. Keeps agent density constant. area_size = np.sqrt(2 * size) agents = Agents(agent_type=agent_type) group = AgentGroup( agent_type=agent_type, size=size, attributes=attributes) agents.add_non_overlapping_group( group, position_gen=lambda: np.random.uniform(-area_size, area_size, 2)) benchmark(agent_agent_block_list, agents.array) assert True
gpl-3.0
jiulongzaitian/kubernetes
hack/verify-flags-underscore.py
205
4659
#!/usr/bin/env python # Copyright 2015 The Kubernetes 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. from __future__ import print_function import argparse import os import re import sys parser = argparse.ArgumentParser() parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*') args = parser.parse_args() # Cargo culted from http://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python def is_binary(pathname): """Return true if the given filename is binary. @raise EnvironmentError: if the file does not exist or cannot be accessed. @attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010 @author: Trent Mick <TrentM@ActiveState.com> @author: Jorge Orpinel <jorge@orpinel.com>""" try: with open(pathname, 'r') as f: CHUNKSIZE = 1024 while 1: chunk = f.read(CHUNKSIZE) if '\0' in chunk: # found null byte return True if len(chunk) < CHUNKSIZE: break # done except: return True return False def get_all_files(rootdir): all_files = [] for root, dirs, files in os.walk(rootdir): # don't visit certain dirs if 'vendor' in dirs: dirs.remove('vendor') if 'staging' in dirs: dirs.remove('staging') if '_output' in dirs: dirs.remove('_output') if '_gopath' in dirs: dirs.remove('_gopath') if 'third_party' in dirs: dirs.remove('third_party') if '.git' in dirs: dirs.remove('.git') if '.make' in dirs: dirs.remove('.make') if 'BUILD' in files: files.remove('BUILD') for name in files: pathname = os.path.join(root, name) if is_binary(pathname): continue all_files.append(pathname) return all_files # Collects all the flags used in golang files and verifies the flags do # not contain underscore. If any flag needs to be excluded from this check, # need to add that flag in hack/verify-flags/excluded-flags.txt. def check_underscore_in_flags(rootdir, files): # preload the 'known' flags which don't follow the - standard pathname = os.path.join(rootdir, "hack/verify-flags/excluded-flags.txt") f = open(pathname, 'r') excluded_flags = set(f.read().splitlines()) f.close() regexs = [ re.compile('Var[P]?\([^,]*, "([^"]*)"'), re.compile('.String[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Int[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Bool[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.Duration[P]?\("([^"]*)",[^,]+,[^)]+\)'), re.compile('.StringSlice[P]?\("([^"]*)",[^,]+,[^)]+\)') ] new_excluded_flags = set() # walk all the files looking for any flags being declared for pathname in files: if not pathname.endswith(".go"): continue f = open(pathname, 'r') data = f.read() f.close() matches = [] for regex in regexs: matches = matches + regex.findall(data) for flag in matches: if any(x in flag for x in excluded_flags): continue if "_" in flag: new_excluded_flags.add(flag) if len(new_excluded_flags) != 0: print("Found a flag declared with an _ but which is not explicitly listed as a valid flag name in hack/verify-flags/excluded-flags.txt") print("Are you certain this flag should not have been declared with an - instead?") l = list(new_excluded_flags) l.sort() print("%s" % "\n".join(l)) sys.exit(1) def main(): rootdir = os.path.dirname(__file__) + "/../" rootdir = os.path.abspath(rootdir) if len(args.filenames) > 0: files = args.filenames else: files = get_all_files(rootdir) check_underscore_in_flags(rootdir, files) if __name__ == "__main__": sys.exit(main())
apache-2.0
myshkov/bnn-analysis
models/bbb_sampler.py
1
4851
""" This module implements Bayes By Backprop -based sampler for NNs. http://jmlr.org/proceedings/papers/v37/blundell15.pdf """ import numpy as np from keras.models import Sequential from keras.layers.core import Activation from keras import backend as K from keras.engine.topology import Layer from sampler import Sampler, SampleStats class BBBSampler(Sampler): """ BBB sampler for NNs. """ def __init__(self, model=None, batch_size=None, n_epochs=None, **kwargs): """ Creates a new BBBSampler object. """ super().__init__(**kwargs) self.sampler_type = 'BBB' self.model = model self.batch_size = batch_size if batch_size is not None else self.train_set_size self.n_epochs = n_epochs def __repr__(self): s = super().__repr__() return s def _fit(self, n_epochs=None, verbose=0, **kwargs): """ Fits the model before sampling. """ n_epochs = n_epochs if n_epochs is not None else self.n_epochs self.model.fit(self.train_x, self.train_y, batch_size=self.batch_size, nb_epoch=n_epochs, verbose=verbose) def _sample_predictive(self, test_x=None, return_stats=False, **kwargs): """ Draws a new sample from the model. """ sample = self.model.predict(test_x, batch_size=self.batch_size) stats = None if return_stats: stats = SampleStats(time=self._running_time()) return [sample], [stats] @classmethod def model_from_description(cls, layers, noise_std, weights_std, batch_size, train_size): """ Creates a BBB model from the specified parameters. """ n_batches = int(train_size / batch_size) step = .01 class BBBLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super().__init__(**kwargs) def build(self, input_shape): input_dim = input_shape[1] shape = [input_dim, self.output_dim] eps_std = step # weights self.eps_w = K.random_normal([input_shape[0]] + shape, std=eps_std) self.mu_w = K.variable(np.random.normal(0., 10. * step, size=shape), name='mu_w') self.rho_w = K.variable(np.random.normal(0., 10. * step, size=shape), name='rho_w') self.W = self.mu_w + self.eps_w * K.log(1.0 + K.exp(self.rho_w)) self.eps_b = K.random_normal([self.output_dim], std=eps_std) self.mu_b = K.variable(np.random.normal(0., 10. * step, size=[self.output_dim]), name='mu_b') self.rho_b = K.variable(np.random.normal(0., 10. * step, size=[self.output_dim]), name='rho_b') self.b = self.mu_b + self.eps_b * K.log(1.0 + K.exp(self.rho_b)) self.trainable_weights = [self.mu_w, self.rho_w, self.mu_b, self.rho_b] def call(self, x, mask=None): return K.squeeze(K.batch_dot(K.expand_dims(x, dim=1), self.W), axis=1) + self.b def get_output_shape_for(self, input_shape): return (input_shape[0], self.output_dim) def log_gaussian(x, mean, std): return -K.log(std) - (x - mean) ** 2 / (2. * std ** 2) def sigma_from_rho(rho): return K.log(1. + K.exp(rho)) / step def variational_objective(model, noise_std, weights_std, batch_size, nb_batches): def loss(y, fx): log_pw = K.variable(0.) log_qw = K.variable(0.) for layer in model.layers: if type(layer) is BBBLayer: log_pw += K.sum(log_gaussian(layer.W, 0., weights_std)) log_pw += K.sum(log_gaussian(layer.b, 0., weights_std)) log_qw += K.sum(log_gaussian(layer.W, layer.mu_w, sigma_from_rho(layer.rho_w))) log_qw += K.sum(log_gaussian(layer.b, layer.mu_b, sigma_from_rho(layer.rho_b))) log_likelihood = K.sum(log_gaussian(y, fx, noise_std)) return K.sum((log_qw - log_pw) / nb_batches - log_likelihood) / batch_size return loss model = Sequential() in_shape = [batch_size, layers[0][0]] # input model.add(BBBLayer(layers[1][0], batch_input_shape=in_shape)) model.add(Activation('relu')) # hidden layers for l in range(2, len(layers) - 1): model.add(BBBLayer(layers[l - 1][0])) model.add(Activation('relu')) # output layer model.add(BBBLayer(1)) loss = variational_objective(model, noise_std, weights_std, batch_size, n_batches) model.compile(loss=loss, optimizer='adam', metrics=['accuracy']) return model
mit
MiLk/ansible
lib/ansible/module_utils/netcli.py
87
9650
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c) 2015 Peter Sprygada, <psprygada@ansible.com> # # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re import shlex import time from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE, BOOLEANS_FALSE from ansible.module_utils.six import string_types, text_type from ansible.module_utils.six.moves import zip def to_list(val): if isinstance(val, (list, tuple)): return list(val) elif val is not None: return [val] else: return list() class FailedConditionsError(Exception): def __init__(self, msg, failed_conditions): super(FailedConditionsError, self).__init__(msg) self.failed_conditions = failed_conditions class FailedConditionalError(Exception): def __init__(self, msg, failed_conditional): super(FailedConditionalError, self).__init__(msg) self.failed_conditional = failed_conditional class AddCommandError(Exception): def __init__(self, msg, command): super(AddCommandError, self).__init__(msg) self.command = command class AddConditionError(Exception): def __init__(self, msg, condition): super(AddConditionError, self).__init__(msg) self.condition = condition class Cli(object): def __init__(self, connection): self.connection = connection self.default_output = connection.default_output or 'text' self._commands = list() @property def commands(self): return [str(c) for c in self._commands] def __call__(self, commands, output=None): objects = list() for cmd in to_list(commands): objects.append(self.to_command(cmd, output)) return self.connection.run_commands(objects) def to_command(self, command, output=None, prompt=None, response=None, **kwargs): output = output or self.default_output if isinstance(command, Command): return command if isinstance(prompt, string_types): prompt = re.compile(re.escape(prompt)) return Command(command, output, prompt=prompt, response=response, **kwargs) def add_commands(self, commands, output=None, **kwargs): for cmd in commands: self._commands.append(self.to_command(cmd, output, **kwargs)) def run_commands(self): responses = self.connection.run_commands(self._commands) for resp, cmd in zip(responses, self._commands): cmd.response = resp # wipe out the commands list to avoid issues if additional # commands are executed later self._commands = list() return responses class Command(object): def __init__(self, command, output=None, prompt=None, response=None, **kwargs): self.command = command self.output = output self.command_string = command self.prompt = prompt self.response = response self.args = kwargs def __str__(self): return self.command_string class CommandRunner(object): def __init__(self, module): self.module = module self.items = list() self.conditionals = set() self.commands = list() self.retries = 10 self.interval = 1 self.match = 'all' self._default_output = module.connection.default_output def add_command(self, command, output=None, prompt=None, response=None, **kwargs): if command in [str(c) for c in self.commands]: raise AddCommandError('duplicated command detected', command=command) cmd = self.module.cli.to_command(command, output=output, prompt=prompt, response=response, **kwargs) self.commands.append(cmd) def get_command(self, command, output=None): for cmd in self.commands: if cmd.command == command: return cmd.response raise ValueError("command '%s' not found" % command) def get_responses(self): return [cmd.response for cmd in self.commands] def add_conditional(self, condition): try: self.conditionals.add(Conditional(condition)) except AttributeError as exc: raise AddConditionError(msg=str(exc), condition=condition) def run(self): while self.retries > 0: self.module.cli.add_commands(self.commands) responses = self.module.cli.run_commands() for item in list(self.conditionals): if item(responses): if self.match == 'any': return item self.conditionals.remove(item) if not self.conditionals: break time.sleep(self.interval) self.retries -= 1 else: failed_conditions = [item.raw for item in self.conditionals] errmsg = 'One or more conditional statements have not been satisfied' raise FailedConditionsError(errmsg, failed_conditions) class Conditional(object): """Used in command modules to evaluate waitfor conditions """ OPERATORS = { 'eq': ['eq', '=='], 'neq': ['neq', 'ne', '!='], 'gt': ['gt', '>'], 'ge': ['ge', '>='], 'lt': ['lt', '<'], 'le': ['le', '<='], 'contains': ['contains'], 'matches': ['matches'] } def __init__(self, conditional, encoding=None): self.raw = conditional try: key, op, val = shlex.split(conditional) except ValueError: raise ValueError('failed to parse conditional') self.key = key self.func = self._func(op) self.value = self._cast_value(val) def __call__(self, data): value = self.get_value(dict(result=data)) return self.func(value) def _cast_value(self, value): if value in BOOLEANS_TRUE: return True elif value in BOOLEANS_FALSE: return False elif re.match(r'^\d+\.d+$', value): return float(value) elif re.match(r'^\d+$', value): return int(value) else: return text_type(value) def _func(self, oper): for func, operators in self.OPERATORS.items(): if oper in operators: return getattr(self, func) raise AttributeError('unknown operator: %s' % oper) def get_value(self, result): try: return self.get_json(result) except (IndexError, TypeError, AttributeError): msg = 'unable to apply conditional to result' raise FailedConditionalError(msg, self.raw) def get_json(self, result): string = re.sub(r"\[[\'|\"]", ".", self.key) string = re.sub(r"[\'|\"]\]", ".", string) parts = re.split(r'\.(?=[^\]]*(?:\[|$))', string) for part in parts: match = re.findall(r'\[(\S+?)\]', part) if match: key = part[:part.find('[')] result = result[key] for m in match: try: m = int(m) except ValueError: m = str(m) result = result[m] else: result = result.get(part) return result def number(self, value): if '.' in str(value): return float(value) else: return int(value) def eq(self, value): return value == self.value def neq(self, value): return value != self.value def gt(self, value): return self.number(value) > self.value def ge(self, value): return self.number(value) >= self.value def lt(self, value): return self.number(value) < self.value def le(self, value): return self.number(value) <= self.value def contains(self, value): return str(self.value) in value def matches(self, value): match = re.search(self.value, value, re.M) return match is not None
gpl-3.0
nhomar/odoo
addons/report/controllers/main.py
210
6943
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.addons.web.http import Controller, route, request from openerp.addons.web.controllers.main import _serialize_exception from openerp.osv import osv from openerp.tools import html_escape import simplejson from werkzeug import exceptions, url_decode from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from werkzeug.datastructures import Headers from reportlab.graphics.barcode import createBarcodeDrawing class ReportController(Controller): #------------------------------------------------------ # Report controllers #------------------------------------------------------ @route([ '/report/<path:converter>/<reportname>', '/report/<path:converter>/<reportname>/<docids>', ], type='http', auth='user', website=True) def report_routes(self, reportname, docids=None, converter=None, **data): report_obj = request.registry['report'] cr, uid, context = request.cr, request.uid, request.context if docids: docids = [int(i) for i in docids.split(',')] options_data = None if data.get('options'): options_data = simplejson.loads(data['options']) if data.get('context'): # Ignore 'lang' here, because the context in data is the one from the webclient *but* if # the user explicitely wants to change the lang, this mechanism overwrites it. data_context = simplejson.loads(data['context']) if data_context.get('lang'): del data_context['lang'] context.update(data_context) if converter == 'html': html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context) return request.make_response(html) elif converter == 'pdf': pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context) pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: raise exceptions.HTTPException(description='Converter %s not implemented.' % converter) #------------------------------------------------------ # Misc. route utils #------------------------------------------------------ @route(['/report/barcode', '/report/barcode/<type>/<path:value>'], type='http', auth="user") def report_barcode(self, type, value, width=600, height=100, humanreadable=0): """Contoller able to render barcode images thanks to reportlab. Samples: <img t-att-src="'/report/barcode/QR/%s' % o.name"/> <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' % ('QR', o.name, 200, 200)"/> :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39', 'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93', 'UPCA', 'USPS_4State' :param humanreadable: Accepted values: 0 (default) or 1. 1 will insert the readable value at the bottom of the output image """ try: width, height, humanreadable = int(width), int(height), bool(humanreadable) barcode = createBarcodeDrawing( type, value=value, format='png', width=width, height=height, humanReadable = humanreadable ) barcode = barcode.asString('png') except (ValueError, AttributeError): raise exceptions.HTTPException(description='Cannot convert into barcode.') return request.make_response(barcode, headers=[('Content-Type', 'image/png')]) @route(['/report/download'], type='http', auth="user") def report_download(self, data, token): """This function is used by 'qwebactionmanager.js' in order to trigger the download of a pdf/controller report. :param data: a javascript array JSON.stringified containg report internal url ([0]) and type [1] :returns: Response with a filetoken cookie and an attachment header """ requestcontent = simplejson.loads(data) url, type = requestcontent[0], requestcontent[1] try: if type == 'qweb-pdf': reportname = url.split('/report/pdf/')[1].split('?')[0] docids = None if '/' in reportname: reportname, docids = reportname.split('/') if docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter='pdf') else: # Particular report: data = url_decode(url.split('?')[1]).items() # decoding the args represented in JSON response = self.report_routes(reportname, converter='pdf', **dict(data)) response.headers.add('Content-Disposition', 'attachment; filename=%s.pdf;' % reportname) response.set_cookie('fileToken', token) return response elif type =='controller': reqheaders = Headers(request.httprequest.headers) response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True) response.set_cookie('fileToken', token) return response else: return except Exception, e: se = _serialize_exception(e) error = { 'code': 200, 'message': "Odoo Server Error", 'data': se } return request.make_response(html_escape(simplejson.dumps(error))) @route(['/report/check_wkhtmltopdf'], type='json', auth="user") def check_wkhtmltopdf(self): return request.registry['report']._check_wkhtmltopdf()
agpl-3.0
semonte/intellij-community
plugins/hg4idea/testData/bin/mercurial/mail.py
91
12504
# mail.py - mail sending bits for mercurial # # Copyright 2006 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from i18n import _ import util, encoding, sslutil import os, smtplib, socket, quopri, time, sys import email.Header, email.MIMEText, email.Utils _oldheaderinit = email.Header.Header.__init__ def _unifiedheaderinit(self, *args, **kw): """ Python 2.7 introduces a backwards incompatible change (Python issue1974, r70772) in email.Generator.Generator code: pre-2.7 code passed "continuation_ws='\t'" to the Header constructor, and 2.7 removed this parameter. Default argument is continuation_ws=' ', which means that the behaviour is different in <2.7 and 2.7 We consider the 2.7 behaviour to be preferable, but need to have an unified behaviour for versions 2.4 to 2.7 """ # override continuation_ws kw['continuation_ws'] = ' ' _oldheaderinit(self, *args, **kw) email.Header.Header.__dict__['__init__'] = _unifiedheaderinit class STARTTLS(smtplib.SMTP): '''Derived class to verify the peer certificate for STARTTLS. This class allows to pass any keyword arguments to SSL socket creation. ''' def __init__(self, sslkwargs, **kwargs): smtplib.SMTP.__init__(self, **kwargs) self._sslkwargs = sslkwargs def starttls(self, keyfile=None, certfile=None): if not self.has_extn("starttls"): msg = "STARTTLS extension not supported by server" raise smtplib.SMTPException(msg) (resp, reply) = self.docmd("STARTTLS") if resp == 220: self.sock = sslutil.ssl_wrap_socket(self.sock, keyfile, certfile, **self._sslkwargs) if not util.safehasattr(self.sock, "read"): # using httplib.FakeSocket with Python 2.5.x or earlier self.sock.read = self.sock.recv self.file = smtplib.SSLFakeFile(self.sock) self.helo_resp = None self.ehlo_resp = None self.esmtp_features = {} self.does_esmtp = 0 return (resp, reply) if util.safehasattr(smtplib.SMTP, '_get_socket'): class SMTPS(smtplib.SMTP): '''Derived class to verify the peer certificate for SMTPS. This class allows to pass any keyword arguments to SSL socket creation. ''' def __init__(self, sslkwargs, keyfile=None, certfile=None, **kwargs): self.keyfile = keyfile self.certfile = certfile smtplib.SMTP.__init__(self, **kwargs) self.default_port = smtplib.SMTP_SSL_PORT self._sslkwargs = sslkwargs def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print >> sys.stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = sslutil.ssl_wrap_socket(new_socket, self.keyfile, self.certfile, **self._sslkwargs) self.file = smtplib.SSLFakeFile(new_socket) return new_socket else: def SMTPS(sslkwargs, keyfile=None, certfile=None, **kwargs): raise util.Abort(_('SMTPS requires Python 2.6 or later')) def _smtp(ui): '''build an smtp connection and return a function to send mail''' local_hostname = ui.config('smtp', 'local_hostname') tls = ui.config('smtp', 'tls', 'none') # backward compatible: when tls = true, we use starttls. starttls = tls == 'starttls' or util.parsebool(tls) smtps = tls == 'smtps' if (starttls or smtps) and not util.safehasattr(socket, 'ssl'): raise util.Abort(_("can't use TLS: Python SSL support not installed")) mailhost = ui.config('smtp', 'host') if not mailhost: raise util.Abort(_('smtp.host not configured - cannot send mail')) verifycert = ui.config('smtp', 'verifycert', 'strict') if verifycert not in ['strict', 'loose']: if util.parsebool(verifycert) is not False: raise util.Abort(_('invalid smtp.verifycert configuration: %s') % (verifycert)) if (starttls or smtps) and verifycert: sslkwargs = sslutil.sslkwargs(ui, mailhost) else: sslkwargs = {} if smtps: ui.note(_('(using smtps)\n')) s = SMTPS(sslkwargs, local_hostname=local_hostname) elif starttls: s = STARTTLS(sslkwargs, local_hostname=local_hostname) else: s = smtplib.SMTP(local_hostname=local_hostname) if smtps: defaultport = 465 else: defaultport = 25 mailport = util.getport(ui.config('smtp', 'port', defaultport)) ui.note(_('sending mail: smtp host %s, port %s\n') % (mailhost, mailport)) s.connect(host=mailhost, port=mailport) if starttls: ui.note(_('(using starttls)\n')) s.ehlo() s.starttls() s.ehlo() if (starttls or smtps) and verifycert: ui.note(_('(verifying remote certificate)\n')) sslutil.validator(ui, mailhost)(s.sock, verifycert == 'strict') username = ui.config('smtp', 'username') password = ui.config('smtp', 'password') if username and not password: password = ui.getpass() if username and password: ui.note(_('(authenticating to mail server as %s)\n') % (username)) try: s.login(username, password) except smtplib.SMTPException, inst: raise util.Abort(inst) def send(sender, recipients, msg): try: return s.sendmail(sender, recipients, msg) except smtplib.SMTPRecipientsRefused, inst: recipients = [r[1] for r in inst.recipients.values()] raise util.Abort('\n' + '\n'.join(recipients)) except smtplib.SMTPException, inst: raise util.Abort(inst) return send def _sendmail(ui, sender, recipients, msg): '''send mail using sendmail.''' program = ui.config('email', 'method') cmdline = '%s -f %s %s' % (program, util.email(sender), ' '.join(map(util.email, recipients))) ui.note(_('sending mail: %s\n') % cmdline) fp = util.popen(cmdline, 'w') fp.write(msg) ret = fp.close() if ret: raise util.Abort('%s %s' % ( os.path.basename(program.split(None, 1)[0]), util.explainexit(ret)[0])) def _mbox(mbox, sender, recipients, msg): '''write mails to mbox''' fp = open(mbox, 'ab+') # Should be time.asctime(), but Windows prints 2-characters day # of month instead of one. Make them print the same thing. date = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime()) fp.write('From %s %s\n' % (sender, date)) fp.write(msg) fp.write('\n\n') fp.close() def connect(ui, mbox=None): '''make a mail connection. return a function to send mail. call as sendmail(sender, list-of-recipients, msg).''' if mbox: open(mbox, 'wb').close() return lambda s, r, m: _mbox(mbox, s, r, m) if ui.config('email', 'method', 'smtp') == 'smtp': return _smtp(ui) return lambda s, r, m: _sendmail(ui, s, r, m) def sendmail(ui, sender, recipients, msg, mbox=None): send = connect(ui, mbox=mbox) return send(sender, recipients, msg) def validateconfig(ui): '''determine if we have enough config data to try sending email.''' method = ui.config('email', 'method', 'smtp') if method == 'smtp': if not ui.config('smtp', 'host'): raise util.Abort(_('smtp specified as email transport, ' 'but no smtp host configured')) else: if not util.findexe(method): raise util.Abort(_('%r specified as email transport, ' 'but not in PATH') % method) def mimetextpatch(s, subtype='plain', display=False): '''Return MIME message suitable for a patch. Charset will be detected as utf-8 or (possibly fake) us-ascii. Transfer encodings will be used if necessary.''' cs = 'us-ascii' if not display: try: s.decode('us-ascii') except UnicodeDecodeError: try: s.decode('utf-8') cs = 'utf-8' except UnicodeDecodeError: # We'll go with us-ascii as a fallback. pass return mimetextqp(s, subtype, cs) def mimetextqp(body, subtype, charset): '''Return MIME message. Quoted-printable transfer encoding will be used if necessary. ''' enc = None for line in body.splitlines(): if len(line) > 950: body = quopri.encodestring(body) enc = "quoted-printable" break msg = email.MIMEText.MIMEText(body, subtype, charset) if enc: del msg['Content-Transfer-Encoding'] msg['Content-Transfer-Encoding'] = enc return msg def _charsets(ui): '''Obtains charsets to send mail parts not containing patches.''' charsets = [cs.lower() for cs in ui.configlist('email', 'charsets')] fallbacks = [encoding.fallbackencoding.lower(), encoding.encoding.lower(), 'utf-8'] for cs in fallbacks: # find unique charsets while keeping order if cs not in charsets: charsets.append(cs) return [cs for cs in charsets if not cs.endswith('ascii')] def _encode(ui, s, charsets): '''Returns (converted) string, charset tuple. Finds out best charset by cycling through sendcharsets in descending order. Tries both encoding and fallbackencoding for input. Only as last resort send as is in fake ascii. Caveat: Do not use for mail parts containing patches!''' try: s.decode('ascii') except UnicodeDecodeError: sendcharsets = charsets or _charsets(ui) for ics in (encoding.encoding, encoding.fallbackencoding): try: u = s.decode(ics) except UnicodeDecodeError: continue for ocs in sendcharsets: try: return u.encode(ocs), ocs except UnicodeEncodeError: pass except LookupError: ui.warn(_('ignoring invalid sendcharset: %s\n') % ocs) # if ascii, or all conversion attempts fail, send (broken) ascii return s, 'us-ascii' def headencode(ui, s, charsets=None, display=False): '''Returns RFC-2047 compliant header from given string.''' if not display: # split into words? s, cs = _encode(ui, s, charsets) return str(email.Header.Header(s, cs)) return s def _addressencode(ui, name, addr, charsets=None): name = headencode(ui, name, charsets) try: acc, dom = addr.split('@') acc = acc.encode('ascii') dom = dom.decode(encoding.encoding).encode('idna') addr = '%s@%s' % (acc, dom) except UnicodeDecodeError: raise util.Abort(_('invalid email address: %s') % addr) except ValueError: try: # too strict? addr = addr.encode('ascii') except UnicodeDecodeError: raise util.Abort(_('invalid local address: %s') % addr) return email.Utils.formataddr((name, addr)) def addressencode(ui, address, charsets=None, display=False): '''Turns address into RFC-2047 compliant header.''' if display or not address: return address or '' name, addr = email.Utils.parseaddr(address) return _addressencode(ui, name, addr, charsets) def addrlistencode(ui, addrs, charsets=None, display=False): '''Turns a list of addresses into a list of RFC-2047 compliant headers. A single element of input list may contain multiple addresses, but output always has one address per item''' if display: return [a.strip() for a in addrs if a.strip()] result = [] for name, addr in email.Utils.getaddresses(addrs): if name or addr: result.append(_addressencode(ui, name, addr, charsets)) return result def mimeencode(ui, s, charsets=None, display=False): '''creates mime text object, encodes it if needed, and sets charset and transfer-encoding accordingly.''' cs = 'us-ascii' if not display: s, cs = _encode(ui, s, charsets) return mimetextqp(s, 'plain', cs)
apache-2.0
staticsan/light-layers
requests/packages/oauthlib/oauth1/rfc5849/signature.py
74
20839
# -*- coding: utf-8 -*- from __future__ import absolute_import """ oauthlib.oauth1.rfc5849.signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module represents a direct implementation of `section 3.4`_ of the spec. Terminology: * Client: software interfacing with an OAuth API * Server: the API provider * Resource Owner: the user who is granting authorization to the client Steps for signing a request: 1. Collect parameters from the uri query, auth header, & body 2. Normalize those parameters 3. Normalize the uri 4. Pass the normalized uri, normalized parameters, and http method to construct the base string 5. Pass the base string and any keys needed to a signing function .. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4 """ import binascii import hashlib import hmac import urlparse from . import utils from oauthlib.common import extract_params, safe_string_equals def construct_base_string(http_method, base_string_uri, normalized_encoded_request_parameters): """**String Construction** Per `section 3.4.1.1`_ of the spec. For example, the HTTP request:: POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencoded Authorization: OAuth realm="Example", oauth_consumer_key="9djdj82h48djs9d2", oauth_token="kkk9d7dh3k39sjv7", oauth_signature_method="HMAC-SHA1", oauth_timestamp="137131201", oauth_nonce="7d8f3e4a", oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D" c2&a3=2+q is represented by the following signature base string (line breaks are for display purposes only):: POST&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q %26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_ key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk 9d7dh3k39sjv7 .. _`section 3.4.1.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.1 """ # The signature base string is constructed by concatenating together, # in order, the following HTTP request elements: # 1. The HTTP request method in uppercase. For example: "HEAD", # "GET", "POST", etc. If the request uses a custom HTTP method, it # MUST be encoded (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 base_string = utils.escape(http_method.upper()) # 2. An "&" character (ASCII code 38). base_string += u'&' # 3. The base string URI from `Section 3.4.1.2`_, after being encoded # (`Section 3.6`_). # # .. _`Section 3.4.1.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.2 # .. _`Section 3.4.6`: http://tools.ietf.org/html/rfc5849#section-3.4.6 base_string += utils.escape(base_string_uri) # 4. An "&" character (ASCII code 38). base_string += u'&' # 5. The request parameters as normalized in `Section 3.4.1.3.2`_, after # being encoded (`Section 3.6`). # # .. _`Section 3.4.1.3.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 # .. _`Section 3.4.6`: http://tools.ietf.org/html/rfc5849#section-3.4.6 base_string += utils.escape(normalized_encoded_request_parameters) return base_string def normalize_base_string_uri(uri): """**Base String URI** Per `section 3.4.1.2`_ of the spec. For example, the HTTP request:: GET /r%20v/X?id=123 HTTP/1.1 Host: EXAMPLE.COM:80 is represented by the base string URI: "http://example.com/r%20v/X". In another example, the HTTPS request:: GET /?q=1 HTTP/1.1 Host: www.example.net:8080 is represented by the base string URI: "https://www.example.net:8080/". .. _`section 3.4.1.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.2 """ if not isinstance(uri, unicode): raise ValueError('uri must be a unicode object.') # FIXME: urlparse does not support unicode scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri) # The scheme, authority, and path of the request resource URI `RFC3986` # are included by constructing an "http" or "https" URI representing # the request resource (without the query or fragment) as follows: # # .. _`RFC2616`: http://tools.ietf.org/html/rfc3986 # 1. The scheme and host MUST be in lowercase. scheme = scheme.lower() netloc = netloc.lower() # 2. The host and port values MUST match the content of the HTTP # request "Host" header field. # TODO: enforce this constraint # 3. The port MUST be included if it is not the default port for the # scheme, and MUST be excluded if it is the default. Specifically, # the port MUST be excluded when making an HTTP request `RFC2616`_ # to port 80 or when making an HTTPS request `RFC2818`_ to port 443. # All other non-default port numbers MUST be included. # # .. _`RFC2616`: http://tools.ietf.org/html/rfc2616 # .. _`RFC2818`: http://tools.ietf.org/html/rfc2818 default_ports = ( (u'http', u'80'), (u'https', u'443'), ) if u':' in netloc: host, port = netloc.split(u':', 1) if (scheme, port) in default_ports: netloc = host return urlparse.urlunparse((scheme, netloc, path, u'', u'', u'')) # ** Request Parameters ** # # Per `section 3.4.1.3`_ of the spec. # # In order to guarantee a consistent and reproducible representation of # the request parameters, the parameters are collected and decoded to # their original decoded form. They are then sorted and encoded in a # particular manner that is often different from their original # encoding scheme, and concatenated into a single string. # # .. _`section 3.4.1.3`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 def collect_parameters(uri_query='', body=[], headers=None, exclude_oauth_signature=True): """**Parameter Sources** Parameters starting with `oauth_` will be unescaped. Body parameters must be supplied as a dict, a list of 2-tuples, or a formencoded query string. Headers must be supplied as a dict. Per `section 3.4.1.3.1`_ of the spec. For example, the HTTP request:: POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1 Host: example.com Content-Type: application/x-www-form-urlencoded Authorization: OAuth realm="Example", oauth_consumer_key="9djdj82h48djs9d2", oauth_token="kkk9d7dh3k39sjv7", oauth_signature_method="HMAC-SHA1", oauth_timestamp="137131201", oauth_nonce="7d8f3e4a", oauth_signature="djosJKDKJSD8743243%2Fjdk33klY%3D" c2&a3=2+q contains the following (fully decoded) parameters used in the signature base sting:: +------------------------+------------------+ | Name | Value | +------------------------+------------------+ | b5 | =%3D | | a3 | a | | c@ | | | a2 | r b | | oauth_consumer_key | 9djdj82h48djs9d2 | | oauth_token | kkk9d7dh3k39sjv7 | | oauth_signature_method | HMAC-SHA1 | | oauth_timestamp | 137131201 | | oauth_nonce | 7d8f3e4a | | c2 | | | a3 | 2 q | +------------------------+------------------+ Note that the value of "b5" is "=%3D" and not "==". Both "c@" and "c2" have empty values. While the encoding rules specified in this specification for the purpose of constructing the signature base string exclude the use of a "+" character (ASCII code 43) to represent an encoded space character (ASCII code 32), this practice is widely used in "application/x-www-form-urlencoded" encoded values, and MUST be properly decoded, as demonstrated by one of the "a3" parameter instances (the "a3" parameter is used twice in this request). .. _`section 3.4.1.3.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 """ headers = headers or {} params = [] # The parameters from the following sources are collected into a single # list of name/value pairs: # * The query component of the HTTP request URI as defined by # `RFC3986, Section 3.4`_. The query component is parsed into a list # of name/value pairs by treating it as an # "application/x-www-form-urlencoded" string, separating the names # and values and decoding them as defined by # `W3C.REC-html40-19980424`_, Section 17.13.4. # # .. _`RFC3986, Section 3.4`: http://tools.ietf.org/html/rfc3986#section-3.4 # .. _`W3C.REC-html40-19980424`: http://tools.ietf.org/html/rfc5849#ref-W3C.REC-html40-19980424 if uri_query: params.extend(urlparse.parse_qsl(uri_query, keep_blank_values=True)) # * The OAuth HTTP "Authorization" header field (`Section 3.5.1`_) if # present. The header's content is parsed into a list of name/value # pairs excluding the "realm" parameter if present. The parameter # values are decoded as defined by `Section 3.5.1`_. # # .. _`Section 3.5.1`: http://tools.ietf.org/html/rfc5849#section-3.5.1 if headers: headers_lower = dict((k.lower(), v) for k, v in headers.items()) authorization_header = headers_lower.get(u'authorization') if authorization_header is not None: params.extend([i for i in utils.parse_authorization_header( authorization_header) if i[0] != u'realm']) # * The HTTP request entity-body, but only if all of the following # conditions are met: # * The entity-body is single-part. # # * The entity-body follows the encoding requirements of the # "application/x-www-form-urlencoded" content-type as defined by # `W3C.REC-html40-19980424`_. # * The HTTP request entity-header includes the "Content-Type" # header field set to "application/x-www-form-urlencoded". # # .._`W3C.REC-html40-19980424`: http://tools.ietf.org/html/rfc5849#ref-W3C.REC-html40-19980424 # TODO: enforce header param inclusion conditions bodyparams = extract_params(body) or [] params.extend(bodyparams) # ensure all oauth params are unescaped unescaped_params = [] for k, v in params: if k.startswith(u'oauth_'): v = utils.unescape(v) unescaped_params.append((k, v)) # The "oauth_signature" parameter MUST be excluded from the signature # base string if present. if exclude_oauth_signature: unescaped_params = filter(lambda i: i[0] != u'oauth_signature', unescaped_params) return unescaped_params def normalize_parameters(params): """**Parameters Normalization** Per `section 3.4.1.3.2`_ of the spec. For example, the list of parameters from the previous section would be normalized as follows: Encoded:: +------------------------+------------------+ | Name | Value | +------------------------+------------------+ | b5 | %3D%253D | | a3 | a | | c%40 | | | a2 | r%20b | | oauth_consumer_key | 9djdj82h48djs9d2 | | oauth_token | kkk9d7dh3k39sjv7 | | oauth_signature_method | HMAC-SHA1 | | oauth_timestamp | 137131201 | | oauth_nonce | 7d8f3e4a | | c2 | | | a3 | 2%20q | +------------------------+------------------+ Sorted:: +------------------------+------------------+ | Name | Value | +------------------------+------------------+ | a2 | r%20b | | a3 | 2%20q | | a3 | a | | b5 | %3D%253D | | c%40 | | | c2 | | | oauth_consumer_key | 9djdj82h48djs9d2 | | oauth_nonce | 7d8f3e4a | | oauth_signature_method | HMAC-SHA1 | | oauth_timestamp | 137131201 | | oauth_token | kkk9d7dh3k39sjv7 | +------------------------+------------------+ Concatenated Pairs:: +-------------------------------------+ | Name=Value | +-------------------------------------+ | a2=r%20b | | a3=2%20q | | a3=a | | b5=%3D%253D | | c%40= | | c2= | | oauth_consumer_key=9djdj82h48djs9d2 | | oauth_nonce=7d8f3e4a | | oauth_signature_method=HMAC-SHA1 | | oauth_timestamp=137131201 | | oauth_token=kkk9d7dh3k39sjv7 | +-------------------------------------+ and concatenated together into a single string (line breaks are for display purposes only):: a2=r%20b&a3=2%20q&a3=a&b5=%3D%253D&c%40=&c2=&oauth_consumer_key=9dj dj82h48djs9d2&oauth_nonce=7d8f3e4a&oauth_signature_method=HMAC-SHA1 &oauth_timestamp=137131201&oauth_token=kkk9d7dh3k39sjv7 .. _`section 3.4.1.3.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 """ # The parameters collected in `Section 3.4.1.3`_ are normalized into a # single string as follows: # # .. _`Section 3.4.1.3`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 # 1. First, the name and value of each parameter are encoded # (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 key_values = [(utils.escape(k), utils.escape(v)) for k, v in params] # 2. The parameters are sorted by name, using ascending byte value # ordering. If two or more parameters share the same name, they # are sorted by their value. key_values.sort() # 3. The name of each parameter is concatenated to its corresponding # value using an "=" character (ASCII code 61) as a separator, even # if the value is empty. parameter_parts = [u'{0}={1}'.format(k, v) for k, v in key_values] # 4. The sorted name/value pairs are concatenated together into a # single string by using an "&" character (ASCII code 38) as # separator. return u'&'.join(parameter_parts) def sign_hmac_sha1(base_string, client_secret, resource_owner_secret): """**HMAC-SHA1** The "HMAC-SHA1" signature method uses the HMAC-SHA1 signature algorithm as defined in `RFC2104`_:: digest = HMAC-SHA1 (key, text) Per `section 3.4.2`_ of the spec. .. _`RFC2104`: http://tools.ietf.org/html/rfc2104 .. _`section 3.4.2`: http://tools.ietf.org/html/rfc5849#section-3.4.2 """ # The HMAC-SHA1 function variables are used in following way: # text is set to the value of the signature base string from # `Section 3.4.1.1`_. # # .. _`Section 3.4.1.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.1 text = base_string # key is set to the concatenated values of: # 1. The client shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 key = utils.escape(client_secret or u'') # 2. An "&" character (ASCII code 38), which MUST be included # even when either secret is empty. key += u'&' # 3. The token shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 key += utils.escape(resource_owner_secret or u'') # FIXME: HMAC does not support unicode! key_utf8 = key.encode('utf-8') text_utf8 = text.encode('utf-8') signature = hmac.new(key_utf8, text_utf8, hashlib.sha1) # digest is used to set the value of the "oauth_signature" protocol # parameter, after the result octet string is base64-encoded # per `RFC2045, Section 6.8`. # # .. _`RFC2045, Section 6.8`: http://tools.ietf.org/html/rfc2045#section-6.8 return binascii.b2a_base64(signature.digest())[:-1].decode('utf-8') def sign_rsa_sha1(base_string, rsa_private_key): """**RSA-SHA1** Per `section 3.4.3`_ of the spec. The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in `RFC3447, Section 8.2`_ (also known as PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To use this method, the client MUST have established client credentials with the server that included its RSA public key (in a manner that is beyond the scope of this specification). NOTE: this method requires the python-rsa library. .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3 .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2 """ # TODO: finish RSA documentation from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA key = RSA.importKey(rsa_private_key) h = SHA.new(base_string) p = PKCS1_v1_5.new(key) return binascii.b2a_base64(p.sign(h))[:-1].decode('utf-8') def sign_plaintext(client_secret, resource_owner_secret): """Sign a request using plaintext. Per `section 3.4.4`_ of the spec. The "PLAINTEXT" method does not employ a signature algorithm. It MUST be used with a transport-layer mechanism such as TLS or SSL (or sent over a secure channel with equivalent protections). It does not utilize the signature base string or the "oauth_timestamp" and "oauth_nonce" parameters. .. _`section 3.4.4`: http://tools.ietf.org/html/rfc5849#section-3.4.4 """ # The "oauth_signature" protocol parameter is set to the concatenated # value of: # 1. The client shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 signature = utils.escape(client_secret or u'') # 2. An "&" character (ASCII code 38), which MUST be included even # when either secret is empty. signature += u'&' # 3. The token shared-secret, after being encoded (`Section 3.6`_). # # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 signature += utils.escape(resource_owner_secret or u'') return signature def verify_hmac_sha1(request, client_secret=None, resource_owner_secret=None): """Verify a HMAC-SHA1 signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4 """ norm_params = normalize_parameters(request.params) uri = normalize_base_string_uri(request.uri) base_string = construct_base_string(request.http_method, uri, norm_params) signature = sign_hmac_sha1(base_string, client_secret, resource_owner_secret) return safe_string_equals(signature, request.signature) def verify_rsa_sha1(request, rsa_public_key): """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature. Per `section 3.4.3`_ of the spec. Note this method requires the PyCrypto library. .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3 """ from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA key = RSA.importKey(rsa_public_key) norm_params = normalize_parameters(request.params) uri = normalize_base_string_uri(request.uri) message = construct_base_string(request.http_method, uri, norm_params) h = SHA.new(message) p = PKCS1_v1_5.new(key) sig = binascii.a2b_base64(request.signature) return p.verify(h, sig) def verify_plaintext(request, client_secret=None, resource_owner_secret=None): """Verify a PLAINTEXT signature. Per `section 3.4`_ of the spec. .. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4 """ signature = sign_plaintext(client_secret, resource_owner_secret) return safe_string_equals(signature, request.signature)
mit
hydrospanner/DForurm
DForurm/env/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py
490
4141
import calendar import time from email.utils import formatdate, parsedate, parsedate_tz from datetime import datetime, timedelta TIME_FMT = "%a, %d %b %Y %H:%M:%S GMT" def expire_after(delta, date=None): date = date or datetime.now() return date + delta def datetime_to_header(dt): return formatdate(calendar.timegm(dt.timetuple())) class BaseHeuristic(object): def warning(self, response): """ Return a valid 1xx warning header value describing the cache adjustments. The response is provided too allow warnings like 113 http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need to explicitly say response is over 24 hours old. """ return '110 - "Response is Stale"' def update_headers(self, response): """Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers. """ return {} def apply(self, response): updated_headers = self.update_headers(response) if updated_headers: response.headers.update(updated_headers) warning_header_value = self.warning(response) if warning_header_value is not None: response.headers.update({'Warning': warning_header_value}) return response class OneDayCache(BaseHeuristic): """ Cache the response by providing an expires 1 day in the future. """ def update_headers(self, response): headers = {} if 'expires' not in response.headers: date = parsedate(response.headers['date']) expires = expire_after(timedelta(days=1), date=datetime(*date[:6])) headers['expires'] = datetime_to_header(expires) headers['cache-control'] = 'public' return headers class ExpiresAfter(BaseHeuristic): """ Cache **all** requests for a defined time period. """ def __init__(self, **kw): self.delta = timedelta(**kw) def update_headers(self, response): expires = expire_after(self.delta) return { 'expires': datetime_to_header(expires), 'cache-control': 'public', } def warning(self, response): tmpl = '110 - Automatically cached for %s. Response might be stale' return tmpl % self.delta class LastModified(BaseHeuristic): """ If there is no Expires header already, fall back on Last-Modified using the heuristic from http://tools.ietf.org/html/rfc7234#section-4.2.2 to calculate a reasonable value. Firefox also does something like this per https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ http://lxr.mozilla.org/mozilla-release/source/netwerk/protocol/http/nsHttpResponseHead.cpp#397 Unlike mozilla we limit this to 24-hr. """ cacheable_by_default_statuses = set([ 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501 ]) def update_headers(self, resp): headers = resp.headers if 'expires' in headers: return {} if 'cache-control' in headers and headers['cache-control'] != 'public': return {} if resp.status not in self.cacheable_by_default_statuses: return {} if 'date' not in headers or 'last-modified' not in headers: return {} date = calendar.timegm(parsedate_tz(headers['date'])) last_modified = parsedate(headers['last-modified']) if date is None or last_modified is None: return {} now = time.time() current_age = max(0, now - date) delta = date - calendar.timegm(last_modified) freshness_lifetime = max(0, min(delta / 10, 24 * 3600)) if freshness_lifetime <= current_age: return {} expires = date + freshness_lifetime return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))} def warning(self, resp): return None
mit
xxvii27/gae-pushtest
bp_includes/lib/captcha.py
30
3056
import urllib2, urllib API_SSL_SERVER="https://www.google.com/recaptcha/api" API_SERVER="http://www.google.com/recaptcha/api" VERIFY_SERVER="www.google.com" class RecaptchaResponse(object): def __init__(self, is_valid, error_code=None): self.is_valid = is_valid self.error_code = error_code def displayhtml (public_key, use_ssl = False, error = None): """Gets the HTML to display for reCAPTCHA public_key -- The public api key use_ssl -- Should the request be sent over ssl? error -- An error message to display (from RecaptchaResponse.error_code)""" error_param = '' if error: error_param = '&error=%s' % error if use_ssl: server = API_SSL_SERVER else: server = API_SERVER return """<script src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script> <noscript> <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type='hidden' name='recaptcha_response_field' value='manual_challenge' /> </noscript> """ % { 'ApiServer' : server, 'PublicKey' : public_key, 'ErrorParam' : error_param, } def submit (recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip): """ Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form recaptcha_response_field -- The value of recaptcha_response_field from the form private_key -- your reCAPTCHA private key remoteip -- the user's ip address """ if not (recaptcha_response_field and recaptcha_challenge_field and len (recaptcha_response_field) and len (recaptcha_challenge_field)): return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol') def encode_if_necessary(s): if isinstance(s, unicode): return s.encode('utf-8') return s params = urllib.urlencode ({ 'privatekey': encode_if_necessary(private_key), 'remoteip' : encode_if_necessary(remoteip), 'challenge': encode_if_necessary(recaptcha_challenge_field), 'response' : encode_if_necessary(recaptcha_response_field), }) request = urllib2.Request ( url = "http://%s/recaptcha/api/verify" % VERIFY_SERVER, data = params, headers = { "Content-type": "application/x-www-form-urlencoded", "User-agent": "reCAPTCHA Python" } ) httpresp = urllib2.urlopen (request) return_values = httpresp.read ().splitlines (); httpresp.close(); return_code = return_values [0] if (return_code == "true"): return RecaptchaResponse (is_valid=True) else: return RecaptchaResponse (is_valid=False, error_code = return_values [1])
lgpl-3.0
ucoin-bot/cutecoin
lib/ucoinpy/documents/peer.py
2
4141
''' Created on 2 déc. 2014 @author: inso ''' import re from ..api.bma import ConnectionHandler from . import Document from .. import PROTOCOL_VERSION, MANAGED_API class Peer(Document): """ Version: VERSION Type: Peer Currency: CURRENCY_NAME PublicKey: NODE_PUBLICKEY Block: BLOCK Endpoints: END_POINT_1 END_POINT_2 END_POINT_3 [...] """ re_type = re.compile("Type: (Peer)") re_pubkey = re.compile("PublicKey: ([1-9A-Za-z][^OIl]{42,45})\n") re_block = re.compile("Block: ([0-9]+-[0-9a-fA-F]{5,40})\n") re_endpoints = re.compile("Endpoints:\n") def __init__(self, version, currency, pubkey, blockid, endpoints, signature): super().__init__(version, currency, [signature]) self.pubkey = pubkey self.blockid = blockid self.endpoints = endpoints @classmethod def from_signed_raw(cls, raw): lines = raw.splitlines(True) n = 0 version = int(Peer.re_version.match(lines[n]).group(1)) n = n + 1 Peer.re_type.match(lines[n]).group(1) n = n + 1 currency = Peer.re_currency.match(lines[n]).group(1) n = n + 1 pubkey = Peer.re_pubkey.match(lines[n]).group(1) n = n + 1 blockid = Peer.re_block.match(lines[n]).group(1) n = n + 1 Peer.re_endpoints.match(lines[n]) n = n + 1 endpoints = [] while not Peer.re_signature.match(lines[n]): endpoint = Endpoint.from_inline(lines[n]) endpoints.append(endpoint) n = n + 1 signature = Peer.re_signature.match(lines[n]).group(1) return cls(version, currency, pubkey, blockid, endpoints, signature) def raw(self): doc = """Version: {0} Type: Peer Currency: {1} PublicKey: {2} Block: {3} Endpoints: """.format(self.version, self.currency, self.pubkey, self.blockid) for endpoint in self.endpoints: doc += "{0}\n".format(endpoint.inline()) doc += "{0}\n".format(self.signatures[0]) return doc class Endpoint(): """ Describing endpoints """ @staticmethod def from_inline(inline): for api in MANAGED_API: if (inline.startswith(api)): if (api == "BASIC_MERKLED_API"): return BMAEndpoint.from_inline(inline) return UnknownEndpoint.from_inline(inline) class UnknownEndpoint(Endpoint): def __init__(self, api, properties): self.api = api self.properties = properties @classmethod def from_inline(cls, inline): api = inline.split()[0] properties = inline.split()[1:] return cls(api, properties) def inline(self): doc = self.api for p in self.properties: doc += " {0}".format(p) return doc class BMAEndpoint(Endpoint): re_inline = re.compile('^BASIC_MERKLED_API(?: ([a-z0-9-_.]*(?:.[a-zA-Z])))?(?: ((?:[0-9.]{1,4}){4}))?(?: ((?:[0-9a-f:]{4,5}){4,8}))?(?: ([0-9]+))$') @classmethod def from_inline(cls, inline): m = BMAEndpoint.re_inline.match(inline) server = m.group(1) ipv4 = m.group(2) ipv6 = m.group(3) port = int(m.group(4)) return cls(server, ipv4, ipv6, port) def __init__(self, server, ipv4, ipv6, port): self.server = server self.ipv4 = ipv4 self.ipv6 = ipv6 self.port = port def inline(self): return "BASIC_MERKLED_API{DNS}{IPv4}{IPv6}{PORT}" \ .format(DNS=(" {0}".format(self.server) if self.server else ""), IPv4=(" {0}".format(self.ipv4) if self.ipv4 else ""), IPv6=(" {0}".format(self.ipv6) if self.ipv6 else ""), PORT=(" {0}".format(self.port) if self.port else "")) def conn_handler(self): if self.server: return ConnectionHandler(self.server, self.port) elif self.ipv4: return ConnectionHandler(self.ipv4, self.port) else: return ConnectionHandler(self.ipv6, self.port)
mit
40223137/2015abc
static/Brython3.1.1-20150328-091302/Lib/unittest/suite.py
748
9715
"""TestSuite""" import sys from . import case from . import util __unittest = True def _call_if_exists(parent, attr): func = getattr(parent, attr, lambda: None) func() class BaseTestSuite(object): """A simple test suite that doesn't provide class or module shared fixtures. """ def __init__(self, tests=()): self._tests = [] self.addTests(tests) def __repr__(self): return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return list(self) == list(other) def __ne__(self, other): return not self == other def __iter__(self): return iter(self._tests) def countTestCases(self): cases = 0 for test in self: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not callable(test): raise TypeError("{} is not callable".format(repr(test))) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): raise TypeError("TestCases and TestSuites must be instantiated " "before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, str): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for test in self: if result.shouldStop: break test(result) return result def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the tests without collecting errors in a TestResult""" for test in self: test.debug() class TestSuite(BaseTestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ def run(self, result, debug=False): topLevel = False if getattr(result, '_testRunEntered', False) is False: result._testRunEntered = topLevel = True for test in self: if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue if not debug: test(result) else: test.debug() if topLevel: self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) result._testRunEntered = False return result def debug(self): """Run the tests without collecting errors in a TestResult""" debug = _DebugResult() self.run(debug, True) ################################ def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__", False): return try: currentClass._classSetupFailed = False except TypeError: # test may actually be a function # so its class will be a builtin-type pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: _call_if_exists(result, '_setupStdout') try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise currentClass._classSetupFailed = True className = util.strclass(currentClass) errorName = 'setUpClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _get_previous_module(self, result): previousModule = None previousClass = getattr(result, '_previousTestClass', None) if previousClass is not None: previousModule = previousClass.__module__ return previousModule def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: module = sys.modules[currentModule] except KeyError: return setUpModule = getattr(module, 'setUpModule', None) if setUpModule is not None: _call_if_exists(result, '_setupStdout') try: setUpModule() except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True errorName = 'setUpModule (%s)' % currentModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _addClassOrModuleLevelException(self, result, exception, errorName): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: result.addError(error, sys.exc_info()) def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except KeyError: return tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: _call_if_exists(result, '_setupStdout') try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if getattr(previousClass, '_classSetupFailed', False): return if getattr(result, '_moduleSetUpFailed', False): return if getattr(previousClass, "__unittest_skip__", False): return tearDownClass = getattr(previousClass, 'tearDownClass', None) if tearDownClass is not None: _call_if_exists(result, '_setupStdout') try: tearDownClass() except Exception as e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) errorName = 'tearDownClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) finally: _call_if_exists(result, '_restoreStdout') class _ErrorHolder(object): """ Placeholder for a TestCase inside a result. As far as a TestResult is concerned, this looks exactly like a unit test. Used to insert arbitrary errors into a test suite run. """ # Inspired by the ErrorHolder from Twisted: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py # attribute used by TestResult._exc_info_to_string failureException = None def __init__(self, description): self.description = description def id(self): return self.description def shortDescription(self): return None def __repr__(self): return "<ErrorHolder description=%r>" % (self.description,) def __str__(self): return self.id() def run(self, result): # could call result.addError(...) - but this test-like object # shouldn't be run anyway pass def __call__(self, result): return self.run(result) def countTestCases(self): return 0 def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class _DebugResult(object): "Used by the TestSuite to hold previous class when running in debug." _previousTestClass = None _moduleSetUpFailed = False shouldStop = False
gpl-3.0
felixbr/nosql-rest-preprocessor
nosql_rest_preprocessor/models.py
1
5131
from __future__ import absolute_import, unicode_literals, print_function, division from nosql_rest_preprocessor import exceptions from nosql_rest_preprocessor.utils import non_mutating class BaseModel(object): required_attributes = set() optional_attributes = None immutable_attributes = set() private_attributes = set() sub_models = {} resolved_attributes = {} @classmethod def validate(cls, obj): cls._check_required_attributes(obj) cls._check_allowed_attributes(obj) # recurse for sub models for attr, sub_model in cls.sub_models.items(): if attr in obj.keys(): sub_model.validate(obj[attr]) return obj @classmethod @non_mutating def prepare_response(cls, obj): # remove non-public attrs for attr in cls.private_attributes: obj.pop(attr, None) # recurse for sub models for attr, sub_model in cls.sub_models.items(): if attr in obj.keys(): obj[attr] = sub_model.prepare_response(obj[attr]) return obj @classmethod def merge_updated(cls, db_obj, new_obj): cls.validate(new_obj) merged_obj = {} # check if previously present immutable attributes should be deleted for key in cls.immutable_attributes: if key in db_obj and key not in new_obj: raise exceptions.ChangingImmutableAttributeError() # copy attributes into merged_obj for key, value in new_obj.items(): cls._check_immutable_attrs_on_update(key, value, db_obj) if key in cls.resolved_attributes and isinstance(value, dict): # ignore resolved attributes in update merged_obj[key] = db_obj[key] else: merged_obj[key] = value # recurse for sub models for attr, sub_model in cls.sub_models.items(): merged_obj[attr] = sub_model.merge_updated(db_obj[attr], new_obj[attr]) return merged_obj @classmethod def _check_immutable_attrs_on_update(cls, key, value, db_obj): # check if immutable attributes should be changed if key in cls.immutable_attributes: if db_obj[key] != value: raise exceptions.ChangingImmutableAttributeError() @classmethod def _check_required_attributes(cls, obj): for attr in cls.required_attributes: if isinstance(attr, tuple): set_wanted = set(attr[1]) set_contained = set(obj.keys()) if attr[0] == 'one_of': if len(set_wanted & set_contained) < 1: raise exceptions.ValidationError() elif attr[0] == 'either_of': if len(set_wanted & set_contained) != 1: raise exceptions.ValidationError() else: raise exceptions.ConfigurationError() else: if attr not in obj.keys(): raise exceptions.ValidationError() @classmethod def _check_allowed_attributes(cls, obj): if cls.optional_attributes is not None: required = cls._required_attributes() for attr in obj.keys(): if attr in required: continue allowed = False for opt_attr in cls.optional_attributes: if attr == opt_attr: allowed = True break elif isinstance(opt_attr, tuple): if opt_attr[0] == 'all_of': if attr in opt_attr[1]: # if one of these is in obj.keys()... if not set(opt_attr[1]).issubset(obj.keys()): # ...all of them have to be there raise exceptions.ValidationError() else: allowed = True break elif opt_attr[0] == 'either_of': if attr in opt_attr[1]: # if one of these is in obj.keys()... if next((key for key in opt_attr[1] if key != attr and key in obj.keys()), None): # ...no other key may be present in obj.keys() raise exceptions.ValidationError() else: allowed = True break else: raise exceptions.ConfigurationError() if not allowed: # if we haven't found attr anywhere in cls.optional_attributes raise exceptions.ValidationError() @classmethod def _required_attributes(cls): required = set() for attr in cls.required_attributes: if isinstance(attr, tuple): required = required | set(attr[1]) else: required.add(attr) return required
mit
olt/mapproxy
mapproxy/test/system/test_arcgis.py
2
5409
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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. from __future__ import division from io import BytesIO from mapproxy.request.wms import WMS111FeatureInfoRequest from mapproxy.test.image import is_png, create_tmp_image from mapproxy.test.http import mock_httpd from mapproxy.test.system import module_setup, module_teardown, SystemTest from nose.tools import eq_ test_config = {} def setup_module(): module_setup(test_config, 'arcgis.yaml') def teardown_module(): module_teardown(test_config) transp = create_tmp_image((512, 512), mode='RGBA', color=(0, 0, 0, 0)) class TestArcgisSource(SystemTest): config = test_config def setup(self): SystemTest.setup(self) self.common_fi_req = WMS111FeatureInfoRequest(url='/service?', param=dict(x='10', y='20', width='200', height='200', layers='app2_with_layers_fi_layer', format='image/png', query_layers='app2_with_layers_fi_layer', styles='', bbox='1000,400,2000,1400', srs='EPSG:3857', info_format='application/json')) def test_get_tile(self): expected_req = [({'path': '/arcgis/rest/services/ExampleLayer/ImageServer/exportImage?f=image&format=png&imageSR=900913&bboxSR=900913&bbox=-20037508.342789244,-20037508.342789244,20037508.342789244,20037508.342789244&size=512,512'}, {'body': transp, 'headers': {'content-type': 'image/png'}}), ] with mock_httpd(('localhost', 42423), expected_req, bbox_aware_query_comparator=True): resp = self.app.get('/tms/1.0.0/app2_layer/0/0/1.png') eq_(resp.content_type, 'image/png') eq_(resp.content_length, len(resp.body)) data = BytesIO(resp.body) assert is_png(data) def test_get_tile_with_layer(self): expected_req = [({'path': '/arcgis/rest/services/ExampleLayer/MapServer/export?f=image&format=png&layers=show:0,1&imageSR=900913&bboxSR=900913&bbox=-20037508.342789244,-20037508.342789244,20037508.342789244,20037508.342789244&size=512,512'}, {'body': transp, 'headers': {'content-type': 'image/png'}}), ] with mock_httpd(('localhost', 42423), expected_req, bbox_aware_query_comparator=True): resp = self.app.get('/tms/1.0.0/app2_with_layers_layer/0/0/1.png') eq_(resp.content_type, 'image/png') eq_(resp.content_length, len(resp.body)) data = BytesIO(resp.body) assert is_png(data) def test_get_tile_from_missing_arcgis_layer(self): expected_req = [({'path': '/arcgis/rest/services/NonExistentLayer/ImageServer/exportImage?f=image&format=png&imageSR=900913&bboxSR=900913&bbox=-20037508.342789244,-20037508.342789244,20037508.342789244,20037508.342789244&size=512,512'}, {'body': b'', 'status': 400}), ] with mock_httpd(('localhost', 42423), expected_req, bbox_aware_query_comparator=True): resp = self.app.get('/tms/1.0.0/app2_wrong_url_layer/0/0/1.png', status=500) eq_(resp.status_code, 500) def test_identify(self): expected_req = [( {'path': '/arcgis/rest/services/ExampleLayer/MapServer/identify?f=json&' 'geometry=1050.000000,1300.000000&returnGeometry=true&imageDisplay=200,200,96' '&mapExtent=1000.0,400.0,2000.0,1400.0&layers=show:1,2,3' '&tolerance=10&geometryType=esriGeometryPoint&sr=3857' }, {'body': b'{"results": []}', 'headers': {'content-type': 'application/json'}}), ] with mock_httpd(('localhost', 42423), expected_req, bbox_aware_query_comparator=True): resp = self.app.get(self.common_fi_req) eq_(resp.content_type, 'application/json') eq_(resp.content_length, len(resp.body)) eq_(resp.body, b'{"results": []}') def test_transformed_identify(self): expected_req = [( {'path': '/arcgis/rest/services/ExampleLayer/MapServer/identify?f=json&' 'geometry=573295.377585,6927820.884193&returnGeometry=true&imageDisplay=200,321,96' '&mapExtent=556597.453966,6446275.84102,890555.926346,6982997.92039&layers=show:1,2,3' '&tolerance=10&geometryType=esriGeometryPoint&sr=3857' }, {'body': b'{"results": []}', 'headers': {'content-type': 'application/json'}}), ] with mock_httpd(('localhost', 42423), expected_req): self.common_fi_req.params.bbox = '5,50,8,53' self.common_fi_req.params.srs = 'EPSG:4326' resp = self.app.get(self.common_fi_req) eq_(resp.content_type, 'application/json') eq_(resp.content_length, len(resp.body)) eq_(resp.body, b'{"results": []}')
apache-2.0
juliakreger/bifrost
playbooks/library/os_ironic_node.py
1
12262
#!/usr/bin/python # coding: utf-8 -*- # (c) 2015, Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False DOCUMENTATION = ''' --- module: os_ironic_node short_description: Activate/Deactivate Bare Metal Resources from OpenStack extends_documentation_fragment: openstack description: - Deploy to nodes controlled by Ironic. options: state: description: - Indicates desired state of the resource choices: ['present', 'absent'] default: present deploy: description: - Indicates if the resource should be deployed. Allows for deployment logic to be disengaged and control of the node power or maintenance state to be changed. choices: ['true', 'false'] default: true uuid: description: - globally unique identifier (UUID) to be given to the resource. required: false default: None ironic_url: description: - If noauth mode is utilized, this is required to be set to the endpoint URL for the Ironic API. Use with "auth" and "auth_type" settings set to None. required: false default: None config_drive: description: - A configdrive file or HTTP(S) URL that will be passed along to the node. required: false default: None instance_info: description: - Definition of the instance information which is used to deploy the node. This information is only required when an instance is set to present. image_source: description: - An HTTP(S) URL where the image can be retrieved from. image_checksum: description: - The checksum of image_source. image_disk_format: description: - The type of image that has been requested to be deployed. power: description: - A setting to allow power state to be asserted allowing nodes that are not yet deployed to be powered on, and nodes that are deployed to be powered off. choices: ['present', 'absent'] default: present maintenance: description: - A setting to allow the direct control if a node is in maintenance mode. required: false default: false maintenance_reason: description: - A string expression regarding the reason a node is in a maintenance mode. required: false default: None requirements: ["shade"] ''' EXAMPLES = ''' # Activate a node by booting an image with a configdrive attached os_ironic_node: cloud: "openstack" uuid: "d44666e1-35b3-4f6b-acb0-88ab7052da69" state: present power: present deploy: True maintenance: False config_drive: "http://192.168.1.1/host-configdrive.iso" instance_info: image_source: "http://192.168.1.1/deploy_image.img" image_checksum: "356a6b55ecc511a20c33c946c4e678af" image_disk_format: "qcow" delegate_to: localhost ''' def _choose_id_value(module): if module.params['uuid']: return module.params['uuid'] if module.params['name']: return module.params['name'] return None # TODO(TheJulia): Change this over to use the machine patch method # in shade once it is available. def _prepare_instance_info_patch(instance_info): patch = [] patch.append({ 'op': 'replace', 'path': '/instance_info', 'value': instance_info }) return patch def _is_true(value): true_values = [True, 'yes', 'Yes', 'True', 'true', 'present', 'on'] if value in true_values: return True return False def _is_false(value): false_values = [False, None, 'no', 'No', 'False', 'false', 'absent', 'off'] if value in false_values: return True return False def _check_set_maintenance(module, cloud, node): if _is_true(module.params['maintenance']): if _is_false(node['maintenance']): cloud.set_machine_maintenance_state( node['uuid'], True, reason=module.params['maintenance_reason']) module.exit_json(changed=True, msg="Node has been set into " "maintenance mode") else: # User has requested maintenance state, node is already in the # desired state, checking to see if the reason has changed. if (str(node['maintenance_reason']) not in str(module.params['maintenance_reason'])): cloud.set_machine_maintenance_state( node['uuid'], True, reason=module.params['maintenance_reason']) module.exit_json(changed=True, msg="Node maintenance reason " "updated, cannot take any " "additional action.") elif _is_false(module.params['maintenance']): if node['maintenance'] is True: cloud.remove_machine_from_maintenance(node['uuid']) return True else: module.fail_json(msg="maintenance parameter was set but a valid " "the value was not recognized.") return False def _check_set_power_state(module, cloud, node): if 'power on' in str(node['power_state']): if _is_false(module.params['power']): # User has requested the node be powered off. cloud.set_machine_power_off(node['uuid']) module.exit_json(changed=True, msg="Power requested off") if 'power off' in str(node['power_state']): if (_is_false(module.params['power']) and _is_false(module.params['state'])): return False if (_is_false(module.params['power']) and _is_false(module.params['state'])): module.exit_json( changed=False, msg="Power for node is %s, node must be reactivated " "OR set to state absent" ) # In the event the power has been toggled on and # deployment has been requested, we need to skip this # step. if (_is_true(module.params['power']) and _is_false(module.params['deploy'])): # Node is powered down when it is not awaiting to be provisioned cloud.set_machine_power_on(node['uuid']) return True # Default False if no action has been taken. return False def main(): argument_spec = openstack_full_argument_spec( uuid=dict(required=False), name=dict(required=False), instance_info=dict(type='dict', required=False), config_drive=dict(required=False), ironic_url=dict(required=False), state=dict(required=False, default='present'), maintenance=dict(required=False), maintenance_reason=dict(required=False), power=dict(required=False, default='present'), deploy=dict(required=False, default=True), ) module_kwargs = openstack_module_kwargs() module = AnsibleModule(argument_spec, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') if (module.params['auth_type'] in [None, 'None'] and module.params['ironic_url'] is None): module.fail_json(msg="Authentication appears disabled, Please " "define an ironic_url parameter") if (module.params['ironic_url'] and module.params['auth_type'] in [None, 'None']): module.params['auth'] = dict( endpoint=module.params['ironic_url'] ) node_id = _choose_id_value(module) if not node_id: module.fail_json(msg="A uuid or name value must be defined " "to use this module.") try: cloud = shade.operator_cloud(**module.params) node = cloud.get_machine(node_id) if node is None: module.fail_json(msg="node not found") uuid = node['uuid'] instance_info = module.params['instance_info'] changed = False # User has reqeusted desired state to be in maintenance state. if module.params['state'] is 'maintenance': module.params['maintenance'] = True if node['provision_state'] in [ 'cleaning', 'deleting', 'wait call-back']: module.fail_json(msg="Node is in %s state, cannot act upon the " "request as the node is in a transition " "state" % node['provision_state']) # TODO(TheJulia) This is in-development code, that requires # code in the shade library that is still in development. if _check_set_maintenance(module, cloud, node): if node['provision_state'] in 'active': module.exit_json(changed=True, result="Maintenance state changed") changed = True node = cloud.get_machine(node_id) if _check_set_power_state(module, cloud, node): changed = True node = cloud.get_machine(node_id) if _is_true(module.params['state']): if _is_false(module.params['deploy']): module.exit_json( changed=changed, result="User request has explicitly disabled " "deployment logic" ) if 'active' in node['provision_state']: module.exit_json( changed=changed, result="Node already in an active state." ) if instance_info is None: module.fail_json( changed=changed, msg="When setting an instance to present, " "instance_info is a required variable.") # TODO(TheJulia): Update instance info, however info is # deployment specific. Perhaps consider adding rebuild # support, although there is a known desire to remove # rebuild support from Ironic at some point in the future. patch = _prepare_instance_info_patch(instance_info) cloud.set_node_instance_info(uuid, patch) cloud.validate_node(uuid) cloud.activate_node(uuid, module.params['config_drive']) # TODO(TheJulia): Add more error checking and a wait option. # We will need to loop, or just add the logic to shade, # although this could be a very long running process as # baremetal deployments are not a "quick" task. module.exit_json(changed=changed, result="node activated") elif _is_false(module.params['state']): if node['provision_state'] not in "deleted": cloud.purge_node_instance_info(uuid) cloud.deactivate_node(uuid) module.exit_json(changed=True, result="deleted") else: module.exit_json(changed=False, result="node not found") else: module.fail_json(msg="State must be present, absent, " "maintenance, off") except shade.OpenStackCloudException as e: module.fail_json(msg=e.message) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * main()
apache-2.0
FNCS/ns-3.24
src/visualizer/visualizer/plugins/olsr.py
182
3935
import gtk import ns.core import ns.network import ns.internet import ns.olsr from visualizer.base import InformationWindow class ShowOlsrRoutingTable(InformationWindow): ( COLUMN_DESTINATION, COLUMN_NEXT_HOP, COLUMN_INTERFACE, COLUMN_NUM_HOPS, ) = range(4) def __init__(self, visualizer, node_index): InformationWindow.__init__(self) self.win = gtk.Dialog(parent=visualizer.window, flags=gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_NO_SEPARATOR, buttons=(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.win.set_default_size(gtk.gdk.screen_width()/2, gtk.gdk.screen_height()/2) self.win.connect("response", self._response_cb) self.win.set_title("OLSR routing table for node %i" % node_index) self.visualizer = visualizer self.node_index = node_index self.table_model = gtk.ListStore(str, str, str, int) treeview = gtk.TreeView(self.table_model) treeview.show() sw = gtk.ScrolledWindow() sw.set_properties(hscrollbar_policy=gtk.POLICY_AUTOMATIC, vscrollbar_policy=gtk.POLICY_AUTOMATIC) sw.show() sw.add(treeview) self.win.vbox.add(sw) # Dest. column = gtk.TreeViewColumn('Destination', gtk.CellRendererText(), text=self.COLUMN_DESTINATION) treeview.append_column(column) # Next hop column = gtk.TreeViewColumn('Next hop', gtk.CellRendererText(), text=self.COLUMN_NEXT_HOP) treeview.append_column(column) # Interface column = gtk.TreeViewColumn('Interface', gtk.CellRendererText(), text=self.COLUMN_INTERFACE) treeview.append_column(column) # Num. Hops column = gtk.TreeViewColumn('Num. Hops', gtk.CellRendererText(), text=self.COLUMN_NUM_HOPS) treeview.append_column(column) self.visualizer.add_information_window(self) self.win.show() def _response_cb(self, win, response): self.win.destroy() self.visualizer.remove_information_window(self) def update(self): node = ns.network.NodeList.GetNode(self.node_index) olsr = node.GetObject(ns.olsr.olsr.RoutingProtocol.GetTypeId()) ipv4 = node.GetObject(ns.internet.Ipv4.GetTypeId()) if olsr is None: return self.table_model.clear() for route in olsr.GetRoutingTableEntries(): tree_iter = self.table_model.append() netdevice = ipv4.GetNetDevice(route.interface) if netdevice is None: interface_name = 'lo' else: interface_name = ns.core.Names.FindName(netdevice) if not interface_name: interface_name = "(interface %i)" % route.interface self.table_model.set(tree_iter, self.COLUMN_DESTINATION, str(route.destAddr), self.COLUMN_NEXT_HOP, str(route.nextAddr), self.COLUMN_INTERFACE, interface_name, self.COLUMN_NUM_HOPS, route.distance) def populate_node_menu(viz, node, menu): ns3_node = ns.network.NodeList.GetNode(node.node_index) olsr = ns3_node.GetObject(ns.olsr.olsr.RoutingProtocol.GetTypeId()) if olsr is None: print "No OLSR" return menu_item = gtk.MenuItem("Show OLSR Routing Table") menu_item.show() def _show_ipv4_routing_table(dummy_menu_item): ShowOlsrRoutingTable(viz, node.node_index) menu_item.connect("activate", _show_ipv4_routing_table) menu.add(menu_item) def register(viz): viz.connect("populate-node-menu", populate_node_menu)
gpl-2.0
fisele/slimta-abusix
slimta/policy/__init__.py
2
4631
# Copyright (c) 2012 Ian C. Good # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # """Package containing useful policies, which can be configured to run before queuing or before relaying the message with the :meth:`slimta.queue.Queue.add_policy()` and :meth:`slimta.relay.Relay.add_policy()`, respectively. If a policy is applied before queuing, it is executed only once and any changes it makes to the |Envelope| will be stored persistently. This is especially useful for tasks such as header and content modification, since these may be more expensive operations and should only run once. If a policy is applied before relaying, it is executed before each delivery attempt and no resulting changes will be persisted to storage. This is useful for policies that have to do with delivery, such as forwarding. """ from __future__ import absolute_import from slimta.core import SlimtaError __all__ = ['PolicyError', 'QueuePolicy', 'RelayPolicy'] class PolicyError(SlimtaError): """Base exception for all custom ``slimta.policy`` errors.""" pass class QueuePolicy(object): """Base class for queue policies. These are run before a message is persistently queued and may overwrite the original |Envelope| with one or many new |Envelope| objects. :: class MyQueuePolicy(QueuePolicy): def apply(self, env): env['X-When-Queued'] = str(time.time()) my_queue.add_policy(MyQueuePolicy()) """ def apply(self, envelope): """:class:`QueuePolicy` sub-classes must override this method, which will be called by the |Queue| before storage. :param envelope: The |Envelope| object the policy execution should apply any changes to. This envelope object *may* be modified, though if new envelopes are returned this object is discarded. :returns: Optionally return or generate an iterable of |Envelope| objects to replace the given ``envelope`` going forward. Returning ``None`` or an empty list will keep using ``envelope``. """ raise NotImplementedError() class RelayPolicy(object): """Base class for relay policies. These are run immediately before a relay attempt is made. :: class MyRelayPolicy(RelayPolicy): def apply(self, env): env['X-When-Delivered'] = str(time.time()) my_relay.add_policy(MyRelayPolicy()) """ def apply(self, envelope): """:class:`RelayPolicy` sub-classes must override this method, which will be called by the |Relay| before delivery. Unlike :meth:`QueuePolicy.apply`, the return value of this method is discarded. Much like :meth:`~slimta.relay.Relay.attempt`, these methods may raise :class:`~slimta.relay.PermanentRelayError` or :class:`~slimta.relay.TransientRelayError` to mark the relay attempt as failed for the entire message. Modifications to the ``envelope`` will be passed on to the :class:`~slimta.relay.Relay`. However, it is unlikely these modifications will be persisted by the :class:`~slimta.queue.QueueStorage` implementation. :param envelope: The |Envelope| object the policy execution should apply any changes to. :raises: :class:`~slimta.relay.PermanentRelayError`, :class:`~slimta.relay.TransientRelayError` """ raise NotImplementedError() # vim:et:fdm=marker:sts=4:sw=4:ts=4
mit
rmfitzpatrick/ansible
lib/ansible/modules/cloud/profitbricks/profitbricks.py
26
21868
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: profitbricks short_description: Create, destroy, start, stop, and reboot a ProfitBricks virtual machine. description: - Create, destroy, update, start, stop, and reboot a ProfitBricks virtual machine. When the virtual machine is created it can optionally wait for it to be 'running' before returning. This module has a dependency on profitbricks >= 1.0.0 version_added: "2.0" options: auto_increment: description: - Whether or not to increment a single number in the name for created virtual machines. default: yes choices: ["yes", "no"] name: description: - The name of the virtual machine. required: true image: description: - The system image ID for creating the virtual machine, e.g. a3eae284-a2fe-11e4-b187-5f1f641608c8. required: true image_password: description: - Password set for the administrative user. required: false version_added: '2.2' ssh_keys: description: - Public SSH keys allowing access to the virtual machine. required: false version_added: '2.2' datacenter: description: - The datacenter to provision this virtual machine. required: false default: null cores: description: - The number of CPU cores to allocate to the virtual machine. required: false default: 2 ram: description: - The amount of memory to allocate to the virtual machine. required: false default: 2048 cpu_family: description: - The CPU family type to allocate to the virtual machine. required: false default: AMD_OPTERON choices: [ "AMD_OPTERON", "INTEL_XEON" ] version_added: '2.2' volume_size: description: - The size in GB of the boot volume. required: false default: 10 bus: description: - The bus type for the volume. required: false default: VIRTIO choices: [ "IDE", "VIRTIO"] instance_ids: description: - list of instance ids, currently only used when state='absent' to remove instances. required: false count: description: - The number of virtual machines to create. required: false default: 1 location: description: - The datacenter location. Use only if you want to create the Datacenter or else this value is ignored. required: false default: us/las choices: [ "us/las", "de/fra", "de/fkb" ] assign_public_ip: description: - This will assign the machine to the public LAN. If no LAN exists with public Internet access it is created. required: false default: false lan: description: - The ID of the LAN you wish to add the servers to. required: false default: 1 subscription_user: description: - The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable. required: false default: null subscription_password: description: - THe ProfitBricks password. Overrides the PB_PASSWORD environment variable. required: false default: null wait: description: - wait for the instance to be in state 'running' before returning required: false default: "yes" choices: [ "yes", "no" ] wait_timeout: description: - how long before wait gives up, in seconds default: 600 remove_boot_volume: description: - remove the bootVolume of the virtual machine you're destroying. required: false default: "yes" choices: ["yes", "no"] state: description: - create or terminate instances required: false default: 'present' choices: [ "running", "stopped", "absent", "present" ] requirements: - "profitbricks" - "python >= 2.6" author: Matt Baldwin (baldwin@stackpointcloud.com) ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Provisioning example. This will create three servers and enumerate their names. - profitbricks: datacenter: Tardis One name: web%02d.stackpointcloud.com cores: 4 ram: 2048 volume_size: 50 cpu_family: INTEL_XEON image: a3eae284-a2fe-11e4-b187-5f1f641608c8 location: us/las count: 3 assign_public_ip: true # Removing Virtual machines - profitbricks: datacenter: Tardis One instance_ids: - 'web001.stackpointcloud.com' - 'web002.stackpointcloud.com' - 'web003.stackpointcloud.com' wait_timeout: 500 state: absent # Starting Virtual Machines. - profitbricks: datacenter: Tardis One instance_ids: - 'web001.stackpointcloud.com' - 'web002.stackpointcloud.com' - 'web003.stackpointcloud.com' wait_timeout: 500 state: running # Stopping Virtual Machines - profitbricks: datacenter: Tardis One instance_ids: - 'web001.stackpointcloud.com' - 'web002.stackpointcloud.com' - 'web003.stackpointcloud.com' wait_timeout: 500 state: stopped ''' import re import uuid import time import traceback HAS_PB_SDK = True try: from profitbricks.client import ProfitBricksService, Volume, Server, Datacenter, NIC, LAN except ImportError: HAS_PB_SDK = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves import xrange from ansible.module_utils._text import to_native LOCATIONS = ['us/las', 'de/fra', 'de/fkb'] uuid_match = re.compile( '[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}', re.I) def _wait_for_completion(profitbricks, promise, wait_timeout, msg): if not promise: return wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): time.sleep(5) operation_result = profitbricks.get_request( request_id=promise['requestId'], status=True) if operation_result['metadata']['status'] == "DONE": return elif operation_result['metadata']['status'] == "FAILED": raise Exception( 'Request failed to complete ' + msg + ' "' + str( promise['requestId']) + '" to complete.') raise Exception( 'Timed out waiting for async operation ' + msg + ' "' + str( promise['requestId'] ) + '" to complete.') def _create_machine(module, profitbricks, datacenter, name): cores = module.params.get('cores') ram = module.params.get('ram') cpu_family = module.params.get('cpu_family') volume_size = module.params.get('volume_size') disk_type = module.params.get('disk_type') image_password = module.params.get('image_password') ssh_keys = module.params.get('ssh_keys') bus = module.params.get('bus') lan = module.params.get('lan') assign_public_ip = module.params.get('assign_public_ip') subscription_user = module.params.get('subscription_user') subscription_password = module.params.get('subscription_password') location = module.params.get('location') image = module.params.get('image') assign_public_ip = module.boolean(module.params.get('assign_public_ip')) wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') if assign_public_ip: public_found = False lans = profitbricks.list_lans(datacenter) for lan in lans['items']: if lan['properties']['public']: public_found = True lan = lan['id'] if not public_found: i = LAN( name='public', public=True) lan_response = profitbricks.create_lan(datacenter, i) _wait_for_completion(profitbricks, lan_response, wait_timeout, "_create_machine") lan = lan_response['id'] v = Volume( name=str(uuid.uuid4()).replace('-', '')[:10], size=volume_size, image=image, image_password=image_password, ssh_keys=ssh_keys, disk_type=disk_type, bus=bus) n = NIC( lan=int(lan) ) s = Server( name=name, ram=ram, cores=cores, cpu_family=cpu_family, create_volumes=[v], nics=[n], ) try: create_server_response = profitbricks.create_server( datacenter_id=datacenter, server=s) _wait_for_completion(profitbricks, create_server_response, wait_timeout, "create_virtual_machine") server_response = profitbricks.get_server( datacenter_id=datacenter, server_id=create_server_response['id'], depth=3 ) except Exception as e: module.fail_json(msg="failed to create the new server: %s" % str(e)) else: return server_response def _startstop_machine(module, profitbricks, datacenter_id, server_id): state = module.params.get('state') try: if state == 'running': profitbricks.start_server(datacenter_id, server_id) else: profitbricks.stop_server(datacenter_id, server_id) return True except Exception as e: module.fail_json(msg="failed to start or stop the virtual machine %s at %s: %s" % (server_id, datacenter_id, str(e))) def _create_datacenter(module, profitbricks): datacenter = module.params.get('datacenter') location = module.params.get('location') wait_timeout = module.params.get('wait_timeout') i = Datacenter( name=datacenter, location=location ) try: datacenter_response = profitbricks.create_datacenter(datacenter=i) _wait_for_completion(profitbricks, datacenter_response, wait_timeout, "_create_datacenter") return datacenter_response except Exception as e: module.fail_json(msg="failed to create the new server(s): %s" % str(e)) def create_virtual_machine(module, profitbricks): """ Create new virtual machine module : AnsibleModule object profitbricks: authenticated profitbricks object Returns: True if a new virtual machine was created, false otherwise """ datacenter = module.params.get('datacenter') name = module.params.get('name') auto_increment = module.params.get('auto_increment') count = module.params.get('count') lan = module.params.get('lan') wait_timeout = module.params.get('wait_timeout') failed = True datacenter_found = False virtual_machines = [] virtual_machine_ids = [] # Locate UUID for datacenter if referenced by name. datacenter_list = profitbricks.list_datacenters() datacenter_id = _get_datacenter_id(datacenter_list, datacenter) if datacenter_id: datacenter_found = True if not datacenter_found: datacenter_response = _create_datacenter(module, profitbricks) datacenter_id = datacenter_response['id'] _wait_for_completion(profitbricks, datacenter_response, wait_timeout, "create_virtual_machine") if auto_increment: numbers = set() count_offset = 1 try: name % 0 except TypeError as e: if e.message.startswith('not all'): name = '%s%%d' % name else: module.fail_json(msg=e.message, exception=traceback.format_exc()) number_range = xrange(count_offset, count_offset + count + len(numbers)) available_numbers = list(set(number_range).difference(numbers)) names = [] numbers_to_use = available_numbers[:count] for number in numbers_to_use: names.append(name % number) else: names = [name] # Prefetch a list of servers for later comparison. server_list = profitbricks.list_servers(datacenter_id) for name in names: # Skip server creation if the server already exists. if _get_server_id(server_list, name): continue create_response = _create_machine(module, profitbricks, str(datacenter_id), name) nics = profitbricks.list_nics(datacenter_id, create_response['id']) for n in nics['items']: if lan == n['properties']['lan']: create_response.update({'public_ip': n['properties']['ips'][0]}) virtual_machines.append(create_response) failed = False results = { 'failed': failed, 'machines': virtual_machines, 'action': 'create', 'instance_ids': { 'instances': [i['id'] for i in virtual_machines], } } return results def remove_virtual_machine(module, profitbricks): """ Removes a virtual machine. This will remove the virtual machine along with the bootVolume. module : AnsibleModule object profitbricks: authenticated profitbricks object. Not yet supported: handle deletion of attached data disks. Returns: True if a new virtual server was deleted, false otherwise """ datacenter = module.params.get('datacenter') instance_ids = module.params.get('instance_ids') remove_boot_volume = module.params.get('remove_boot_volume') changed = False if not isinstance(module.params.get('instance_ids'), list) or len(module.params.get('instance_ids')) < 1: module.fail_json(msg='instance_ids should be a list of virtual machine ids or names, aborting') # Locate UUID for datacenter if referenced by name. datacenter_list = profitbricks.list_datacenters() datacenter_id = _get_datacenter_id(datacenter_list, datacenter) if not datacenter_id: module.fail_json(msg='Virtual data center \'%s\' not found.' % str(datacenter)) # Prefetch server list for later comparison. server_list = profitbricks.list_servers(datacenter_id) for instance in instance_ids: # Locate UUID for server if referenced by name. server_id = _get_server_id(server_list, instance) if server_id: # Remove the server's boot volume if remove_boot_volume: _remove_boot_volume(module, profitbricks, datacenter_id, server_id) # Remove the server try: server_response = profitbricks.delete_server(datacenter_id, server_id) except Exception as e: module.fail_json(msg="failed to terminate the virtual server: %s" % to_native(e), exception=traceback.format_exc()) else: changed = True return changed def _remove_boot_volume(module, profitbricks, datacenter_id, server_id): """ Remove the boot volume from the server """ try: server = profitbricks.get_server(datacenter_id, server_id) volume_id = server['properties']['bootVolume']['id'] volume_response = profitbricks.delete_volume(datacenter_id, volume_id) except Exception as e: module.fail_json(msg="failed to remove the server's boot volume: %s" % to_native(e), exception=traceback.format_exc()) def startstop_machine(module, profitbricks, state): """ Starts or Stops a virtual machine. module : AnsibleModule object profitbricks: authenticated profitbricks object. Returns: True when the servers process the action successfully, false otherwise. """ if not isinstance(module.params.get('instance_ids'), list) or len(module.params.get('instance_ids')) < 1: module.fail_json(msg='instance_ids should be a list of virtual machine ids or names, aborting') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') changed = False datacenter = module.params.get('datacenter') instance_ids = module.params.get('instance_ids') # Locate UUID for datacenter if referenced by name. datacenter_list = profitbricks.list_datacenters() datacenter_id = _get_datacenter_id(datacenter_list, datacenter) if not datacenter_id: module.fail_json(msg='Virtual data center \'%s\' not found.' % str(datacenter)) # Prefetch server list for later comparison. server_list = profitbricks.list_servers(datacenter_id) for instance in instance_ids: # Locate UUID of server if referenced by name. server_id = _get_server_id(server_list, instance) if server_id: _startstop_machine(module, profitbricks, datacenter_id, server_id) changed = True if wait: wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): matched_instances = [] for res in profitbricks.list_servers(datacenter_id)['items']: if state == 'running': if res['properties']['vmState'].lower() == state: matched_instances.append(res) elif state == 'stopped': if res['properties']['vmState'].lower() == 'shutoff': matched_instances.append(res) if len(matched_instances) < len(instance_ids): time.sleep(5) else: break if wait_timeout <= time.time(): # waiting took too long module.fail_json(msg="wait for virtual machine state timeout on %s" % time.asctime()) return (changed) def _get_datacenter_id(datacenters, identity): """ Fetch and return datacenter UUID by datacenter name if found. """ for datacenter in datacenters['items']: if identity in (datacenter['properties']['name'], datacenter['id']): return datacenter['id'] return None def _get_server_id(servers, identity): """ Fetch and return server UUID by server name if found. """ for server in servers['items']: if identity in (server['properties']['name'], server['id']): return server['id'] return None def main(): module = AnsibleModule( argument_spec=dict( datacenter=dict(), name=dict(), image=dict(), cores=dict(type='int', default=2), ram=dict(type='int', default=2048), cpu_family=dict(choices=['AMD_OPTERON', 'INTEL_XEON'], default='AMD_OPTERON'), volume_size=dict(type='int', default=10), disk_type=dict(choices=['HDD', 'SSD'], default='HDD'), image_password=dict(default=None, no_log=True), ssh_keys=dict(type='list', default=[]), bus=dict(choices=['VIRTIO', 'IDE'], default='VIRTIO'), lan=dict(type='int', default=1), count=dict(type='int', default=1), auto_increment=dict(type='bool', default=True), instance_ids=dict(type='list', default=[]), subscription_user=dict(), subscription_password=dict(no_log=True), location=dict(choices=LOCATIONS, default='us/las'), assign_public_ip=dict(type='bool', default=False), wait=dict(type='bool', default=True), wait_timeout=dict(type='int', default=600), remove_boot_volume=dict(type='bool', default=True), state=dict(default='present'), ) ) if not HAS_PB_SDK: module.fail_json(msg='profitbricks required for this module') subscription_user = module.params.get('subscription_user') subscription_password = module.params.get('subscription_password') profitbricks = ProfitBricksService( username=subscription_user, password=subscription_password) state = module.params.get('state') if state == 'absent': if not module.params.get('datacenter'): module.fail_json(msg='datacenter parameter is required ' + 'for running or stopping machines.') try: (changed) = remove_virtual_machine(module, profitbricks) module.exit_json(changed=changed) except Exception as e: module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc()) elif state in ('running', 'stopped'): if not module.params.get('datacenter'): module.fail_json(msg='datacenter parameter is required for ' + 'running or stopping machines.') try: (changed) = startstop_machine(module, profitbricks, state) module.exit_json(changed=changed) except Exception as e: module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc()) elif state == 'present': if not module.params.get('name'): module.fail_json(msg='name parameter is required for new instance') if not module.params.get('image'): module.fail_json(msg='image parameter is required for new instance') if not module.params.get('subscription_user'): module.fail_json(msg='subscription_user parameter is ' + 'required for new instance') if not module.params.get('subscription_password'): module.fail_json(msg='subscription_password parameter is ' + 'required for new instance') try: (machine_dict_array) = create_virtual_machine(module, profitbricks) module.exit_json(**machine_dict_array) except Exception as e: module.fail_json(msg='failed to set instance state: %s' % to_native(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
gpl-3.0
jorik041/scikit-learn
sklearn/tests/test_common.py
127
7665
""" General tests for all estimators in sklearn. """ # Authors: Andreas Mueller <amueller@ais.uni-bonn.de> # Gael Varoquaux gael.varoquaux@normalesup.org # License: BSD 3 clause from __future__ import print_function import os import warnings import sys import pkgutil from sklearn.externals.six import PY3 from sklearn.utils.testing import assert_false, clean_warning_registry from sklearn.utils.testing import all_estimators from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_in from sklearn.utils.testing import ignore_warnings import sklearn from sklearn.cluster.bicluster import BiclusterMixin from sklearn.linear_model.base import LinearClassifierMixin from sklearn.utils.estimator_checks import ( _yield_all_checks, CROSS_DECOMPOSITION, check_parameters_default_constructible, check_class_weight_balanced_linear_classifier, check_transformer_n_iter, check_non_transformer_estimators_n_iter, check_get_params_invariance) def test_all_estimator_no_base_class(): # test that all_estimators doesn't find abstract classes. for name, Estimator in all_estimators(): msg = ("Base estimators such as {0} should not be included" " in all_estimators").format(name) assert_false(name.lower().startswith('base'), msg=msg) def test_all_estimators(): # Test that estimators are default-constructible, clonable # and have working repr. estimators = all_estimators(include_meta_estimators=True) # Meta sanity-check to make sure that the estimator introspection runs # properly assert_greater(len(estimators), 0) for name, Estimator in estimators: # some can just not be sensibly default constructed yield check_parameters_default_constructible, name, Estimator def test_non_meta_estimators(): # input validation etc for non-meta estimators estimators = all_estimators() for name, Estimator in estimators: if issubclass(Estimator, BiclusterMixin): continue if name.startswith("_"): continue for check in _yield_all_checks(name, Estimator): yield check, name, Estimator def test_configure(): # Smoke test the 'configure' step of setup, this tests all the # 'configure' functions in the setup.pys in the scikit cwd = os.getcwd() setup_path = os.path.abspath(os.path.join(sklearn.__path__[0], '..')) setup_filename = os.path.join(setup_path, 'setup.py') if not os.path.exists(setup_filename): return try: os.chdir(setup_path) old_argv = sys.argv sys.argv = ['setup.py', 'config'] clean_warning_registry() with warnings.catch_warnings(): # The configuration spits out warnings when not finding # Blas/Atlas development headers warnings.simplefilter('ignore', UserWarning) if PY3: with open('setup.py') as f: exec(f.read(), dict(__name__='__main__')) else: execfile('setup.py', dict(__name__='__main__')) finally: sys.argv = old_argv os.chdir(cwd) def test_class_weight_balanced_linear_classifiers(): classifiers = all_estimators(type_filter='classifier') clean_warning_registry() with warnings.catch_warnings(record=True): linear_classifiers = [ (name, clazz) for name, clazz in classifiers if 'class_weight' in clazz().get_params().keys() and issubclass(clazz, LinearClassifierMixin)] for name, Classifier in linear_classifiers: if name == "LogisticRegressionCV": # Contrary to RidgeClassifierCV, LogisticRegressionCV use actual # CV folds and fit a model for each CV iteration before averaging # the coef. Therefore it is expected to not behave exactly as the # other linear model. continue yield check_class_weight_balanced_linear_classifier, name, Classifier @ignore_warnings def test_import_all_consistency(): # Smoke test to check that any name in a __all__ list is actually defined # in the namespace of the module or package. pkgs = pkgutil.walk_packages(path=sklearn.__path__, prefix='sklearn.', onerror=lambda _: None) submods = [modname for _, modname, _ in pkgs] for modname in submods + ['sklearn']: if ".tests." in modname: continue package = __import__(modname, fromlist="dummy") for name in getattr(package, '__all__', ()): if getattr(package, name, None) is None: raise AttributeError( "Module '{0}' has no attribute '{1}'".format( modname, name)) def test_root_import_all_completeness(): EXCEPTIONS = ('utils', 'tests', 'base', 'setup') for _, modname, _ in pkgutil.walk_packages(path=sklearn.__path__, onerror=lambda _: None): if '.' in modname or modname.startswith('_') or modname in EXCEPTIONS: continue assert_in(modname, sklearn.__all__) def test_non_transformer_estimators_n_iter(): # Test that all estimators of type which are non-transformer # and which have an attribute of max_iter, return the attribute # of n_iter atleast 1. for est_type in ['regressor', 'classifier', 'cluster']: regressors = all_estimators(type_filter=est_type) for name, Estimator in regressors: # LassoLars stops early for the default alpha=1.0 for # the iris dataset. if name == 'LassoLars': estimator = Estimator(alpha=0.) else: estimator = Estimator() if hasattr(estimator, "max_iter"): # These models are dependent on external solvers like # libsvm and accessing the iter parameter is non-trivial. if name in (['Ridge', 'SVR', 'NuSVR', 'NuSVC', 'RidgeClassifier', 'SVC', 'RandomizedLasso', 'LogisticRegressionCV']): continue # Tested in test_transformer_n_iter below elif (name in CROSS_DECOMPOSITION or name in ['LinearSVC', 'LogisticRegression']): continue else: # Multitask models related to ENet cannot handle # if y is mono-output. yield (check_non_transformer_estimators_n_iter, name, estimator, 'Multi' in name) def test_transformer_n_iter(): transformers = all_estimators(type_filter='transformer') for name, Estimator in transformers: estimator = Estimator() # Dependent on external solvers and hence accessing the iter # param is non-trivial. external_solver = ['Isomap', 'KernelPCA', 'LocallyLinearEmbedding', 'RandomizedLasso', 'LogisticRegressionCV'] if hasattr(estimator, "max_iter") and name not in external_solver: yield check_transformer_n_iter, name, estimator def test_get_params_invariance(): # Test for estimators that support get_params, that # get_params(deep=False) is a subset of get_params(deep=True) # Related to issue #4465 estimators = all_estimators(include_meta_estimators=False, include_other=True) for name, Estimator in estimators: if hasattr(Estimator, 'get_params'): yield check_get_params_invariance, name, Estimator
bsd-3-clause
surgebiswas/poker
PokerBots_2017/Johnny/numpy/f2py/tests/util.py
66
9351
""" Utility functions for - building and importing modules on test time, using a temporary location - detecting if compilers are present """ from __future__ import division, absolute_import, print_function import os import sys import subprocess import tempfile import shutil import atexit import textwrap import re import random from numpy.compat import asbytes, asstr import numpy.f2py from numpy.testing import SkipTest, temppath try: from hashlib import md5 except ImportError: from md5 import new as md5 # # Maintaining a temporary module directory # _module_dir = None def _cleanup(): global _module_dir if _module_dir is not None: try: sys.path.remove(_module_dir) except ValueError: pass try: shutil.rmtree(_module_dir) except (IOError, OSError): pass _module_dir = None def get_module_dir(): global _module_dir if _module_dir is None: _module_dir = tempfile.mkdtemp() atexit.register(_cleanup) if _module_dir not in sys.path: sys.path.insert(0, _module_dir) return _module_dir def get_temp_module_name(): # Assume single-threaded, and the module dir usable only by this thread d = get_module_dir() for j in range(5403, 9999999): name = "_test_ext_module_%d" % j fn = os.path.join(d, name) if name not in sys.modules and not os.path.isfile(fn + '.py'): return name raise RuntimeError("Failed to create a temporary module name") def _memoize(func): memo = {} def wrapper(*a, **kw): key = repr((a, kw)) if key not in memo: try: memo[key] = func(*a, **kw) except Exception as e: memo[key] = e raise ret = memo[key] if isinstance(ret, Exception): raise ret return ret wrapper.__name__ = func.__name__ return wrapper # # Building modules # @_memoize def build_module(source_files, options=[], skip=[], only=[], module_name=None): """ Compile and import a f2py module, built from the given files. """ code = ("import sys; sys.path = %s; import numpy.f2py as f2py2e; " "f2py2e.main()" % repr(sys.path)) d = get_module_dir() # Copy files dst_sources = [] for fn in source_files: if not os.path.isfile(fn): raise RuntimeError("%s is not a file" % fn) dst = os.path.join(d, os.path.basename(fn)) shutil.copyfile(fn, dst) dst_sources.append(dst) fn = os.path.join(os.path.dirname(fn), '.f2py_f2cmap') if os.path.isfile(fn): dst = os.path.join(d, os.path.basename(fn)) if not os.path.isfile(dst): shutil.copyfile(fn, dst) # Prepare options if module_name is None: module_name = get_temp_module_name() f2py_opts = ['-c', '-m', module_name] + options + dst_sources if skip: f2py_opts += ['skip:'] + skip if only: f2py_opts += ['only:'] + only # Build cwd = os.getcwd() try: os.chdir(d) cmd = [sys.executable, '-c', code] + f2py_opts p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: raise RuntimeError("Running f2py failed: %s\n%s" % (cmd[4:], asstr(out))) finally: os.chdir(cwd) # Partial cleanup for fn in dst_sources: os.unlink(fn) # Import __import__(module_name) return sys.modules[module_name] @_memoize def build_code(source_code, options=[], skip=[], only=[], suffix=None, module_name=None): """ Compile and import Fortran code using f2py. """ if suffix is None: suffix = '.f' with temppath(suffix=suffix) as path: with open(path, 'w') as f: f.write(source_code) return build_module([path], options=options, skip=skip, only=only, module_name=module_name) # # Check if compilers are available at all... # _compiler_status = None def _get_compiler_status(): global _compiler_status if _compiler_status is not None: return _compiler_status _compiler_status = (False, False, False) # XXX: this is really ugly. But I don't know how to invoke Distutils # in a safer way... code = """ import os import sys sys.path = %(syspath)s def configuration(parent_name='',top_path=None): global config from numpy.distutils.misc_util import Configuration config = Configuration('', parent_name, top_path) return config from numpy.distutils.core import setup setup(configuration=configuration) config_cmd = config.get_config_cmd() have_c = config_cmd.try_compile('void foo() {}') print('COMPILERS:%%d,%%d,%%d' %% (have_c, config.have_f77c(), config.have_f90c())) sys.exit(99) """ code = code % dict(syspath=repr(sys.path)) with temppath(suffix='.py') as script: with open(script, 'w') as f: f.write(code) cmd = [sys.executable, script, 'config'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() m = re.search(asbytes(r'COMPILERS:(\d+),(\d+),(\d+)'), out) if m: _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))), bool(int(m.group(3)))) # Finished return _compiler_status def has_c_compiler(): return _get_compiler_status()[0] def has_f77_compiler(): return _get_compiler_status()[1] def has_f90_compiler(): return _get_compiler_status()[2] # # Building with distutils # @_memoize def build_module_distutils(source_files, config_code, module_name, **kw): """ Build a module via distutils and import it. """ from numpy.distutils.misc_util import Configuration from numpy.distutils.core import setup d = get_module_dir() # Copy files dst_sources = [] for fn in source_files: if not os.path.isfile(fn): raise RuntimeError("%s is not a file" % fn) dst = os.path.join(d, os.path.basename(fn)) shutil.copyfile(fn, dst) dst_sources.append(dst) # Build script config_code = textwrap.dedent(config_code).replace("\n", "\n ") code = """\ import os import sys sys.path = %(syspath)s def configuration(parent_name='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('', parent_name, top_path) %(config_code)s return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) """ % dict(config_code=config_code, syspath=repr(sys.path)) script = os.path.join(d, get_temp_module_name() + '.py') dst_sources.append(script) f = open(script, 'wb') f.write(asbytes(code)) f.close() # Build cwd = os.getcwd() try: os.chdir(d) cmd = [sys.executable, script, 'build_ext', '-i'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: raise RuntimeError("Running distutils build failed: %s\n%s" % (cmd[4:], asstr(out))) finally: os.chdir(cwd) # Partial cleanup for fn in dst_sources: os.unlink(fn) # Import __import__(module_name) return sys.modules[module_name] # # Unittest convenience # class F2PyTest(object): code = None sources = None options = [] skip = [] only = [] suffix = '.f' module = None module_name = None def setUp(self): if self.module is not None: return # Check compiler availability first if not has_c_compiler(): raise SkipTest("No C compiler available") codes = [] if self.sources: codes.extend(self.sources) if self.code is not None: codes.append(self.suffix) needs_f77 = False needs_f90 = False for fn in codes: if fn.endswith('.f'): needs_f77 = True elif fn.endswith('.f90'): needs_f90 = True if needs_f77 and not has_f77_compiler(): raise SkipTest("No Fortran 77 compiler available") if needs_f90 and not has_f90_compiler(): raise SkipTest("No Fortran 90 compiler available") # Build the module if self.code is not None: self.module = build_code(self.code, options=self.options, skip=self.skip, only=self.only, suffix=self.suffix, module_name=self.module_name) if self.sources is not None: self.module = build_module(self.sources, options=self.options, skip=self.skip, only=self.only, module_name=self.module_name)
mit
hongbin/magnum
magnum/common/pythonk8sclient/client/models/V1beta3_EnvVar.py
15
1575
#!/usr/bin/env python """ Copyright 2015 Reverb Technologies, 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. """ class V1beta3_EnvVar(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attributeMap (dict): The key is attribute name and the value is json key in definition. """ self.swaggerTypes = { 'name': 'str', 'value': 'str' } self.attributeMap = { 'name': 'name', 'value': 'value' } #name of the environment variable; must be a C_IDENTIFIER self.name = None # str #value of the environment variable; defaults to empty string self.value = None # str
apache-2.0
les69/calvin-base
calvin/runtime/north/portmanager.py
2
37414
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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. from calvin.utilities.calvin_callback import CalvinCB from calvin.actor.actorport import InPort, OutPort from calvin.runtime.south import endpoint from calvin.runtime.north.calvin_proto import CalvinTunnel import calvin.requests.calvinresponse as response from calvin.utilities import calvinlogger from calvin.actor.actor import ShadowActor _log = calvinlogger.get_logger(__name__) class PortManager(object): """ PortManager handles the setup of communication between ports intra- & inter-runtimes """ def __init__(self, node, proto): super(PortManager, self).__init__() self.node = node self.monitor = self.node.monitor self.proto = proto # Register that we are interested in peer's requests for token transport tunnels self.proto.register_tunnel_handler('token', CalvinCB(self.tunnel_request_handles)) self.tunnels = {} # key: peer_node_id, value: tunnel instances self.ports = {} # key: port_id, value: port self.pending_tunnels = {} # key: peer_node_id, value: list of CalvinCB instances self.disconnecting_ports={} # key: port_id, value: list of peer port ids that are disconnecting and waiting for ack def tunnel_request_handles(self, tunnel): """ Incoming tunnel request for token transport """ # TODO check if we want a tunnel first self.tunnels[tunnel.peer_node_id] = tunnel tunnel.register_tunnel_down(CalvinCB(self.tunnel_down, tunnel)) tunnel.register_tunnel_up(CalvinCB(self.tunnel_up, tunnel)) tunnel.register_recv(CalvinCB(self.tunnel_recv_handler, tunnel)) # We accept it by returning True return True def tunnel_down(self, tunnel): """ Callback that the tunnel is not accepted or is going down """ tunnel_peer_id = tunnel.peer_node_id try: self.tunnels.pop(tunnel_peer_id) except: pass # If a port connect have ordered a tunnel then it have a callback in pending # which want information on the failure if tunnel_peer_id in self.pending_tunnels: for cb in self.pending_tunnels[tunnel_peer_id]: try: cb(status=response.CalvinResponse(False)) except: pass self.pending_tunnels.pop(tunnel_peer_id) # We should always return True which sends an OK on the destruction of the tunnel return True def tunnel_up(self, tunnel): """ Callback that the tunnel is working """ tunnel_peer_id = tunnel.peer_node_id # If a port connect have ordered a tunnel then it have a callback in pending # which want to continue with the connection if tunnel_peer_id in self.pending_tunnels: for cb in self.pending_tunnels[tunnel_peer_id]: try: cb(status=response.CalvinResponse(True)) except: pass self.pending_tunnels.pop(tunnel_peer_id) def recv_token_handler(self, tunnel, payload): """ Gets called when a token arrives on any port """ try: port = self._get_local_port(port_id=payload['peer_port_id']) port.endpoint.recv_token(payload) except: # Inform other end that it sent token to a port that does not exist on this node or # that we have initiated a disconnect (endpoint does not have recv_token). # Can happen e.g. when the actor and port just migrated and the token was in the air reply = {'cmd': 'TOKEN_REPLY', 'port_id':payload['port_id'], 'peer_port_id': payload['peer_port_id'], 'sequencenbr': payload['sequencenbr'], 'value': 'ABORT'} tunnel.send(reply) def recv_token_reply_handler(self, tunnel, payload): """ Gets called when a token is (N)ACKed for any port """ try: port = self._get_local_port(port_id=payload['port_id']) except: pass else: # Send the reply to correct endpoint (an outport may have several when doing fan-out) for e in port.endpoints: # We might have started disconnect before getting the reply back, just ignore in that case # it is sorted out if we connect again try: if e.get_peer()[1] == payload['peer_port_id']: e.reply(payload['sequencenbr'], payload['value']) break except: pass def tunnel_recv_handler(self, tunnel, payload): """ Gets called when we receive a message over a tunnel """ if 'cmd' in payload: if 'TOKEN' == payload['cmd']: self.recv_token_handler(tunnel, payload) elif 'TOKEN_REPLY' == payload['cmd']: self.recv_token_reply_handler(tunnel, payload) def connection_request(self, payload): """ A request from a peer to connect a port""" _log.analyze(self.node.id, "+", payload, peer_node_id=payload['from_rt_uuid']) if not ('peer_port_id' in payload or ('peer_actor_id' in payload and 'peer_port_name' in payload and 'peer_port_dir' in payload)): # Not enough info to find port _log.analyze(self.node.id, "+ NOT ENOUGH DATA", payload, peer_node_id=payload['from_rt_uuid']) return response.CalvinResponse(response.BAD_REQUEST) try: port = self._get_local_port(payload['peer_actor_id'], payload['peer_port_name'], payload['peer_port_dir'], payload['peer_port_id']) except: # We don't have the port _log.analyze(self.node.id, "+ PORT NOT FOUND", payload, peer_node_id=payload['from_rt_uuid']) return response.CalvinResponse(response.NOT_FOUND) else: if not 'tunnel_id' in payload: # TODO implement connection requests not via tunnel raise NotImplementedError() tunnel = self.tunnels[payload['from_rt_uuid']] if tunnel.id != payload['tunnel_id']: # For some reason does the tunnel id not match the one we have to connect to the peer # Likely due to that we have not yet received a tunnel request from the peer that replace our tunnel id # Can happen when race of simultaneous link setup and commands can be received out of order _log.analyze(self.node.id, "+ WRONG TUNNEL", payload, peer_node_id=payload['from_rt_uuid']) return response.CalvinResponse(response.GONE) if isinstance(port, InPort): endp = endpoint.TunnelInEndpoint(port, tunnel, payload['from_rt_uuid'], payload['port_id'], self.node.sched.trigger_loop) else: endp = endpoint.TunnelOutEndpoint(port, tunnel, payload['from_rt_uuid'], payload['port_id'], self.node.sched.trigger_loop) self.monitor.register_out_endpoint(endp) invalid_endpoint = port.attach_endpoint(endp) # Remove previous endpoint if invalid_endpoint: if isinstance(invalid_endpoint, endpoint.TunnelOutEndpoint): self.monitor.unregister_out_endpoint(invalid_endpoint) invalid_endpoint.destroy() # Update storage if isinstance(port, InPort): self.node.storage.add_port(port, self.node.id, port.owner.id, "in") else: self.node.storage.add_port(port, self.node.id, port.owner.id, "out") _log.analyze(self.node.id, "+ OK", payload, peer_node_id=payload['from_rt_uuid']) return response.CalvinResponse(response.OK, {'port_id': port.id}) def connect(self, callback=None, actor_id=None, port_name=None, port_dir=None, port_id=None, peer_node_id=None, peer_actor_id=None, peer_port_name=None, peer_port_dir=None, peer_port_id=None): """ Obtain any missing information to enable making a connection and make actual connect callback: an optional callback that gets called with status when finished local port identified by: actor_id, port_name and port_dir='in'/'out' or port_id peer_node_id: an optional node id the peer port is locate on, will use storage to find it if not supplied peer port (remote or local) identified by: peer_actor_id, peer_port_name and peer_port_dir='in'/'out' or peer_port_id connect -----------------------------> _connect -> _connect_via_tunnel -> _connected_via_tunnel -! \> _connect_by_peer_port_id / \-> _connect_via_local -! \-> _connect_by_actor_id ---/ """ # Collect all parameters into a state that we keep between the chain of callbacks needed to complete a connection state = { 'callback': callback, 'actor_id': actor_id, 'port_name': port_name, 'port_dir': port_dir, 'port_id': port_id, 'peer_node_id': peer_node_id, 'peer_actor_id': peer_actor_id, 'peer_port_name': peer_port_name, 'peer_port_dir': peer_port_dir, 'peer_port_id': peer_port_id } _log.analyze(self.node.id, "+", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id'], tb=True) try: port = self._get_local_port(actor_id, port_name, port_dir, port_id) except: # not local if port_id: status = response.CalvinResponse(response.BAD_REQUEST, "First port %s must be local" % (port_id)) else: status = response.CalvinResponse(response.BAD_REQUEST, "First port %s on actor %s must be local" % (port_name, actor_id)) if callback: callback(status=status, actor_id=actor_id, port_name=port_name, port_id=port_id, peer_node_id=peer_node_id, peer_actor_id=peer_actor_id, peer_port_name=peer_port_name, peer_port_id=peer_port_id) return else: raise Exception(str(status)) else: # Found locally state['port_id'] = port.id # Check if the peer port is local even if a missing peer_node_id if not peer_node_id and peer_actor_id in self.node.am.actors.iterkeys(): state['peer_node_id'] = self.node.id if not state['peer_node_id'] and state['peer_port_id']: try: self._get_local_port(None, None, None, peer_port_id) except: # not local pass else: # Found locally state['peer_node_id'] = self.node.id # Still no peer node id? ... if not state['peer_node_id']: if state['peer_port_id']: # ... but an id of a port lets ask for more info self.node.storage.get_port(state['peer_port_id'], CalvinCB(self._connect_by_peer_port_id, **state)) return elif state['peer_actor_id'] and state['peer_port_name']: # ... but an id of an actor lets ask for more info self.node.storage.get_actor(state['peer_actor_id'], CalvinCB(self._connect_by_peer_actor_id, **state)) return else: # ... and no info on how to get more info, abort status=response.CalvinResponse(response.BAD_REQUEST, "Need peer_node_id (%s), peer_actor_id(%s) and/or peer_port_id(%s)" % (peer_node_id, peer_actor_id, peer_port_id)) if callback: callback(status=status, actor_id=actor_id, port_name=port_name, port_id=port_id, peer_node_id=peer_node_id, peer_actor_id=peer_actor_id, peer_port_name=peer_port_name, peer_port_id=peer_port_id) return else: raise Exception(str(status)) else: if not ((peer_actor_id and peer_port_name) or peer_port_id): # We miss information on to find the peer port status=response.CalvinResponse(response.BAD_REQUEST, "Need peer_port_name (%s), peer_actor_id(%s) and/or peer_port_id(%s)" % (peer_port_name, peer_actor_id, peer_port_id)) if callback: callback(status=status, actor_id=actor_id, port_name=port_name, port_id=port_id, peer_node_id=peer_node_id, peer_actor_id=peer_actor_id, peer_port_name=peer_port_name, peer_port_id=peer_port_id) return else: raise Exception(str(status)) self._connect(**state) def _connect_by_peer_port_id(self, key, value, **state): """ Gets called when storage responds with peer port information """ _log.analyze(self.node.id, "+", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id'], tb=True) if not isinstance(value, dict): if state['callback']: state['callback'](status=response.CalvinResponse(response.BAD_REQUEST, "Storage return invalid information"), **state) return else: raise Exception("Storage return invalid information") if not state['peer_node_id'] and 'node_id' in value and value['node_id']: state['peer_node_id'] = value['node_id'] else: if state['callback']: state['callback'](status=response.CalvinResponse(response.BAD_REQUEST, "Storage return invalid information"), **state) return else: raise Exception("Storage return invalid information") self._connect(**state) def _connect_by_peer_actor_id(self, key, value, **state): """ Gets called when storage responds with peer actor information""" _log.analyze(self.node.id, "+", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id'], tb=True) if not isinstance(value, dict): if state['callback']: state['callback'](status=response.CalvinResponse(response.BAD_REQUEST, "Storage return invalid information"), **state) return else: raise Exception("Storage return invalid information") if not state['peer_node_id'] and 'node_id' in value and value['node_id']: state['peer_node_id'] = value['node_id'] else: if state['callback']: state['callback'](status=response.CalvinResponse(response.BAD_REQUEST, "Storage return invalid information"), **state) return else: raise Exception("Storage return invalid information") self._connect(**state) def _connect(self, **state): """ Do the connection of ports, all neccessary information supplied but maybe not all pre-requisites for remote connections. """ _log.analyze(self.node.id, "+", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id'], tb=True) # Local connect if self.node.id == state['peer_node_id']: _log.analyze(self.node.id, "+ LOCAL", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id']) port1 = self._get_local_port(state['actor_id'], state['port_name'], state['port_dir'], state['port_id']) port2 = self._get_local_port(state['peer_actor_id'], state['peer_port_name'], state['peer_port_dir'], state['peer_port_id']) # Local connect wants the first port to be an inport inport , outport = (port1, port2) if isinstance(port1, InPort) else (port2, port1) self._connect_via_local(inport, outport) if state['callback']: state['callback'](status=response.CalvinResponse(True) , **state) return None # Remote connection # TODO Currently we only have support for setting up a remote connection via tunnel tunnel = None if not state['peer_node_id'] in self.tunnels.iterkeys(): # No tunnel to peer, get one first _log.analyze(self.node.id, "+ GET TUNNEL", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id']) tunnel = self.proto.tunnel_new(state['peer_node_id'], 'token', {}) tunnel.register_tunnel_down(CalvinCB(self.tunnel_down, tunnel)) tunnel.register_tunnel_up(CalvinCB(self.tunnel_up, tunnel)) tunnel.register_recv(CalvinCB(self.tunnel_recv_handler, tunnel)) self.tunnels[state['peer_node_id']] = tunnel else: tunnel = self.tunnels[state['peer_node_id']] if tunnel.status == CalvinTunnel.STATUS.PENDING: if not state['peer_node_id'] in self.pending_tunnels: self.pending_tunnels[state['peer_node_id']] = [] # call _connect_via_tunnel when we get the response of the tunnel self.pending_tunnels[state['peer_node_id']].append(CalvinCB(self._connect_via_tunnel, **state)) return elif tunnel.status == CalvinTunnel.STATUS.TERMINATED: # TODO should we retry at this level? if state['callback']: state['callback'](status=response.CalvinResponse(response.INTERNAL_ERROR), **state) return _log.analyze(self.node.id, "+ HAD TUNNEL", dict({k: state[k] for k in state.keys() if k != 'callback'},tunnel_status=self.tunnels[state['peer_node_id']].status), peer_node_id=state['peer_node_id']) self._connect_via_tunnel(status=response.CalvinResponse(True), **state) def _connect_via_tunnel(self, status=None, **state): """ All information and hopefully (status OK) a tunnel to the peer is available for a port connect""" port = self._get_local_port(state['actor_id'], state['port_name'], state['port_dir'], state['port_id']) _log.analyze(self.node.id, "+ " + str(status), dict({k: state[k] for k in state.keys() if k != 'callback'},port_is_connected=port.is_connected_to(state['peer_port_id'])), peer_node_id=state['peer_node_id'], tb=True) if port.is_connected_to(state['peer_port_id']): # The other end beat us to connecting the port, lets just report success and return _log.analyze(self.node.id, "+ IS CONNECTED", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id']) if state['callback']: state['callback'](status=response.CalvinResponse(True), **state) return None if not status: # Failed getting a tunnel, just inform the one wanting to connect if state['callback']: state['callback'](status=response.CalvinResponse(response.INTERNAL_ERROR), **state) return None # Finally we have all information and a tunnel # Lets ask the peer if it can connect our port. tunnel = self.tunnels[state['peer_node_id']] _log.analyze(self.node.id, "+ SENDING", dict({k: state[k] for k in state.keys() if k != 'callback'},tunnel_status=self.tunnels[state['peer_node_id']].status), peer_node_id=state['peer_node_id']) if 'retries' not in state: state['retries'] = 0 self.proto.port_connect(callback=CalvinCB(self._connected_via_tunnel, **state), port_id=state['port_id'], peer_node_id=state['peer_node_id'], peer_port_id=state['peer_port_id'], peer_actor_id=state['peer_actor_id'], peer_port_name=state['peer_port_name'], peer_port_dir=state['peer_port_dir'], tunnel=tunnel) def _connected_via_tunnel(self, reply, **state): """ Gets called when remote responds to our request for port connection """ _log.analyze(self.node.id, "+ " + str(reply), {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id'], tb=True) if reply in [response.BAD_REQUEST, response.NOT_FOUND, response.GATEWAY_TIMEOUT]: # Other end did not accept our port connection request if state['retries'] < 2 and state['peer_node_id']: # Maybe it is on another node now lets retry and lookup the port state['peer_node_id'] = None state['retries'] += 1 self.node.storage.get_port(state['peer_port_id'], CalvinCB(self._connect_by_peer_port_id, **state)) return None if state['callback']: state['callback'](status=response.CalvinResponse(response.NOT_FOUND), **state) return None if reply == response.GONE: # Other end did not accept our port connection request, likely due to they have not got the message # about the tunnel in time _log.analyze(self.node.id, "+ RETRY", {k: state[k] for k in state.keys() if k != 'callback'}, peer_node_id=state['peer_node_id']) if state['retries']<3: state['retries'] += 1 # Status here just indicate that we should have a tunnel self._connect_via_tunnel(status=response.CalvinResponse(True), **state) return None else: if state['callback']: state['callback'](status=response.CalvinResponse(False), **state) return None # Set up the port's endpoint tunnel = self.tunnels[state['peer_node_id']] port = self.ports[state['port_id']] if isinstance(port, InPort): endp = endpoint.TunnelInEndpoint(port, tunnel, state['peer_node_id'], reply.data['port_id'], self.node.sched.trigger_loop) else: endp = endpoint.TunnelOutEndpoint(port, tunnel, state['peer_node_id'], reply.data['port_id'], self.node.sched.trigger_loop) # register into main loop self.monitor.register_out_endpoint(endp) invalid_endpoint = port.attach_endpoint(endp) # remove previous endpoint if invalid_endpoint: if isinstance(invalid_endpoint, endpoint.TunnelOutEndpoint): self.monitor.unregister_out_endpoint(invalid_endpoint) invalid_endpoint.destroy() # Done connecting the port if state['callback']: state['callback'](status=response.CalvinResponse(True), **state) # Update storage if isinstance(port, InPort): self.node.storage.add_port(port, self.node.id, port.owner.id, "in") else: self.node.storage.add_port(port, self.node.id, port.owner.id, "out") def _connect_via_local(self, inport, outport): """ Both connecting ports are local, just connect them """ _log.analyze(self.node.id, "+", {}) ein = endpoint.LocalInEndpoint(inport, outport) eout = endpoint.LocalOutEndpoint(outport, inport) invalid_endpoint = inport.attach_endpoint(ein) if invalid_endpoint: invalid_endpoint.destroy() invalid_endpoint = outport.attach_endpoint(eout) if invalid_endpoint: if isinstance(invalid_endpoint, endpoint.TunnelOutEndpoint): self.monitor.unregister_out_endpoint(invalid_endpoint) invalid_endpoint.destroy() # Update storage self.node.storage.add_port(inport, self.node.id, inport.owner.id, "in") self.node.storage.add_port(outport, self.node.id, outport.owner.id, "out") def disconnect(self, callback=None, actor_id=None, port_name=None, port_dir=None, port_id=None): """ Do disconnect for port(s) callback: an optional callback that gets called with status when finished ports identified by only local actor_id: actor_id: the actor that all ports will be disconnected on callback will be called once when all ports are diconnected or first failed local port identified by: actor_id, port_name and port_dir='in'/'out' or port_id callback will be called once when all peer ports (fanout) are disconnected or first failed disconnect -*> _disconnect_port -*> _disconnected_port (-*> _disconnecting_actor_cb) -> ! """ port_ids = [] if actor_id and not (port_id or port_name or port_dir): # We disconnect all ports on an actor try: actor = self.node.am.actors[actor_id] except: # actor not found status = response.CalvinResponse(response.NOT_FOUND, "Actor %s must be local" % (actor_id)) if callback: callback(status=status, actor_id=actor_id, port_name=port_name, port_id=port_id) return else: raise Exception(str(status)) else: port_ids.extend([p.id for p in actor.inports.itervalues()]) port_ids.extend([p.id for p in actor.outports.itervalues()]) # Need to collect all callbacks into one if callback: callback = CalvinCB(self._disconnecting_actor_cb, _callback=callback, port_ids=port_ids) else: # Just one port to disconnect if port_id: port_ids.append(port_id) else: # Awkward but lets get the port id from name etc so that the rest can loop over port ids try: port = self._get_local_port(actor_id, port_name, port_dir, port_id) except: # not local status = response.CalvinResponse(response.NOT_FOUND, "Port %s on actor %s must be local" % (port_name if port_name else port_id, actor_id if actor_id else "some")) if callback: callback(status=status, actor_id=actor_id, port_name=port_name, port_id=port_id) return else: raise Exception(str(status)) else: # Found locally port_ids.append(port.id) _log.analyze(self.node.id, "+", {'port_ids': port_ids}) # Run over copy of list of ports since modified inside the loop for port_id in port_ids[:]: self._disconnect_port(callback, port_id) def _disconnect_port(self, callback=None, port_id=None): """ Obtain any missing information to enable disconnecting one port and make the disconnect""" # Collect all parameters into a state that we keep for the sub functions and callback state = { 'callback': callback, 'port_id': port_id, 'peer_ids': None } # Check if port actually is local try: port = self._get_local_port(None, None, None, port_id) except: # not local status = response.CalvinResponse(response.NOT_FOUND, "Port %s must be local" % (port_id)) if callback: callback(status=status, port_id=port_id) return else: raise Exception(str(status)) else: # Found locally state['port_name'] = port.name state['port_dir'] = "in" if isinstance(port, InPort) else "out" state['actor_id'] = port.owner.id if port.owner else None port = self.ports[state['port_id']] # Now check the peer port, peer_ids is list of (peer_node_id, peer_port_id) tuples peer_ids = [] if isinstance(port, InPort): # Inport only have one possible peer peer_ids = [port.get_peer()] else: # Outport have several possible peers peer_ids = port.get_peers() # Disconnect and destroy the endpoints endpoints = port.disconnect() for ep in endpoints: if isinstance(ep, endpoint.TunnelOutEndpoint): self.monitor.unregister_out_endpoint(ep) ep.destroy() ok = True for peer_node_id, peer_port_id in peer_ids: if peer_node_id == 'local': # Use the disconnect request function since does not matter if local or remote request if not self.disconnection_request({'peer_port_id': peer_port_id}): ok = False # Inform all the remote ports of the disconnect remote_peers = [pp for pp in peer_ids if pp[0] and pp[0] != 'local'] # Keep track of disconnection of remote peer ports self.disconnecting_ports[state['port_id']] = remote_peers for peer_node_id, peer_port_id in remote_peers: self.proto.port_disconnect(callback=CalvinCB(self._disconnected_port, peer_id=(peer_node_id, peer_port_id), **state), port_id=state['port_id'], peer_node_id=peer_node_id, peer_port_id=peer_port_id) # Done disconnecting the port if not remote_peers or not ok: self.disconnecting_ports.pop(state['port_id']) if state['callback']: _log.analyze(self.node.id, "+ DONE", {k: state[k] for k in state.keys() if k != 'callback'}) state['callback'](status=response.CalvinResponse(ok) , **state) def _disconnected_port(self, reply, **state): """ Get called for each peer port when diconnecting but callback should only be called once""" try: # Remove this peer from the list of remote peer ports self.disconnecting_ports[state['port_id']].remove(state['peer_id']) except: pass if not reply: # Got failed response do callback, but also remove port from dictionary indicating we have sent the callback self.disconnecting_ports.pop(state['port_id']) if state['callback']: state['callback'](status=response.CalvinResponse(False), **state) if state['port_id'] in self.disconnecting_ports: if not self.disconnecting_ports[state['port_id']]: # We still have port in dictionary and now list is empty hence we should send OK self.disconnecting_ports.pop(state['port_id']) if state['callback']: state['callback'](status=response.CalvinResponse(True), **state) def _disconnecting_actor_cb(self, status, _callback, port_ids, **state): """ Get called for each of the actor's ports when disconnecting, but callback should only be called once status: OK or not _callback: original callback port_ids: list of port ids kept in context between calls when *changed* by this function, do not replace it state: dictionary keeping disconnect information """ # Send negative response if not already done it if not status and port_ids: if _callback: del port_ids[:] _callback(status=response.CalvinResponse(False), actor_id=state['actor_id']) if state['port_id'] in port_ids: # Remove this port from list port_ids.remove(state['port_id']) # If all ports done send positive response if not port_ids: if _callback: _callback(status=response.CalvinResponse(True), actor_id=state['actor_id']) def disconnection_request(self, payload): """ A request from a peer to disconnect a port""" if not ('peer_port_id' in payload or ('peer_actor_id' in payload and 'peer_port_name' in payload and 'peer_port_dir' in payload)): # Not enough info to find port return response.CalvinResponse(response.BAD_REQUEST) # Check if port actually is local try: port = self._get_local_port(payload['peer_actor_id'] if 'peer_actor_id' in payload else None, payload['peer_port_name'] if 'peer_port_name' in payload else None, payload['peer_port_dir'] if 'peer_port_dir' in payload else None, payload['peer_port_id'] if 'peer_port_id' in payload else None) except: # We don't have the port return response.CalvinResponse(response.NOT_FOUND) else: # Disconnect and destroy endpoints endpoints = port.disconnect() for ep in endpoints: if isinstance(ep, endpoint.TunnelOutEndpoint): self.monitor.unregister_out_endpoint(ep) ep.destroy() return response.CalvinResponse(True) def add_ports_of_actor(self, actor): """ Add an actor's ports to the dictionary, used by actor manager """ for port in actor.inports.values(): self.ports[port.id] = port for port in actor.outports.values(): self.ports[port.id] = port def remove_ports_of_actor(self, actor): """ Remove an actor's ports in the dictionary, used by actor manager """ for port in actor.inports.values(): self.ports.pop(port.id) for port in actor.outports.values(): self.ports.pop(port.id) def _get_local_port(self, actor_id=None, port_name=None, port_dir=None, port_id=None): """ Return a port if it is local otherwise raise exception """ if port_id and port_id in self.ports: return self.ports[port_id] if port_name and actor_id and port_dir: for port in self.ports.itervalues(): if port.name == port_name and port.owner and port.owner.id == actor_id and isinstance(port, InPort if port_dir == "in" else OutPort): return port # For new shadow actors we create the port _log.analyze(self.node.id, "+ SHADOW PORT?", {'actor_id': actor_id, 'port_name': port_name, 'port_dir': port_dir, 'port_id': port_id}) actor = self.node.am.actors.get(actor_id, None) _log.debug("SHADOW ACTOR: %s, %s, %s" % (("SHADOW" if isinstance(actor, ShadowActor) else "NOT SHADOW"), type(actor), actor)) if isinstance(actor, ShadowActor): port = actor.create_shadow_port(port_name, port_dir, port_id) _log.analyze(self.node.id, "+ CREATED SHADOW PORT", {'actor_id': actor_id, 'port_name': port_name, 'port_dir': port_dir, 'port_id': port.id if port else None}) if port: self.ports[port.id] = port return port raise Exception("Port '%s' not found locally" % (port_id if port_id else str(actor_id)+"/"+str(port_name)+":"+str(port_dir)))
apache-2.0
BetterWorks/pysaml2
src/saml2/client.py
1
42487
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2011 Umeå University # # 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. """Contains classes and functions that a SAML2.0 Service Provider (SP) may use to conclude its tasks. """ import saml2 import time import base64 import urllib from urlparse import urlparse try: from urlparse import parse_qs except ImportError: # Compatibility with Python <= 2.5 from cgi import parse_qs from saml2.time_util import instant, not_on_or_after from saml2.s_utils import signature from saml2.s_utils import sid from saml2.s_utils import do_attributes from saml2.s_utils import decode_base64_and_inflate #from saml2.s_utils import deflate_and_base64_encode from saml2 import samlp, saml, class_name from saml2 import VERSION from saml2.sigver import pre_signature_part from saml2.sigver import security_context, signed_instance_factory from saml2.soap import SOAPClient from saml2.binding import send_using_soap, http_redirect_message from saml2.binding import http_post_message from saml2.population import Population from saml2.virtual_org import VirtualOrg from saml2.config import config_factory #from saml2.response import authn_response from saml2.response import response_factory from saml2.response import LogoutResponse from saml2.response import AuthnResponse from saml2.response import attribute_response from saml2 import BINDING_HTTP_REDIRECT from saml2 import BINDING_SOAP from saml2 import BINDING_HTTP_POST from saml2 import BINDING_PAOS SSO_BINDING = saml2.BINDING_HTTP_REDIRECT FORM_SPEC = """<form method="post" action="%s"> <input type="hidden" name="SAMLRequest" value="%s" /> <input type="hidden" name="RelayState" value="%s" /> <input type="submit" value="Submit" /> </form>""" LAX = False IDPDISC_POLICY = "urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol:single" class IdpUnspecified(Exception): pass class VerifyError(Exception): pass class LogoutError(Exception): pass class Saml2Client(object): """ The basic pySAML2 service provider class """ def __init__(self, config=None, identity_cache=None, state_cache=None, virtual_organization=None, config_file="", logger=None): """ :param config: A saml2.config.Config instance :param identity_cache: Where the class should store identity information :param state_cache: Where the class should keep state information :param virtual_organization: Which if any virtual organization this SP belongs to """ self.users = Population(identity_cache) # for server state storage if state_cache is None: self.state = {} # in memory storage else: self.state = state_cache if config: self.config = config elif config_file: self.config = config_factory("sp", config_file) else: raise Exception("Missing configuration") self.metadata = self.config.metadata if logger is None: self.logger = self.config.setup_logger() else: self.logger = logger # we copy the config.debug variable in an internal # field for convenience and because we may need to # change it during the tests self.debug = self.config.debug self.sec = security_context(self.config, log=self.logger, debug=self.debug) if virtual_organization: self.vorg = VirtualOrg(self, virtual_organization) else: self.vorg = None if "allow_unsolicited" in self.config: self.allow_unsolicited = self.config.allow_unsolicited else: self.allow_unsolicited = False if getattr(self.config, 'authn_requests_signed', 'false') == 'true': self.authn_requests_signed_default = True else: self.authn_requests_signed_default = False if getattr(self.config, 'logout_requests_signed', 'false') == 'true': self.logout_requests_signed_default = True else: self.logout_requests_signed_default = False # # Private methods # def _relay_state(self, session_id): vals = [session_id, str(int(time.time()))] if self.config.secret is None: vals.append(signature("", vals)) else: vals.append(signature(self.config.secret, vals)) return "|".join(vals) def _issuer(self, entityid=None): """ Return an Issuer instance """ if entityid: if isinstance(entityid, saml.Issuer): return entityid else: return saml.Issuer(text=entityid, format=saml.NAMEID_FORMAT_ENTITY) else: return saml.Issuer(text=self.config.entityid, format=saml.NAMEID_FORMAT_ENTITY) def _sso_location(self, entityid=None, binding=BINDING_HTTP_REDIRECT): if entityid: # verify that it's in the metadata try: return self.config.single_sign_on_services(entityid, binding)[0] except IndexError: if self.logger: self.logger.info("_sso_location: %s, %s" % (entityid, binding)) return IdpUnspecified("No IdP to send to given the premises") # get the idp location from the configuration alternative the # metadata. If there is more than one IdP in the configuration # raise exception eids = self.config.idps() if len(eids) > 1: raise IdpUnspecified("Too many IdPs to choose from: %s" % eids) try: loc = self.config.single_sign_on_services(eids.keys()[0], binding)[0] return loc except IndexError: return IdpUnspecified("No IdP to send to given the premises") def _my_name(self): return self.config.name # # Public API # def service_url(self, binding=BINDING_HTTP_POST): _res = self.config.endpoint("assertion_consumer_service", binding) if _res: return _res[0] else: return None def response(self, post, outstanding, log=None, decode=True, asynchop=True): """ Deal with an AuthnResponse or LogoutResponse :param post: The reply as a dictionary :param outstanding: A dictionary with session IDs as keys and the original web request from the user before redirection as values. :param log: where loggin should go. :param decode: Whether the response is Base64 encoded or not :param asynchop: Whether the response was return over a asynchronous connection. SOAP for instance is synchronous :return: An response.AuthnResponse or response.LogoutResponse instance """ # If the request contains a samlResponse, try to validate it try: saml_response = post['SAMLResponse'] except KeyError: return None try: _ = self.config.entityid except KeyError: raise Exception("Missing entity_id specification") if log is None: log = self.logger reply_addr = self.service_url() resp = None if saml_response: try: resp = response_factory(saml_response, self.config, reply_addr, outstanding, log, debug=self.debug, decode=decode, asynchop=asynchop, allow_unsolicited=self.allow_unsolicited) except Exception, exc: if log: log.error("%s" % exc) if isinstance(exc, RuntimeError): raise return None if log: log.debug(">> %s", resp) resp = resp.verify() if resp is None: log.error("Response could not be verified") return if isinstance(resp, AuthnResponse): self.users.add_information_about_person(resp.session_info()) if log: log.info("--- ADDED person info ----") elif isinstance(resp, LogoutResponse): self.handle_logout_response(resp, log) elif log: log.error("Response type not supported: %s" % saml2.class_name(resp)) return resp def authn_request(self, query_id, destination, service_url, spentityid, my_name="", vorg="", scoping=None, log=None, sign=None, binding=saml2.BINDING_HTTP_POST, nameid_format=saml.NAMEID_FORMAT_TRANSIENT): """ Creates an authentication request. :param query_id: The identifier for this request :param destination: Where the request should be sent. :param service_url: Where the reply should be sent. :param spentityid: The entity identifier for this service. :param my_name: The name of this service. :param vorg: The vitual organization the service belongs to. :param scoping: The scope of the request :param log: A service to which logs should be written :param sign: Whether the request should be signed or not. :param binding: The protocol to use for the Response !! :return: <samlp:AuthnRequest> instance """ request = samlp.AuthnRequest( id= query_id, version= VERSION, issue_instant= instant(), assertion_consumer_service_url= service_url, protocol_binding= binding ) if destination: request.destination = destination if my_name: request.provider_name = my_name if scoping: request.scoping = scoping # Profile stuff, should be configurable if nameid_format == saml.NAMEID_FORMAT_TRANSIENT: name_id_policy = samlp.NameIDPolicy(allow_create="true", format=nameid_format) else: name_id_policy = samlp.NameIDPolicy(format=nameid_format) if vorg: try: name_id_policy.sp_name_qualifier = vorg name_id_policy.format = saml.NAMEID_FORMAT_PERSISTENT except KeyError: pass if sign is None: sign = self.authn_requests_signed_default if sign: request.signature = pre_signature_part(request.id, self.sec.my_cert, 1) to_sign = [(class_name(request), request.id)] else: to_sign = [] request.name_id_policy = name_id_policy request.issuer = self._issuer(spentityid) if log is None: log = self.logger if log: log.info("REQUEST: %s" % request) return signed_instance_factory(request, self.sec, to_sign) def authn(self, location, session_id, vorg="", scoping=None, log=None, sign=None, binding=saml2.BINDING_HTTP_POST, service_url_binding=None): """ Construct a Authentication Request :param location: The URL of the destination :param session_id: The ID of the session :param vorg: The virtual organization if any that is involved :param scoping: How the request should be scoped, default == Not :param log: A log function to use for logging :param sign: If the request should be signed :param binding: The binding to use, default = HTTP POST :return: An AuthnRequest instance """ spentityid = self.config.entityid if service_url_binding is None: service_url = self.service_url(binding) else: service_url = self.service_url(service_url_binding) if binding == BINDING_PAOS: my_name = None location = None else: my_name = self._my_name() if log is None: log = self.logger if log: log.info("spentityid: %s" % spentityid) log.info("service_url: %s" % service_url) log.info("my_name: %s" % my_name) return self.authn_request(session_id, location, service_url, spentityid, my_name, vorg, scoping, log, sign, binding=binding) def authenticate(self, entityid=None, relay_state="", binding=saml2.BINDING_HTTP_REDIRECT, log=None, vorg="", scoping=None, sign=None): """ Makes an authentication request. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param log: Where to write log messages :param vorg: The entity_id of the virtual organization I'm a member of :param scoping: For which IdPs this query are aimed. :param sign: Whether the request should be signed or not. :return: AuthnRequest response """ location = self._sso_location(entityid) session_id = sid() _req_str = "%s" % self.authn(location, session_id, vorg, scoping, log, sign) if log: log.info("AuthNReq: %s" % _req_str) if binding == saml2.BINDING_HTTP_POST: # No valid ticket; Send a form to the client # THIS IS NOT TO BE USED RIGHT NOW if log: log.info("HTTP POST") (head, response) = http_post_message(_req_str, location, relay_state) elif binding == saml2.BINDING_HTTP_REDIRECT: if log: log.info("HTTP REDIRECT") (head, _body) = http_redirect_message(_req_str, location, relay_state) response = head[0] else: raise Exception("Unkown binding type: %s" % binding) return session_id, response def create_attribute_query(self, session_id, subject_id, destination, issuer_id=None, attribute=None, sp_name_qualifier=None, name_qualifier=None, nameid_format=None, sign=False): """ Constructs an AttributeQuery :param session_id: The identifier of the session :param subject_id: The identifier of the subject :param destination: To whom the query should be sent :param issuer_id: Identifier of the issuer :param attribute: A dictionary of attributes and values that is asked for. The key are one of 4 variants: 3-tuple of name_format,name and friendly_name, 2-tuple of name_format and name, 1-tuple with name or just the name as a string. :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param nameid_format: The format of the name ID :param sign: Whether the query should be signed or not. :return: An AttributeQuery instance """ subject = saml.Subject( name_id = saml.NameID( text=subject_id, format=nameid_format, sp_name_qualifier=sp_name_qualifier, name_qualifier=name_qualifier), ) query = samlp.AttributeQuery( id=session_id, version=VERSION, issue_instant=instant(), destination=destination, issuer=self._issuer(issuer_id), subject=subject, ) if sign: query.signature = pre_signature_part(query.id, self.sec.my_cert, 1) if attribute: query.attribute = do_attributes(attribute) if sign: signed_query = self.sec.sign_attribute_query_using_xmlsec( "%s" % query) return samlp.attribute_query_from_string(signed_query) else: return query def attribute_query(self, subject_id, destination, issuer_id=None, attribute=None, sp_name_qualifier=None, name_qualifier=None, nameid_format=None, log=None, real_id=None): """ Does a attribute request to an attribute authority, this is by default done over SOAP. Other bindings could be used but not supported right now. :param subject_id: The identifier of the subject :param destination: To whom the query should be sent :param issuer_id: Who is sending this query :param attribute: A dictionary of attributes and values that is asked for :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param nameid_format: The format of the name ID :param log: Function to use for logging :param real_id: The identifier which is the key to this entity in the identity database :return: The attributes returned """ if log is None: log = self.logger session_id = sid() issuer = self._issuer(issuer_id) request = self.create_attribute_query(session_id, subject_id, destination, issuer, attribute, sp_name_qualifier, name_qualifier, nameid_format=nameid_format) if log: log.info("Request, created: %s" % request) soapclient = SOAPClient(destination, self.config.key_file, self.config.cert_file, ca_certs=self.config.ca_certs) if log: log.info("SOAP client initiated") try: response = soapclient.send(request) except Exception, exc: if log: log.info("SoapClient exception: %s" % (exc,)) return None if log: log.info("SOAP request sent and got response: %s" % response) # fil = open("response.xml", "w") # fil.write(response) # fil.close() if response: if log: log.info("Verifying response") try: # synchronous operation aresp = attribute_response(self.config, issuer, log=log) except Exception, exc: if log: log.error("%s", (exc,)) return None _resp = aresp.loads(response, False, soapclient.response).verify() if _resp is None: if log: log.error("Didn't like the response") return None session_info = _resp.session_info() if session_info: if real_id is not None: session_info["name_id"] = real_id self.users.add_information_about_person(session_info) if log: log.info("session: %s" % session_info) return session_info else: if log: log.info("No response") return None def construct_logout_request(self, subject_id, destination, issuer_entity_id, reason=None, expire=None): """ Constructs a LogoutRequest :param subject_id: The identifier of the subject :param destination: :param issuer_entity_id: The entity ID of the IdP the request is target at. :param reason: An indication of the reason for the logout, in the form of a URI reference. :param expire: The time at which the request expires, after which the recipient may discard the message. :return: A LogoutRequest instance """ session_id = sid() # create NameID from subject_id name_id = saml.NameID( text = self.users.get_entityid(subject_id, issuer_entity_id, False)) request = samlp.LogoutRequest( id=session_id, version=VERSION, issue_instant=instant(), destination=destination, issuer=self._issuer(), name_id = name_id ) if reason: request.reason = reason if expire: request.not_on_or_after = expire return request def global_logout(self, subject_id, reason="", expire=None, sign=None, log=None, return_to="/"): """ More or less a layer of indirection :-/ Bootstrapping the whole thing by finding all the IdPs that should be notified. :param subject_id: The identifier of the subject that wants to be logged out. :param reason: Why the subject wants to log out :param expire: The latest the log out should happen. :param sign: Whether the request should be signed or not. This also depends on what binding is used. :param log: A logging function :param return_to: Where to send the user after she has been logged out. :return: Depends on which binding is used: If the HTTP redirect binding then a HTTP redirect, if SOAP binding has been used the just the result of that conversation. """ if log is None: log = self.logger if log: log.info("logout request for: %s" % subject_id) # find out which IdPs/AAs I should notify entity_ids = self.users.issuers_of_info(subject_id) return self._logout(subject_id, entity_ids, reason, expire, sign, log, return_to) def _logout(self, subject_id, entity_ids, reason, expire, sign=None, log=None, return_to="/"): # check time if not not_on_or_after(expire): # I've run out of time # Do the local logout anyway self.local_logout(subject_id) return 0, "504 Gateway Timeout", [], [] # for all where I can use the SOAP binding, do those first not_done = entity_ids[:] response = False if log is None: log = self.logger for entity_id in entity_ids: response = False for binding in [BINDING_SOAP, BINDING_HTTP_POST, BINDING_HTTP_REDIRECT]: destinations = self.config.single_logout_services(entity_id, binding) if not destinations: continue destination = destinations[0] if log: log.info("destination to provider: %s" % destination) request = self.construct_logout_request(subject_id, destination, entity_id, reason, expire) to_sign = [] #if sign and binding != BINDING_HTTP_REDIRECT: if sign is None: sign = self.logout_requests_signed_default if sign: request.signature = pre_signature_part(request.id, self.sec.my_cert, 1) to_sign = [(class_name(request), request.id)] if log: log.info("REQUEST: %s" % request) request = signed_instance_factory(request, self.sec, to_sign) if binding == BINDING_SOAP: response = send_using_soap(request, destination, self.config.key_file, self.config.cert_file, log=log, ca_certs=self.config.ca_certs) if response: if log: log.info("Verifying response") response = self.logout_response(response, log) if response: not_done.remove(entity_id) if log: log.info("OK response from %s" % destination) else: if log: log.info( "NOT OK response from %s" % destination) else: session_id = request.id rstate = self._relay_state(session_id) self.state[session_id] = {"entity_id": entity_id, "operation": "SLO", "entity_ids": entity_ids, "subject_id": subject_id, "reason": reason, "not_on_of_after": expire, "sign": sign, "return_to": return_to} if binding == BINDING_HTTP_POST: (head, body) = http_post_message(request, destination, rstate) code = "200 OK" else: (head, body) = http_redirect_message(request, destination, rstate) code = "302 Found" return session_id, code, head, body if not_done: # upstream should try later raise LogoutError("%s" % (entity_ids,)) return 0, "", [], response def local_logout(self, subject_id): """ Remove the user from the cache, equals local logout :param subject_id: The identifier of the subject """ self.users.remove_person(subject_id) return True def handle_logout_response(self, response, log): """ handles a Logout response :param response: A response.Response instance :param log: A logging function :return: 4-tuple of (session_id of the last sent logout request, response message, response headers and message) """ if log is None: log = self.logger if log: log.info("state: %s" % (self.state,)) status = self.state[response.in_response_to] if log: log.info("status: %s" % (status,)) issuer = response.issuer() if log: log.info("issuer: %s" % issuer) del self.state[response.in_response_to] if status["entity_ids"] == [issuer]: # done self.local_logout(status["subject_id"]) return 0, "200 Ok", [("Content-type","text/html")], [] else: status["entity_ids"].remove(issuer) return self._logout(status["subject_id"], status["entity_ids"], status["reason"], status["not_on_or_after"], status["sign"], log, ) def logout_response(self, xmlstr, log=None, binding=BINDING_SOAP): """ Deal with a LogoutResponse :param xmlstr: The response as a xml string :param log: logging function :param binding: What type of binding this message came through. :return: None if the reply doesn't contain a valid SAML LogoutResponse, otherwise the reponse if the logout was successful and None if it was not. """ response = None if log is None: log = self.logger if xmlstr: try: # expected return address return_addr = self.config.endpoint("single_logout_service", binding=binding)[0] except Exception: if log: log.info("Not supposed to handle this!") return None try: response = LogoutResponse(self.sec, return_addr, debug=self.debug, log=log) except Exception, exc: if log: log.info("%s" % exc) return None if binding == BINDING_HTTP_REDIRECT: xmlstr = decode_base64_and_inflate(xmlstr) elif binding == BINDING_HTTP_POST: xmlstr = base64.b64decode(xmlstr) if log: log.debug("XMLSTR: %s" % xmlstr) response = response.loads(xmlstr, False) if response: response = response.verify() if not response: return None if log: log.debug(response) return self.handle_logout_response(response, log) return response def http_redirect_logout_request(self, get, subject_id, log=None): """ Deal with a LogoutRequest received through HTTP redirect :param get: The request as a dictionary :param subject_id: the id of the current logged user :return: a tuple with a list of header tuples (presently only location) and a status which will be True in case of success or False otherwise. """ headers = [] success = False if log is None: log = self.logger try: saml_request = get['SAMLRequest'] except KeyError: return None if saml_request: xml = decode_base64_and_inflate(saml_request) request = samlp.logout_request_from_string(xml) if log: log.debug(request) if request.name_id.text == subject_id: status = samlp.STATUS_SUCCESS success = self.local_logout(subject_id) else: status = samlp.STATUS_REQUEST_DENIED response, destination = self .make_logout_response( request.issuer.text, request.id, status) if log: log.info("RESPONSE: {0:>s}".format(response)) if 'RelayState' in get: rstate = get['RelayState'] else: rstate = "" (headers, _body) = http_redirect_message(str(response), destination, rstate, 'SAMLResponse') return headers, success def logout_request(self, request, subject_id, log=None, binding=BINDING_HTTP_REDIRECT): """ Deal with a LogoutRequest :param request: The request. The format depends on which binding is used. :param subject_id: the id of the current logged user :return: What is returned also depends on which binding is used. """ if log is None: log = self.logger if binding == BINDING_HTTP_REDIRECT: return self.http_redirect_logout_request(request, subject_id, log) def make_logout_response(self, idp_entity_id, request_id, status_code, binding=BINDING_HTTP_REDIRECT): """ Constructs a LogoutResponse :param idp_entity_id: The entityid of the IdP that want to do the logout :param request_id: The Id of the request we are replying to :param status_code: The status code of the response :param binding: The type of binding that will be used for the response :return: A LogoutResponse instance """ destination = self.config.single_logout_services(idp_entity_id, binding)[0] status = samlp.Status( status_code=samlp.StatusCode(value=status_code)) response = samlp.LogoutResponse( id=sid(), version=VERSION, issue_instant=instant(), destination=destination, issuer=self._issuer(), in_response_to=request_id, status=status, ) return response, destination def add_vo_information_about_user(self, subject_id): """ Add information to the knowledge I have about the user. This is for Virtual organizations. :param subject_id: The subject identifier :return: A possibly extended knowledge. """ ava = {} try: (ava, _) = self.users.get_identity(subject_id) except KeyError: pass # is this a Virtual Organization situation if self.vorg: if self.vorg.do_aggregation(subject_id): # Get the extended identity ava = self.users.get_identity(subject_id)[0] return ava #noinspection PyUnusedLocal def is_session_valid(self, _session_id): """ Place holder. Supposed to check if the session is still valid. """ return True def authz_decision_query_using_assertion(self, entityid, assertion, action=None, resource=None, subject=None, binding=saml2.BINDING_HTTP_REDIRECT, log=None, sign=False): """ Makes an authz decision query. :param entityid: The entity ID of the IdP to send the request to :param assertion: :param action: :param resource: :param subject: :param binding: Which binding to use for sending the request :param log: Where to write log messages :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance """ if action: if isinstance(action, basestring): _action = [saml.Action(text=action)] else: _action = [saml.Action(text=a) for a in action] else: _action = None return self.authz_decision_query(entityid, _action, saml.Evidence(assertion=assertion), resource, subject, binding, log, sign) #noinspection PyUnusedLocal def authz_decision_query(self, entityid, action, evidence=None, resource=None, subject=None, binding=saml2.BINDING_HTTP_REDIRECT, log=None, sign=None): """ Creates an authz decision query. :param entityid: The entity ID of the IdP to send the request to :param action: The action you want to perform (has to be at least one) :param evidence: Why you should be able to perform the action :param resource: The resource you want to perform the action on :param subject: Who wants to do the thing :param binding: Which binding to use for sending the request :param log: Where to write log messages :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance """ spentityid = self._issuer() service_url = self.service_url() my_name = self._my_name() if log is None: log = self.logger if log: log.info("spentityid: %s" % spentityid) log.info("service_url: %s" % service_url) log.info("my_name: %s" % my_name) # authen_req = self.authn_request(session_id, location, # service_url, spentityid, my_name, vorg, # scoping, log, sign) request = samlp.AuthzDecisionQuery(action, evidence, resource, subject=subject, issuer=spentityid, id=sid(), issue_instant=instant(), version=VERSION, destination=entityid) return request #noinspection PyUnusedLocal def authz_decision_query_response(self, response, log=None): """ Verify that the response is OK """ pass #noinspection PyUnusedLocal def do_authz_decision_query(self, entityid, assertion=None, log=None, sign=False): authz_decision_query = self.authz_decision_query(entityid, assertion) for destination in self.config.authz_services(entityid): to_sign = [] if sign : authz_decision_query.signature = pre_signature_part( authz_decision_query.id, self.sec.my_cert, 1) to_sign.append((class_name(authz_decision_query), authz_decision_query.id)) authz_decision_query = signed_instance_factory(authz_decision_query, self.sec, to_sign) response = send_using_soap(authz_decision_query, destination, self.config.key_file, self.config.cert_file, log=log, ca_certs=self.config.ca_certs) if response: if log: log.info("Verifying response") response = self.authz_decision_query_response(response, log) if response: #not_done.remove(entity_id) if log: log.info("OK response from %s" % destination) return response else: if log: log.info("NOT OK response from %s" % destination) return None def request_to_discovery_service(self, disc_url, return_url="", policy="", returnIDParam="", is_passive=False ): """ Created the HTTP redirect URL needed to send the user to the discovery service. :param disc_url: The URL of the discovery service :param return_url: The discovery service MUST redirect the user agent to this location in response to this request :param policy: A parameter name used to indicate the desired behavior controlling the processing of the discovery service :param returnIDParam: A parameter name used to return the unique identifier of the selected identity provider to the original requester. :param is_passive: A boolean value of "true" or "false" that controls whether the discovery service is allowed to visibly interact with the user agent. :return: A URL """ pdir = {"entityID": self.config.entityid} if return_url: pdir["return"] = return_url if policy and policy != IDPDISC_POLICY: pdir["policy"] = policy if returnIDParam: pdir["returnIDParam"] = returnIDParam if is_passive: pdir["is_passive"] = "true" params = urllib.urlencode(pdir) return "%s?%s" % (disc_url, params) def get_idp_from_discovery_service(self, query="", url="", returnIDParam=""): """ Deal with the reponse url from a Discovery Service :param url: the url the user was redirected back to :param returnIDParam: This is where the identifier of the IdP is place if it was specified in the query otherwise in 'entityID' :return: The IdP identifier or "" if none was given """ if url: part = urlparse(url) qsd = parse_qs(part[4]) elif query: qsd = parse_qs(query) else: qsd = {} if returnIDParam: try: return qsd[returnIDParam][0] except KeyError: return "" else: try: return qsd["entityID"][0] except KeyError: return ""
bsd-2-clause
chouseknecht/ansible
lib/ansible/modules/storage/netapp/netapp_e_amg_role.py
52
7909
#!/usr/bin/python # (c) 2016, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: netapp_e_amg_role short_description: NetApp E-Series update the role of a storage array within an Asynchronous Mirror Group (AMG). description: - Update a storage array to become the primary or secondary instance in an asynchronous mirror group version_added: '2.2' author: Kevin Hulquest (@hulquest) options: api_username: required: true description: - The username to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_password: required: true description: - The password to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_url: required: true description: - The url to the SANtricity WebServices Proxy or embedded REST API. validate_certs: required: false default: true description: - Should https certificates be validated? type: bool ssid: description: - The ID of the primary storage array for the async mirror action required: yes role: description: - Whether the array should be the primary or secondary array for the AMG required: yes choices: ['primary', 'secondary'] noSync: description: - Whether to avoid synchronization prior to role reversal required: no default: no type: bool force: description: - Whether to force the role reversal regardless of the online-state of the primary required: no default: no type: bool """ EXAMPLES = """ - name: Update the role of a storage array netapp_e_amg_role: name: updating amg role role: primary ssid: "{{ ssid }}" api_url: "{{ netapp_api_url }}" api_username: "{{ netapp_api_username }}" api_password: "{{ netapp_api_password }}" validate_certs: "{{ netapp_api_validate_certs }}" """ RETURN = """ msg: description: Failure message returned: failure type: str sample: "No Async Mirror Group with the name." """ import json import traceback from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.error import HTTPError from ansible.module_utils._text import to_native from ansible.module_utils.urls import open_url HEADERS = { "Content-Type": "application/json", "Accept": "application/json", } def request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False): try: r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) except HTTPError as e: r = e.fp try: raw_data = r.read() if raw_data: data = json.loads(raw_data) else: raw_data = None except Exception: if ignore_errors: pass else: raise Exception(raw_data) resp_code = r.getcode() if resp_code >= 400 and not ignore_errors: raise Exception(resp_code, data) else: return resp_code, data def has_match(module, ssid, api_url, api_pwd, api_usr, body, name): amg_exists = False has_desired_role = False amg_id = None amg_data = None get_amgs = 'storage-systems/%s/async-mirrors' % ssid url = api_url + get_amgs try: amg_rc, amgs = request(url, url_username=api_usr, url_password=api_pwd, headers=HEADERS) except Exception: module.fail_json(msg="Failed to find AMGs on storage array. Id [%s]" % (ssid)) for amg in amgs: if amg['label'] == name: amg_exists = True amg_id = amg['id'] amg_data = amg if amg['localRole'] == body.get('role'): has_desired_role = True return amg_exists, has_desired_role, amg_id, amg_data def update_amg(module, ssid, api_url, api_usr, api_pwd, body, amg_id): endpoint = 'storage-systems/%s/async-mirrors/%s/role' % (ssid, amg_id) url = api_url + endpoint post_data = json.dumps(body) try: request(url, data=post_data, method='POST', url_username=api_usr, url_password=api_pwd, headers=HEADERS) except Exception as e: module.fail_json( msg="Failed to change role of AMG. Id [%s]. AMG Id [%s]. Error [%s]" % (ssid, amg_id, to_native(e)), exception=traceback.format_exc()) status_endpoint = 'storage-systems/%s/async-mirrors/%s' % (ssid, amg_id) status_url = api_url + status_endpoint try: rc, status = request(status_url, method='GET', url_username=api_usr, url_password=api_pwd, headers=HEADERS) except Exception as e: module.fail_json( msg="Failed to check status of AMG after role reversal. " "Id [%s]. AMG Id [%s]. Error [%s]" % (ssid, amg_id, to_native(e)), exception=traceback.format_exc()) # Here we wait for the role reversal to complete if 'roleChangeProgress' in status: while status['roleChangeProgress'] != "none": try: rc, status = request(status_url, method='GET', url_username=api_usr, url_password=api_pwd, headers=HEADERS) except Exception as e: module.fail_json( msg="Failed to check status of AMG after role reversal. " "Id [%s]. AMG Id [%s]. Error [%s]" % (ssid, amg_id, to_native(e)), exception=traceback.format_exc()) return status def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( name=dict(required=True, type='str'), role=dict(required=True, choices=['primary', 'secondary']), noSync=dict(required=False, type='bool', default=False), force=dict(required=False, type='bool', default=False), ssid=dict(required=True, type='str'), api_url=dict(required=True), api_username=dict(required=False), api_password=dict(required=False, no_log=True), )) module = AnsibleModule(argument_spec=argument_spec) p = module.params ssid = p.pop('ssid') api_url = p.pop('api_url') user = p.pop('api_username') pwd = p.pop('api_password') name = p.pop('name') if not api_url.endswith('/'): api_url += '/' agm_exists, has_desired_role, async_id, amg_data = has_match(module, ssid, api_url, pwd, user, p, name) if not agm_exists: module.fail_json(msg="No Async Mirror Group with the name: '%s' was found" % name) elif has_desired_role: module.exit_json(changed=False, **amg_data) else: amg_data = update_amg(module, ssid, api_url, user, pwd, p, async_id) if amg_data: module.exit_json(changed=True, **amg_data) else: module.exit_json(changed=True, msg="AMG role changed.") if __name__ == '__main__': main()
gpl-3.0
dimecoinco/Dimecoin-1.5a
contrib/bitrpc/bitrpc.py
2348
7835
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:8332") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:8332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Bitcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a Bitcoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
mit
Distrotech/mercurial
tests/test-walkrepo.py
5
1874
import os from mercurial import hg, ui from mercurial.scmutil import walkrepos from mercurial.util import checklink from os import mkdir, chdir from os.path import join as pjoin u = ui.ui() sym = checklink('.') hg.repository(u, 'top1', create=1) mkdir('subdir') chdir('subdir') hg.repository(u, 'sub1', create=1) mkdir('subsubdir') chdir('subsubdir') hg.repository(u, 'subsub1', create=1) chdir(os.path.pardir) if sym: os.symlink(os.path.pardir, 'circle') os.symlink(pjoin('subsubdir', 'subsub1'), 'subsub1') def runtest(): reposet = frozenset(walkrepos('.', followsym=True)) if sym and (len(reposet) != 3): print "reposet = %r" % (reposet,) print ("Found %d repositories when I should have found 3" % (len(reposet),)) if (not sym) and (len(reposet) != 2): print "reposet = %r" % (reposet,) print ("Found %d repositories when I should have found 2" % (len(reposet),)) sub1set = frozenset((pjoin('.', 'sub1'), pjoin('.', 'circle', 'subdir', 'sub1'))) if len(sub1set & reposet) != 1: print "sub1set = %r" % (sub1set,) print "reposet = %r" % (reposet,) print "sub1set and reposet should have exactly one path in common." sub2set = frozenset((pjoin('.', 'subsub1'), pjoin('.', 'subsubdir', 'subsub1'))) if len(sub2set & reposet) != 1: print "sub2set = %r" % (sub2set,) print "reposet = %r" % (reposet,) print "sub1set and reposet should have exactly one path in common." sub3 = pjoin('.', 'circle', 'top1') if sym and sub3 not in reposet: print "reposet = %r" % (reposet,) print "Symbolic links are supported and %s is not in reposet" % (sub3,) runtest() if sym: # Simulate not having symlinks. del os.path.samestat sym = False runtest()
gpl-2.0
MarkTheF4rth/youtube-dl
youtube_dl/extractor/comedycentral.py
23
11797
from __future__ import unicode_literals import re from .mtv import MTVServicesInfoExtractor from ..compat import ( compat_str, compat_urllib_parse, ) from ..utils import ( ExtractorError, float_or_none, unified_strdate, ) class ComedyCentralIE(MTVServicesInfoExtractor): _VALID_URL = r'''(?x)https?://(?:www\.)?cc\.com/ (video-clips|episodes|cc-studios|video-collections|full-episodes) /(?P<title>.*)''' _FEED_URL = 'http://comedycentral.com/feeds/mrss/' _TEST = { 'url': 'http://www.cc.com/video-clips/kllhuv/stand-up-greg-fitzsimmons--uncensored---too-good-of-a-mother', 'md5': 'c4f48e9eda1b16dd10add0744344b6d8', 'info_dict': { 'id': 'cef0cbb3-e776-4bc9-b62e-8016deccb354', 'ext': 'mp4', 'title': 'CC:Stand-Up|Greg Fitzsimmons: Life on Stage|Uncensored - Too Good of a Mother', 'description': 'After a certain point, breastfeeding becomes c**kblocking.', }, } class ComedyCentralShowsIE(MTVServicesInfoExtractor): IE_DESC = 'The Daily Show / The Colbert Report' # urls can be abbreviations like :thedailyshow # urls for episodes like: # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524 _VALID_URL = r'''(?x)^(:(?P<shortname>tds|thedailyshow) |https?://(:www\.)? (?P<showname>thedailyshow|thecolbertreport)\.(?:cc\.)?com/ ((?:full-)?episodes/(?:[0-9a-z]{6}/)?(?P<episode>.*)| (?P<clip> (?:(?:guests/[^/]+|videos|video-playlists|special-editions|news-team/[^/]+)/[^/]+/(?P<videotitle>[^/?#]+)) |(the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?)) |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)) )| (?P<interview> extended-interviews/(?P<interID>[0-9a-z]+)/ (?:playlist_tds_extended_)?(?P<interview_title>[^/?#]*?) (?:/[^/?#]?|[?#]|$)))) ''' _TESTS = [{ 'url': 'http://thedailyshow.cc.com/watch/thu-december-13-2012/kristen-stewart', 'md5': '4e2f5cb088a83cd8cdb7756132f9739d', 'info_dict': { 'id': 'ab9ab3e7-5a98-4dbe-8b21-551dc0523d55', 'ext': 'mp4', 'upload_date': '20121213', 'description': 'Kristen Stewart learns to let loose in "On the Road."', 'uploader': 'thedailyshow', 'title': 'thedailyshow kristen-stewart part 1', } }, { 'url': 'http://thedailyshow.cc.com/extended-interviews/b6364d/sarah-chayes-extended-interview', 'info_dict': { 'id': 'sarah-chayes-extended-interview', 'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."', 'title': 'thedailyshow Sarah Chayes Extended Interview', }, 'playlist': [ { 'info_dict': { 'id': '0baad492-cbec-4ec1-9e50-ad91c291127f', 'ext': 'mp4', 'upload_date': '20150129', 'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."', 'uploader': 'thedailyshow', 'title': 'thedailyshow sarah-chayes-extended-interview part 1', }, }, { 'info_dict': { 'id': '1e4fb91b-8ce7-4277-bd7c-98c9f1bbd283', 'ext': 'mp4', 'upload_date': '20150129', 'description': 'Carnegie Endowment Senior Associate Sarah Chayes discusses how corrupt institutions function throughout the world in her book "Thieves of State: Why Corruption Threatens Global Security."', 'uploader': 'thedailyshow', 'title': 'thedailyshow sarah-chayes-extended-interview part 2', }, }, ], 'params': { 'skip_download': True, }, }, { 'url': 'http://thedailyshow.cc.com/extended-interviews/xm3fnq/andrew-napolitano-extended-interview', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/videos/29w6fx/-realhumanpraise-for-fox-news', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/videos/gh6urb/neil-degrasse-tyson-pt--1?xrs=eml_col_031114', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/guests/michael-lewis/3efna8/exclusive---michael-lewis-extended-interview-pt--3', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/episodes/sy7yv0/april-8--2014---denis-leary', 'only_matching': True, }, { 'url': 'http://thecolbertreport.cc.com/episodes/8ase07/april-8--2014---jane-goodall', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/video-playlists/npde3s/the-daily-show-19088-highlights', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/video-playlists/t6d9sg/the-daily-show-20038-highlights/be3cwo', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/special-editions/2l8fdb/special-edition---a-look-back-at-food', 'only_matching': True, }, { 'url': 'http://thedailyshow.cc.com/news-team/michael-che/7wnfel/we-need-to-talk-about-israel', 'only_matching': True, }] _available_formats = ['3500', '2200', '1700', '1200', '750', '400'] _video_extensions = { '3500': 'mp4', '2200': 'mp4', '1700': 'mp4', '1200': 'mp4', '750': 'mp4', '400': 'mp4', } _video_dimensions = { '3500': (1280, 720), '2200': (960, 540), '1700': (768, 432), '1200': (640, 360), '750': (512, 288), '400': (384, 216), } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) if mobj.group('shortname'): return self.url_result('http://www.cc.com/shows/the-daily-show-with-trevor-noah/full-episodes') if mobj.group('clip'): if mobj.group('videotitle'): epTitle = mobj.group('videotitle') elif mobj.group('showname') == 'thedailyshow': epTitle = mobj.group('tdstitle') else: epTitle = mobj.group('cntitle') dlNewest = False elif mobj.group('interview'): epTitle = mobj.group('interview_title') dlNewest = False else: dlNewest = not mobj.group('episode') if dlNewest: epTitle = mobj.group('showname') else: epTitle = mobj.group('episode') show_name = mobj.group('showname') webpage, htmlHandle = self._download_webpage_handle(url, epTitle) if dlNewest: url = htmlHandle.geturl() mobj = re.match(self._VALID_URL, url, re.VERBOSE) if mobj is None: raise ExtractorError('Invalid redirected URL: ' + url) if mobj.group('episode') == '': raise ExtractorError('Redirected URL is still not specific: ' + url) epTitle = (mobj.group('episode') or mobj.group('videotitle')).rpartition('/')[-1] mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage) if len(mMovieParams) == 0: # The Colbert Report embeds the information in a without # a URL prefix; so extract the alternate reference # and then add the URL prefix manually. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video|playlist).*?:.*?)"', webpage) if len(altMovieParams) == 0: raise ExtractorError('unable to find Flash URL in webpage ' + url) else: mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])] uri = mMovieParams[0][1] # Correct cc.com in uri uri = re.sub(r'(episode:[^.]+)(\.cc)?\.com', r'\1.com', uri) index_url = 'http://%s.cc.com/feeds/mrss?%s' % (show_name, compat_urllib_parse.urlencode({'uri': uri})) idoc = self._download_xml( index_url, epTitle, 'Downloading show index', 'Unable to download episode index') title = idoc.find('./channel/title').text description = idoc.find('./channel/description').text entries = [] item_els = idoc.findall('.//item') for part_num, itemEl in enumerate(item_els): upload_date = unified_strdate(itemEl.findall('./pubDate')[0].text) thumbnail = itemEl.find('.//{http://search.yahoo.com/mrss/}thumbnail').attrib.get('url') content = itemEl.find('.//{http://search.yahoo.com/mrss/}content') duration = float_or_none(content.attrib.get('duration')) mediagen_url = content.attrib['url'] guid = itemEl.find('./guid').text.rpartition(':')[-1] cdoc = self._download_xml( mediagen_url, epTitle, 'Downloading configuration for segment %d / %d' % (part_num + 1, len(item_els))) turls = [] for rendition in cdoc.findall('.//rendition'): finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text) turls.append(finfo) formats = [] for format, rtmp_video_url in turls: w, h = self._video_dimensions.get(format, (None, None)) formats.append({ 'format_id': 'vhttp-%s' % format, 'url': self._transform_rtmp_url(rtmp_video_url), 'ext': self._video_extensions.get(format, 'mp4'), 'height': h, 'width': w, }) formats.append({ 'format_id': 'rtmp-%s' % format, 'url': rtmp_video_url.replace('viacomccstrm', 'viacommtvstrm'), 'ext': self._video_extensions.get(format, 'mp4'), 'height': h, 'width': w, }) self._sort_formats(formats) subtitles = self._extract_subtitles(cdoc, guid) virtual_id = show_name + ' ' + epTitle + ' part ' + compat_str(part_num + 1) entries.append({ 'id': guid, 'title': virtual_id, 'formats': formats, 'uploader': show_name, 'upload_date': upload_date, 'duration': duration, 'thumbnail': thumbnail, 'description': description, 'subtitles': subtitles, }) return { '_type': 'playlist', 'id': epTitle, 'entries': entries, 'title': show_name + ' ' + title, 'description': description, }
unlicense
AgostonSzepessy/servo
tests/wpt/web-platform-tests/tools/pywebsocket/src/test/testdata/handlers/blank_wsh.py
499
1557
# Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # intentionally left blank
mpl-2.0
Anonymous-X6/django
django/db/backends/postgresql/version.py
632
1517
""" Extracts the version of the PostgreSQL server. """ import re # This reg-exp is intentionally fairly flexible here. # Needs to be able to handle stuff like: # PostgreSQL #.#.# # EnterpriseDB #.# # PostgreSQL #.# beta# # PostgreSQL #.#beta# VERSION_RE = re.compile(r'\S+ (\d+)\.(\d+)\.?(\d+)?') def _parse_version(text): "Internal parsing method. Factored out for testing purposes." major, major2, minor = VERSION_RE.search(text).groups() try: return int(major) * 10000 + int(major2) * 100 + int(minor) except (ValueError, TypeError): return int(major) * 10000 + int(major2) * 100 def get_version(connection): """ Returns an integer representing the major, minor and revision number of the server. Format is the one used for the return value of libpq PQServerVersion()/``server_version`` connection attribute (available in newer psycopg2 versions.) For example, 90304 for 9.3.4. The last two digits will be 00 in the case of releases (e.g., 90400 for 'PostgreSQL 9.4') or in the case of beta and prereleases (e.g. 90100 for 'PostgreSQL 9.1beta2'). PQServerVersion()/``server_version`` doesn't execute a query so try that first, then fallback to a ``SELECT version()`` query. """ if hasattr(connection, 'server_version'): return connection.server_version else: with connection.cursor() as cursor: cursor.execute("SELECT version()") return _parse_version(cursor.fetchone()[0])
bsd-3-clause
cosurgi/trunk
examples/test/test_Ip2_FrictMat_CpmMat_FrictPhys.py
10
1264
from yade import * from yade import plot,qt import sys young=25e9 poisson=.2 sigmaT=3e6 frictionAngle=atan(1) density=4800 ## 4800 # twice the density, since porosity is about .5 (.62) epsCrackOnset=1e-4 relDuctility=300 intRadius=1.5 concMat = O.materials.append(CpmMat(young=young,poisson=poisson,density=4800,sigmaT=3e6,relDuctility=30,epsCrackOnset=1e-4,neverDamage=False)) frictMat = O.materials.append(FrictMat(young=young,poisson=poisson,density=4800)) b1 = sphere((0,0,0),1,material=concMat) b1.state.vel = Vector3(1,0,0) b2 = sphere((0,5,0),1,material=concMat) b2.state.vel = Vector3(2,-2,0) b3 = sphere((0,-4,0),1,material=frictMat) b3.state.vel = Vector3(1,3,0) b4 = facet(((2,-5,-5),(2,-5,10),(2,10,-5)),material=frictMat) O.bodies.append((b1,b2,b3,b4)) O.dt = 5e-6 O.engines=[ ForceResetter(), InsertionSortCollider([Bo1_Sphere_Aabb(),Bo1_Facet_Aabb()]), InteractionLoop( [ Ig2_Sphere_Sphere_ScGeom(), Ig2_Facet_Sphere_ScGeom() ], [ Ip2_CpmMat_CpmMat_CpmPhys(), Ip2_FrictMat_CpmMat_FrictPhys(), Ip2_FrictMat_FrictMat_FrictPhys(), ], [ Law2_ScGeom_CpmPhys_Cpm(), Law2_ScGeom_FrictPhys_CundallStrack() ] ), NewtonIntegrator(label='newton'), ] O.step() try: from yade import qt qt.View() except: O.run()
gpl-2.0
raj-zealous/DrupalProject
sites/all/modules/contrib/proj4js/lib/proj4js/tools/jsmin.py
513
7471
#!/usr/bin/python # This code is original from jsmin by Douglas Crockford, it was translated to # Python by Baruch Even. The original code had the following copyright and # license. # # /* jsmin.c # 2007-01-08 # # Copyright (c) 2002 Douglas Crockford (www.crockford.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # The Software shall be used for Good, not Evil. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # */ from StringIO import StringIO def jsmin(js): ins = StringIO(js) outs = StringIO() JavascriptMinify().minify(ins, outs) str = outs.getvalue() if len(str) > 0 and str[0] == '\n': str = str[1:] return str def isAlphanum(c): """return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character. """ return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or (c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126)); class UnterminatedComment(Exception): pass class UnterminatedStringLiteral(Exception): pass class UnterminatedRegularExpression(Exception): pass class JavascriptMinify(object): def _outA(self): self.outstream.write(self.theA) def _outB(self): self.outstream.write(self.theB) def _get(self): """return the next character from stdin. Watch out for lookahead. If the character is a control character, translate it to a space or linefeed. """ c = self.theLookahead self.theLookahead = None if c == None: c = self.instream.read(1) if c >= ' ' or c == '\n': return c if c == '': # EOF return '\000' if c == '\r': return '\n' return ' ' def _peek(self): self.theLookahead = self._get() return self.theLookahead def _next(self): """get the next character, excluding comments. peek() is used to see if a '/' is followed by a '/' or '*'. """ c = self._get() if c == '/': p = self._peek() if p == '/': c = self._get() while c > '\n': c = self._get() return c if p == '*': c = self._get() while 1: c = self._get() if c == '*': if self._peek() == '/': self._get() return ' ' if c == '\000': raise UnterminatedComment() return c def _action(self, action): """do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! action recognizes a regular expression if it is preceded by ( or , or =. """ if action <= 1: self._outA() if action <= 2: self.theA = self.theB if self.theA == "'" or self.theA == '"': while 1: self._outA() self.theA = self._get() if self.theA == self.theB: break if self.theA <= '\n': raise UnterminatedStringLiteral() if self.theA == '\\': self._outA() self.theA = self._get() if action <= 3: self.theB = self._next() if self.theB == '/' and (self.theA == '(' or self.theA == ',' or self.theA == '=' or self.theA == ':' or self.theA == '[' or self.theA == '?' or self.theA == '!' or self.theA == '&' or self.theA == '|'): self._outA() self._outB() while 1: self.theA = self._get() if self.theA == '/': break elif self.theA == '\\': self._outA() self.theA = self._get() elif self.theA <= '\n': raise UnterminatedRegularExpression() self._outA() self.theB = self._next() def _jsmin(self): """Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. """ self.theA = '\n' self._action(3) while self.theA != '\000': if self.theA == ' ': if isAlphanum(self.theB): self._action(1) else: self._action(2) elif self.theA == '\n': if self.theB in ['{', '[', '(', '+', '-']: self._action(1) elif self.theB == ' ': self._action(3) else: if isAlphanum(self.theB): self._action(1) else: self._action(2) else: if self.theB == ' ': if isAlphanum(self.theA): self._action(1) else: self._action(3) elif self.theB == '\n': if self.theA in ['}', ']', ')', '+', '-', '"', '\'']: self._action(1) else: if isAlphanum(self.theA): self._action(1) else: self._action(3) else: self._action(1) def minify(self, instream, outstream): self.instream = instream self.outstream = outstream self.theA = None self.thaB = None self.theLookahead = None self._jsmin() self.instream.close() if __name__ == '__main__': import sys jsm = JavascriptMinify() jsm.minify(sys.stdin, sys.stdout)
gpl-2.0
NeCTAR-RC/cinder
cinder/tests/db/fakes.py
43
1389
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 OpenStack Foundation # 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. """Stubouts, mocks and fixtures for the test suite.""" from cinder import db class FakeModel(object): """Stubs out for model.""" def __init__(self, values): self.values = values def __getattr__(self, name): return self.values[name] def __getitem__(self, key): if key in self.values: return self.values[key] else: raise NotImplementedError() def __repr__(self): return '<FakeModel: %s>' % self.values def stub_out(stubs, funcs): """Set the stubs in mapping in the db api.""" for func in funcs: func_name = '_'.join(func.__name__.split('_')[1:]) stubs.Set(db, func_name, func)
apache-2.0
kailIII/emaresa
trunk.pe/report_aeroo/wizard/report_actions_remove.py
5
4658
############################################################################## # # Copyright (c) 2008-2011 Alistek Ltd (http://www.alistek.com) All Rights Reserved. # General contacts <info@alistek.com> # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your option) any later version. # # This module is GPLv3 or newer and incompatible # with OpenERP SA "AGPL + Private Use License"! # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## import wizard import pooler from tools.translate import _ def ir_del(cr, uid, id): obj = pooler.get_pool(cr.dbname).get('ir.values') return obj.unlink(cr, uid, [id]) class report_actions_remove_wizard(wizard.interface): ''' Remove print button ''' form = '''<?xml version="1.0"?> <form string="Remove print button"> <label string="Or you want to remove print button for this report?"/> </form>''' ex_form = '''<?xml version="1.0"?> <form string="Remove print button"> <label string="No Report Action to delete for this report"/> </form>''' done_form = '''<?xml version="1.0"?> <form string="Remove print button"> <label string="The print button is successfully removed"/> </form>''' def _do_action(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) report = pool.get(data['model']).read(cr, uid, data['id'], ['report_wizard'], context=context) if report['report_wizard']: pool.get('ir.actions.act_window').unlink(cr, uid, data['report_action_id'], context=context) else: event_id = pool.get('ir.values').search(cr, uid, [('value','=','ir.actions.report.xml,%d' % data['id'])])[0] res = ir_del(cr, uid, event_id) return {} def _check(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) report = pool.get(data['model']).browse(cr, uid, data['id'], context=context) if report.report_wizard: act_win_obj = pool.get('ir.actions.act_window') act_win_ids = act_win_obj.search(cr, uid, [('res_model','=','aeroo.print_actions')], context=context) for act_win in act_win_obj.browse(cr, uid, act_win_ids, context=context): act_win_context = eval(act_win.context, {}) if act_win_context.get('report_action_id')==report.id: data['report_action_id'] = act_win.id return 'remove' return 'no_exist' else: ids = pool.get('ir.values').search(cr, uid, [('value','=',report.type+','+str(data['id']))]) if not ids: return 'no_exist' else: return 'remove' states = { 'init': { 'actions': [], 'result': {'type':'choice','next_state':_check} }, 'remove': { 'actions': [], 'result': {'type': 'form', 'arch': form, 'fields': {}, 'state': (('end', _('_No')), ('process', _('_Yes')))}, }, 'no_exist': { 'actions': [], 'result': {'type': 'form', 'arch': ex_form, 'fields': {}, 'state': (('end', _('_Close')),)}, }, 'process': { 'actions': [_do_action], 'result': {'type': 'state', 'state': 'done'}, }, 'done': { 'actions': [], 'result': {'type': 'form', 'arch': done_form, 'fields': {}, 'state': (('exit', _('_Close')),)}, }, 'exit': { 'actions': [], 'result': {'type': 'state', 'state': 'end'}, }, } report_actions_remove_wizard('aeroo.report_actions_remove')
agpl-3.0
math-a3k/django-ai
tests/test_models/migrations/0011_add_is_inferred_and_minor_tweaks.py
1
2196
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-12-20 15:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_models', '0010_myunsupervisedlearningtechnique'), ] operations = [ migrations.AddField( model_name='mystatisticalmodel', name='is_inferred', field=models.BooleanField( default=False, verbose_name='Is Inferred?'), ), migrations.AddField( model_name='mysupervisedlearningtechnique', name='is_inferred', field=models.BooleanField( default=False, verbose_name='Is Inferred?'), ), migrations.AddField( model_name='myunsupervisedlearningtechnique', name='is_inferred', field=models.BooleanField( default=False, verbose_name='Is Inferred?'), ), migrations.AlterField( model_name='mystatisticalmodel', name='sm_type', field=models.SmallIntegerField(blank=True, choices=[ (0, 'General / System'), (1, 'Classification'), (2, 'Regression')], default=0, null=True, verbose_name='Statistical Technique Type'), ), migrations.AlterField( model_name='mysupervisedlearningtechnique', name='sm_type', field=models.SmallIntegerField(blank=True, choices=[ (0, 'General / System'), (1, 'Classification'), (2, 'Regression')], default=0, null=True, verbose_name='Statistical Technique Type'), ), migrations.AlterField( model_name='myunsupervisedlearningtechnique', name='sm_type', field=models.SmallIntegerField(blank=True, choices=[ (0, 'General / System'), (1, 'Classification'), (2, 'Regression')], default=0, null=True, verbose_name='Statistical Technique Type'), ), ]
lgpl-3.0
minhtuancn/odoo
addons/hr_timesheet_sheet/__init__.py
434
1127
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_timesheet_sheet import wizard import report import res_config # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
SiddheshK15/android_kernel_cyanogen_msm8916
scripts/rt-tester/rt-tester.py
11005
5307
#!/usr/bin/python # # rt-mutex tester # # (C) 2006 Thomas Gleixner <tglx@linutronix.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # import os import sys import getopt import shutil import string # Globals quiet = 0 test = 0 comments = 0 sysfsprefix = "/sys/devices/system/rttest/rttest" statusfile = "/status" commandfile = "/command" # Command opcodes cmd_opcodes = { "schedother" : "1", "schedfifo" : "2", "lock" : "3", "locknowait" : "4", "lockint" : "5", "lockintnowait" : "6", "lockcont" : "7", "unlock" : "8", "signal" : "11", "resetevent" : "98", "reset" : "99", } test_opcodes = { "prioeq" : ["P" , "eq" , None], "priolt" : ["P" , "lt" , None], "priogt" : ["P" , "gt" , None], "nprioeq" : ["N" , "eq" , None], "npriolt" : ["N" , "lt" , None], "npriogt" : ["N" , "gt" , None], "unlocked" : ["M" , "eq" , 0], "trylock" : ["M" , "eq" , 1], "blocked" : ["M" , "eq" , 2], "blockedwake" : ["M" , "eq" , 3], "locked" : ["M" , "eq" , 4], "opcodeeq" : ["O" , "eq" , None], "opcodelt" : ["O" , "lt" , None], "opcodegt" : ["O" , "gt" , None], "eventeq" : ["E" , "eq" , None], "eventlt" : ["E" , "lt" , None], "eventgt" : ["E" , "gt" , None], } # Print usage information def usage(): print "rt-tester.py <-c -h -q -t> <testfile>" print " -c display comments after first command" print " -h help" print " -q quiet mode" print " -t test mode (syntax check)" print " testfile: read test specification from testfile" print " otherwise from stdin" return # Print progress when not in quiet mode def progress(str): if not quiet: print str # Analyse a status value def analyse(val, top, arg): intval = int(val) if top[0] == "M": intval = intval / (10 ** int(arg)) intval = intval % 10 argval = top[2] elif top[0] == "O": argval = int(cmd_opcodes.get(arg, arg)) else: argval = int(arg) # progress("%d %s %d" %(intval, top[1], argval)) if top[1] == "eq" and intval == argval: return 1 if top[1] == "lt" and intval < argval: return 1 if top[1] == "gt" and intval > argval: return 1 return 0 # Parse the commandline try: (options, arguments) = getopt.getopt(sys.argv[1:],'chqt') except getopt.GetoptError, ex: usage() sys.exit(1) # Parse commandline options for option, value in options: if option == "-c": comments = 1 elif option == "-q": quiet = 1 elif option == "-t": test = 1 elif option == '-h': usage() sys.exit(0) # Select the input source if arguments: try: fd = open(arguments[0]) except Exception,ex: sys.stderr.write("File not found %s\n" %(arguments[0])) sys.exit(1) else: fd = sys.stdin linenr = 0 # Read the test patterns while 1: linenr = linenr + 1 line = fd.readline() if not len(line): break line = line.strip() parts = line.split(":") if not parts or len(parts) < 1: continue if len(parts[0]) == 0: continue if parts[0].startswith("#"): if comments > 1: progress(line) continue if comments == 1: comments = 2 progress(line) cmd = parts[0].strip().lower() opc = parts[1].strip().lower() tid = parts[2].strip() dat = parts[3].strip() try: # Test or wait for a status value if cmd == "t" or cmd == "w": testop = test_opcodes[opc] fname = "%s%s%s" %(sysfsprefix, tid, statusfile) if test: print fname continue while 1: query = 1 fsta = open(fname, 'r') status = fsta.readline().strip() fsta.close() stat = status.split(",") for s in stat: s = s.strip() if s.startswith(testop[0]): # Separate status value val = s[2:].strip() query = analyse(val, testop, dat) break if query or cmd == "t": break progress(" " + status) if not query: sys.stderr.write("Test failed in line %d\n" %(linenr)) sys.exit(1) # Issue a command to the tester elif cmd == "c": cmdnr = cmd_opcodes[opc] # Build command string and sys filename cmdstr = "%s:%s" %(cmdnr, dat) fname = "%s%s%s" %(sysfsprefix, tid, commandfile) if test: print fname continue fcmd = open(fname, 'w') fcmd.write(cmdstr) fcmd.close() except Exception,ex: sys.stderr.write(str(ex)) sys.stderr.write("\nSyntax error in line %d\n" %(linenr)) if not test: fd.close() sys.exit(1) # Normal exit pass print "Pass" sys.exit(0)
gpl-2.0
Makeystreet/makeystreet
woot/apps/catalog/views/review.py
1
5983
from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render from django.utils import timezone from woot.apps.catalog.forms import CreateProductReviewForm,\ CreateShopReviewForm, CreateSpaceReviewForm from woot.apps.catalog.models.core import Product, Shop, Space, NewProduct from woot.apps.catalog.models.review import ProductReview, ShopReview,\ SpaceReview from .helper import get_user_details_json static_blob = settings.STATIC_BLOB def all_reviews(request): product_reviews = ProductReview.objects.all() shop_reviews = ShopReview.objects.all() space_reviews = SpaceReview.objects.all() context = { 'static_blob': static_blob, 'user_details': get_user_details_json(request), 'product_reviews': product_reviews, 'shop_reviews': shop_reviews, 'space_reviews': space_reviews, } return render(request, 'catalog/all_reviews.html', context) def store_review(request, review_id): try: user_details = get_user_details_json(request) review = ShopReview.objects.get(id=review_id) review.upvotes = review.voteshopreview_set.filter(vote=True) context = { 'static_blob': static_blob, 'user_details': user_details, 'review': review, } return render(request, 'catalog/store_review.html', context) except ShopReview.DoesNotExist: raise Http404 def product_review(request, review_id): try: user_details = get_user_details_json(request) review = ProductReview.objects.get(id=review_id) review.upvotes = review.voteproductreview_set.filter(vote=True) context = { 'static_blob': static_blob, 'user_details': user_details, 'review': review, } return render(request, 'catalog/product_review.html', context) except ProductReview.DoesNotExist: raise Http404 def space_review(request, review_id): try: user_details = get_user_details_json(request) review = SpaceReview.objects.get(id=review_id) review.upvotes = review.votespacereview_set.filter(vote=True) context = { 'static_blob': static_blob, 'user_details': user_details, 'review': review, } return render(request, 'catalog/space_review.html', context) except SpaceReview.DoesNotExist: raise Http404 def create_review(request): if request.method == "POST": if request.POST.get('val_type', '') == 'PART': form = CreateProductReviewForm(request.POST) if form.is_valid(): r = ProductReview() r.title = form.cleaned_data['val_title'] r.review = form.cleaned_data['val_review'] r.user = request.user r.rating = form.cleaned_data['val_rating'] r.added_time = timezone.now() product_data_split = form.cleaned_data['val_part'].split('_') product_type = product_data_split[0] product_id = int(product_data_split[1]) if product_type == 'old': product = Product.objects.get(id=product_id) r.product = product elif product_type == 'new': product = NewProduct.objects.get(id=product_id) r.product = product r.save() return HttpResponseRedirect(reverse('catalog:all_reviews')) else: print(form.errors) elif request.POST.get('val_type', '') == 'SHOP': form = CreateShopReviewForm(request.POST) if form.is_valid(): r = ShopReview() r.title = form.cleaned_data['val_title'] r.review = form.cleaned_data['val_review'] r.user = request.user r.rating = form.cleaned_data['val_rating'] r.added_time = timezone.now() shop_data_split = form.cleaned_data['val_shop'].split('_') shop_type = shop_data_split[0] shop_id = int(shop_data_split[1]) if shop_type == 'old': shop = Shop.objects.get(id=shop_id) r.shop = shop elif shop_type == 'new': shop = NewProduct.objects.get(id=shop_id) r.shop = shop r.save() return HttpResponseRedirect(reverse('catalog:all_reviews')) else: print(form.errors) elif request.POST.get('val_type', '') == 'SPACE': form = CreateSpaceReviewForm(request.POST) if form.is_valid(): r = SpaceReview() r.title = form.cleaned_data['val_title'] r.review = form.cleaned_data['val_review'] r.user = request.user r.rating = form.cleaned_data['val_rating'] r.added_time = timezone.now() space_data_split = form.cleaned_data['val_space'].split('_') space_type = space_data_split[0] space_id = int(space_data_split[1]) if space_type == 'old': space = Space.objects.get(id=space_id) r.space = space elif space_type == 'new': space = NewProduct.objects.get(id=space_id) r.space = space r.save() return HttpResponseRedirect(reverse('catalog:all_reviews')) else: print(form.errors) else: pass context = { 'static_blob': static_blob, 'user_details': get_user_details_json(request), } return render(request, 'catalog/create_product_review.html', context)
apache-2.0
ar7z1/ansible
lib/ansible/modules/remote_management/oneview/oneview_network_set.py
146
5167
#!/usr/bin/python # Copyright (c) 2016-2017 Hewlett Packard Enterprise Development LP # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: oneview_network_set short_description: Manage HPE OneView Network Set resources description: - Provides an interface to manage Network Set resources. Can create, update, or delete. version_added: "2.4" requirements: - hpOneView >= 4.0.0 author: - Felipe Bulsoni (@fgbulsoni) - Thiago Miotto (@tmiotto) - Adriane Cardozo (@adriane-cardozo) options: state: description: - Indicates the desired state for the Network Set resource. - C(present) will ensure data properties are compliant with OneView. - C(absent) will remove the resource from OneView, if it exists. default: present choices: ['present', 'absent'] data: description: - List with the Network Set properties. required: true extends_documentation_fragment: - oneview - oneview.validateetag ''' EXAMPLES = ''' - name: Create a Network Set oneview_network_set: config: /etc/oneview/oneview_config.json state: present data: name: OneViewSDK Test Network Set networkUris: - Test Ethernet Network_1 # can be a name - /rest/ethernet-networks/e4360c9d-051d-4931-b2aa-7de846450dd8 # or a URI delegate_to: localhost - name: Update the Network Set name to 'OneViewSDK Test Network Set - Renamed' and change the associated networks oneview_network_set: config: /etc/oneview/oneview_config.json state: present data: name: OneViewSDK Test Network Set newName: OneViewSDK Test Network Set - Renamed networkUris: - Test Ethernet Network_1 delegate_to: localhost - name: Delete the Network Set oneview_network_set: config: /etc/oneview/oneview_config.json state: absent data: name: OneViewSDK Test Network Set - Renamed delegate_to: localhost - name: Update the Network set with two scopes oneview_network_set: config: /etc/oneview/oneview_config.json state: present data: name: OneViewSDK Test Network Set scopeUris: - /rest/scopes/01SC123456 - /rest/scopes/02SC123456 delegate_to: localhost ''' RETURN = ''' network_set: description: Has the facts about the Network Set. returned: On state 'present', but can be null. type: dict ''' from ansible.module_utils.oneview import OneViewModuleBase, OneViewModuleResourceNotFound class NetworkSetModule(OneViewModuleBase): MSG_CREATED = 'Network Set created successfully.' MSG_UPDATED = 'Network Set updated successfully.' MSG_DELETED = 'Network Set deleted successfully.' MSG_ALREADY_PRESENT = 'Network Set is already present.' MSG_ALREADY_ABSENT = 'Network Set is already absent.' MSG_ETHERNET_NETWORK_NOT_FOUND = 'Ethernet Network not found: ' RESOURCE_FACT_NAME = 'network_set' argument_spec = dict( state=dict(default='present', choices=['present', 'absent']), data=dict(required=True, type='dict')) def __init__(self): super(NetworkSetModule, self).__init__(additional_arg_spec=self.argument_spec, validate_etag_support=True) self.resource_client = self.oneview_client.network_sets def execute_module(self): resource = self.get_by_name(self.data.get('name')) if self.state == 'present': return self._present(resource) elif self.state == 'absent': return self.resource_absent(resource) def _present(self, resource): scope_uris = self.data.pop('scopeUris', None) self._replace_network_name_by_uri(self.data) result = self.resource_present(resource, self.RESOURCE_FACT_NAME) if scope_uris is not None: result = self.resource_scopes_set(result, self.RESOURCE_FACT_NAME, scope_uris) return result def _get_ethernet_network_by_name(self, name): result = self.oneview_client.ethernet_networks.get_by('name', name) return result[0] if result else None def _get_network_uri(self, network_name_or_uri): if network_name_or_uri.startswith('/rest/ethernet-networks'): return network_name_or_uri else: enet_network = self._get_ethernet_network_by_name(network_name_or_uri) if enet_network: return enet_network['uri'] else: raise OneViewModuleResourceNotFound(self.MSG_ETHERNET_NETWORK_NOT_FOUND + network_name_or_uri) def _replace_network_name_by_uri(self, data): if 'networkUris' in data: data['networkUris'] = [self._get_network_uri(x) for x in data['networkUris']] def main(): NetworkSetModule().run() if __name__ == '__main__': main()
gpl-3.0
semplea/characters-meta
python/alchemy/examples/alchemy_vision_v1.py
1
1466
import json from os.path import join, dirname from watson_developer_cloud import AlchemyVisionV1 alchemy_vision = AlchemyVisionV1(api_key='c851400276c1acbd020210847f8677e6d1577c26') # Face recognition with open(join(dirname(__file__), '../resources/face.jpg'), 'rb') as image_file: print(json.dumps(alchemy_vision.recognize_faces(image_file, knowledge_graph=True), indent=2)) face_url = 'https://upload.wikimedia.org/wikipedia/commons/9/9d/Barack_Obama.jpg' print(json.dumps(alchemy_vision.recognize_faces(image_url=face_url, knowledge_graph=True), indent=2)) # Image tagging with open(join(dirname(__file__), '../resources/test.jpg'), 'rb') as image_file: print(json.dumps(alchemy_vision.get_image_keywords(image_file, knowledge_graph=True, force_show_all=True), indent=2)) # Text recognition with open(join(dirname(__file__), '../resources/text.png'), 'rb') as image_file: print(json.dumps(alchemy_vision.get_image_scene_text(image_file), indent=2)) print(json.dumps(alchemy_vision.get_image_keywords( image_url='https://upload.wikimedia.org/wikipedia/commons/8/81/Morris-Chair-Ironwood.jpg'), indent=2)) # Image link extraction print(json.dumps(alchemy_vision.get_image_links(url='http://www.zillow.com/'), indent=2)) with open(join(dirname(__file__), '../resources/example.html'), 'r') as webpage: print(json.dumps(alchemy_vision.get_image_links(html=webpage.read()), indent=2))
mit
scw/ansible
lib/ansible/galaxy/api.py
82
5143
#!/usr/bin/env python ######################################################################## # # (C) 2013, James Cammarata <jcammarata@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ######################################################################## import json from urllib2 import urlopen, quote as urlquote from urlparse import urlparse from ansible.errors import AnsibleError class GalaxyAPI(object): ''' This class is meant to be used as a API client for an Ansible Galaxy server ''' SUPPORTED_VERSIONS = ['v1'] def __init__(self, galaxy, api_server): self.galaxy = galaxy try: urlparse(api_server, scheme='https') except: raise AnsibleError("Invalid server API url passed: %s" % api_server) server_version = self.get_server_api_version('%s/api/' % (api_server)) if not server_version: raise AnsibleError("Could not retrieve server API version: %s" % api_server) if server_version in self.SUPPORTED_VERSIONS: self.baseurl = '%s/api/%s' % (api_server, server_version) self.version = server_version # for future use self.galaxy.display.vvvvv("Base API: %s" % self.baseurl) else: raise AnsibleError("Unsupported Galaxy server API version: %s" % server_version) def get_server_api_version(self, api_server): """ Fetches the Galaxy API current version to ensure the API server is up and reachable. """ #TODO: fix galaxy server which returns current_version path (/api/v1) vs actual version (v1) # also should set baseurl using supported_versions which has path return 'v1' try: data = json.load(urlopen(api_server)) return data.get("current_version", 'v1') except Exception as e: # TODO: report error return None def lookup_role_by_name(self, role_name, notify=True): """ Find a role by name """ role_name = urlquote(role_name) try: parts = role_name.split(".") user_name = ".".join(parts[0:-1]) role_name = parts[-1] if notify: self.galaxy.display.display("- downloading role '%s', owned by %s" % (role_name, user_name)) except: raise AnsibleError("- invalid role name (%s). Specify role as format: username.rolename" % role_name) url = '%s/roles/?owner__username=%s&name=%s' % (self.baseurl, user_name, role_name) self.galaxy.display.vvvv("- %s" % (url)) try: data = json.load(urlopen(url)) if len(data["results"]) != 0: return data["results"][0] except: # TODO: report on connection/availability errors pass return None def fetch_role_related(self, related, role_id): """ Fetch the list of related items for the given role. The url comes from the 'related' field of the role. """ try: url = '%s/roles/%d/%s/?page_size=50' % (self.baseurl, int(role_id), related) data = json.load(urlopen(url)) results = data['results'] done = (data.get('next', None) == None) while not done: url = '%s%s' % (self.baseurl, data['next']) self.galaxy.display.display(url) data = json.load(urlopen(url)) results += data['results'] done = (data.get('next', None) == None) return results except: return None def get_list(self, what): """ Fetch the list of items specified. """ try: url = '%s/%s/?page_size' % (self.baseurl, what) data = json.load(urlopen(url)) if "results" in data: results = data['results'] else: results = data done = True if "next" in data: done = (data.get('next', None) == None) while not done: url = '%s%s' % (self.baseurl, data['next']) self.galaxy.display.display(url) data = json.load(urlopen(url)) results += data['results'] done = (data.get('next', None) == None) return results except Exception as error: raise AnsibleError("Failed to download the %s list: %s" % (what, str(error)))
gpl-3.0
heke123/chromium-crosswalk
tools/chrome_proxy/common/chrome_proxy_measurements.py
5
4301
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import logging from common import chrome_proxy_metrics as metrics from telemetry.core import exceptions from telemetry.page import page_test def WaitForViaHeader(tab, url="http://check.googlezip.net/test.html"): """Wait until responses start coming back with the Chrome Proxy via header. Poll |url| in |tab| until the Chrome Proxy via header is present in a response. This function is useful when testing with the Data Saver API, since Chrome won't actually start sending requests to the Data Reduction Proxy until the Data Saver API fetch completes. This function can be used to wait for the Data Saver API fetch to complete. """ tab.Navigate('data:text/html;base64,%s' % base64.b64encode( '<html><body><script>' 'window.via_header_found = false;' 'function PollDRPCheck(url, wanted_via) {' 'if (via_header_found) { return true; }' 'try {' 'var xmlhttp = new XMLHttpRequest();' 'xmlhttp.open("GET",url,true);' 'xmlhttp.onload=function(e) {' # Store the last response received for debugging, this will be shown # in telemetry dumps if the request fails or times out. 'window.last_xhr_response_headers = xmlhttp.getAllResponseHeaders();' 'var via=xmlhttp.getResponseHeader("via");' 'if (via && via.indexOf(wanted_via) != -1) {' 'window.via_header_found = true;' '}' '};' 'xmlhttp.timeout=30000;' 'xmlhttp.send();' '} catch (err) {' '/* Return normally if the xhr request failed. */' '}' 'return false;' '}' '</script>' 'Waiting for Chrome to start using the DRP...' '</body></html>')) # Ensure the page has started loading before attempting the DRP check. tab.WaitForJavaScriptExpression('performance.timing.loadEventStart', 60) expected_via_header = metrics.CHROME_PROXY_VIA_HEADER if ChromeProxyValidation.extra_via_header: expected_via_header = ChromeProxyValidation.extra_via_header tab.WaitForJavaScriptExpression( 'PollDRPCheck("%s", "%s")' % (url, expected_via_header), 60) class ChromeProxyValidation(page_test.PageTest): """Base class for all chrome proxy correctness measurements.""" # Value of the extra via header. |None| if no extra via header is expected. extra_via_header = None def __init__(self, restart_after_each_page=False, metrics=None, clear_cache_before_each_run=True): super(ChromeProxyValidation, self).__init__( needs_browser_restart_after_each_page=restart_after_each_page, clear_cache_before_each_run=clear_cache_before_each_run) self._metrics = metrics self._page = None def CustomizeBrowserOptions(self, options): # Enable the chrome proxy (data reduction proxy). options.AppendExtraBrowserArgs('--enable-spdy-proxy-auth') self._is_chrome_proxy_enabled = True # Disable quic option, otherwise request headers won't be visible. options.AppendExtraBrowserArgs('--disable-quic') def DisableChromeProxy(self): self.options.browser_options.extra_browser_args.discard( '--enable-spdy-proxy-auth') self._is_chrome_proxy_enabled = False def WillNavigateToPage(self, page, tab): if self._is_chrome_proxy_enabled: WaitForViaHeader(tab) if self.clear_cache_before_each_run: tab.ClearCache(force=True) assert self._metrics self._metrics.Start(page, tab) def ValidateAndMeasurePage(self, page, tab, results): self._page = page # Wait for the load event. tab.WaitForJavaScriptExpression('performance.timing.loadEventStart', 300) assert self._metrics self._metrics.Stop(page, tab) if ChromeProxyValidation.extra_via_header: self._metrics.AddResultsForExtraViaHeader( tab, results, ChromeProxyValidation.extra_via_header) self.AddResults(tab, results) def AddResults(self, tab, results): raise NotImplementedError def StopBrowserAfterPage(self, browser, page): # pylint: disable=W0613 if hasattr(page, 'restart_after') and page.restart_after: return True return False
bsd-3-clause
mmclenna/engine
sky/tools/create_ios_sdk.py
1
1820
#!/usr/bin/env python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import subprocess import shutil import sys import os def main(): parser = argparse.ArgumentParser(description='Creates the Flutter iOS SDK') parser.add_argument('--dst', type=str, required=True) parser.add_argument('--device-out-dir', type=str, required=True) parser.add_argument('--simulator-out-dir', type=str, required=True) args = parser.parse_args() device_sdk = os.path.join(args.device_out_dir, 'Flutter') simulator_sdk = os.path.join(args.simulator_out_dir, 'Flutter') flutter_framework_binary = 'Flutter.framework/Flutter' device_dylib = os.path.join(args.device_out_dir, flutter_framework_binary) simulator_dylib = os.path.join(args.simulator_out_dir, flutter_framework_binary) if not os.path.isdir(device_sdk): print 'Cannot find iOS device SDK at', device_sdk return 1 if not os.path.isdir(simulator_sdk): print 'Cannot find iOS simulator SDK at', simulator_sdk return 1 if not os.path.isfile(device_dylib): print 'Cannot find iOS device dylib at', device_dylib return 1 if not os.path.isfile(simulator_dylib): print 'Cannot find iOS device dylib at', simulator_dylib return 1 shutil.rmtree(args.dst, True) shutil.copytree(device_sdk, args.dst) sim_tools = 'Tools/iphonesimulator' shutil.copytree(os.path.join(simulator_sdk, sim_tools), os.path.join(args.dst, sim_tools)) subprocess.call([ 'lipo', device_dylib, simulator_dylib, '-create', '-output', os.path.join(args.dst, 'Tools/common/Flutter.framework/Flutter') ]) if __name__ == '__main__': sys.exit(main())
bsd-3-clause
gpg/gpgme
lang/python/tests/final.py
1
1048
#!/usr/bin/env python # Copyright (C) 2016 g10 Code GmbH # # This file is part of GPGME. # # GPGME is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # GPGME is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see <https://www.gnu.org/licenses/>. from __future__ import absolute_import, print_function, unicode_literals import os import subprocess import support _ = support # to appease pyflakes. del absolute_import, print_function, unicode_literals subprocess.check_call([ os.path.join(os.getenv('top_srcdir'), "tests", "start-stop-agent"), "--stop" ])
lgpl-2.1
nkhuyu/airflow
airflow/migrations/versions/1507a7289a2f_create_is_encrypted.py
37
1408
"""create is_encrypted Revision ID: 1507a7289a2f Revises: e3a246e0dc1 Create Date: 2015-08-18 18:57:51.927315 """ # revision identifiers, used by Alembic. revision = '1507a7289a2f' down_revision = 'e3a246e0dc1' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.engine.reflection import Inspector from airflow import settings connectionhelper = sa.Table( 'connection', sa.MetaData(), sa.Column('id', sa.Integer, primary_key=True), sa.Column('is_encrypted') ) def upgrade(): # first check if the user already has this done. This should only be # true for users who are upgrading from a previous version of Airflow # that predates Alembic integration inspector = Inspector.from_engine(settings.engine) # this will only be true if 'connection' already exists in the db, # but not if alembic created it in a previous migration if 'connection' in inspector.get_table_names(): col_names = [c['name'] for c in inspector.get_columns('connection')] if 'is_encrypted' in col_names: return op.add_column( 'connection', sa.Column('is_encrypted', sa.Boolean, unique=False, default=False)) conn = op.get_bind() conn.execute( connectionhelper.update().values(is_encrypted=False) ) def downgrade(): op.drop_column('connection', 'is_encrypted')
apache-2.0
campbe13/openhatch
vendor/packages/amqp/amqp/basic_message.py
38
3954
"""Messages for AMQP""" # Copyright (C) 2007-2008 Barry Pederson <bp@barryp.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 from __future__ import absolute_import from .serialization import GenericContent __all__ = ['Message'] class Message(GenericContent): """A Message for use with the Channnel.basic_* methods.""" #: Instances of this class have these attributes, which #: are passed back and forth as message properties between #: client and server PROPERTIES = [ ('content_type', 'shortstr'), ('content_encoding', 'shortstr'), ('application_headers', 'table'), ('delivery_mode', 'octet'), ('priority', 'octet'), ('correlation_id', 'shortstr'), ('reply_to', 'shortstr'), ('expiration', 'shortstr'), ('message_id', 'shortstr'), ('timestamp', 'timestamp'), ('type', 'shortstr'), ('user_id', 'shortstr'), ('app_id', 'shortstr'), ('cluster_id', 'shortstr') ] def __init__(self, body='', children=None, channel=None, **properties): """Expected arg types body: string children: (not supported) Keyword properties may include: content_type: shortstr MIME content type content_encoding: shortstr MIME content encoding application_headers: table Message header field table, a dict with string keys, and string | int | Decimal | datetime | dict values. delivery_mode: octet Non-persistent (1) or persistent (2) priority: octet The message priority, 0 to 9 correlation_id: shortstr The application correlation identifier reply_to: shortstr The destination to reply to expiration: shortstr Message expiration specification message_id: shortstr The application message identifier timestamp: datetime.datetime The message timestamp type: shortstr The message type name user_id: shortstr The creating user id app_id: shortstr The creating application id cluster_id: shortstr Intra-cluster routing identifier Unicode bodies are encoded according to the 'content_encoding' argument. If that's None, it's set to 'UTF-8' automatically. example:: msg = Message('hello world', content_type='text/plain', application_headers={'foo': 7}) """ super(Message, self).__init__(**properties) self.body = body self.channel = channel def __eq__(self, other): """Check if the properties and bodies of this Message and another Message are the same. Received messages may contain a 'delivery_info' attribute, which isn't compared. """ try: return (super(Message, self).__eq__(other) and self.body == other.body) except AttributeError: return NotImplemented
agpl-3.0
pshen/ansible
lib/ansible/modules/network/eos/eos_facts.py
56
10878
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = """ --- module: eos_facts version_added: "2.2" author: "Peter Sprygada (@privateip)" short_description: Collect facts from remote devices running Arista EOS description: - Collects a base set of device facts from a remote device that is running eos. This module prepends all of the base network fact keys with C(ansible_net_<fact>). The facts module will always collect a base set of facts from the device and can enable or disable collection of additional facts. extends_documentation_fragment: eos options: gather_subset: description: - When supplied, this argument will restrict the facts collected to a given subset. Possible values for this argument include all, hardware, config, and interfaces. Can specify a list of values to include a larger subset. Values can also be used with an initial C(M(!)) to specify that a specific subset should not be collected. required: false default: '!config' """ EXAMPLES = """ # Collect all facts from the device - eos_facts: gather_subset: all # Collect only the config and default facts - eos_facts: gather_subset: - config # Do not collect hardware facts - eos_facts: gather_subset: - "!hardware" """ RETURN = """ ansible_net_gather_subset: description: The list of fact subsets collected from the device returned: always type: list # default ansible_net_model: description: The model name returned from the device returned: always type: str ansible_net_serialnum: description: The serial number of the remote device returned: always type: str ansible_net_version: description: The operating system version running on the remote device returned: always type: str ansible_net_hostname: description: The configured hostname of the device returned: always type: str ansible_net_image: description: The image file the device is running returned: always type: str ansible_net_fqdn: description: The fully qualified domain name of the device returned: always type: str # hardware ansible_net_filesystems: description: All file system names available on the device returned: when hardware is configured type: list ansible_net_memfree_mb: description: The available free memory on the remote device in Mb returned: when hardware is configured type: int ansible_net_memtotal_mb: description: The total memory on the remote device in Mb returned: when hardware is configured type: int # config ansible_net_config: description: The current active config from the device returned: when config is configured type: str # interfaces ansible_net_all_ipv4_addresses: description: All IPv4 addresses configured on the device returned: when interfaces is configured type: list ansible_net_all_ipv6_addresses: description: All IPv6 addresses configured on the device returned: when interfaces is configured type: list ansible_net_interfaces: description: A hash of all interfaces running on the system returned: when interfaces is configured type: dict ansible_net_neighbors: description: The list of LLDP neighbors from the remote device returned: when interfaces is configured type: dict """ import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems from ansible.module_utils.eos import run_commands from ansible.module_utils.eos import eos_argument_spec, check_args class FactsBase(object): COMMANDS = frozenset() def __init__(self, module): self.module = module self.facts = dict() self.responses = None def populate(self): self.responses = run_commands(self.module, list(self.COMMANDS)) class Default(FactsBase): SYSTEM_MAP = { 'version': 'version', 'serialNumber': 'serialnum', 'modelName': 'model' } COMMANDS = [ 'show version | json', 'show hostname | json', 'bash timeout 5 cat /mnt/flash/boot-config' ] def populate(self): super(Default, self).populate() data = self.responses[0] for key, value in iteritems(self.SYSTEM_MAP): if key in data: self.facts[value] = data[key] self.facts.update(self.responses[1]) self.facts.update(self.parse_image()) def parse_image(self): data = self.responses[2] if isinstance(data, dict): data = data['messages'][0] match = re.search(r'SWI=(.+)$', data, re.M) if match: value = match.group(1) else: value = None return dict(image=value) class Hardware(FactsBase): COMMANDS = [ 'dir all-filesystems', 'show version | json' ] def populate(self): super(Hardware, self).populate() self.facts.update(self.populate_filesystems()) self.facts.update(self.populate_memory()) def populate_filesystems(self): data = self.responses[0] if isinstance(data, dict): data = data['messages'][0] fs = re.findall(r'^Directory of (.+)/', data, re.M) return dict(filesystems=fs) def populate_memory(self): values = self.responses[1] return dict( memfree_mb=int(values['memFree']) / 1024, memtotal_mb=int(values['memTotal']) / 1024 ) class Config(FactsBase): COMMANDS = ['show running-config'] def populate(self): super(Config, self).populate() self.facts['config'] = self.responses[0] class Interfaces(FactsBase): INTERFACE_MAP = { 'description': 'description', 'physicalAddress': 'macaddress', 'mtu': 'mtu', 'bandwidth': 'bandwidth', 'duplex': 'duplex', 'lineProtocolStatus': 'lineprotocol', 'interfaceStatus': 'operstatus', 'forwardingModel': 'type' } COMMANDS = [ 'show interfaces | json', 'show lldp neighbors | json' ] def populate(self): super(Interfaces, self).populate() self.facts['all_ipv4_addresses'] = list() self.facts['all_ipv6_addresses'] = list() data = self.responses[0] self.facts['interfaces'] = self.populate_interfaces(data) data = self.responses[1] self.facts['neighbors'] = self.populate_neighbors(data['lldpNeighbors']) def populate_interfaces(self, data): facts = dict() for key, value in iteritems(data['interfaces']): intf = dict() for remote, local in iteritems(self.INTERFACE_MAP): if remote in value: intf[local] = value[remote] if 'interfaceAddress' in value: intf['ipv4'] = dict() for entry in value['interfaceAddress']: intf['ipv4']['address'] = entry['primaryIp']['address'] intf['ipv4']['masklen'] = entry['primaryIp']['maskLen'] self.add_ip_address(entry['primaryIp']['address'], 'ipv4') if 'interfaceAddressIp6' in value: intf['ipv6'] = dict() for entry in value['interfaceAddressIp6']['globalUnicastIp6s']: intf['ipv6']['address'] = entry['address'] intf['ipv6']['subnet'] = entry['subnet'] self.add_ip_address(entry['address'], 'ipv6') facts[key] = intf return facts def add_ip_address(self, address, family): if family == 'ipv4': self.facts['all_ipv4_addresses'].append(address) else: self.facts['all_ipv6_addresses'].append(address) def populate_neighbors(self, neighbors): facts = dict() for value in neighbors: port = value['port'] if port not in facts: facts[port] = list() lldp = dict() lldp['host'] = value['neighborDevice'] lldp['port'] = value['neighborPort'] facts[port].append(lldp) return facts FACT_SUBSETS = dict( default=Default, hardware=Hardware, interfaces=Interfaces, config=Config ) VALID_SUBSETS = frozenset(FACT_SUBSETS.keys()) def main(): """main entry point for module execution """ argument_spec = dict( gather_subset=dict(default=['!config'], type='list') ) argument_spec.update(eos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) gather_subset = module.params['gather_subset'] runable_subsets = set() exclude_subsets = set() for subset in gather_subset: if subset == 'all': runable_subsets.update(VALID_SUBSETS) continue if subset.startswith('!'): subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: module.fail_json(msg='Subset must be one of [%s], got %s' % (', '.join(VALID_SUBSETS), subset)) if exclude: exclude_subsets.add(subset) else: runable_subsets.add(subset) if not runable_subsets: runable_subsets.update(VALID_SUBSETS) runable_subsets.difference_update(exclude_subsets) runable_subsets.add('default') facts = dict() facts['gather_subset'] = list(runable_subsets) instances = list() for key in runable_subsets: instances.append(FACT_SUBSETS[key](module)) for inst in instances: inst.populate() facts.update(inst.facts) ansible_facts = dict() for key, value in iteritems(facts): key = 'ansible_net_%s' % key ansible_facts[key] = value module.exit_json(ansible_facts=ansible_facts, warnings=warnings) if __name__ == '__main__': main()
gpl-3.0
calinerd/AWS
LAMBDA/Lambda_AutoUpdate_SecurityGroup_to_Allow_inbound_All_CloudFront_IPs_443.py
1
6268
''' Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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 boto3 import hashlib import json import urllib2 # Name of the service, as seen in the ip-groups.json file, to extract information for SERVICE = "CLOUDFRONT" # Ports your application uses that need inbound permissions from the service for INGRESS_PORTS = [ 443 ] # Tags which identify the security groups you want to update SECURITY_GROUP_TAGS = { 'Name': 'SG_Allow_CF_IPs_443', 'AutoUpdate': 'true' } def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) message = json.loads(event['Records'][0]['Sns']['Message']) # Load the ip ranges from the url ip_ranges = json.loads(get_ip_groups_json(message['url'], message['md5'])) # extract the service ranges cf_ranges = get_ranges_for_service(ip_ranges, SERVICE) # update the security groups result = update_security_groups(cf_ranges) return result def get_ip_groups_json(url, expected_hash): print("Updating from " + url) response = urllib2.urlopen(url) ip_json = response.read() m = hashlib.md5() m.update(ip_json) hash = m.hexdigest() if hash != expected_hash: raise Exception('MD5 Mismatch: got ' + hash + ' expected ' + expected_hash) return ip_json def get_ranges_for_service(ranges, service): service_ranges = list() for prefix in ranges['prefixes']: if prefix['service'] == service: print('Found ' + service + ' range: ' + prefix['ip_prefix']) service_ranges.append(prefix['ip_prefix']) return service_ranges def update_security_groups(new_ranges): client = boto3.client('ec2') groups = get_security_groups_for_update(client) print ('Found ' + str(len(groups)) + ' SecurityGroups to update') result = list() updated = 0 for group in groups: if update_security_group(client, group, new_ranges): updated += 1 result.append('Updated ' + group['GroupId']) result.append('Updated ' + str(updated) + ' of ' + str(len(groups)) + ' SecurityGroups') return result def update_security_group(client, group, new_ranges): added = 0 removed = 0 if len(group['IpPermissions']) > 0: for permission in group['IpPermissions']: if INGRESS_PORTS.count(permission['ToPort']) > 0: old_prefixes = list() to_revoke = list() to_add = list() for range in permission['IpRanges']: cidr = range['CidrIp'] old_prefixes.append(cidr) if new_ranges.count(cidr) == 0: to_revoke.append(range) print(group['GroupId'] + ": Revoking " + cidr + ":" + str(permission['ToPort'])) for range in new_ranges: if old_prefixes.count(range) == 0: to_add.append({ 'CidrIp': range }) print(group['GroupId'] + ": Adding " + range + ":" + str(permission['ToPort'])) removed += revoke_permissions(client, group, permission, to_revoke) added += add_permissions(client, group, permission, to_add) else: for port in INGRESS_PORTS: to_add = list() for range in new_ranges: to_add.append({ 'CidrIp': range }) print(group['GroupId'] + ": Adding " + range + ":" + str(port)) permission = { 'ToPort': port, 'FromPort': port, 'IpProtocol': 'tcp'} added += add_permissions(client, group, permission, to_add) print (group['GroupId'] + ": Added " + str(added) + ", Revoked " + str(removed)) return (added > 0 or removed > 0) def revoke_permissions(client, group, permission, to_revoke): if len(to_revoke) > 0: revoke_params = { 'ToPort': permission['ToPort'], 'FromPort': permission['FromPort'], 'IpRanges': to_revoke, 'IpProtocol': permission['IpProtocol'] } client.revoke_security_group_ingress(GroupId=group['GroupId'], IpPermissions=[revoke_params]) return len(to_revoke) def add_permissions(client, group, permission, to_add): if len(to_add) > 0: add_params = { 'ToPort': permission['ToPort'], 'FromPort': permission['FromPort'], 'IpRanges': to_add, 'IpProtocol': permission['IpProtocol'] } client.authorize_security_group_ingress(GroupId=group['GroupId'], IpPermissions=[add_params]) return len(to_add) def get_security_groups_for_update(client): filters = list(); for key, value in SECURITY_GROUP_TAGS.iteritems(): filters.extend( [ { 'Name': "tag-key", 'Values': [ key ] }, { 'Name': "tag-value", 'Values': [ value ] } ] ) response = client.describe_security_groups(Filters=filters) return response['SecurityGroups'] ''' Sample Event From SNS: { "Records": [ { "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:EXAMPLE", "EventSource": "aws:sns", "Sns": { "SignatureVersion": "1", "Timestamp": "1970-01-01T00:00:00.000Z", "Signature": "EXAMPLE", "SigningCertUrl": "EXAMPLE", "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", "Message": "{\"create-time\": \"yyyy-mm-ddThh:mm:ss+00:00\", \"synctoken\": \"0123456789\", \"md5\": \"03a8199d0c03ddfec0e542f8bf650ee7\", \"url\": \"https://ip-ranges.amazonaws.com/ip-ranges.json\"}", "Type": "Notification", "UnsubscribeUrl": "EXAMPLE", "TopicArn": "arn:aws:sns:EXAMPLE", "Subject": "TestInvoke" } } ] } '''
unlicense
ftomassetti/intellij-community
python/lib/Lib/ntpath.py
80
16985
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames """Common pathname manipulations, WindowsNT/95 version. Instead of importing this module directly, import os and refer to this module as os.path. """ import os import stat import sys __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","getctime", "islink","exists","lexists","isdir","isfile", "ismount","walk","expanduser","expandvars","normpath","abspath", "splitunc","curdir","pardir","sep","pathsep","defpath","altsep", "extsep","devnull","realpath","supports_unicode_filenames"] # strings representing various path-related bits and pieces curdir = '.' pardir = '..' extsep = '.' sep = '\\' pathsep = ';' altsep = '/' defpath = '.;C:\\bin' if 'ce' in sys.builtin_module_names: defpath = '\\Windows' elif 'os2' in sys.builtin_module_names: # OS/2 w/ VACPP altsep = '/' devnull = 'nul' # Normalize the case of a pathname and map slashes to backslashes. # Other normalizations (such as optimizing '../' away) are not done # (this is done by normpath). def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" return s.replace("/", "\\").lower() # Return whether a path is absolute. # Trivial in Posix, harder on the Mac or MS-DOS. # For DOS it is absolute if it starts with a slash or backslash (current # volume), or if a pathname after the volume letter and colon / UNC resource # starts with a slash or backslash. def isabs(s): """Test whether a path is absolute""" s = splitdrive(s)[1] return s != '' and s[:1] in '/\\' # Join two (or more) paths. def join(a, *p): """Join two or more pathname components, inserting "\\" as needed""" path = a for b in p: b_wins = 0 # set to 1 iff b makes path irrelevant if path == "": b_wins = 1 elif isabs(b): # This probably wipes out path so far. However, it's more # complicated if path begins with a drive letter: # 1. join('c:', '/a') == 'c:/a' # 2. join('c:/', '/a') == 'c:/a' # But # 3. join('c:/a', '/b') == '/b' # 4. join('c:', 'd:/') = 'd:/' # 5. join('c:/', 'd:/') = 'd:/' if path[1:2] != ":" or b[1:2] == ":": # Path doesn't start with a drive letter, or cases 4 and 5. b_wins = 1 # Else path has a drive letter, and b doesn't but is absolute. elif len(path) > 3 or (len(path) == 3 and path[-1] not in "/\\"): # case 3 b_wins = 1 if b_wins: path = b else: # Join, and ensure there's a separator. assert len(path) > 0 if path[-1] in "/\\": if b and b[0] in "/\\": path += b[1:] else: path += b elif path[-1] == ":": path += b elif b: if b[0] in "/\\": path += b else: path += "\\" + b else: # path is not empty and does not end with a backslash, # but b is empty; since, e.g., split('a/') produces # ('a', ''), it's best if join() adds a backslash in # this case. path += '\\' return path # Split a path in a drive specification (a drive letter followed by a # colon) and the path specification. # It is always true that drivespec + pathspec == p def splitdrive(p): """Split a pathname into drive and path specifiers. Returns a 2-tuple "(drive,path)"; either part may be empty""" if p[1:2] == ':': return p[0:2], p[2:] return '', p # Parse UNC paths def splitunc(p): """Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have an UNC part. """ if p[1:2] == ':': return '', p # Drive letter present firstTwo = p[0:2] if firstTwo == '//' or firstTwo == '\\\\': # is a UNC path: # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter # \\machine\mountpoint\directories... # directory ^^^^^^^^^^^^^^^ normp = normcase(p) index = normp.find('\\', 2) if index == -1: ##raise RuntimeError, 'illegal UNC path: "' + p + '"' return ("", p) index = normp.find('\\', index + 1) if index == -1: index = len(p) return p[:index], p[index:] return '', p # Split a path in head (everything up to the last '/') and tail (the # rest). After the trailing '/' is stripped, the invariant # join(head, tail) == p holds. # The resulting head won't end in '/' unless it is the root. def split(p): """Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.""" d, p = splitdrive(p) # set i to index beyond p's last slash i = len(p) while i and p[i-1] not in '/\\': i = i - 1 head, tail = p[:i], p[i:] # now tail has no slashes # remove trailing slashes from head, unless it's all slashes head2 = head while head2 and head2[-1] in '/\\': head2 = head2[:-1] head = head2 or head return d + head, tail # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p. def splitext(p): """Split the extension from a pathname. Extension is everything from the last dot to the end. Return (root, ext), either part may be empty.""" i = p.rfind('.') if i<=max(p.rfind('/'), p.rfind('\\')): return p, '' else: return p[:i], p[i:] # Return the tail (basename) part of a path. def basename(p): """Returns the final component of a pathname""" return split(p)[1] # Return the head (dirname) part of a path. def dirname(p): """Returns the directory component of a pathname""" return split(p)[0] # Return the longest prefix of all list elements. def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) n = min(len(s1), len(s2)) for i in xrange(n): if s1[i] != s2[i]: return s1[:i] return s1[:n] # Get size, mtime, atime of files. def getsize(filename): """Return the size of a file, reported by os.stat()""" return os.stat(filename).st_size def getmtime(filename): """Return the last modification time of a file, reported by os.stat()""" return os.stat(filename).st_mtime def getatime(filename): """Return the last access time of a file, reported by os.stat()""" return os.stat(filename).st_atime def getctime(filename): """Return the creation time of a file, reported by os.stat().""" return os.stat(filename).st_ctime # Is a path a symbolic link? # This will always return false on systems where posix.lstat doesn't exist. def islink(path): """Test for symbolic link. On WindowsNT/95 always returns false""" return False # Does a path exist? def exists(path): """Test whether a path exists""" try: st = os.stat(path) except os.error: return False return True lexists = exists # Is a path a dos directory? # This follows symbolic links, so both islink() and isdir() can be true # for the same path. def isdir(path): """Test whether a path is a directory""" try: st = os.stat(path) except os.error: return False return stat.S_ISDIR(st.st_mode) # Is a path a regular file? # This follows symbolic links, so both islink() and isdir() can be true # for the same path. def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode) # Is a path a mount point? Either a root (with or without drive letter) # or an UNC path with at most a / or \ after the mount point. def ismount(path): """Test whether a path is a mount point (defined as root of drive)""" unc, rest = splitunc(path) if unc: return rest in ("", "/", "\\") p = splitdrive(path)[1] return len(p) == 1 and p[0] in '/\\' # Directory tree walk. # For each directory under top (including top itself, but excluding # '.' and '..'), func(arg, dirname, filenames) is called, where # dirname is the name of the directory and filenames is the list # of files (and subdirectories etc.) in the directory. # The func may modify the filenames list, to implement a filter, # or to impose a different order of visiting. def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" try: names = os.listdir(top) except os.error: return func(arg, top, names) exceptions = ('.', '..') for name in names: if name not in exceptions: name = join(top, name) if isdir(name): walk(name, func, arg) # Expand paths beginning with '~' or '~user'. # '~' means $HOME; '~user' means that user's home directory. # If the path doesn't begin with '~', or if the user or $HOME is unknown, # the path is returned unchanged (leaving error reporting to whatever # function is called with the expanded path as argument). # See also module 'glob' for expansion of *, ? and [...] in pathnames. # (A function should also be defined to do full *sh-style environment # variable expansion.) def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] not in '/\\': i = i + 1 if i == 1: if 'HOME' in os.environ: userhome = os.environ['HOME'] elif not 'HOMEPATH' in os.environ: return path else: try: drive = os.environ['HOMEDRIVE'] except KeyError: drive = '' userhome = join(drive, os.environ['HOMEPATH']) else: return path return userhome + path[i:] # Expand paths containing shell variable substitutions. # The following rules apply: # - no expansion within single quotes # - no escape character, except for '$$' which is translated into '$' # - ${varname} is accepted. # - varnames can be made out of letters, digits and the character '_' # XXX With COMMAND.COM you can use any characters in a variable name, # XXX except '^|<>='. def expandvars(path): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" if '$' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' res = '' index = 0 pathlen = len(path) while index < pathlen: c = path[index] if c == '\'': # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = path.index('\'') res = res + '\'' + path[:index + 1] except ValueError: res = res + path index = pathlen - 1 elif c == '$': # variable or '$$' if path[index + 1:index + 2] == '$': res = res + c index = index + 1 elif path[index + 1:index + 2] == '{': path = path[index+2:] pathlen = len(path) try: index = path.index('}') var = path[:index] if var in os.environ: res = res + os.environ[var] except ValueError: res = res + path index = pathlen - 1 else: var = '' index = index + 1 c = path[index:index + 1] while c != '' and c in varchars: var = var + c index = index + 1 c = path[index:index + 1] if var in os.environ: res = res + os.environ[var] if c != '': res = res + c else: res = res + c index = index + 1 return res # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B. # Previously, this function also truncated pathnames to 8+3 format, # but as this module is called "ntpath", that's obviously wrong! def normpath(path): """Normalize path, eliminating double slashes, etc.""" path = path.replace("/", "\\") prefix, path = splitdrive(path) # We need to be careful here. If the prefix is empty, and the path starts # with a backslash, it could either be an absolute path on the current # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It # is therefore imperative NOT to collapse multiple backslashes blindly in # that case. # The code below preserves multiple backslashes when there is no drive # letter. This means that the invalid filename \\\a\b is preserved # unchanged, where a\\\b is normalised to a\b. It's not clear that there # is any better behaviour for such edge cases. if prefix == '': # No drive letter - preserve initial backslashes while path[:1] == "\\": prefix = prefix + "\\" path = path[1:] else: # We have a drive letter - collapse initial backslashes if path.startswith("\\"): prefix = prefix + "\\" path = path.lstrip("\\") comps = path.split("\\") i = 0 while i < len(comps): if comps[i] in ('.', ''): del comps[i] elif comps[i] == '..': if i > 0 and comps[i-1] != '..': del comps[i-1:i+1] i -= 1 elif i == 0 and prefix.endswith("\\"): del comps[i] else: i += 1 else: i += 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append('.') return prefix + "\\".join(comps) # Return an absolute path. try: from nt import _getfullpathname except ImportError: # not running on Windows - mock up something sensible import java.io.File from org.python.core.Py import newString def abspath(path): """Return the absolute version of a path.""" if not isabs(path): path = join(os.getcwd(), path) if not splitunc(path)[0] and not splitdrive(path)[0]: # cwd lacks a UNC mount point, so it should have a drive # letter (but lacks one): determine it canon_path = newString(java.io.File(path).getCanonicalPath()) drive = splitdrive(canon_path)[0] path = join(drive, path) return normpath(path) else: # use native Windows method on Windows def abspath(path): """Return the absolute version of a path.""" if path: # Empty path must return current working directory. try: path = _getfullpathname(path) except WindowsError: pass # Bad path - return unchanged. else: path = os.getcwd() return normpath(path) # realpath is a no-op on systems without islink support realpath = abspath # Win9x family and earlier have no Unicode filename support. supports_unicode_filenames = (hasattr(sys, "getwindowsversion") and sys.getwindowsversion()[3] >= 2)
apache-2.0
BorisJeremic/Real-ESSI-Examples
analytic_solution/test_cases/Contact/Dynamic_Shear_Behaviour/Frictional_SDOF_With_Damping/c_t_0.1/NonLinHardShear/compare_HDF5_ALL.py
424
3382
#!/usr/bin/python import h5py import sys import numpy as np import os import re import random # find the path to my own python function: cur_dir=os.getcwd() sep='test_cases' test_DIR=cur_dir.split(sep,1)[0] scriptDIR=test_DIR+'compare_function' sys.path.append(scriptDIR) # import my own function for color and comparator from mycomparator import * from mycolor_fun import * # the real essi hdf5 results h5_result_new = sys.argv[1] h5_result_ori = sys.argv[2] disp_pass_or_fail=h5diff_disp(h5_result_ori,h5_result_new) Gauss_pass_or_fail = 1 try: Gauss_pass_or_fail=h5diff_Gauss_output(h5_result_ori,h5_result_new) except KeyError: pass Element_Output_pass_or_fail = 1 try: Element_Output_pass_or_fail=h5diff_Element_output(h5_result_ori,h5_result_new) except KeyError: pass if disp_pass_or_fail and Gauss_pass_or_fail and Element_Output_pass_or_fail: print headOK(), "All hdf5 results are the same." print headOKCASE(),"-----------Done this case!-----------------" else: if disp_pass_or_fail==0: print headFailed(),"-----------Displacement has mismatches!-----------------" if Gauss_pass_or_fail==0: print headFailed(),"-----------StressStrain has mismatches!-----------------" if Element_Output_pass_or_fail==0: print headFailed(),"-----------Element output has mismatches!-----------------" # # The allowable tolerance between the ori_vals and new_vals values. # tolerance=1e-5 # machine_epsilon=1e-16 # ori_vals=[] # new_vals=[] # ori_vals.append(find_max_disp(h5_result_ori,0)) # new_vals.append(find_max_disp(h5_result_new,0)) # # if multiple steps, compare the max_disp of random steps # Nstep = find_disp_Nstep(h5_result_ori) # if Nstep>5 : # for i in xrange(1,4): # test_step=random.randint(1,Nstep-1) # ori_vals.append(find_max_disp(h5_result_ori,test_step)) # new_vals.append(find_max_disp(h5_result_new,test_step)) # # calculate the errors # errors=[] # for index, x in enumerate(ori_vals): # if(abs(x))>machine_epsilon: # errors.append(abs((new_vals[index]-x)/x)) # else: # errors.append(machine_epsilon) # # compare and form the flags # flags=[] # for item in errors: # if abs(item)<tolerance: # flags.append('pass') # else: # flags.append('failed') # # print the results # case_flag=1 # print headrun() , "-----------Testing results-----------------" # print headstep() ,'{0} {1} {2} {3}'.format('back_value ','new_value ','error ','flag') # for index, x in enumerate(errors): # if(abs(x)<tolerance): # print headOK() ,'{0:e} {1:e} {2:0.2f} {3}'.format(ori_vals[index],new_vals[index], x, flags[index] ) # else: # case_flag=0 # print headFailed() ,'{0:e} {1:e} {2:0.2f} {3}'.format(ori_vals[index],new_vals[index], x, flags[index] ) # if(case_flag==1): # print headOKCASE(),"-----------Done this case!-----------------" # legacy backup # automatically find the script directory. # sys.path.append("/home/yuan/Dropbox/3essi_self_verification/test_suite/scripts" ) # script_dir=sys.argv[1] # print headstart() , "Running test cases..." # print headlocation(), os.path.dirname(os.path.abspath(__file__)) # file_in=open("ori_vals_values.txt","r") # Input the 1st line, which is the ori_vals value. # ori_vals= float(file_in.readline()) # Input the 2nd line, which is the HDF5 output filename. # new_vals=find_max_disp(file_in.readline()); # file_in.close()
cc0-1.0
sbidoul/odoo
addons/share/__openerp__.py
250
2317
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2011 OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name' : 'Share any Document', 'version' : '2.0', 'depends' : ['base', 'mail'], 'author' : 'OpenERP SA', 'category': 'Tools', 'description': """ This module adds generic sharing tools to your current OpenERP database. ======================================================================== It specifically adds a 'share' button that is available in the Web client to share any kind of OpenERP data with colleagues, customers, friends. The system will work by creating new users and groups on the fly, and by combining the appropriate access rights and ir.rules to ensure that the shared users only have access to the data that has been shared with them. This is extremely useful for collaborative work, knowledge sharing, synchronization with other companies. """, 'website': 'https://www.odoo.com', 'demo': ['share_demo.xml'], 'data': [ 'security/share_security.xml', 'security/ir.model.access.csv', 'res_users_view.xml', 'wizard/share_wizard_view.xml', 'share_data.xml', 'views/share.xml', ], 'installable': True, 'auto_install': True, 'web': True, 'qweb' : ['static/src/xml/*.xml'], } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
tik0/inkscapeGrid
share/extensions/scour.py
3
110803
#!/usr/bin/env python # -*- coding: utf-8 -*- # Scour # # Copyright 2010 Jeff Schiller # Copyright 2010 Louis Simard # # This file is part of Scour, http://www.codedread.com/scour/ # # This library is free software; you can redistribute it and/or modify # it either under the terms of the Apache License, Version 2.0, or, at # your option, under the terms and conditions of the GNU General # Public License, Version 2 or newer as published by the Free Software # Foundation. You may obtain a copy of these Licenses at: # # http://www.apache.org/licenses/LICENSE-2.0 # https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # # 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. # Notes: # rubys' path-crunching ideas here: http://intertwingly.net/code/svgtidy/spec.rb # (and implemented here: http://intertwingly.net/code/svgtidy/svgtidy.rb ) # Yet more ideas here: http://wiki.inkscape.org/wiki/index.php/Save_Cleaned_SVG # # * Process Transformations # * Collapse all group based transformations # Even more ideas here: http://esw.w3.org/topic/SvgTidy # * analysis of path elements to see if rect can be used instead? (must also need to look # at rounded corners) # Next Up: # - why are marker-start, -end not removed from the style attribute? # - why are only overflow style properties considered and not attributes? # - only remove unreferenced elements if they are not children of a referenced element # - add an option to remove ids if they match the Inkscape-style of IDs # - investigate point-reducing algorithms # - parse transform attribute # - if a <g> has only one element in it, collapse the <g> (ensure transform, etc are carried down) # necessary to get true division from __future__ import division import os import sys import xml.dom.minidom import re import math from svg_regex import svg_parser from svg_transform import svg_transform_parser import optparse from yocto_css import parseCssString # Python 2.3- did not have Decimal try: from decimal import * except ImportError: print >>sys.stderr, "Scour requires Python 2.4." # Import Psyco if available try: import psyco psyco.full() except ImportError: pass APP = 'scour' VER = '0.26+r220' COPYRIGHT = 'Copyright Jeff Schiller, Louis Simard, 2012' NS = { 'SVG': 'http://www.w3.org/2000/svg', 'XLINK': 'http://www.w3.org/1999/xlink', 'SODIPODI': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', 'INKSCAPE': 'http://www.inkscape.org/namespaces/inkscape', 'ADOBE_ILLUSTRATOR': 'http://ns.adobe.com/AdobeIllustrator/10.0/', 'ADOBE_GRAPHS': 'http://ns.adobe.com/Graphs/1.0/', 'ADOBE_SVG_VIEWER': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/', 'ADOBE_VARIABLES': 'http://ns.adobe.com/Variables/1.0/', 'ADOBE_SFW': 'http://ns.adobe.com/SaveForWeb/1.0/', 'ADOBE_EXTENSIBILITY': 'http://ns.adobe.com/Extensibility/1.0/', 'ADOBE_FLOWS': 'http://ns.adobe.com/Flows/1.0/', 'ADOBE_IMAGE_REPLACEMENT': 'http://ns.adobe.com/ImageReplacement/1.0/', 'ADOBE_CUSTOM': 'http://ns.adobe.com/GenericCustomNamespace/1.0/', 'ADOBE_XPATH': 'http://ns.adobe.com/XPath/1.0/' } unwanted_ns = [ NS['SODIPODI'], NS['INKSCAPE'], NS['ADOBE_ILLUSTRATOR'], NS['ADOBE_GRAPHS'], NS['ADOBE_SVG_VIEWER'], NS['ADOBE_VARIABLES'], NS['ADOBE_SFW'], NS['ADOBE_EXTENSIBILITY'], NS['ADOBE_FLOWS'], NS['ADOBE_IMAGE_REPLACEMENT'], NS['ADOBE_CUSTOM'], NS['ADOBE_XPATH'] ] svgAttributes = [ 'clip-rule', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'line-height', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'opacity', 'overflow', 'stop-color', 'stop-opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'visibility' ] colors = { 'aliceblue': 'rgb(240, 248, 255)', 'antiquewhite': 'rgb(250, 235, 215)', 'aqua': 'rgb( 0, 255, 255)', 'aquamarine': 'rgb(127, 255, 212)', 'azure': 'rgb(240, 255, 255)', 'beige': 'rgb(245, 245, 220)', 'bisque': 'rgb(255, 228, 196)', 'black': 'rgb( 0, 0, 0)', 'blanchedalmond': 'rgb(255, 235, 205)', 'blue': 'rgb( 0, 0, 255)', 'blueviolet': 'rgb(138, 43, 226)', 'brown': 'rgb(165, 42, 42)', 'burlywood': 'rgb(222, 184, 135)', 'cadetblue': 'rgb( 95, 158, 160)', 'chartreuse': 'rgb(127, 255, 0)', 'chocolate': 'rgb(210, 105, 30)', 'coral': 'rgb(255, 127, 80)', 'cornflowerblue': 'rgb(100, 149, 237)', 'cornsilk': 'rgb(255, 248, 220)', 'crimson': 'rgb(220, 20, 60)', 'cyan': 'rgb( 0, 255, 255)', 'darkblue': 'rgb( 0, 0, 139)', 'darkcyan': 'rgb( 0, 139, 139)', 'darkgoldenrod': 'rgb(184, 134, 11)', 'darkgray': 'rgb(169, 169, 169)', 'darkgreen': 'rgb( 0, 100, 0)', 'darkgrey': 'rgb(169, 169, 169)', 'darkkhaki': 'rgb(189, 183, 107)', 'darkmagenta': 'rgb(139, 0, 139)', 'darkolivegreen': 'rgb( 85, 107, 47)', 'darkorange': 'rgb(255, 140, 0)', 'darkorchid': 'rgb(153, 50, 204)', 'darkred': 'rgb(139, 0, 0)', 'darksalmon': 'rgb(233, 150, 122)', 'darkseagreen': 'rgb(143, 188, 143)', 'darkslateblue': 'rgb( 72, 61, 139)', 'darkslategray': 'rgb( 47, 79, 79)', 'darkslategrey': 'rgb( 47, 79, 79)', 'darkturquoise': 'rgb( 0, 206, 209)', 'darkviolet': 'rgb(148, 0, 211)', 'deeppink': 'rgb(255, 20, 147)', 'deepskyblue': 'rgb( 0, 191, 255)', 'dimgray': 'rgb(105, 105, 105)', 'dimgrey': 'rgb(105, 105, 105)', 'dodgerblue': 'rgb( 30, 144, 255)', 'firebrick': 'rgb(178, 34, 34)', 'floralwhite': 'rgb(255, 250, 240)', 'forestgreen': 'rgb( 34, 139, 34)', 'fuchsia': 'rgb(255, 0, 255)', 'gainsboro': 'rgb(220, 220, 220)', 'ghostwhite': 'rgb(248, 248, 255)', 'gold': 'rgb(255, 215, 0)', 'goldenrod': 'rgb(218, 165, 32)', 'gray': 'rgb(128, 128, 128)', 'grey': 'rgb(128, 128, 128)', 'green': 'rgb( 0, 128, 0)', 'greenyellow': 'rgb(173, 255, 47)', 'honeydew': 'rgb(240, 255, 240)', 'hotpink': 'rgb(255, 105, 180)', 'indianred': 'rgb(205, 92, 92)', 'indigo': 'rgb( 75, 0, 130)', 'ivory': 'rgb(255, 255, 240)', 'khaki': 'rgb(240, 230, 140)', 'lavender': 'rgb(230, 230, 250)', 'lavenderblush': 'rgb(255, 240, 245)', 'lawngreen': 'rgb(124, 252, 0)', 'lemonchiffon': 'rgb(255, 250, 205)', 'lightblue': 'rgb(173, 216, 230)', 'lightcoral': 'rgb(240, 128, 128)', 'lightcyan': 'rgb(224, 255, 255)', 'lightgoldenrodyellow': 'rgb(250, 250, 210)', 'lightgray': 'rgb(211, 211, 211)', 'lightgreen': 'rgb(144, 238, 144)', 'lightgrey': 'rgb(211, 211, 211)', 'lightpink': 'rgb(255, 182, 193)', 'lightsalmon': 'rgb(255, 160, 122)', 'lightseagreen': 'rgb( 32, 178, 170)', 'lightskyblue': 'rgb(135, 206, 250)', 'lightslategray': 'rgb(119, 136, 153)', 'lightslategrey': 'rgb(119, 136, 153)', 'lightsteelblue': 'rgb(176, 196, 222)', 'lightyellow': 'rgb(255, 255, 224)', 'lime': 'rgb( 0, 255, 0)', 'limegreen': 'rgb( 50, 205, 50)', 'linen': 'rgb(250, 240, 230)', 'magenta': 'rgb(255, 0, 255)', 'maroon': 'rgb(128, 0, 0)', 'mediumaquamarine': 'rgb(102, 205, 170)', 'mediumblue': 'rgb( 0, 0, 205)', 'mediumorchid': 'rgb(186, 85, 211)', 'mediumpurple': 'rgb(147, 112, 219)', 'mediumseagreen': 'rgb( 60, 179, 113)', 'mediumslateblue': 'rgb(123, 104, 238)', 'mediumspringgreen': 'rgb( 0, 250, 154)', 'mediumturquoise': 'rgb( 72, 209, 204)', 'mediumvioletred': 'rgb(199, 21, 133)', 'midnightblue': 'rgb( 25, 25, 112)', 'mintcream': 'rgb(245, 255, 250)', 'mistyrose': 'rgb(255, 228, 225)', 'moccasin': 'rgb(255, 228, 181)', 'navajowhite': 'rgb(255, 222, 173)', 'navy': 'rgb( 0, 0, 128)', 'oldlace': 'rgb(253, 245, 230)', 'olive': 'rgb(128, 128, 0)', 'olivedrab': 'rgb(107, 142, 35)', 'orange': 'rgb(255, 165, 0)', 'orangered': 'rgb(255, 69, 0)', 'orchid': 'rgb(218, 112, 214)', 'palegoldenrod': 'rgb(238, 232, 170)', 'palegreen': 'rgb(152, 251, 152)', 'paleturquoise': 'rgb(175, 238, 238)', 'palevioletred': 'rgb(219, 112, 147)', 'papayawhip': 'rgb(255, 239, 213)', 'peachpuff': 'rgb(255, 218, 185)', 'peru': 'rgb(205, 133, 63)', 'pink': 'rgb(255, 192, 203)', 'plum': 'rgb(221, 160, 221)', 'powderblue': 'rgb(176, 224, 230)', 'purple': 'rgb(128, 0, 128)', 'rebeccapurple': 'rgb(102, 51, 153)', 'red': 'rgb(255, 0, 0)', 'rosybrown': 'rgb(188, 143, 143)', 'royalblue': 'rgb( 65, 105, 225)', 'saddlebrown': 'rgb(139, 69, 19)', 'salmon': 'rgb(250, 128, 114)', 'sandybrown': 'rgb(244, 164, 96)', 'seagreen': 'rgb( 46, 139, 87)', 'seashell': 'rgb(255, 245, 238)', 'sienna': 'rgb(160, 82, 45)', 'silver': 'rgb(192, 192, 192)', 'skyblue': 'rgb(135, 206, 235)', 'slateblue': 'rgb(106, 90, 205)', 'slategray': 'rgb(112, 128, 144)', 'slategrey': 'rgb(112, 128, 144)', 'snow': 'rgb(255, 250, 250)', 'springgreen': 'rgb( 0, 255, 127)', 'steelblue': 'rgb( 70, 130, 180)', 'tan': 'rgb(210, 180, 140)', 'teal': 'rgb( 0, 128, 128)', 'thistle': 'rgb(216, 191, 216)', 'tomato': 'rgb(255, 99, 71)', 'turquoise': 'rgb( 64, 224, 208)', 'violet': 'rgb(238, 130, 238)', 'wheat': 'rgb(245, 222, 179)', 'white': 'rgb(255, 255, 255)', 'whitesmoke': 'rgb(245, 245, 245)', 'yellow': 'rgb(255, 255, 0)', 'yellowgreen': 'rgb(154, 205, 50)', } default_attributes = { # excluded all attributes with 'auto' as default # SVG 1.1 presentation attributes 'baseline-shift': 'baseline', 'clip-path': 'none', 'clip-rule': 'nonzero', 'color': '#000', 'color-interpolation-filters': 'linearRGB', 'color-interpolation': 'sRGB', 'direction': 'ltr', 'display': 'inline', 'enable-background': 'accumulate', 'fill': '#000', 'fill-opacity': '1', 'fill-rule': 'nonzero', 'filter': 'none', 'flood-color': '#000', 'flood-opacity': '1', 'font-size-adjust': 'none', 'font-size': 'medium', 'font-stretch': 'normal', 'font-style': 'normal', 'font-variant': 'normal', 'font-weight': 'normal', 'glyph-orientation-horizontal': '0deg', 'letter-spacing': 'normal', 'lighting-color': '#fff', 'marker': 'none', 'marker-start': 'none', 'marker-mid': 'none', 'marker-end': 'none', 'mask': 'none', 'opacity': '1', 'pointer-events': 'visiblePainted', 'stop-color': '#000', 'stop-opacity': '1', 'stroke': 'none', 'stroke-dasharray': 'none', 'stroke-dashoffset': '0', 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter', 'stroke-miterlimit': '4', 'stroke-opacity': '1', 'stroke-width': '1', 'text-anchor': 'start', 'text-decoration': 'none', 'unicode-bidi': 'normal', 'visibility': 'visible', 'word-spacing': 'normal', 'writing-mode': 'lr-tb', # SVG 1.2 tiny properties 'audio-level': '1', 'solid-color': '#000', 'solid-opacity': '1', 'text-align': 'start', 'vector-effect': 'none', 'viewport-fill': 'none', 'viewport-fill-opacity': '1', } def isSameSign(a,b): return (a <= 0 and b <= 0) or (a >= 0 and b >= 0) scinumber = re.compile(r"[-+]?(\d*\.?)?\d+[eE][-+]?\d+") number = re.compile(r"[-+]?(\d*\.?)?\d+") sciExponent = re.compile(r"[eE]([-+]?\d+)") unit = re.compile("(em|ex|px|pt|pc|cm|mm|in|%){1,1}$") class Unit(object): # Integer constants for units. INVALID = -1 NONE = 0 PCT = 1 PX = 2 PT = 3 PC = 4 EM = 5 EX = 6 CM = 7 MM = 8 IN = 9 # String to Unit. Basically, converts unit strings to their integer constants. s2u = { '': NONE, '%': PCT, 'px': PX, 'pt': PT, 'pc': PC, 'em': EM, 'ex': EX, 'cm': CM, 'mm': MM, 'in': IN, } # Unit to String. Basically, converts unit integer constants to their corresponding strings. u2s = { NONE: '', PCT: '%', PX: 'px', PT: 'pt', PC: 'pc', EM: 'em', EX: 'ex', CM: 'cm', MM: 'mm', IN: 'in', } # @staticmethod def get(unitstr): if unitstr is None: return Unit.NONE try: return Unit.s2u[unitstr] except KeyError: return Unit.INVALID # @staticmethod def str(unitint): try: return Unit.u2s[unitint] except KeyError: return 'INVALID' get = staticmethod(get) str = staticmethod(str) class SVGLength(object): def __init__(self, str): try: # simple unitless and no scientific notation self.value = float(str) if int(self.value) == self.value: self.value = int(self.value) self.units = Unit.NONE except ValueError: # we know that the length string has an exponent, a unit, both or is invalid # parse out number, exponent and unit self.value = 0 unitBegin = 0 scinum = scinumber.match(str) if scinum != None: # this will always match, no need to check it numMatch = number.match(str) expMatch = sciExponent.search(str, numMatch.start(0)) self.value = (float(numMatch.group(0)) * 10 ** float(expMatch.group(1))) unitBegin = expMatch.end(1) else: # unit or invalid numMatch = number.match(str) if numMatch != None: self.value = float(numMatch.group(0)) unitBegin = numMatch.end(0) if int(self.value) == self.value: self.value = int(self.value) if unitBegin != 0 : unitMatch = unit.search(str, unitBegin) if unitMatch != None : self.units = Unit.get(unitMatch.group(0)) # invalid else: # TODO: this needs to set the default for the given attribute (how?) self.value = 0 self.units = Unit.INVALID def findElementsWithId(node, elems=None): """ Returns all elements with id attributes """ if elems is None: elems = {} id = node.getAttribute('id') if id != '' : elems[id] = node if node.hasChildNodes() : for child in node.childNodes: # from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html # we are only really interested in nodes of type Element (1) if child.nodeType == 1 : findElementsWithId(child, elems) return elems referencingProps = ['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker-start', 'marker-end', 'marker-mid'] def findReferencedElements(node, ids=None): """ Returns the number of times an ID is referenced as well as all elements that reference it. node is the node at which to start the search. The return value is a map which has the id as key and each value is an array where the first value is a count and the second value is a list of nodes that referenced it. Currently looks at fill, stroke, clip-path, mask, marker, and xlink:href attributes. """ global referencingProps if ids is None: ids = {} # TODO: input argument ids is clunky here (see below how it is called) # GZ: alternative to passing dict, use **kwargs # if this node is a style element, parse its text into CSS if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: # one stretch of text, please! (we could use node.normalize(), but # this actually modifies the node, and we don't want to keep # whitespace around if there's any) stylesheet = "".join([child.nodeValue for child in node.childNodes]) if stylesheet != '': cssRules = parseCssString(stylesheet) for rule in cssRules: for propname in rule['properties']: propval = rule['properties'][propname] findReferencingProperty(node, propname, propval, ids) return ids # else if xlink:href is set, then grab the id href = node.getAttributeNS(NS['XLINK'],'href') if href != '' and len(href) > 1 and href[0] == '#': # we remove the hash mark from the beginning of the id id = href[1:] if id in ids: ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] # now get all style properties and the fill, stroke, filter attributes styles = node.getAttribute('style').split(';') for attr in referencingProps: styles.append(':'.join([attr, node.getAttribute(attr)])) for style in styles: propval = style.split(':') if len(propval) == 2 : prop = propval[0].strip() val = propval[1].strip() findReferencingProperty(node, prop, val, ids) if node.hasChildNodes() : for child in node.childNodes: if child.nodeType == 1 : findReferencedElements(child, ids) return ids def findReferencingProperty(node, prop, val, ids): global referencingProps if prop in referencingProps and val != '' : if len(val) >= 7 and val[0:5] == 'url(#' : id = val[5:val.find(')')] if ids.has_key(id) : ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] # if the url has a quote in it, we need to compensate elif len(val) >= 8 : id = None # double-quote if val[0:6] == 'url("#' : id = val[6:val.find('")')] # single-quote elif val[0:6] == "url('#" : id = val[6:val.find("')")] if id != None: if ids.has_key(id) : ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] numIDsRemoved = 0 numElemsRemoved = 0 numAttrsRemoved = 0 numRastersEmbedded = 0 numPathSegmentsReduced = 0 numCurvesStraightened = 0 numBytesSavedInPathData = 0 numBytesSavedInColors = 0 numBytesSavedInIDs = 0 numBytesSavedInLengths = 0 numBytesSavedInTransforms = 0 numPointsRemovedFromPolygon = 0 numCommentBytes = 0 def flattenDefs(doc): """ Puts all defined elements into a newly created defs in the document. This function handles recursive defs elements. """ defs = doc.documentElement.getElementsByTagName('defs') if defs.length > 1: topDef = doc.createElementNS(NS['SVG'], 'defs') for defElem in defs: # Remove all children of this defs and put it into the topDef. while defElem.hasChildNodes(): topDef.appendChild(defElem.firstChild) defElem.parentNode.removeChild(defElem) if topDef.hasChildNodes(): doc.documentElement.insertBefore(topDef, doc.documentElement.firstChild) def removeUnusedDefs(doc, defElem, elemsToRemove=None): if elemsToRemove is None: elemsToRemove = [] identifiedElements = findElementsWithId(doc.documentElement) referencedIDs = findReferencedElements(doc.documentElement) keepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc'] for elem in defElem.childNodes: # only look at it if an element and not referenced anywhere else if elem.nodeType == 1 and (elem.getAttribute('id') == '' or \ (not elem.getAttribute('id') in referencedIDs)): # we only inspect the children of a group in a defs if the group # is not referenced anywhere else if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: elemsToRemove = removeUnusedDefs(doc, elem, elemsToRemove) # we only remove if it is not one of our tags we always keep (see above) elif not elem.nodeName in keepTags: elemsToRemove.append(elem) return elemsToRemove def removeUnreferencedElements(doc): """ Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document. """ global numElemsRemoved num = 0 # Remove certain unreferenced elements outside of defs removeTags = ['linearGradient', 'radialGradient', 'pattern'] identifiedElements = findElementsWithId(doc.documentElement) referencedIDs = findReferencedElements(doc.documentElement) for id in identifiedElements: if not id in referencedIDs: goner = identifiedElements[id] if goner != None and goner.parentNode != None and goner.nodeName in removeTags: goner.parentNode.removeChild(goner) num += 1 numElemsRemoved += 1 # Remove most unreferenced elements inside defs defs = doc.documentElement.getElementsByTagName('defs') for aDef in defs: elemsToRemove = removeUnusedDefs(doc, aDef) for elem in elemsToRemove: elem.parentNode.removeChild(elem) numElemsRemoved += 1 num += 1 return num def shortenIDs(doc, unprotectedElements=None): """ Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shortening ID names in the document. """ num = 0 identifiedElements = findElementsWithId(doc.documentElement) if unprotectedElements is None: unprotectedElements = identifiedElements referencedIDs = findReferencedElements(doc.documentElement) # Make idList (list of idnames) sorted by reference count # descending, so the highest reference count is first. # First check that there's actually a defining element for the current ID name. # (Cyn: I've seen documents with #id references but no element with that ID!) idList = [(referencedIDs[rid][0], rid) for rid in referencedIDs if rid in unprotectedElements] idList.sort(reverse=True) idList = [rid for count, rid in idList] curIdNum = 1 for rid in idList: curId = intToID(curIdNum) # First make sure that *this* element isn't already using # the ID name we want to give it. if curId != rid: # Then, skip ahead if the new ID is already in identifiedElement. while curId in identifiedElements: curIdNum += 1 curId = intToID(curIdNum) # Then go rename it. num += renameID(doc, rid, curId, identifiedElements, referencedIDs) curIdNum += 1 return num def intToID(idnum): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return rid def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs): """ Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of another element in doc. Returns the number of bytes saved by this replacement. """ num = 0 definingNode = identifiedElements[idFrom] definingNode.setAttribute("id", idTo) del identifiedElements[idFrom] identifiedElements[idTo] = definingNode referringNodes = referencedIDs[idFrom] # Look for the idFrom ID name in each of the referencing elements, # exactly like findReferencedElements would. # Cyn: Duplicated processing! for node in referringNodes[1]: # if this node is a style element, parse its text into CSS if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: # node.firstChild will be either a CDATA or a Text node now if node.firstChild != None: # concatenate the value of all children, in case # there's a CDATASection node surrounded by whitespace # nodes # (node.normalize() will NOT work here, it only acts on Text nodes) oldValue = "".join([child.nodeValue for child in node.childNodes]) # not going to reparse the whole thing newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url(#'" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url(#"' + idFrom + '")', 'url(#' + idTo + ')') # and now replace all the children with this new stylesheet. # again, this is in case the stylesheet was a CDATASection node.childNodes[:] = [node.ownerDocument.createTextNode(newValue)] num += len(oldValue) - len(newValue) # if xlink:href is set to #idFrom, then change the id href = node.getAttributeNS(NS['XLINK'],'href') if href == '#' + idFrom: node.setAttributeNS(NS['XLINK'],'href', '#' + idTo) num += len(idFrom) - len(idTo) # if the style has url(#idFrom), then change the id styles = node.getAttribute('style') if styles != '': newValue = styles.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') node.setAttribute('style', newValue) num += len(styles) - len(newValue) # now try the fill, stroke, filter attributes for attr in referencingProps: oldValue = node.getAttribute(attr) if oldValue != '': newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') node.setAttribute(attr, newValue) num += len(oldValue) - len(newValue) del referencedIDs[idFrom] referencedIDs[idTo] = referringNodes return num def unprotected_ids(doc, options): u"""Returns a list of unprotected IDs within the document doc.""" identifiedElements = findElementsWithId(doc.documentElement) if not (options.protect_ids_noninkscape or options.protect_ids_list or options.protect_ids_prefix): return identifiedElements if options.protect_ids_list: protect_ids_list = options.protect_ids_list.split(",") if options.protect_ids_prefix: protect_ids_prefixes = options.protect_ids_prefix.split(",") for id in identifiedElements.keys(): protected = False if options.protect_ids_noninkscape and not id[-1].isdigit(): protected = True if options.protect_ids_list and id in protect_ids_list: protected = True if options.protect_ids_prefix: for prefix in protect_ids_prefixes: if id.startswith(prefix): protected = True if protected: del identifiedElements[id] return identifiedElements def removeUnreferencedIDs(referencedIDs, identifiedElements): """ Removes the unreferenced ID attributes. Returns the number of ID attributes removed """ global numIDsRemoved keepTags = ['font'] num = 0; for id in identifiedElements.keys(): node = identifiedElements[id] if referencedIDs.has_key(id) == False and not node.nodeName in keepTags: node.removeAttribute('id') numIDsRemoved += 1 num += 1 return num def removeNamespacedAttributes(node, namespaces): global numAttrsRemoved num = 0 if node.nodeType == 1 : # remove all namespace'd attributes from this element attrList = node.attributes attrsToRemove = [] for attrNum in xrange(attrList.length): attr = attrList.item(attrNum) if attr != None and attr.namespaceURI in namespaces: attrsToRemove.append(attr.nodeName) for attrName in attrsToRemove : num += 1 numAttrsRemoved += 1 node.removeAttribute(attrName) # now recurse for children for child in node.childNodes: num += removeNamespacedAttributes(child, namespaces) return num def removeNamespacedElements(node, namespaces): global numElemsRemoved num = 0 if node.nodeType == 1 : # remove all namespace'd child nodes from this element childList = node.childNodes childrenToRemove = [] for child in childList: if child != None and child.namespaceURI in namespaces: childrenToRemove.append(child) for child in childrenToRemove : num += 1 numElemsRemoved += 1 node.removeChild(child) # now recurse for children for child in node.childNodes: num += removeNamespacedElements(child, namespaces) return num def removeMetadataElements(doc): global numElemsRemoved num = 0 # clone the list, as the tag list is live from the DOM elementsToRemove = [element for element in doc.documentElement.getElementsByTagName('metadata')] for element in elementsToRemove: element.parentNode.removeChild(element) num += 1 numElemsRemoved += 1 return num def removeNestedGroups(node): """ This walks further and further down the tree, removing groups which do not have any attributes or a title/desc child and promoting their children up one level """ global numElemsRemoved num = 0 groupsToRemove = [] # Only consider <g> elements for promotion if this element isn't a <switch>. # (partial fix for bug 594930, required by the SVG spec however) if not (node.nodeType == 1 and node.nodeName == 'switch'): for child in node.childNodes: if child.nodeName == 'g' and child.namespaceURI == NS['SVG'] and len(child.attributes) == 0: # only collapse group if it does not have a title or desc as a direct descendant, for grandchild in child.childNodes: if grandchild.nodeType == 1 and grandchild.namespaceURI == NS['SVG'] and \ grandchild.nodeName in ['title','desc']: break else: groupsToRemove.append(child) for g in groupsToRemove: while g.childNodes.length > 0: g.parentNode.insertBefore(g.firstChild, g) g.parentNode.removeChild(g) numElemsRemoved += 1 num += 1 # now recurse for children for child in node.childNodes: if child.nodeType == 1: num += removeNestedGroups(child) return num def moveCommonAttributesToParentGroup(elem, referencedElements): """ This recursively calls this function on all children of the passed in element and then iterates over all child elements and removes common inheritable attributes from the children and places them in the parent group. But only if the parent contains nothing but element children and whitespace. The attributes are only removed from the children if the children are not referenced by other elements in the document. """ num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == 1: # only add and recurse if the child is not referenced elsewhere if not child.getAttribute('id') in referencedElements: childElements.append(child) num += moveCommonAttributesToParentGroup(child, referencedElements) # else if the parent has non-whitespace text children, do not # try to move common attributes elif child.nodeType == 3 and child.nodeValue.strip(): return num # only process the children if there are more than one element if len(childElements) <= 1: return num commonAttrs = {} # add all inheritable properties of the first child element # FIXME: Note there is a chance that the first child is a set/animate in which case # its fill attribute is not what we want to look at, we should look for the first # non-animate/set element attrList = childElements[0].attributes for num in xrange(attrList.length): attr = attrList.item(num) # this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html # and http://www.w3.org/TR/SVGTiny12/attributeTable.html if attr.nodeName in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: # we just add all the attributes from the first child commonAttrs[attr.nodeName] = attr.nodeValue # for each subsequent child element for childNum in xrange(len(childElements)): # skip first child if childNum == 0: continue child = childElements[childNum] # if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute) if child.localName in ['set', 'animate', 'animateColor', 'animateTransform', 'animateMotion']: continue distinctAttrs = [] # loop through all current 'common' attributes for name in commonAttrs.keys(): # if this child doesn't match that attribute, schedule it for removal if child.getAttribute(name) != commonAttrs[name]: distinctAttrs.append(name) # remove those attributes which are not common for name in distinctAttrs: del commonAttrs[name] # commonAttrs now has all the inheritable attributes which are common among all child elements for name in commonAttrs.keys(): for child in childElements: child.removeAttribute(name) elem.setAttribute(name, commonAttrs[name]) # update our statistic (we remove N*M attributes and add back in M attributes) num += (len(childElements)-1) * len(commonAttrs) return num def createGroupsForCommonAttributes(elem): """ Creates <g> elements to contain runs of 3 or more consecutive child elements having at least one common attribute. Common attributes are not promoted to the <g> by this function. This is handled by moveCommonAttributesToParentGroup. If all children have a common attribute, an extra <g> is not created. This function acts recursively on the given element. """ num = 0 global numElemsRemoved # TODO perhaps all of the Presentation attributes in http://www.w3.org/TR/SVG/struct.html#GElement # could be added here # Cyn: These attributes are the same as in moveAttributesToParentGroup, and must always be for curAttr in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: # Iterate through the children in reverse order, so item(i) for # items we have yet to visit still returns the correct nodes. curChild = elem.childNodes.length - 1 while curChild >= 0: childNode = elem.childNodes.item(curChild) if childNode.nodeType == 1 and childNode.getAttribute(curAttr) != '': # We're in a possible run! Track the value and run length. value = childNode.getAttribute(curAttr) runStart, runEnd = curChild, curChild # Run elements includes only element tags, no whitespace/comments/etc. # Later, we calculate a run length which includes these. runElements = 1 # Backtrack to get all the nodes having the same # attribute value, preserving any nodes in-between. while runStart > 0: nextNode = elem.childNodes.item(runStart - 1) if nextNode.nodeType == 1: if nextNode.getAttribute(curAttr) != value: break else: runElements += 1 runStart -= 1 else: runStart -= 1 if runElements >= 3: # Include whitespace/comment/etc. nodes in the run. while runEnd < elem.childNodes.length - 1: if elem.childNodes.item(runEnd + 1).nodeType == 1: break else: runEnd += 1 runLength = runEnd - runStart + 1 if runLength == elem.childNodes.length: # Every child has this # If the current parent is a <g> already, if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: # do not act altogether on this attribute; all the # children have it in common. # Let moveCommonAttributesToParentGroup do it. curChild = -1 continue # otherwise, it might be an <svg> element, and # even if all children have the same attribute value, # it's going to be worth making the <g> since # <svg> doesn't support attributes like 'stroke'. # Fall through. # Create a <g> element from scratch. # We need the Document for this. document = elem.ownerDocument group = document.createElementNS(NS['SVG'], 'g') # Move the run of elements to the group. # a) ADD the nodes to the new group. group.childNodes[:] = elem.childNodes[runStart:runEnd + 1] for child in group.childNodes: child.parentNode = group # b) REMOVE the nodes from the element. elem.childNodes[runStart:runEnd + 1] = [] # Include the group in elem's children. elem.childNodes.insert(runStart, group) group.parentNode = elem num += 1 curChild = runStart - 1 numElemsRemoved -= 1 else: curChild -= 1 else: curChild -= 1 # each child gets the same treatment, recursively for childNode in elem.childNodes: if childNode.nodeType == 1: num += createGroupsForCommonAttributes(childNode) return num def removeUnusedAttributesOnParent(elem): """ This recursively calls this function on all children of the element passed in, then removes any unused attributes on this elem if none of the children inherit it """ num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == 1: childElements.append(child) num += removeUnusedAttributesOnParent(child) # only process the children if there are more than one element if len(childElements) <= 1: return num # get all attribute values on this parent attrList = elem.attributes unusedAttrs = {} for num in xrange(attrList.length): attr = attrList.item(num) if attr.nodeName in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: unusedAttrs[attr.nodeName] = attr.nodeValue # for each child, if at least one child inherits the parent's attribute, then remove for childNum in xrange(len(childElements)): child = childElements[childNum] inheritedAttrs = [] for name in unusedAttrs.keys(): val = child.getAttribute(name) if val == '' or val == None or val == 'inherit': inheritedAttrs.append(name) for a in inheritedAttrs: del unusedAttrs[a] # unusedAttrs now has all the parent attributes that are unused for name in unusedAttrs.keys(): elem.removeAttribute(name) num += 1 return num def removeDuplicateGradientStops(doc): global numElemsRemoved num = 0 for gradType in ['linearGradient', 'radialGradient']: for grad in doc.getElementsByTagName(gradType): stops = {} stopsToRemove = [] for stop in grad.getElementsByTagName('stop'): # convert percentages into a floating point number offsetU = SVGLength(stop.getAttribute('offset')) if offsetU.units == Unit.PCT: offset = offsetU.value / 100.0 elif offsetU.units == Unit.NONE: offset = offsetU.value else: offset = 0 # set the stop offset value to the integer or floating point equivalent if int(offset) == offset: stop.setAttribute('offset', str(int(offset))) else: stop.setAttribute('offset', str(offset)) color = stop.getAttribute('stop-color') opacity = stop.getAttribute('stop-opacity') style = stop.getAttribute('style') if stops.has_key(offset) : oldStop = stops[offset] if oldStop[0] == color and oldStop[1] == opacity and oldStop[2] == style: stopsToRemove.append(stop) stops[offset] = [color, opacity, style] for stop in stopsToRemove: stop.parentNode.removeChild(stop) num += 1 numElemsRemoved += 1 # linear gradients return num def collapseSinglyReferencedGradients(doc): global numElemsRemoved num = 0 identifiedElements = findElementsWithId(doc.documentElement) # make sure to reset the ref'ed ids for when we are running this in testscour for rid,nodeCount in findReferencedElements(doc.documentElement).iteritems(): count = nodeCount[0] nodes = nodeCount[1] # Make sure that there's actually a defining element for the current ID name. # (Cyn: I've seen documents with #id references but no element with that ID!) if count == 1 and rid in identifiedElements: elem = identifiedElements[rid] if elem != None and elem.nodeType == 1 and elem.nodeName in ['linearGradient', 'radialGradient'] \ and elem.namespaceURI == NS['SVG']: # found a gradient that is referenced by only 1 other element refElem = nodes[0] if refElem.nodeType == 1 and refElem.nodeName in ['linearGradient', 'radialGradient'] \ and refElem.namespaceURI == NS['SVG']: # elem is a gradient referenced by only one other gradient (refElem) # add the stops to the referencing gradient (this removes them from elem) if len(refElem.getElementsByTagName('stop')) == 0: stopsToAdd = elem.getElementsByTagName('stop') for stop in stopsToAdd: refElem.appendChild(stop) # adopt the gradientUnits, spreadMethod, gradientTransform attributes if # they are unspecified on refElem for attr in ['gradientUnits','spreadMethod','gradientTransform']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # if both are radialGradients, adopt elem's fx,fy,cx,cy,r attributes if # they are unspecified on refElem if elem.nodeName == 'radialGradient' and refElem.nodeName == 'radialGradient': for attr in ['fx','fy','cx','cy','r']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # if both are linearGradients, adopt elem's x1,y1,x2,y2 attributes if # they are unspecified on refElem if elem.nodeName == 'linearGradient' and refElem.nodeName == 'linearGradient': for attr in ['x1','y1','x2','y2']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # now remove the xlink:href from refElem refElem.removeAttributeNS(NS['XLINK'], 'href') # now delete elem elem.parentNode.removeChild(elem) numElemsRemoved += 1 num += 1 return num def removeDuplicateGradients(doc): global numElemsRemoved num = 0 gradientsToRemove = {} duplicateToMaster = {} for gradType in ['linearGradient', 'radialGradient']: grads = doc.getElementsByTagName(gradType) for grad in grads: # TODO: should slice grads from 'grad' here to optimize for ograd in grads: # do not compare gradient to itself if grad == ograd: continue # compare grad to ograd (all properties, then all stops) # if attributes do not match, go to next gradient someGradAttrsDoNotMatch = False for attr in ['gradientUnits','spreadMethod','gradientTransform','x1','y1','x2','y2','cx','cy','fx','fy','r']: if grad.getAttribute(attr) != ograd.getAttribute(attr): someGradAttrsDoNotMatch = True break; if someGradAttrsDoNotMatch: continue # compare xlink:href values too if grad.getAttributeNS(NS['XLINK'], 'href') != ograd.getAttributeNS(NS['XLINK'], 'href'): continue # all gradient properties match, now time to compare stops stops = grad.getElementsByTagName('stop') ostops = ograd.getElementsByTagName('stop') if stops.length != ostops.length: continue # now compare stops stopsNotEqual = False for i in xrange(stops.length): if stopsNotEqual: break stop = stops.item(i) ostop = ostops.item(i) for attr in ['offset', 'stop-color', 'stop-opacity', 'style']: if stop.getAttribute(attr) != ostop.getAttribute(attr): stopsNotEqual = True break if stopsNotEqual: continue # ograd is a duplicate of grad, we schedule it to be removed UNLESS # ograd is ALREADY considered a 'master' element if not gradientsToRemove.has_key(ograd): if not duplicateToMaster.has_key(ograd): if not gradientsToRemove.has_key(grad): gradientsToRemove[grad] = [] gradientsToRemove[grad].append( ograd ) duplicateToMaster[ograd] = grad # get a collection of all elements that are referenced and their referencing elements referencedIDs = findReferencedElements(doc.documentElement) for masterGrad in gradientsToRemove.keys(): master_id = masterGrad.getAttribute('id') # print 'master='+master_id for dupGrad in gradientsToRemove[masterGrad]: # if the duplicate gradient no longer has a parent that means it was # already re-mapped to another master gradient if not dupGrad.parentNode: continue dup_id = dupGrad.getAttribute('id') # print 'dup='+dup_id # print referencedIDs[dup_id] # for each element that referenced the gradient we are going to remove for elem in referencedIDs[dup_id][1]: # find out which attribute referenced the duplicate gradient for attr in ['fill', 'stroke']: v = elem.getAttribute(attr) if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": elem.setAttribute(attr, 'url(#'+master_id+')') if elem.getAttributeNS(NS['XLINK'], 'href') == '#'+dup_id: elem.setAttributeNS(NS['XLINK'], 'href', '#'+master_id) styles = _getStyle(elem) for style in styles: v = styles[style] if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": styles[style] = 'url(#'+master_id+')' _setStyle(elem, styles) # now that all referencing elements have been re-mapped to the master # it is safe to remove this gradient from the document dupGrad.parentNode.removeChild(dupGrad) numElemsRemoved += 1 num += 1 return num def _getStyle(node): u"""Returns the style attribute of a node as a dictionary.""" if node.nodeType == 1 and len(node.getAttribute('style')) > 0 : styleMap = { } rawStyles = node.getAttribute('style').split(';') for style in rawStyles: propval = style.split(':') if len(propval) == 2 : styleMap[propval[0].strip()] = propval[1].strip() return styleMap else: return {} def _setStyle(node, styleMap): u"""Sets the style attribute of a node to the dictionary ``styleMap``.""" fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap.keys()]) if fixedStyle != '' : node.setAttribute('style', fixedStyle) elif node.getAttribute('style'): node.removeAttribute('style') return node def repairStyle(node, options): num = 0 styleMap = _getStyle(node) if styleMap: # I've seen this enough to know that I need to correct it: # fill: url(#linearGradient4918) rgb(0, 0, 0); for prop in ['fill', 'stroke'] : if styleMap.has_key(prop) : chunk = styleMap[prop].split(') ') if len(chunk) == 2 and (chunk[0][:5] == 'url(#' or chunk[0][:6] == 'url("#' or chunk[0][:6] == "url('#") and chunk[1] == 'rgb(0, 0, 0)' : styleMap[prop] = chunk[0] + ')' num += 1 # Here is where we can weed out unnecessary styles like: # opacity:1 if styleMap.has_key('opacity') : opacity = float(styleMap['opacity']) # if opacity='0' then all fill and stroke properties are useless, remove them if opacity == 0.0 : for uselessStyle in ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-linejoin', 'stroke-opacity', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] : if styleMap.has_key(uselessStyle): del styleMap[uselessStyle] num += 1 # if stroke:none, then remove all stroke-related properties (stroke-width, etc) # TODO: should also detect if the computed value of this element is stroke="none" if styleMap.has_key('stroke') and styleMap['stroke'] == 'none' : for strokestyle in [ 'stroke-width', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] : if styleMap.has_key(strokestyle) : del styleMap[strokestyle] num += 1 # TODO: This is actually a problem if a parent element has a specified stroke # we need to properly calculate computed values del styleMap['stroke'] # if fill:none, then remove all fill-related properties (fill-rule, etc) if styleMap.has_key('fill') and styleMap['fill'] == 'none' : for fillstyle in [ 'fill-rule', 'fill-opacity' ] : if styleMap.has_key(fillstyle) : del styleMap[fillstyle] num += 1 # fill-opacity: 0 if styleMap.has_key('fill-opacity') : fillOpacity = float(styleMap['fill-opacity']) if fillOpacity == 0.0 : for uselessFillStyle in [ 'fill', 'fill-rule' ] : if styleMap.has_key(uselessFillStyle): del styleMap[uselessFillStyle] num += 1 # stroke-opacity: 0 if styleMap.has_key('stroke-opacity') : strokeOpacity = float(styleMap['stroke-opacity']) if strokeOpacity == 0.0 : for uselessStrokeStyle in [ 'stroke', 'stroke-width', 'stroke-linejoin', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset' ] : if styleMap.has_key(uselessStrokeStyle): del styleMap[uselessStrokeStyle] num += 1 # stroke-width: 0 if styleMap.has_key('stroke-width') : strokeWidth = SVGLength(styleMap['stroke-width']) if strokeWidth.value == 0.0 : for uselessStrokeStyle in [ 'stroke', 'stroke-linejoin', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity' ] : if styleMap.has_key(uselessStrokeStyle): del styleMap[uselessStrokeStyle] num += 1 # remove font properties for non-text elements # I've actually observed this in real SVG content if not mayContainTextNodes(node): for fontstyle in [ 'font-family', 'font-size', 'font-stretch', 'font-size-adjust', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'line-height', 'kerning', 'text-align', 'text-anchor', 'text-decoration', 'text-rendering', 'unicode-bidi', 'word-spacing', 'writing-mode'] : if styleMap.has_key(fontstyle) : del styleMap[fontstyle] num += 1 # remove inkscape-specific styles # TODO: need to get a full list of these for inkscapeStyle in ['-inkscape-font-specification']: if styleMap.has_key(inkscapeStyle): del styleMap[inkscapeStyle] num += 1 if styleMap.has_key('overflow') : # overflow specified on element other than svg, marker, pattern if not node.nodeName in ['svg','marker','pattern']: del styleMap['overflow'] num += 1 # it is a marker, pattern or svg # as long as this node is not the document <svg>, then only # remove overflow='hidden'. See # http://www.w3.org/TR/2010/WD-SVG11-20100622/masking.html#OverflowProperty elif node != node.ownerDocument.documentElement: if styleMap['overflow'] == 'hidden': del styleMap['overflow'] num += 1 # else if outer svg has a overflow="visible", we can remove it elif styleMap['overflow'] == 'visible': del styleMap['overflow'] num += 1 # now if any of the properties match known SVG attributes we prefer attributes # over style so emit them and remove them from the style map if options.style_to_xml: for propName in styleMap.keys() : if propName in svgAttributes : node.setAttribute(propName, styleMap[propName]) del styleMap[propName] _setStyle(node, styleMap) # recurse for our child elements for child in node.childNodes : num += repairStyle(child,options) return num def mayContainTextNodes(node): """ Returns True if the passed-in node is probably a text element, or at least one of its descendants is probably a text element. If False is returned, it is guaranteed that the passed-in node has no business having text-based attributes. If True is returned, the passed-in node should not have its text-based attributes removed. """ # Cached result of a prior call? try: return node.mayContainTextNodes except AttributeError: pass result = True # Default value # Comment, text and CDATA nodes don't have attributes and aren't containers if node.nodeType != 1: result = False # Non-SVG elements? Unknown elements! elif node.namespaceURI != NS['SVG']: result = True # Blacklisted elements. Those are guaranteed not to be text elements. elif node.nodeName in ['rect', 'circle', 'ellipse', 'line', 'polygon', 'polyline', 'path', 'image', 'stop']: result = False # Group elements. If we're missing any here, the default of True is used. elif node.nodeName in ['g', 'clipPath', 'marker', 'mask', 'pattern', 'linearGradient', 'radialGradient', 'symbol']: result = False for child in node.childNodes: if mayContainTextNodes(child): result = True # Everything else should be considered a future SVG-version text element # at best, or an unknown element at worst. result will stay True. # Cache this result before returning it. node.mayContainTextNodes = result return result def taint(taintedSet, taintedAttribute): u"""Adds an attribute to a set of attributes. Related attributes are also included.""" taintedSet.add(taintedAttribute) if taintedAttribute == 'marker': taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']: taintedSet.add('marker') return taintedSet def removeDefaultAttributeValues(node, options, tainted=set()): u"""'tainted' keeps a set of attributes defined in parent nodes. For such attributes, we don't delete attributes with default values.""" num = 0 if node.nodeType != 1: return 0 # gradientUnits: objectBoundingBox if node.getAttribute('gradientUnits') == 'objectBoundingBox': node.removeAttribute('gradientUnits') num += 1 # spreadMethod: pad if node.getAttribute('spreadMethod') == 'pad': node.removeAttribute('spreadMethod') num += 1 # x1: 0% if node.getAttribute('x1') != '': x1 = SVGLength(node.getAttribute('x1')) if x1.value == 0: node.removeAttribute('x1') num += 1 # y1: 0% if node.getAttribute('y1') != '': y1 = SVGLength(node.getAttribute('y1')) if y1.value == 0: node.removeAttribute('y1') num += 1 # x2: 100% if node.getAttribute('x2') != '': x2 = SVGLength(node.getAttribute('x2')) if (x2.value == 100 and x2.units == Unit.PCT) or (x2.value == 1 and x2.units == Unit.NONE): node.removeAttribute('x2') num += 1 # y2: 0% if node.getAttribute('y2') != '': y2 = SVGLength(node.getAttribute('y2')) if y2.value == 0: node.removeAttribute('y2') num += 1 # fx: equal to rx if node.getAttribute('fx') != '': if node.getAttribute('fx') == node.getAttribute('cx'): node.removeAttribute('fx') num += 1 # fy: equal to ry if node.getAttribute('fy') != '': if node.getAttribute('fy') == node.getAttribute('cy'): node.removeAttribute('fy') num += 1 # cx: 50% if node.getAttribute('cx') != '': cx = SVGLength(node.getAttribute('cx')) if (cx.value == 50 and cx.units == Unit.PCT) or (cx.value == 0.5 and cx.units == Unit.NONE): node.removeAttribute('cx') num += 1 # cy: 50% if node.getAttribute('cy') != '': cy = SVGLength(node.getAttribute('cy')) if (cy.value == 50 and cy.units == Unit.PCT) or (cy.value == 0.5 and cy.units == Unit.NONE): node.removeAttribute('cy') num += 1 # r: 50% if node.getAttribute('r') != '': r = SVGLength(node.getAttribute('r')) if (r.value == 50 and r.units == Unit.PCT) or (r.value == 0.5 and r.units == Unit.NONE): node.removeAttribute('r') num += 1 # Summarily get rid of some more attributes attributes = [node.attributes.item(i).nodeName for i in range(node.attributes.length)] for attribute in attributes: if attribute not in tainted: if attribute in default_attributes.keys(): if node.getAttribute(attribute) == default_attributes[attribute]: node.removeAttribute(attribute) num += 1 else: tainted = taint(tainted, attribute) # These attributes might also occur as styles styles = _getStyle(node) for attribute in styles.keys(): if attribute not in tainted: if attribute in default_attributes.keys(): if styles[attribute] == default_attributes[attribute]: del styles[attribute] num += 1 else: tainted = taint(tainted, attribute) _setStyle(node, styles) # recurse for our child elements for child in node.childNodes : num += removeDefaultAttributeValues(child, options, tainted.copy()) return num rgb = re.compile(r"\s*rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*") rgbp = re.compile(r"\s*rgb\(\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*\)\s*") def convertColor(value): """ Converts the input color string and returns a #RRGGBB (or #RGB if possible) string """ s = value if s in colors.keys(): s = colors[s] rgbpMatch = rgbp.match(s) if rgbpMatch != None : r = int(float(rgbpMatch.group(1)) * 255.0 / 100.0) g = int(float(rgbpMatch.group(2)) * 255.0 / 100.0) b = int(float(rgbpMatch.group(3)) * 255.0 / 100.0) s = '#%02x%02x%02x' % (r, g, b) else: rgbMatch = rgb.match(s) if rgbMatch != None : r = int( rgbMatch.group(1) ) g = int( rgbMatch.group(2) ) b = int( rgbMatch.group(3) ) s = '#%02x%02x%02x' % (r, g, b) if s[0] == '#': s = s.lower() if len(s)==7 and s[1]==s[2] and s[3]==s[4] and s[5]==s[6]: s = '#'+s[1]+s[3]+s[5] return s def convertColors(element) : """ Recursively converts all color properties into #RRGGBB format if shorter """ numBytes = 0 if element.nodeType != 1: return 0 # set up list of color attributes for each element type attrsToConvert = [] if element.nodeName in ['rect', 'circle', 'ellipse', 'polygon', \ 'line', 'polyline', 'path', 'g', 'a']: attrsToConvert = ['fill', 'stroke'] elif element.nodeName in ['stop']: attrsToConvert = ['stop-color'] elif element.nodeName in ['solidColor']: attrsToConvert = ['solid-color'] # now convert all the color formats styles = _getStyle(element) for attr in attrsToConvert: oldColorValue = element.getAttribute(attr) if oldColorValue != '': newColorValue = convertColor(oldColorValue) oldBytes = len(oldColorValue) newBytes = len(newColorValue) if oldBytes > newBytes: element.setAttribute(attr, newColorValue) numBytes += (oldBytes - len(element.getAttribute(attr))) # colors might also hide in styles if attr in styles.keys(): oldColorValue = styles[attr] newColorValue = convertColor(oldColorValue) oldBytes = len(oldColorValue) newBytes = len(newColorValue) if oldBytes > newBytes: styles[attr] = newColorValue numBytes += (oldBytes - len(element.getAttribute(attr))) _setStyle(element, styles) # now recurse for our child elements for child in element.childNodes : numBytes += convertColors(child) return numBytes # TODO: go over what this method does and see if there is a way to optimize it # TODO: go over the performance of this method and see if I can save memory/speed by # reusing data structures, etc def cleanPath(element, options) : """ Cleans the path string (d attribute) of the element """ global numBytesSavedInPathData global numPathSegmentsReduced global numCurvesStraightened # this gets the parser object from svg_regex.py oldPathStr = element.getAttribute('d') path = svg_parser.parse(oldPathStr) # This determines whether the stroke has round linecaps. If it does, # we do not want to collapse empty segments, as they are actually rendered. withRoundLineCaps = element.getAttribute('stroke-linecap') == 'round' # The first command must be a moveto, and whether it's relative (m) # or absolute (M), the first set of coordinates *is* absolute. So # the first iteration of the loop below will get x,y and startx,starty. # convert absolute coordinates into relative ones. # Reuse the data structure 'path', since we're not adding or removing subcommands. # Also reuse the coordinate lists since we're not adding or removing any. for pathIndex in xrange(0, len(path)): cmd, data = path[pathIndex] # Changes to cmd don't get through to the data structure i = 0 # adjust abs to rel # only the A command has some values that we don't want to adjust (radii, rotation, flags) if cmd == 'A': for i in xrange(i, len(data), 7): data[i+5] -= x data[i+6] -= y x += data[i+5] y += data[i+6] path[pathIndex] = ('a', data) elif cmd == 'a': x += sum(data[5::7]) y += sum(data[6::7]) elif cmd == 'H': for i in xrange(i, len(data)): data[i] -= x x += data[i] path[pathIndex] = ('h', data) elif cmd == 'h': x += sum(data) elif cmd == 'V': for i in xrange(i, len(data)): data[i] -= y y += data[i] path[pathIndex] = ('v', data) elif cmd == 'v': y += sum(data) elif cmd == 'M': startx, starty = data[0], data[1] # If this is a path starter, don't convert its first # coordinate to relative; that would just make it (0, 0) if pathIndex != 0: data[0] -= x data[1] -= y x, y = startx, starty i = 2 for i in xrange(i, len(data), 2): data[i] -= x data[i+1] -= y x += data[i] y += data[i+1] path[pathIndex] = ('m', data) elif cmd in ['L','T']: for i in xrange(i, len(data), 2): data[i] -= x data[i+1] -= y x += data[i] y += data[i+1] path[pathIndex] = (cmd.lower(), data) elif cmd in ['m']: if pathIndex == 0: # START OF PATH - this is an absolute moveto # followed by relative linetos startx, starty = data[0], data[1] x, y = startx, starty i = 2 else: startx = x + data[0] starty = y + data[1] for i in xrange(i, len(data), 2): x += data[i] y += data[i+1] elif cmd in ['l','t']: x += sum(data[0::2]) y += sum(data[1::2]) elif cmd in ['S','Q']: for i in xrange(i, len(data), 4): data[i] -= x data[i+1] -= y data[i+2] -= x data[i+3] -= y x += data[i+2] y += data[i+3] path[pathIndex] = (cmd.lower(), data) elif cmd in ['s','q']: x += sum(data[2::4]) y += sum(data[3::4]) elif cmd == 'C': for i in xrange(i, len(data), 6): data[i] -= x data[i+1] -= y data[i+2] -= x data[i+3] -= y data[i+4] -= x data[i+5] -= y x += data[i+4] y += data[i+5] path[pathIndex] = ('c', data) elif cmd == 'c': x += sum(data[4::6]) y += sum(data[5::6]) elif cmd in ['z','Z']: x, y = startx, starty path[pathIndex] = ('z', data) # remove empty segments # Reuse the data structure 'path' and the coordinate lists, even if we're # deleting items, because these deletions are relatively cheap. if not withRoundLineCaps: for pathIndex in xrange(0, len(path)): cmd, data = path[pathIndex] i = 0 if cmd in ['m','l','t']: if cmd == 'm': # remove m0,0 segments if pathIndex > 0 and data[0] == data[i+1] == 0: # 'm0,0 x,y' can be replaces with 'lx,y', # except the first m which is a required absolute moveto path[pathIndex] = ('l', data[2:]) numPathSegmentsReduced += 1 else: # else skip move coordinate i = 2 while i < len(data): if data[i] == data[i+1] == 0: del data[i:i+2] numPathSegmentsReduced += 1 else: i += 2 elif cmd == 'c': while i < len(data): if data[i] == data[i+1] == data[i+2] == data[i+3] == data[i+4] == data[i+5] == 0: del data[i:i+6] numPathSegmentsReduced += 1 else: i += 6 elif cmd == 'a': while i < len(data): if data[i+5] == data[i+6] == 0: del data[i:i+7] numPathSegmentsReduced += 1 else: i += 7 elif cmd == 'q': while i < len(data): if data[i] == data[i+1] == data[i+2] == data[i+3] == 0: del data[i:i+4] numPathSegmentsReduced += 1 else: i += 4 elif cmd in ['h','v']: oldLen = len(data) path[pathIndex] = (cmd, [coord for coord in data if coord != 0]) numPathSegmentsReduced += len(path[pathIndex][1]) - oldLen # fixup: Delete subcommands having no coordinates. path = [elem for elem in path if len(elem[1]) > 0 or elem[0] == 'z'] # convert straight curves into lines newPath = [path[0]] for (cmd,data) in path[1:]: i = 0 newData = data if cmd == 'c': newData = [] while i < len(data): # since all commands are now relative, we can think of previous point as (0,0) # and new point (dx,dy) is (data[i+4],data[i+5]) # eqn of line will be y = (dy/dx)*x or if dx=0 then eqn of line is x=0 (p1x,p1y) = (data[i],data[i+1]) (p2x,p2y) = (data[i+2],data[i+3]) dx = data[i+4] dy = data[i+5] foundStraightCurve = False if dx == 0: if p1x == 0 and p2x == 0: foundStraightCurve = True else: m = dy/dx if p1y == m*p1x and p2y == m*p2x: foundStraightCurve = True if foundStraightCurve: # flush any existing curve coords first if newData: newPath.append( (cmd,newData) ) newData = [] # now create a straight line segment newPath.append( ('l', [dx,dy]) ) numCurvesStraightened += 1 else: newData.extend(data[i:i+6]) i += 6 if newData or cmd == 'z' or cmd == 'Z': newPath.append( (cmd,newData) ) path = newPath # collapse all consecutive commands of the same type into one command prevCmd = '' prevData = [] newPath = [] for (cmd,data) in path: # flush the previous command if it is not the same type as the current command if prevCmd != '': if cmd != prevCmd or cmd == 'm': newPath.append( (prevCmd, prevData) ) prevCmd = '' prevData = [] # if the previous and current commands are the same type, # or the previous command is moveto and the current is lineto, collapse, # but only if they are not move commands (since move can contain implicit lineto commands) if (cmd == prevCmd or (cmd == 'l' and prevCmd == 'm')) and cmd != 'm': prevData.extend(data) # save last command and data else: prevCmd = cmd prevData = data # flush last command and data if prevCmd != '': newPath.append( (prevCmd, prevData) ) path = newPath # convert to shorthand path segments where possible newPath = [] for (cmd,data) in path: # convert line segments into h,v where possible if cmd == 'l': i = 0 lineTuples = [] while i < len(data): if data[i] == 0: # vertical if lineTuples: # flush the existing line command newPath.append( ('l', lineTuples) ) lineTuples = [] # append the v and then the remaining line coords newPath.append( ('v', [data[i+1]]) ) numPathSegmentsReduced += 1 elif data[i+1] == 0: if lineTuples: # flush the line command, then append the h and then the remaining line coords newPath.append( ('l', lineTuples) ) lineTuples = [] newPath.append( ('h', [data[i]]) ) numPathSegmentsReduced += 1 else: lineTuples.extend(data[i:i+2]) i += 2 if lineTuples: newPath.append( ('l', lineTuples) ) # also handle implied relative linetos elif cmd == 'm': i = 2 lineTuples = [data[0], data[1]] while i < len(data): if data[i] == 0: # vertical if lineTuples: # flush the existing m/l command newPath.append( (cmd, lineTuples) ) lineTuples = [] cmd = 'l' # dealing with linetos now # append the v and then the remaining line coords newPath.append( ('v', [data[i+1]]) ) numPathSegmentsReduced += 1 elif data[i+1] == 0: if lineTuples: # flush the m/l command, then append the h and then the remaining line coords newPath.append( (cmd, lineTuples) ) lineTuples = [] cmd = 'l' # dealing with linetos now newPath.append( ('h', [data[i]]) ) numPathSegmentsReduced += 1 else: lineTuples.extend(data[i:i+2]) i += 2 if lineTuples: newPath.append( (cmd, lineTuples) ) # convert Bézier curve segments into s where possible elif cmd == 'c': bez_ctl_pt = (0,0) i = 0 curveTuples = [] while i < len(data): # rotate by 180deg means negate both coordinates # if the previous control point is equal then we can substitute a # shorthand bezier command if bez_ctl_pt[0] == data[i] and bez_ctl_pt[1] == data[i+1]: if curveTuples: newPath.append( ('c', curveTuples) ) curveTuples = [] # append the s command newPath.append( ('s', [data[i+2], data[i+3], data[i+4], data[i+5]]) ) numPathSegmentsReduced += 1 else: j = 0 while j <= 5: curveTuples.append(data[i+j]) j += 1 # set up control point for next curve segment bez_ctl_pt = (data[i+4]-data[i+2], data[i+5]-data[i+3]) i += 6 if curveTuples: newPath.append( ('c', curveTuples) ) # convert quadratic curve segments into t where possible elif cmd == 'q': quad_ctl_pt = (0,0) i = 0 curveTuples = [] while i < len(data): if quad_ctl_pt[0] == data[i] and quad_ctl_pt[1] == data[i+1]: if curveTuples: newPath.append( ('q', curveTuples) ) curveTuples = [] # append the t command newPath.append( ('t', [data[i+2], data[i+3]]) ) numPathSegmentsReduced += 1 else: j = 0; while j <= 3: curveTuples.append(data[i+j]) j += 1 quad_ctl_pt = (data[i+2]-data[i], data[i+3]-data[i+1]) i += 4 if curveTuples: newPath.append( ('q', curveTuples) ) else: newPath.append( (cmd, data) ) path = newPath # for each h or v, collapse unnecessary coordinates that run in the same direction # i.e. "h-100-100" becomes "h-200" but "h300-100" does not change # Reuse the data structure 'path', since we're not adding or removing subcommands. # Also reuse the coordinate lists, even if we're deleting items, because these # deletions are relatively cheap. for pathIndex in xrange(1, len(path)): cmd, data = path[pathIndex] if cmd in ['h','v'] and len(data) > 1: coordIndex = 1 while coordIndex < len(data): if isSameSign(data[coordIndex - 1], data[coordIndex]): data[coordIndex - 1] += data[coordIndex] del data[coordIndex] numPathSegmentsReduced += 1 else: coordIndex += 1 # it is possible that we have consecutive h, v, c, t commands now # so again collapse all consecutive commands of the same type into one command prevCmd = '' prevData = [] newPath = [path[0]] for (cmd,data) in path[1:]: # flush the previous command if it is not the same type as the current command if prevCmd != '': if cmd != prevCmd or cmd == 'm': newPath.append( (prevCmd, prevData) ) prevCmd = '' prevData = [] # if the previous and current commands are the same type, collapse if cmd == prevCmd and cmd != 'm': prevData.extend(data) # save last command and data else: prevCmd = cmd prevData = data # flush last command and data if prevCmd != '': newPath.append( (prevCmd, prevData) ) path = newPath newPathStr = serializePath(path, options) numBytesSavedInPathData += ( len(oldPathStr) - len(newPathStr) ) element.setAttribute('d', newPathStr) def parseListOfPoints(s): """ Parse string into a list of points. Returns a list of containing an even number of coordinate strings """ i = 0 # (wsp)? comma-or-wsp-separated coordinate pairs (wsp)? # coordinate-pair = coordinate comma-or-wsp coordinate # coordinate = sign? integer # comma-wsp: (wsp+ comma? wsp*) | (comma wsp*) ws_nums = re.split(r"\s*,?\s*", s.strip()) nums = [] # also, if 100-100 is found, split it into two also # <polygon points="100,-100,100-100,100-100-100,-100-100" /> for i in xrange(len(ws_nums)): negcoords = ws_nums[i].split("-") # this string didn't have any negative coordinates if len(negcoords) == 1: nums.append(negcoords[0]) # we got negative coords else: for j in xrange(len(negcoords)): if j == 0: # first number could be positive if negcoords[0] != '': nums.append(negcoords[0]) # but it could also be negative elif len(nums) == 0: nums.append('-' + negcoords[j]) # otherwise all other strings will be negative else: # unless we accidentally split a number that was in scientific notation # and had a negative exponent (500.00e-1) prev = nums[len(nums)-1] if prev[len(prev)-1] in ['e', 'E']: nums[len(nums)-1] = prev + '-' + negcoords[j] else: nums.append( '-'+negcoords[j] ) # if we have an odd number of points, return empty if len(nums) % 2 != 0: return [] # now resolve into Decimal values i = 0 while i < len(nums): try: nums[i] = getcontext().create_decimal(nums[i]) nums[i + 1] = getcontext().create_decimal(nums[i + 1]) except decimal.InvalidOperation: # one of the lengths had a unit or is an invalid number return [] i += 2 return nums def cleanPolygon(elem, options): """ Remove unnecessary closing point of polygon points attribute """ global numPointsRemovedFromPolygon pts = parseListOfPoints(elem.getAttribute('points')) N = len(pts)/2 if N >= 2: (startx,starty) = pts[:2] (endx,endy) = pts[-2:] if startx == endx and starty == endy: del pts[-2:] numPointsRemovedFromPolygon += 1 elem.setAttribute('points', scourCoordinates(pts, options, True)) def cleanPolyline(elem, options): """ Scour the polyline points attribute """ pts = parseListOfPoints(elem.getAttribute('points')) elem.setAttribute('points', scourCoordinates(pts, options, True)) def serializePath(pathObj, options): """ Reserializes the path data with some cleanups. """ # elliptical arc commands must have comma/wsp separating the coordinates # this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754 return ''.join([cmd + scourCoordinates(data, options, (cmd == 'a')) for cmd, data in pathObj]) def serializeTransform(transformObj): """ Reserializes the transform data with some cleanups. """ return ' '.join( [command + '(' + ' '.join( [scourUnitlessLength(number) for number in numbers] ) + ')' for command, numbers in transformObj] ) def scourCoordinates(data, options, forceCommaWsp = False): """ Serializes coordinate data with some cleanups: - removes all trailing zeros after the decimal - integerize coordinates if possible - removes extraneous whitespace - adds spaces between values in a subcommand if required (or if forceCommaWsp is True) """ if data != None: newData = [] c = 0 previousCoord = '' for coord in data: scouredCoord = scourUnitlessLength(coord, needsRendererWorkaround=options.renderer_workaround) # only need the comma if the current number starts with a digit # (numbers can start with - without needing a comma before) # or if forceCommaWsp is True # or if this number starts with a dot and the previous number # had *no* dot or exponent (so we can go like -5.5.5 for -5.5,0.5 # and 4e4.5 for 40000,0.5) if c > 0 and (forceCommaWsp or scouredCoord[0].isdigit() or (scouredCoord[0] == '.' and not ('.' in previousCoord or 'e' in previousCoord)) ): newData.append( ' ' ) # add the scoured coordinate to the path string newData.append( scouredCoord ) previousCoord = scouredCoord c += 1 # What we need to do to work around GNOME bugs 548494, 563933 and # 620565, which are being fixed and unfixed in Ubuntu, is # to make sure that a dot doesn't immediately follow a command # (so 'h50' and 'h0.5' are allowed, but not 'h.5'). # Then, we need to add a space character after any coordinates # having an 'e' (scientific notation), so as to have the exponent # separate from the next number. if options.renderer_workaround: if len(newData) > 0: for i in xrange(1, len(newData)): if newData[i][0] == '-' and 'e' in newData[i - 1]: newData[i - 1] += ' ' return ''.join(newData) else: return ''.join(newData) return '' def scourLength(length): """ Scours a length. Accepts units. """ length = SVGLength(length) return scourUnitlessLength(length.value) + Unit.str(length.units) def scourUnitlessLength(length, needsRendererWorkaround=False): # length is of a numeric type """ Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units. """ # reduce to the proper number of digits if not isinstance(length, Decimal): length = getcontext().create_decimal(str(length)) # if the value is an integer, it may still have .0[...] attached to it for some reason # remove those if int(length) == length: length = getcontext().create_decimal(int(length)) # gather the non-scientific notation version of the coordinate. # this may actually be in scientific notation if the value is # sufficiently large or small, so this is a misnomer. nonsci = unicode(length).lower().replace("e+", "e") if not needsRendererWorkaround: if len(nonsci) > 2 and nonsci[:2] == '0.': nonsci = nonsci[1:] # remove the 0, leave the dot elif len(nonsci) > 3 and nonsci[:3] == '-0.': nonsci = '-' + nonsci[2:] # remove the 0, leave the minus and dot if len(nonsci) > 3: # avoid calling normalize unless strictly necessary # and then the scientific notation version, with E+NUMBER replaced with # just eNUMBER, since SVG accepts this. sci = unicode(length.normalize()).lower().replace("e+", "e") if len(sci) < len(nonsci): return sci else: return nonsci else: return nonsci def reducePrecision(element) : """ Because opacities, letter spacings, stroke widths and all that don't need to be preserved in SVG files with 9 digits of precision. Takes all of these attributes, in the given element node and its children, and reduces their precision to the current Decimal context's precision. Also checks for the attributes actually being lengths, not 'inherit', 'none' or anything that isn't an SVGLength. Returns the number of bytes saved after performing these reductions. """ num = 0 styles = _getStyle(element) for lengthAttr in ['opacity', 'flood-opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'stroke-miterlimit', 'stroke-dashoffset', 'letter-spacing', 'word-spacing', 'kerning', 'font-size-adjust', 'font-size', 'stroke-width']: val = element.getAttribute(lengthAttr) if val != '': valLen = SVGLength(val) if valLen.units != Unit.INVALID: # not an absolute/relative size or inherit, can be % though newVal = scourLength(val) if len(newVal) < len(val): num += len(val) - len(newVal) element.setAttribute(lengthAttr, newVal) # repeat for attributes hidden in styles if lengthAttr in styles.keys(): val = styles[lengthAttr] valLen = SVGLength(val) if valLen.units != Unit.INVALID: newVal = scourLength(val) if len(newVal) < len(val): num += len(val) - len(newVal) styles[lengthAttr] = newVal _setStyle(element, styles) for child in element.childNodes: if child.nodeType == 1: num += reducePrecision(child) return num def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new angle in the range ]-360, 360[. # The modulo operator yields results with the sign of the # divisor, so for negative dividends, we preserve the sign # of the angle. if angle < 0: angle %= -360 else: angle %= 360 # 720 degrees is unneccessary, as 360 covers all angles. # As "-x" is shorter than "35x" and "-xxx" one character # longer than positive angles <= 260, we constrain angle # range to [-90, 270[ (or, equally valid: ]-100, 260]). if angle >= 270: angle -= 360 elif angle < -90: angle += 360 return angle def optimizeTransform(transform): """ Optimises a series of transformations parsed from a single transform="" attribute. The transformation list is modified in-place. """ # FIXME: reordering these would optimize even more cases: # first: Fold consecutive runs of the same transformation # extra: Attempt to cast between types to create sameness: # "matrix(0 1 -1 0 0 0) rotate(180) scale(-1)" all # are rotations (90, 180, 180) -- thus "rotate(90)" # second: Simplify transforms where numbers are optional. # third: Attempt to simplify any single remaining matrix() # # if there's only one transformation and it's a matrix, # try to make it a shorter non-matrix transformation # NOTE: as matrix(a b c d e f) in SVG means the matrix: # |¯ a c e ¯| make constants |¯ A1 A2 A3 ¯| # | b d f | translating them | B1 B2 B3 | # |_ 0 0 1 _| to more readable |_ 0 0 1 _| if len(transform) == 1 and transform[0][0] == 'matrix': matrix = A1, B1, A2, B2, A3, B3 = transform[0][1] # |¯ 1 0 0 ¯| # | 0 1 0 | Identity matrix (no transformation) # |_ 0 0 1 _| if matrix == [1, 0, 0, 1, 0, 0]: del transform[0] # |¯ 1 0 X ¯| # | 0 1 Y | Translation by (X, Y). # |_ 0 0 1 _| elif (A1 == 1 and A2 == 0 and B1 == 0 and B2 == 1): transform[0] = ('translate', [A3, B3]) # |¯ X 0 0 ¯| # | 0 Y 0 | Scaling by (X, Y). # |_ 0 0 1 _| elif ( A2 == 0 and A3 == 0 and B1 == 0 and B3 == 0): transform[0] = ('scale', [A1, B2]) # |¯ cos(A) -sin(A) 0 ¯| Rotation by angle A, # | sin(A) cos(A) 0 | clockwise, about the origin. # |_ 0 0 1 _| A is in degrees, [-180...180]. elif (A1 == B2 and -1 <= A1 <= 1 and A3 == 0 and -B1 == A2 and -1 <= B1 <= 1 and B3 == 0 # as cos² A + sin² A == 1 and as decimal trig is approximate: # FIXME: the "epsilon" term here should really be some function # of the precision of the (sin|cos)_A terms, not 1e-15: and abs((B1 ** 2) + (A1 ** 2) - 1) < Decimal("1e-15")): sin_A, cos_A = B1, A1 # while asin(A) and acos(A) both only have an 180° range # the sign of sin(A) and cos(A) varies across quadrants, # letting us hone in on the angle the matrix represents: # -- => < -90 | -+ => -90..0 | ++ => 0..90 | +- => >= 90 # # http://en.wikipedia.org/wiki/File:Sine_cosine_plot.svg # shows asin has the correct angle the middle quadrants: A = Decimal(str(math.degrees(math.asin(float(sin_A))))) if cos_A < 0: # otherwise needs adjusting from the edges if sin_A < 0: A = -180 - A else: A = 180 - A transform[0] = ('rotate', [A]) # Simplify transformations where numbers are optional. for type, args in transform: if type == 'translate': # Only the X coordinate is required for translations. # If the Y coordinate is unspecified, it's 0. if len(args) == 2 and args[1] == 0: del args[1] elif type == 'rotate': args[0] = optimizeAngle(args[0]) # angle # Only the angle is required for rotations. # If the coordinates are unspecified, it's the origin (0, 0). if len(args) == 3 and args[1] == args[2] == 0: del args[1:] elif type == 'scale': # Only the X scaling factor is required. # If the Y factor is unspecified, it's the same as X. if len(args) == 2 and args[0] == args[1]: del args[1] # Attempt to coalesce runs of the same transformation. # Translations followed immediately by other translations, # rotations followed immediately by other rotations, # scaling followed immediately by other scaling, # are safe to add. # Identity skewX/skewY are safe to remove, but how do they accrete? # |¯ 1 0 0 ¯| # | tan(A) 1 0 | skews X coordinates by angle A # |_ 0 0 1 _| # # |¯ 1 tan(A) 0 ¯| # | 0 1 0 | skews Y coordinates by angle A # |_ 0 0 1 _| # # FIXME: A matrix followed immediately by another matrix # would be safe to multiply together, too. i = 1 while i < len(transform): currType, currArgs = transform[i] prevType, prevArgs = transform[i - 1] if currType == prevType == 'translate': prevArgs[0] += currArgs[0] # x # for y, only add if the second translation has an explicit y if len(currArgs) == 2: if len(prevArgs) == 2: prevArgs[1] += currArgs[1] # y elif len(prevArgs) == 1: prevArgs.append(currArgs[1]) # y del transform[i] if prevArgs[0] == prevArgs[1] == 0: # Identity translation! i -= 1 del transform[i] elif (currType == prevType == 'rotate' and len(prevArgs) == len(currArgs) == 1): # Only coalesce if both rotations are from the origin. prevArgs[0] = optimizeAngle(prevArgs[0] + currArgs[0]) del transform[i] elif currType == prevType == 'scale': prevArgs[0] *= currArgs[0] # x # handle an implicit y if len(prevArgs) == 2 and len(currArgs) == 2: # y1 * y2 prevArgs[1] *= currArgs[1] elif len(prevArgs) == 1 and len(currArgs) == 2: # create y2 = uniformscalefactor1 * y2 prevArgs.append(prevArgs[0] * currArgs[1]) elif len(prevArgs) == 2 and len(currArgs) == 1: # y1 * uniformscalefactor2 prevArgs[1] *= currArgs[0] del transform[i] if prevArgs[0] == prevArgs[1] == 1: # Identity scale! i -= 1 del transform[i] else: i += 1 # Some fixups are needed for single-element transformation lists, since # the loop above was to coalesce elements with their predecessors in the # list, and thus it required 2 elements. i = 0 while i < len(transform): currType, currArgs = transform[i] if ((currType == 'skewX' or currType == 'skewY') and len(currArgs) == 1 and currArgs[0] == 0): # Identity skew! del transform[i] elif ((currType == 'rotate') and len(currArgs) == 1 and currArgs[0] == 0): # Identity rotation! del transform[i] else: i += 1 def optimizeTransforms(element, options) : """ Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions. """ num = 0 for transformAttr in ['transform', 'patternTransform', 'gradientTransform']: val = element.getAttribute(transformAttr) if val != '': transform = svg_transform_parser.parse(val) optimizeTransform(transform) newVal = serializeTransform(transform) if len(newVal) < len(val): if len(newVal): element.setAttribute(transformAttr, newVal) else: element.removeAttribute(transformAttr) num += len(val) - len(newVal) for child in element.childNodes: if child.nodeType == 1: num += optimizeTransforms(child, options) return num def removeComments(element) : """ Removes comments from the element and its children. """ global numCommentBytes if isinstance(element, xml.dom.minidom.Document): # must process the document object separately, because its # documentElement's nodes have None as their parentNode # iterate in reverse order to prevent mess-ups with renumbering for index in xrange(len(element.childNodes) - 1, -1, -1): subelement = element.childNodes[index] if isinstance(subelement, xml.dom.minidom.Comment): numCommentBytes += len(subelement.data) element.removeChild(subelement) else: removeComments(subelement) elif isinstance(element, xml.dom.minidom.Comment): numCommentBytes += len(element.data) element.parentNode.removeChild(element) else: # iterate in reverse order to prevent mess-ups with renumbering for index in xrange(len(element.childNodes) - 1, -1, -1): subelement = element.childNodes[index] removeComments(subelement) def embedRasters(element, options) : import base64 import urllib """ Converts raster references to inline images. NOTE: there are size limits to base64-encoding handling in browsers """ global numRastersEmbedded href = element.getAttributeNS(NS['XLINK'],'href') # if xlink:href is set, then grab the id if href != '' and len(href) > 1: # find if href value has filename ext ext = os.path.splitext(os.path.basename(href))[1].lower()[1:] # look for 'png', 'jpg', and 'gif' extensions if ext == 'png' or ext == 'jpg' or ext == 'gif': # file:// URLs denote files on the local system too if href[:7] == 'file://': href = href[7:] # does the file exist? if os.path.isfile(href): # if this is not an absolute path, set path relative # to script file based on input arg infilename = '.' if options.infilename: infilename = options.infilename href = os.path.join(os.path.dirname(infilename), href) rasterdata = '' # test if file exists locally if os.path.isfile(href): # open raster file as raw binary raster = open( href, "rb") rasterdata = raster.read() elif href[:7] == 'http://': webFile = urllib.urlopen( href ) rasterdata = webFile.read() webFile.close() # ... should we remove all images which don't resolve? if rasterdata != '' : # base64-encode raster b64eRaster = base64.b64encode( rasterdata ) # set href attribute to base64-encoded equivalent if b64eRaster != '': # PNG and GIF both have MIME Type 'image/[ext]', but # JPEG has MIME Type 'image/jpeg' if ext == 'jpg': ext = 'jpeg' element.setAttributeNS(NS['XLINK'], 'href', 'data:image/' + ext + ';base64,' + b64eRaster) numRastersEmbedded += 1 del b64eRaster def properlySizeDoc(docElement, options): # get doc width and height w = SVGLength(docElement.getAttribute('width')) h = SVGLength(docElement.getAttribute('height')) # if width/height are not unitless or px then it is not ok to rewrite them into a viewBox. # well, it may be OK for Web browsers and vector editors, but not for librsvg. if options.renderer_workaround: if ((w.units != Unit.NONE and w.units != Unit.PX) or (h.units != Unit.NONE and h.units != Unit.PX)): return # else we have a statically sized image and we should try to remedy that # parse viewBox attribute vbSep = re.split("\\s*\\,?\\s*", docElement.getAttribute('viewBox'), 3) # if we have a valid viewBox we need to check it vbWidth,vbHeight = 0,0 if len(vbSep) == 4: try: # if x or y are specified and non-zero then it is not ok to overwrite it vbX = float(vbSep[0]) vbY = float(vbSep[1]) if vbX != 0 or vbY != 0: return # if width or height are not equal to doc width/height then it is not ok to overwrite it vbWidth = float(vbSep[2]) vbHeight = float(vbSep[3]) if vbWidth != w.value or vbHeight != h.value: return # if the viewBox did not parse properly it is invalid and ok to overwrite it except ValueError: pass # at this point it's safe to set the viewBox and remove width/height docElement.setAttribute('viewBox', '0 0 %s %s' % (w.value, h.value)) docElement.removeAttribute('width') docElement.removeAttribute('height') def remapNamespacePrefix(node, oldprefix, newprefix): if node == None or node.nodeType != 1: return if node.prefix == oldprefix: localName = node.localName namespace = node.namespaceURI doc = node.ownerDocument parent = node.parentNode # create a replacement node newNode = None if newprefix != '': newNode = doc.createElementNS(namespace, newprefix+":"+localName) else: newNode = doc.createElement(localName); # add all the attributes attrList = node.attributes for i in xrange(attrList.length): attr = attrList.item(i) newNode.setAttributeNS( attr.namespaceURI, attr.localName, attr.nodeValue) # clone and add all the child nodes for child in node.childNodes: newNode.appendChild(child.cloneNode(True)) # replace old node with new node parent.replaceChild( newNode, node ) # set the node to the new node in the remapped namespace prefix node = newNode # now do all child nodes for child in node.childNodes : remapNamespacePrefix(child, oldprefix, newprefix) def makeWellFormed(str): xml_ents = { '<':'&lt;', '>':'&gt;', '&':'&amp;', "'":'&apos;', '"':'&quot;'} # starr = [] # for c in str: # if c in xml_ents: # starr.append(xml_ents[c]) # else: # starr.append(c) # this list comprehension is short-form for the above for-loop: return ''.join([xml_ents[c] if c in xml_ents else c for c in str]) # hand-rolled serialization function that has the following benefits: # - pretty printing # - somewhat judicious use of whitespace # - ensure id attributes are first def serializeXML(element, options, ind = 0, preserveWhitespace = False): outParts = [] indent = ind I='' if options.indent_type == 'tab': I='\t' elif options.indent_type == 'space': I=' ' outParts.extend([(I * ind), '<', element.nodeName]) # always serialize the id or xml:id attributes first if element.getAttribute('id') != '': id = element.getAttribute('id') quot = '"' if id.find('"') != -1: quot = "'" outParts.extend([' id=', quot, id, quot]) if element.getAttribute('xml:id') != '': id = element.getAttribute('xml:id') quot = '"' if id.find('"') != -1: quot = "'" outParts.extend([' xml:id=', quot, id, quot]) # now serialize the other attributes attrList = element.attributes for num in xrange(attrList.length) : attr = attrList.item(num) if attr.nodeName == 'id' or attr.nodeName == 'xml:id': continue # if the attribute value contains a double-quote, use single-quotes quot = '"' if attr.nodeValue.find('"') != -1: quot = "'" attrValue = makeWellFormed( attr.nodeValue ) outParts.append(' ') # preserve xmlns: if it is a namespace prefix declaration if attr.prefix != None: outParts.extend([attr.prefix, ':']) elif attr.namespaceURI != None: if attr.namespaceURI == 'http://www.w3.org/2000/xmlns/' and attr.nodeName.find('xmlns') == -1: outParts.append('xmlns:') elif attr.namespaceURI == 'http://www.w3.org/1999/xlink': outParts.append('xlink:') outParts.extend([attr.localName, '=', quot, attrValue, quot]) if attr.nodeName == 'xml:space': if attrValue == 'preserve': preserveWhitespace = True elif attrValue == 'default': preserveWhitespace = False # if no children, self-close children = element.childNodes if children.length > 0: outParts.append('>') onNewLine = False for child in element.childNodes: # element node if child.nodeType == 1: if preserveWhitespace: outParts.append(serializeXML(child, options, 0, preserveWhitespace)) else: outParts.extend(['\n', serializeXML(child, options, indent + 1, preserveWhitespace)]) onNewLine = True # text node elif child.nodeType == 3: # trim it only in the case of not being a child of an element # where whitespace might be important if preserveWhitespace: outParts.append(makeWellFormed(child.nodeValue)) else: outParts.append(makeWellFormed(child.nodeValue.strip())) # CDATA node elif child.nodeType == 4: outParts.extend(['<![CDATA[', child.nodeValue, ']]>']) # Comment node elif child.nodeType == 8: outParts.extend(['<!--', child.nodeValue, '-->']) # TODO: entities, processing instructions, what else? else: # ignore the rest pass if onNewLine: outParts.append(I * ind) outParts.extend(['</', element.nodeName, '>']) if indent > 0: outParts.append('\n') else: outParts.append('/>') if indent > 0: outParts.append('\n') return "".join(outParts) # this is the main method # input is a string representation of the input XML # returns a string representation of the output XML def scourString(in_string, options=None): if options is None: options = _options_parser.get_default_values() getcontext().prec = options.digits global numAttrsRemoved global numStylePropsFixed global numElemsRemoved global numBytesSavedInColors global numCommentsRemoved global numBytesSavedInIDs global numBytesSavedInLengths global numBytesSavedInTransforms doc = xml.dom.minidom.parseString(in_string) # for whatever reason this does not always remove all inkscape/sodipodi attributes/elements # on the first pass, so we do it multiple times # does it have to do with removal of children affecting the childlist? if options.keep_editor_data == False: while removeNamespacedElements( doc.documentElement, unwanted_ns ) > 0 : pass while removeNamespacedAttributes( doc.documentElement, unwanted_ns ) > 0 : pass # remove the xmlns: declarations now xmlnsDeclsToRemove = [] attrList = doc.documentElement.attributes for num in xrange(attrList.length) : if attrList.item(num).nodeValue in unwanted_ns : xmlnsDeclsToRemove.append(attrList.item(num).nodeName) for attr in xmlnsDeclsToRemove : doc.documentElement.removeAttribute(attr) numAttrsRemoved += 1 # ensure namespace for SVG is declared # TODO: what if the default namespace is something else (i.e. some valid namespace)? if doc.documentElement.getAttribute('xmlns') != 'http://www.w3.org/2000/svg': doc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg') # TODO: throw error or warning? # check for redundant SVG namespace declaration attrList = doc.documentElement.attributes xmlnsDeclsToRemove = [] redundantPrefixes = [] for i in xrange(attrList.length): attr = attrList.item(i) name = attr.nodeName val = attr.nodeValue if name[0:6] == 'xmlns:' and val == 'http://www.w3.org/2000/svg': redundantPrefixes.append(name[6:]) xmlnsDeclsToRemove.append(name) for attrName in xmlnsDeclsToRemove: doc.documentElement.removeAttribute(attrName) for prefix in redundantPrefixes: remapNamespacePrefix(doc.documentElement, prefix, '') if options.strip_comments: numCommentsRemoved = removeComments(doc) # repair style (remove unnecessary style properties and change them into XML attributes) numStylePropsFixed = repairStyle(doc.documentElement, options) # convert colors to #RRGGBB format if options.simple_colors: numBytesSavedInColors = convertColors(doc.documentElement) # remove <metadata> if the user wants to if options.remove_metadata: removeMetadataElements(doc) # flattend defs elements into just one defs element flattenDefs(doc) # remove unreferenced gradients/patterns outside of defs # and most unreferenced elements inside of defs while removeUnreferencedElements(doc) > 0: pass # remove empty defs, metadata, g # NOTE: these elements will be removed if they just have whitespace-only text nodes for tag in ['defs', 'metadata', 'g'] : for elem in doc.documentElement.getElementsByTagName(tag) : removeElem = not elem.hasChildNodes() if removeElem == False : for child in elem.childNodes : if child.nodeType in [1, 4, 8]: break elif child.nodeType == 3 and not child.nodeValue.isspace(): break else: removeElem = True if removeElem : elem.parentNode.removeChild(elem) numElemsRemoved += 1 if options.strip_ids: bContinueLooping = True while bContinueLooping: identifiedElements = unprotected_ids(doc, options) referencedIDs = findReferencedElements(doc.documentElement) bContinueLooping = (removeUnreferencedIDs(referencedIDs, identifiedElements) > 0) while removeDuplicateGradientStops(doc) > 0: pass # remove gradients that are only referenced by one other gradient while collapseSinglyReferencedGradients(doc) > 0: pass # remove duplicate gradients while removeDuplicateGradients(doc) > 0: pass # create <g> elements if there are runs of elements with the same attributes. # this MUST be before moveCommonAttributesToParentGroup. if options.group_create: createGroupsForCommonAttributes(doc.documentElement) # move common attributes to parent group # NOTE: the if the <svg> element's immediate children # all have the same value for an attribute, it must not # get moved to the <svg> element. The <svg> element # doesn't accept fill=, stroke= etc.! referencedIds = findReferencedElements(doc.documentElement) for child in doc.documentElement.childNodes: numAttrsRemoved += moveCommonAttributesToParentGroup(child, referencedIds) # remove unused attributes from parent numAttrsRemoved += removeUnusedAttributesOnParent(doc.documentElement) # Collapse groups LAST, because we've created groups. If done before # moveAttributesToParentGroup, empty <g>'s may remain. if options.group_collapse: while removeNestedGroups(doc.documentElement) > 0: pass # remove unnecessary closing point of polygons and scour points for polygon in doc.documentElement.getElementsByTagName('polygon') : cleanPolygon(polygon, options) # scour points of polyline for polyline in doc.documentElement.getElementsByTagName('polyline') : cleanPolyline(polyline, options) # clean path data for elem in doc.documentElement.getElementsByTagName('path') : if elem.getAttribute('d') == '': elem.parentNode.removeChild(elem) else: cleanPath(elem, options) # shorten ID names as much as possible if options.shorten_ids: numBytesSavedInIDs += shortenIDs(doc, unprotected_ids(doc, options)) # scour lengths (including coordinates) for type in ['svg', 'image', 'rect', 'circle', 'ellipse', 'line', 'linearGradient', 'radialGradient', 'stop', 'filter']: for elem in doc.getElementsByTagName(type): for attr in ['x', 'y', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry', 'x1', 'y1', 'x2', 'y2', 'fx', 'fy', 'offset']: if elem.getAttribute(attr) != '': elem.setAttribute(attr, scourLength(elem.getAttribute(attr))) # more length scouring in this function numBytesSavedInLengths = reducePrecision(doc.documentElement) # remove default values of attributes numAttrsRemoved += removeDefaultAttributeValues(doc.documentElement, options) # reduce the length of transformation attributes numBytesSavedInTransforms = optimizeTransforms(doc.documentElement, options) # convert rasters references to base64-encoded strings if options.embed_rasters: for elem in doc.documentElement.getElementsByTagName('image') : embedRasters(elem, options) # properly size the SVG document (ideally width/height should be 100% with a viewBox) if options.enable_viewboxing: properlySizeDoc(doc.documentElement, options) # output the document as a pretty string with a single space for indent # NOTE: removed pretty printing because of this problem: # http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/ # rolled our own serialize function here to save on space, put id first, customize indentation, etc # out_string = doc.documentElement.toprettyxml(' ') out_string = serializeXML(doc.documentElement, options) + '\n' # now strip out empty lines lines = [] # Get rid of empty lines for line in out_string.splitlines(True): if line.strip(): lines.append(line) # return the string with its XML prolog and surrounding comments if options.strip_xml_prolog == False: total_output = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' else: total_output = "" for child in doc.childNodes: if child.nodeType == 1: total_output += "".join(lines) else: # doctypes, entities, comments total_output += child.toxml() + '\n' return total_output # used mostly by unit tests # input is a filename # returns the minidom doc representation of the SVG def scourXmlFile(filename, options=None): in_string = open(filename).read() out_string = scourString(in_string, options) return xml.dom.minidom.parseString(out_string.encode('utf-8')) # GZ: Seems most other commandline tools don't do this, is it really wanted? class HeaderedFormatter(optparse.IndentedHelpFormatter): """ Show application name, version number, and copyright statement above usage information. """ def format_usage(self, usage): return "%s %s\n%s\n%s" % (APP, VER, COPYRIGHT, optparse.IndentedHelpFormatter.format_usage(self, usage)) # GZ: would prefer this to be in a function or class scope, but tests etc need # access to the defaults anyway _options_parser = optparse.OptionParser( usage="%prog [-i input.svg] [-o output.svg] [OPTIONS]", description=("If the input/output files are specified with a svgz" " extension, then compressed SVG is assumed. If the input file is not" " specified, stdin is used. If the output file is not specified, " " stdout is used."), formatter=HeaderedFormatter(max_help_position=30), version=VER) _options_parser.add_option("--disable-simplify-colors", action="store_false", dest="simple_colors", default=True, help="won't convert all colors to #RRGGBB format") _options_parser.add_option("--disable-style-to-xml", action="store_false", dest="style_to_xml", default=True, help="won't convert styles into XML attributes") _options_parser.add_option("--disable-group-collapsing", action="store_false", dest="group_collapse", default=True, help="won't collapse <g> elements") _options_parser.add_option("--create-groups", action="store_true", dest="group_create", default=False, help="create <g> elements for runs of elements with identical attributes") _options_parser.add_option("--enable-id-stripping", action="store_true", dest="strip_ids", default=False, help="remove all un-referenced ID attributes") _options_parser.add_option("--enable-comment-stripping", action="store_true", dest="strip_comments", default=False, help="remove all <!-- --> comments") _options_parser.add_option("--shorten-ids", action="store_true", dest="shorten_ids", default=False, help="shorten all ID attributes to the least number of letters possible") _options_parser.add_option("--disable-embed-rasters", action="store_false", dest="embed_rasters", default=True, help="won't embed rasters as base64-encoded data") _options_parser.add_option("--keep-editor-data", action="store_true", dest="keep_editor_data", default=False, help="won't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes") _options_parser.add_option("--remove-metadata", action="store_true", dest="remove_metadata", default=False, help="remove <metadata> elements (which may contain license metadata etc.)") _options_parser.add_option("--renderer-workaround", action="store_true", dest="renderer_workaround", default=True, help="work around various renderer bugs (currently only librsvg) (default)") _options_parser.add_option("--no-renderer-workaround", action="store_false", dest="renderer_workaround", default=True, help="do not work around various renderer bugs (currently only librsvg)") _options_parser.add_option("--strip-xml-prolog", action="store_true", dest="strip_xml_prolog", default=False, help="won't output the <?xml ?> prolog") _options_parser.add_option("--enable-viewboxing", action="store_true", dest="enable_viewboxing", default=False, help="changes document width/height to 100%/100% and creates viewbox coordinates") # GZ: this is confusing, most people will be thinking in terms of # decimal places, which is not what decimal precision is doing _options_parser.add_option("-p", "--set-precision", action="store", type=int, dest="digits", default=5, help="set number of significant digits (default: %default)") _options_parser.add_option("-i", action="store", dest="infilename", help=optparse.SUPPRESS_HELP) _options_parser.add_option("-o", action="store", dest="outfilename", help=optparse.SUPPRESS_HELP) _options_parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False, help="suppress non-error output") _options_parser.add_option("--indent", action="store", type="string", dest="indent_type", default="space", help="indentation of the output: none, space, tab (default: %default)") _options_parser.add_option("--protect-ids-noninkscape", action="store_true", dest="protect_ids_noninkscape", default=False, help="Don't change IDs not ending with a digit") _options_parser.add_option("--protect-ids-list", action="store", type="string", dest="protect_ids_list", default=None, help="Don't change IDs given in a comma-separated list") _options_parser.add_option("--protect-ids-prefix", action="store", type="string", dest="protect_ids_prefix", default=None, help="Don't change IDs starting with the given prefix") def maybe_gziped_file(filename, mode="r"): if os.path.splitext(filename)[1].lower() in (".svgz", ".gz"): import gzip return gzip.GzipFile(filename, mode) return file(filename, mode) def parse_args(args=None): options, rargs = _options_parser.parse_args(args) if rargs: _options_parser.error("Additional arguments not handled: %r, see --help" % rargs) if options.digits < 0: _options_parser.error("Can't have negative significant digits, see --help") if not options.indent_type in ["tab", "space", "none"]: _options_parser.error("Invalid value for --indent, see --help") if options.infilename and options.outfilename and options.infilename == options.outfilename: _options_parser.error("Input filename is the same as output filename") if options.infilename: infile = maybe_gziped_file(options.infilename) # GZ: could catch a raised IOError here and report else: # GZ: could sniff for gzip compression here infile = sys.stdin if options.outfilename: outfile = maybe_gziped_file(options.outfilename, "wb") else: outfile = sys.stdout return options, [infile, outfile] def getReport(): return ' Number of elements removed: ' + str(numElemsRemoved) + os.linesep + \ ' Number of attributes removed: ' + str(numAttrsRemoved) + os.linesep + \ ' Number of unreferenced id attributes removed: ' + str(numIDsRemoved) + os.linesep + \ ' Number of style properties fixed: ' + str(numStylePropsFixed) + os.linesep + \ ' Number of raster images embedded inline: ' + str(numRastersEmbedded) + os.linesep + \ ' Number of path segments reduced/removed: ' + str(numPathSegmentsReduced) + os.linesep + \ ' Number of bytes saved in path data: ' + str(numBytesSavedInPathData) + os.linesep + \ ' Number of bytes saved in colors: ' + str(numBytesSavedInColors) + os.linesep + \ ' Number of points removed from polygons: ' + str(numPointsRemovedFromPolygon) + os.linesep + \ ' Number of bytes saved in comments: ' + str(numCommentBytes) + os.linesep + \ ' Number of bytes saved in id attributes: ' + str(numBytesSavedInIDs) + os.linesep + \ ' Number of bytes saved in lengths: ' + str(numBytesSavedInLengths) + os.linesep + \ ' Number of bytes saved in transformations: ' + str(numBytesSavedInTransforms) if __name__ == '__main__': if sys.platform == "win32": from time import clock as get_tick else: # GZ: is this different from time.time() in any way? def get_tick(): return os.times()[0] start = get_tick() options, (input, output) = parse_args() if not options.quiet: print >>sys.stderr, "%s %s\n%s" % (APP, VER, COPYRIGHT) # do the work in_string = input.read() out_string = scourString(in_string, options).encode("UTF-8") output.write(out_string) # Close input and output files input.close() output.close() end = get_tick() # GZ: not using globals would be good too if not options.quiet: print >>sys.stderr, ' File:', input.name, \ os.linesep + ' Time taken:', str(end-start) + 's' + os.linesep, \ getReport() oldsize = len(in_string) newsize = len(out_string) sizediff = (newsize / oldsize) * 100 print >>sys.stderr, ' Original file size:', oldsize, 'bytes;', \ 'new file size:', newsize, 'bytes (' + str(sizediff)[:5] + '%)'
gpl-2.0
mastizada/kuma
vendor/packages/sqlalchemy/test/sql/test_constraints.py
6
15445
from sqlalchemy.test.testing import assert_raises, assert_raises_message from sqlalchemy import * from sqlalchemy import exc, schema from sqlalchemy.test import * from sqlalchemy.test import config, engines from sqlalchemy.engine import ddl from sqlalchemy.test.testing import eq_ from sqlalchemy.test.assertsql import AllOf, RegexSQL, ExactSQL, CompiledSQL from sqlalchemy.dialects.postgresql import base as postgresql class ConstraintTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): def setup(self): global metadata metadata = MetaData(testing.db) def teardown(self): metadata.drop_all() def test_constraint(self): employees = Table('employees', metadata, Column('id', Integer), Column('soc', String(40)), Column('name', String(30)), PrimaryKeyConstraint('id', 'soc') ) elements = Table('elements', metadata, Column('id', Integer), Column('stuff', String(30)), Column('emp_id', Integer), Column('emp_soc', String(40)), PrimaryKeyConstraint('id', name='elements_primkey'), ForeignKeyConstraint(['emp_id', 'emp_soc'], ['employees.id', 'employees.soc']) ) metadata.create_all() def test_double_fk_usage_raises(self): f = ForeignKey('b.id') Column('x', Integer, f) assert_raises(exc.InvalidRequestError, Column, "y", Integer, f) def test_circular_constraint(self): a = Table("a", metadata, Column('id', Integer, primary_key=True), Column('bid', Integer), ForeignKeyConstraint(["bid"], ["b.id"], name="afk") ) b = Table("b", metadata, Column('id', Integer, primary_key=True), Column("aid", Integer), ForeignKeyConstraint(["aid"], ["a.id"], use_alter=True, name="bfk") ) metadata.create_all() def test_circular_constraint_2(self): a = Table("a", metadata, Column('id', Integer, primary_key=True), Column('bid', Integer, ForeignKey("b.id")), ) b = Table("b", metadata, Column('id', Integer, primary_key=True), Column("aid", Integer, ForeignKey("a.id", use_alter=True, name="bfk")), ) metadata.create_all() @testing.fails_on('mysql', 'FIXME: unknown') def test_check_constraint(self): foo = Table('foo', metadata, Column('id', Integer, primary_key=True), Column('x', Integer), Column('y', Integer), CheckConstraint('x>y')) bar = Table('bar', metadata, Column('id', Integer, primary_key=True), Column('x', Integer, CheckConstraint('x>7')), Column('z', Integer) ) metadata.create_all() foo.insert().execute(id=1,x=9,y=5) assert_raises(exc.SQLError, foo.insert().execute, id=2,x=5,y=9) bar.insert().execute(id=1,x=10) assert_raises(exc.SQLError, bar.insert().execute, id=2,x=5) def test_unique_constraint(self): foo = Table('foo', metadata, Column('id', Integer, primary_key=True), Column('value', String(30), unique=True)) bar = Table('bar', metadata, Column('id', Integer, primary_key=True), Column('value', String(30)), Column('value2', String(30)), UniqueConstraint('value', 'value2', name='uix1') ) metadata.create_all() foo.insert().execute(id=1, value='value1') foo.insert().execute(id=2, value='value2') bar.insert().execute(id=1, value='a', value2='a') bar.insert().execute(id=2, value='a', value2='b') assert_raises(exc.SQLError, foo.insert().execute, id=3, value='value1') assert_raises(exc.SQLError, bar.insert().execute, id=3, value='a', value2='b') def test_index_create(self): employees = Table('employees', metadata, Column('id', Integer, primary_key=True), Column('first_name', String(30)), Column('last_name', String(30)), Column('email_address', String(30))) employees.create() i = Index('employee_name_index', employees.c.last_name, employees.c.first_name) i.create() assert i in employees.indexes i2 = Index('employee_email_index', employees.c.email_address, unique=True) i2.create() assert i2 in employees.indexes def test_index_create_camelcase(self): """test that mixed-case index identifiers are legal""" employees = Table('companyEmployees', metadata, Column('id', Integer, primary_key=True), Column('firstName', String(30)), Column('lastName', String(30)), Column('emailAddress', String(30))) employees.create() i = Index('employeeNameIndex', employees.c.lastName, employees.c.firstName) i.create() i = Index('employeeEmailIndex', employees.c.emailAddress, unique=True) i.create() # Check that the table is useable. This is mostly for pg, # which can be somewhat sticky with mixed-case identifiers employees.insert().execute(firstName='Joe', lastName='Smith', id=0) ss = employees.select().execute().fetchall() assert ss[0].firstName == 'Joe' assert ss[0].lastName == 'Smith' def test_index_create_inline(self): """Test indexes defined with tables""" events = Table('events', metadata, Column('id', Integer, primary_key=True), Column('name', String(30), index=True, unique=True), Column('location', String(30), index=True), Column('sport', String(30)), Column('announcer', String(30)), Column('winner', String(30))) Index('sport_announcer', events.c.sport, events.c.announcer, unique=True) Index('idx_winners', events.c.winner) eq_( set([ ix.name for ix in events.indexes ]), set(['ix_events_name', 'ix_events_location', 'sport_announcer', 'idx_winners']) ) self.assert_sql_execution( testing.db, lambda: events.create(testing.db), RegexSQL("^CREATE TABLE events"), AllOf( ExactSQL('CREATE UNIQUE INDEX ix_events_name ON events (name)'), ExactSQL('CREATE INDEX ix_events_location ON events (location)'), ExactSQL('CREATE UNIQUE INDEX sport_announcer ON events (sport, announcer)'), ExactSQL('CREATE INDEX idx_winners ON events (winner)') ) ) # verify that the table is functional events.insert().execute(id=1, name='hockey finals', location='rink', sport='hockey', announcer='some canadian', winner='sweden') ss = events.select().execute().fetchall() def test_too_long_idx_name(self): dialect = testing.db.dialect.__class__() for max_ident, max_index in [(22, None), (256, 22)]: dialect.max_identifier_length = max_ident dialect.max_index_name_length = max_index for tname, cname, exp in [ ('sometable', 'this_name_is_too_long', 'ix_sometable_t_09aa'), ('sometable', 'this_name_alsois_long', 'ix_sometable_t_3cf1'), ]: t1 = Table(tname, MetaData(), Column(cname, Integer, index=True), ) ix1 = list(t1.indexes)[0] self.assert_compile( schema.CreateIndex(ix1), "CREATE INDEX %s " "ON %s (%s)" % (exp, tname, cname), dialect=dialect ) dialect.max_identifier_length = 22 dialect.max_index_name_length = None t1 = Table('t', MetaData(), Column('c', Integer)) assert_raises( exc.IdentifierError, schema.CreateIndex(Index( "this_other_name_is_too_long_for_what_were_doing", t1.c.c)).compile, dialect=dialect ) class ConstraintCompilationTest(TestBase, AssertsCompiledSQL): def _test_deferrable(self, constraint_factory): t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer), constraint_factory(deferrable=True)) sql = str(schema.CreateTable(t).compile(bind=testing.db)) assert 'DEFERRABLE' in sql, sql assert 'NOT DEFERRABLE' not in sql, sql t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer), constraint_factory(deferrable=False)) sql = str(schema.CreateTable(t).compile(bind=testing.db)) assert 'NOT DEFERRABLE' in sql t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer), constraint_factory(deferrable=True, initially='IMMEDIATE')) sql = str(schema.CreateTable(t).compile(bind=testing.db)) assert 'NOT DEFERRABLE' not in sql assert 'INITIALLY IMMEDIATE' in sql t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer), constraint_factory(deferrable=True, initially='DEFERRED')) sql = str(schema.CreateTable(t).compile(bind=testing.db)) assert 'NOT DEFERRABLE' not in sql assert 'INITIALLY DEFERRED' in sql def test_deferrable_pk(self): factory = lambda **kw: PrimaryKeyConstraint('a', **kw) self._test_deferrable(factory) def test_deferrable_table_fk(self): factory = lambda **kw: ForeignKeyConstraint(['b'], ['tbl.a'], **kw) self._test_deferrable(factory) def test_deferrable_column_fk(self): t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer, ForeignKey('tbl.a', deferrable=True, initially='DEFERRED'))) self.assert_compile( schema.CreateTable(t), "CREATE TABLE tbl (a INTEGER, b INTEGER, FOREIGN KEY(b) REFERENCES tbl (a) DEFERRABLE INITIALLY DEFERRED)", ) def test_deferrable_unique(self): factory = lambda **kw: UniqueConstraint('b', **kw) self._test_deferrable(factory) def test_deferrable_table_check(self): factory = lambda **kw: CheckConstraint('a < b', **kw) self._test_deferrable(factory) def test_deferrable_column_check(self): t = Table('tbl', MetaData(), Column('a', Integer), Column('b', Integer, CheckConstraint('a < b', deferrable=True, initially='DEFERRED'))) self.assert_compile( schema.CreateTable(t), "CREATE TABLE tbl (a INTEGER, b INTEGER CHECK (a < b) DEFERRABLE INITIALLY DEFERRED)" ) def test_use_alter(self): m = MetaData() t = Table('t', m, Column('a', Integer), ) t2 = Table('t2', m, Column('a', Integer, ForeignKey('t.a', use_alter=True, name='fk_ta')), Column('b', Integer, ForeignKey('t.a', name='fk_tb')), # to ensure create ordering ... ) e = engines.mock_engine(dialect_name='postgresql') m.create_all(e) m.drop_all(e) e.assert_sql([ 'CREATE TABLE t (a INTEGER)', 'CREATE TABLE t2 (a INTEGER, b INTEGER, CONSTRAINT fk_tb FOREIGN KEY(b) REFERENCES t (a))', 'ALTER TABLE t2 ADD CONSTRAINT fk_ta FOREIGN KEY(a) REFERENCES t (a)', 'ALTER TABLE t2 DROP CONSTRAINT fk_ta', 'DROP TABLE t2', 'DROP TABLE t' ]) def test_add_drop_constraint(self): m = MetaData() t = Table('tbl', m, Column('a', Integer), Column('b', Integer) ) t2 = Table('t2', m, Column('a', Integer), Column('b', Integer) ) constraint = CheckConstraint('a < b',name="my_test_constraint", deferrable=True,initially='DEFERRED', table=t) # before we create an AddConstraint, # the CONSTRAINT comes out inline self.assert_compile( schema.CreateTable(t), "CREATE TABLE tbl (" "a INTEGER, " "b INTEGER, " "CONSTRAINT my_test_constraint CHECK (a < b) DEFERRABLE INITIALLY DEFERRED" ")" ) self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE tbl ADD CONSTRAINT my_test_constraint " "CHECK (a < b) DEFERRABLE INITIALLY DEFERRED" ) # once we make an AddConstraint, # inline compilation of the CONSTRAINT # is disabled self.assert_compile( schema.CreateTable(t), "CREATE TABLE tbl (" "a INTEGER, " "b INTEGER" ")" ) self.assert_compile( schema.DropConstraint(constraint), "ALTER TABLE tbl DROP CONSTRAINT my_test_constraint" ) self.assert_compile( schema.DropConstraint(constraint, cascade=True), "ALTER TABLE tbl DROP CONSTRAINT my_test_constraint CASCADE" ) constraint = ForeignKeyConstraint(["b"], ["t2.a"]) t.append_constraint(constraint) self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE tbl ADD FOREIGN KEY(b) REFERENCES t2 (a)" ) constraint = ForeignKeyConstraint([t.c.a], [t2.c.b]) t.append_constraint(constraint) self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE tbl ADD FOREIGN KEY(a) REFERENCES t2 (b)" ) constraint = UniqueConstraint("a", "b", name="uq_cst") t2.append_constraint(constraint) self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE t2 ADD CONSTRAINT uq_cst UNIQUE (a, b)" ) constraint = UniqueConstraint(t2.c.a, t2.c.b, name="uq_cs2") self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE t2 ADD CONSTRAINT uq_cs2 UNIQUE (a, b)" ) assert t.c.a.primary_key is False constraint = PrimaryKeyConstraint(t.c.a) assert t.c.a.primary_key is True self.assert_compile( schema.AddConstraint(constraint), "ALTER TABLE tbl ADD PRIMARY KEY (a)" )
mpl-2.0
klmitch/pbr
pbr/hooks/__init__.py
101
1086
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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. from pbr.hooks import backwards from pbr.hooks import commands from pbr.hooks import files from pbr.hooks import metadata def setup_hook(config): """Filter config parsed from a setup.cfg to inject our defaults.""" metadata_config = metadata.MetadataConfig(config) metadata_config.run() backwards.BackwardsCompatConfig(config).run() commands.CommandsConfig(config).run() files.FilesConfig(config, metadata_config.get_name()).run()
apache-2.0
efortuna/AndroidSDKClone
ndk/prebuilt/linux-x86_64/lib/python2.7/textwrap.py
110
17037
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> __revision__ = "$Id$" import string, re try: _unicode = unicode except NameError: # If Python is built without Unicode support, the unicode type # will not exist. Fake one. class _unicode(object): pass # Do the right thing with boolean values for all known Python versions # (so this module can be copied to projects that don't depend on Python # 2.3, e.g. Optik and Docutils) by uncommenting the block of code below. #try: # True, False #except NameError: # (True, False) = (1, 0) __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. break_on_hyphens (default: true) Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words. drop_whitespace (default: true) Drop leading and trailing whitespace from lines. """ whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile( r'(\s+|' # any whitespace r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(\s+)') # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[%s]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote r'\Z' # end of chunk % string.lowercase) def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens # recompile the regexes for Unicode mode -- done in this clumsy way for # backwards compatibility because it's rather common to monkey-patch # the TextWrapper class' wordsep_re attribute. self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U) self.wordsep_simple_re_uni = re.compile( self.wordsep_simple_re.pattern, re.U) # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs() if self.replace_whitespace: if isinstance(text, str): text = text.translate(self.whitespace_trans) elif isinstance(text, _unicode): text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' if break_on_hyphens is True, or in: 'Look,', ' ', 'goof-ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', option!' otherwise. """ if isinstance(text, _unicode): if self.break_on_hyphens: pat = self.wordsep_re_uni else: pat = self.wordsep_simple_re_uni else: if self.break_on_hyphens: pat = self.wordsep_re else: pat = self.wordsep_simple_re chunks = pat.split(text) chunks = filter(None, chunks) # remove empty chunks return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ # Figure out when indent is larger than the specified width, and make # sure at least one character is stripped off on every pass if width < 1: space_left = 1 else: space_left = width - cur_len # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Current line and previous winner have no common whitespace: # there is no margin. else: margin = "" break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print dedent("Hello there.\n This is indented.")
apache-2.0
Xdynix/PixivPixie
bundle_cli.py
1
2691
import os import subprocess import sys from pixiv_pixie.cli import main as cli_main, NAME BINARY_PATH = 'lib' DATA_PATH = 'data' def is_packaged(): # Return true if executing from packaged file return hasattr(sys, 'frozen') def get_path(path, package_prefix=DATA_PATH): if os.path.isabs(path) or not is_packaged(): return path else: return os.path.join( sys.prefix, os.path.join(package_prefix, path) ) def build( script, name=None, one_file=False, no_console=False, icon=None, binary_path=BINARY_PATH, addition_binary=None, data_path=DATA_PATH, addition_data=None, hidden_import=None, distpath=None, workpath=None, specpath=None, addition_args=None, ): args = [] if name is not None: args.extend(('-n', name)) if one_file: args.append('-F') if no_console: args.append('-w') if icon is not None: args.extend(('-i', icon)) if addition_args is None: addition_args = [] def add_resource(add_type, path, resources): for resource in resources: args.append('--add-{}'.format(add_type)) if isinstance(resource, tuple) or isinstance(resource, list): src = resource[0] dest = resource[1] args.append(src + os.path.pathsep + os.path.join(path, dest)) else: args.append( resource + os.path.pathsep + os.path.join(path, resource), ) if addition_binary is not None: add_resource( add_type='binary', path=binary_path, resources=addition_binary, ) if addition_data is not None: add_resource( add_type='data', path=data_path, resources=addition_data, ) if hidden_import is not None: for m in hidden_import: args.extend(('--hidden-import', m)) if distpath is not None: args.extend(('--distpath', distpath)) if workpath is not None: args.extend(('--workpath', workpath)) if specpath is not None: args.extend(('--specpath', specpath)) subprocess.call(['pyinstaller'] + args + addition_args + [script]) def main(): if not is_packaged(): build( __file__, name=NAME, one_file=True, addition_binary=[ ('freeimage-3.15.1-win64.dll', '') ], addition_args=[ '-y', '--clean', ], ) else: cli_main() if __name__ == '__main__': main()
apache-2.0
krichter722/binutils-gdb
gdb/testsuite/gdb.perf/lib/perftest/perftest.py
46
2768
# Copyright (C) 2013-2015 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import testresult import reporter from measure import Measure from measure import MeasurementCpuTime from measure import MeasurementWallTime from measure import MeasurementVmSize class TestCase(object): """Base class of all performance testing cases. Each sub-class should override methods execute_test, in which several GDB operations are performed and measured by attribute measure. Sub-class can also override method warm_up optionally if the test case needs warm up. """ def __init__(self, name, measure): """Constructor of TestCase. Construct an instance of TestCase with a name and a measure which is to measure the test by several different measurements. """ self.name = name self.measure = measure def execute_test(self): """Abstract method to do the actual tests.""" raise NotImplementedError("Abstract Method.") def warm_up(self): """Do some operations to warm up the environment.""" pass def run(self, warm_up=True, append=True): """Run this test case. It is a template method to invoke method warm_up, execute_test, and finally report the measured results. If parameter warm_up is True, run method warm_up. If parameter append is True, the test result will be appended instead of overwritten. """ if warm_up: self.warm_up() self.execute_test() self.measure.report(reporter.TextReporter(append), self.name) class TestCaseWithBasicMeasurements(TestCase): """Test case measuring CPU time, wall time and memory usage.""" def __init__(self, name): result_factory = testresult.SingleStatisticResultFactory() measurements = [MeasurementCpuTime(result_factory.create_result()), MeasurementWallTime(result_factory.create_result()), MeasurementVmSize(result_factory.create_result())] super (TestCaseWithBasicMeasurements, self).__init__ (name, Measure(measurements))
gpl-2.0
frnsys/broca
tests/test_pipeline.py
2
14889
import unittest from broca import Pipe, Pipeline from broca.preprocess import BasicCleaner, HTMLCleaner from broca.tokenize.keyword import OverkillTokenizer, RAKETokenizer class PipelineTests(unittest.TestCase): def setUp(self): self.docs = [ '''In the Before-Time, there was only the Vast Empty. No space nor time did continue, all the dimensions were held in their nonexistence. The Great Nicolas Cage thus was sprung into existence through His very will, and saw all nothing, and was displeased.''', '''As a Galactic Ocean floated by, Nicolas Cage reached out His hand and grasped it. He looked at it with His glorious eyes and instantaneously began to stretch it and bend it. He found amusement in the handling of these Sacred Galactic Seas. And so, Cage reached out His mighty hand and took another Ocean into the sacred warmth of His mighty palms.''' ] def test_pipeline(self): expected = [ ['time', 'vast', 'empty', 'space', 'time', 'continue', 'dimension', 'hold', 'nonexistence', 'great', 'spring', 'displeased', 'nicolas cage', 'existence'], ['galactic', 'ocean', 'float', 'hand', 'grasp', 'look', 'glorious', 'eye', 'instantaneously', 'begin', 'stretch', 'bend', 'find', 'amusement', 'handling', 'sacred', 'galactic', 'sea', 'mighty', 'hand', 'ocean', 'sacred', 'warmth', 'mighty', 'palm', 'cage reach', 'nicolas cage', 'reach'] ] pipeline = Pipeline(BasicCleaner(), OverkillTokenizer(min_count=1, threshold=0.1), refresh=True) output = pipeline(self.docs) for o, e in zip(output, expected): self.assertEqual(set(o), set(e)) def test_incompatible_pipeline(self): self.assertRaises(Exception, Pipeline, OverkillTokenizer(), BasicCleaner(), refresh=True) def test_multi_pipeline(self): pipeline = Pipeline( BasicCleaner(), [ OverkillTokenizer(min_count=1, threshold=0.1), RAKETokenizer() ], refresh=True ) expected = [ [ ['vast', 'empty', 'space', 'time', 'continue', 'dimension', 'hold', 'nonexistence', 'great', 'spring', 'displeased', 'nicolas cage', 'existence'], ['galactic', 'ocean', 'float', 'hand', 'grasp', 'look', 'glorious', 'eye', 'instantaneously', 'begin', 'stretch', 'bend', 'find', 'amusement', 'handling', 'sacred', 'galactic', 'sea', 'mighty', 'hand', 'ocean', 'sacred', 'warmth', 'mighty', 'palm', 'cage reach', 'nicolas cage', 'reach'] ], [ ['great nicolas cage', 'vast empty', 'sprung', 'nonexistence', 'dimensions', 'held', 'existence', 'displeased', 'continue', 'time', 'space'], ['sacred galactic seas', 'galactic ocean floated', 'nicolas cage reached', 'cage reached', 'sacred warmth', 'glorious eyes', 'mighty palms', 'found amusement', 'instantaneously began', 'mighty hand', 'ocean', 'hand', 'looked', 'stretch', 'grasped', 'handling', 'bend'] ] ] outputs = pipeline(self.docs) for i, output in enumerate(outputs): for o, e in zip(output, expected[i]): self.assertEqual(set(o), set(e)) def test_nested_pipeline(self): docs = ['<div>{}</div>'.format(d) for d in self.docs] expected = [ ['time', 'vast', 'empty', 'space', 'time', 'continue', 'dimension', 'hold', 'nonexistence', 'great', 'spring', 'displeased', 'nicolas cage', 'existence'], ['galactic', 'ocean', 'float', 'hand', 'grasp', 'look', 'glorious', 'eye', 'instantaneously', 'begin', 'stretch', 'bend', 'find', 'amusement', 'handling', 'sacred', 'galactic', 'sea', 'mighty', 'hand', 'ocean', 'sacred', 'warmth', 'mighty', 'palm', 'cage reach', 'nicolas cage', 'reach'] ] nested_pipeline = Pipeline(HTMLCleaner(), BasicCleaner(), refresh=True) pipeline = Pipeline(nested_pipeline, OverkillTokenizer(), refresh=True) output = pipeline(docs) for o, e in zip(output, expected): self.assertEqual(set(o), set(e)) def test_nested_multipipeline(self): docs = ['<div>{}</div>'.format(d) for d in self.docs] expected = [ [ ['vast', 'empty', 'space', 'time', 'continue', 'dimension', 'hold', 'nonexistence', 'great', 'spring', 'displeased', 'nicolas cage', 'existence'], ['galactic', 'ocean', 'float', 'hand', 'grasp', 'look', 'glorious', 'eye', 'instantaneously', 'begin', 'stretch', 'bend', 'find', 'amusement', 'handling', 'sacred', 'galactic', 'sea', 'mighty', 'hand', 'ocean', 'sacred', 'warmth', 'mighty', 'palm', 'cage reach', 'nicolas cage', 'reach'] ], [ ['great nicolas cage', 'vast empty', 'sprung', 'nonexistence', 'dimensions', 'held', 'existence', 'displeased', 'continue', 'time', 'space'], ['sacred galactic seas', 'galactic ocean floated', 'nicolas cage reached', 'cage reached', 'sacred warmth', 'glorious eyes', 'mighty palms', 'found amusement', 'instantaneously began', 'mighty hand', 'ocean', 'hand', 'looked', 'stretch', 'grasped', 'handling', 'bend'] ] ] nested_multipipeline = Pipeline( BasicCleaner(), [ OverkillTokenizer(min_count=1, threshold=0.1), RAKETokenizer() ], refresh=True ) pipeline = Pipeline(HTMLCleaner(), nested_multipipeline, refresh=True) outputs = pipeline(docs) for i, output in enumerate(outputs): for o, e in zip(output, expected[i]): self.assertEqual(set(o), set(e)) def test_cryo_diff_pipe_init(self): pipeline = Pipeline( BasicCleaner(), ) output1 = pipeline(self.docs) pipeline = Pipeline( BasicCleaner(), ) output2 = pipeline(self.docs) self.assertEqual(output1, output2) # Make sure cryo picks up on differently initialized classes pipeline = Pipeline( BasicCleaner(lowercase=False), ) output3 = pipeline(self.docs) self.assertNotEqual(output1, output3) def test_dynamic_pipe_types(self): self.assertEqual(Pipe.type.foo, Pipe.type.foo) self.assertEqual(Pipe.type.bar, Pipe.type.bar) self.assertNotEqual(Pipe.type.foo, Pipe.type.bar) def test_valid_branching_pipeline_multiout_to_branches(self): class A(Pipe): input = Pipe.type.a output = (Pipe.type.b, Pipe.type.c, Pipe.type.d) class B(Pipe): input = Pipe.type.b output = Pipe.type.b_out class C(Pipe): input = Pipe.type.c output = Pipe.type.c_out class D(Pipe): input = Pipe.type.d output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.d_out) output = Pipe.type.e try: Pipeline( A(), (B(), C(), D()), E() ) except Exception: self.fail('Valid pipeline raised exception') def test_invalid_branching_pipeline_multiout_to_branches(self): class A(Pipe): input = Pipe.type.a # A outputs tuples output = (Pipe.type.b, Pipe.type.c, Pipe.type.d) class B(Pipe): input = Pipe.type.b output = Pipe.type.b_out class C(Pipe): input = Pipe.type.c output = Pipe.type.c_out class D(Pipe): input = Pipe.type.d output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.d_out) output = Pipe.type.e # Wrong branch size self.assertRaises(Exception, Pipeline, A(), (B(), C()), E()) # Wrong branch order self.assertRaises(Exception, Pipeline, A(), (C(), B(), D()), E()) # Wrong input type class D_(Pipe): input = Pipe.type.x output = Pipe.type.d_out self.assertRaises(Exception, Pipeline, A(), (B(), C(), D_()), E()) # Wrong output size class A_(Pipe): input = Pipe.type.a output = (Pipe.type.b, Pipe.type.c) self.assertRaises(Exception, Pipeline, A_(), (B(), C(), D()), E()) # Wrong output types class A_(Pipe): input = Pipe.type.a output = (Pipe.type.b, Pipe.type.c, Pipe.type.y) self.assertRaises(Exception, Pipeline, A_(), (B(), C(), D()), E()) def test_valid_branching_pipeline_branches_to_branches(self): class A(Pipe): input = Pipe.type.a # A outputs tuples output = (Pipe.type.b, Pipe.type.c, Pipe.type.d) class B(Pipe): input = Pipe.type.b output = Pipe.type.b class C(Pipe): input = Pipe.type.c output = Pipe.type.c class D(Pipe): input = Pipe.type.d output = Pipe.type.d class E(Pipe): input = (Pipe.type.b, Pipe.type.c, Pipe.type.d) output = Pipe.type.e try: Pipeline( A(), (B(), C(), D()), (B(), C(), D()), E() ) except Exception: self.fail('Valid pipeline raised exception') def test_invalid_branching_pipeline_branches_to_branches(self): class A(Pipe): input = Pipe.type.a # A outputs tuples output = (Pipe.type.b, Pipe.type.c, Pipe.type.d) class B(Pipe): input = Pipe.type.b output = Pipe.type.x class C(Pipe): input = Pipe.type.c output = Pipe.type.x class D(Pipe): input = Pipe.type.d output = Pipe.type.x class E(Pipe): input = (Pipe.type.b, Pipe.type.c, Pipe.type.d) output = Pipe.type.e self.assertRaises(Exception, Pipeline, A(), (B(), C(), D()), (B(), C(), D()), E()) def test_valid_branching_pipeline_one_output_to_branches(self): class A(Pipe): input = Pipe.type.a # A does not output tuples output = Pipe.type.x class B(Pipe): input = Pipe.type.x output = Pipe.type.b_out class C(Pipe): input = Pipe.type.x output = Pipe.type.c_out class D(Pipe): input = Pipe.type.x output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.d_out) output = Pipe.type.e try: Pipeline( A(), (B(), C(), D()), E() ) except Exception: self.fail('Valid pipeline raised exception') def test_invalid_branching_pipeline_one_output_to_branches(self): class A(Pipe): input = Pipe.type.a # A does not output tuples output = Pipe.type.x class B(Pipe): input = Pipe.type.x output = Pipe.type.b_out class C(Pipe): input = Pipe.type.x output = Pipe.type.c_out class D(Pipe): input = Pipe.type.y output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.d_out) output = Pipe.type.e self.assertRaises(Exception, Pipeline, A(), (B(), C(), D()), E()) def test_invalid_branching_pipeline_reduce_pipe(self): class A(Pipe): input = Pipe.type.a # A does not output tuples output = Pipe.type.x class B(Pipe): input = Pipe.type.x output = Pipe.type.b_out class C(Pipe): input = Pipe.type.x output = Pipe.type.c_out class D(Pipe): input = Pipe.type.x output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.y) output = Pipe.type.e self.assertRaises(Exception, Pipeline, A(), (B(), C(), D()), E()) def test_valid_branching_pipeline_start_with_branches(self): class B(Pipe): input = Pipe.type.x output = Pipe.type.b_out class C(Pipe): input = Pipe.type.x output = Pipe.type.c_out class D(Pipe): input = Pipe.type.x output = Pipe.type.d_out class E(Pipe): input = (Pipe.type.b_out, Pipe.type.c_out, Pipe.type.d_out) output = Pipe.type.e try: Pipeline( (B(), C(), D()), E() ) except Exception: self.fail('Valid pipeline raised exception') def test_valid_branching_pipeline_end_with_branches(self): class A(Pipe): input = Pipe.type.a # A does not output tuples output = Pipe.type.x class B(Pipe): input = Pipe.type.x output = Pipe.type.b_out class C(Pipe): input = Pipe.type.x output = Pipe.type.c_out class D(Pipe): input = Pipe.type.x output = Pipe.type.d_out try: Pipeline( A(), (B(), C(), D()), ) except Exception: self.fail('Valid pipeline raised exception') def test_branching_pipeline(self): class A(Pipe): input = Pipe.type.vals output = Pipe.type.vals def __call__(self, vals): return [v+1 for v in vals] class B(Pipe): input = Pipe.type.vals output = Pipe.type.vals def __call__(self, vals): return [v+2 for v in vals] class C(Pipe): input = Pipe.type.vals output = Pipe.type.vals def __call__(self, vals): return [v+3 for v in vals] class D(Pipe): input = Pipe.type.vals output = Pipe.type.vals def __call__(self, vals): return [v+4 for v in vals] class E(Pipe): input = (Pipe.type.vals, Pipe.type.vals, Pipe.type.vals) output = Pipe.type.vals def __call__(self, vals1, vals2, vals3): return [sum([v1,v2,v3]) for v1,v2,v3 in zip(vals1,vals2,vals3)] p = Pipeline( A(), (B(), C(), D()), (B(), C(), D()), E() ) out = p([1,2,3,4]) self.assertEqual(out, [24,27,30,33])
mit
p0psicles/SickRage
lib/github/InputGitAuthor.py
47
2633
# -*- coding: utf-8 -*- # ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # # # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # # ############################################################################## import github.GithubObject class InputGitAuthor(object): """ """ def __init__(self, name, email, date=github.GithubObject.NotSet): """ :param name: string :param email: string :param date: string """ assert isinstance(name, (str, unicode)), name assert isinstance(email, (str, unicode)), email assert date is github.GithubObject.NotSet or isinstance(date, (str, unicode)), date # @todo Datetime? self.__name = name self.__email = email self.__date = date @property def _identity(self): identity = { "name": self.__name, "email": self.__email, } if self.__date is not github.GithubObject.NotSet: identity["date"] = self.__date return identity
gpl-3.0
ressu/SickGear
lib/requests/packages/chardet/big5freq.py
3133
82594
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Big5 frequency table # by Taiwan's Mandarin Promotion Council # <http://www.edu.tw:81/mandr/> # # 128 --> 0.42261 # 256 --> 0.57851 # 512 --> 0.74851 # 1024 --> 0.89384 # 2048 --> 0.97583 # # Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98 # Random Distribution Ration = 512/(5401-512)=0.105 # # Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75 #Char to FreqOrder table BIG5_TABLE_SIZE = 5376 Big5CharToFreqOrder = ( 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16 3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32 1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64 3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80 4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96 5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160 2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176 1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192 3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224 1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240 3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256 2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288 3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304 1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320 5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352 5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368 1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416 3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432 3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464 2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480 2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528 3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544 1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560 1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576 1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592 2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624 4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640 1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656 5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672 2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752 5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784 1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832 5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848 1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880 3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896 4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912 3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960 1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976 4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992 3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008 3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024 2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040 5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056 3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072 5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088 1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104 2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120 1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152 1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168 4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184 3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248 2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264 5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280 1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296 2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312 1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328 1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344 5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360 5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376 5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392 3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408 4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424 4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440 2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456 5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472 3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504 5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520 5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536 1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552 2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568 3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584 4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600 5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616 3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632 4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648 1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664 1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680 4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696 1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728 1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744 1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760 3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792 5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808 2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824 1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840 1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856 5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888 4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920 2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952 1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968 1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000 4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016 4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032 1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048 3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064 5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080 5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096 1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112 2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128 1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144 3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160 2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176 3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192 2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208 4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224 4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240 3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272 3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304 3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320 4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336 3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352 1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368 5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400 5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416 1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448 4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464 4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496 2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512 2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528 3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544 1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560 4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576 2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592 1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608 1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624 2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640 3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656 1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672 5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688 1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704 4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720 1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752 1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768 4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784 4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800 2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816 1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832 4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864 5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880 2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896 3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912 4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944 5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960 5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976 1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992 4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008 4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024 2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040 3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056 3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072 2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088 1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104 4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120 3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136 3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152 2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168 4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184 5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200 3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216 2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232 3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248 1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264 2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280 3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296 4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312 2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328 2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344 5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360 1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376 2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392 1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408 3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424 4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440 2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456 3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472 3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488 2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504 4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520 2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536 3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552 4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568 5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584 3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616 1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632 4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648 1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664 4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680 5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712 5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728 5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744 2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760 3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776 2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792 2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824 1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840 4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856 3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872 3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904 2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936 2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952 4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968 1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984 4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000 1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016 3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048 3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064 5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080 5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096 3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112 3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128 1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144 2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160 5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176 1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192 1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208 3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240 1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256 4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272 5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288 2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304 3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336 1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352 2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368 2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384 5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400 5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416 5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432 2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448 2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464 1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480 4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496 3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512 3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528 4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544 4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560 2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576 2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592 5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608 4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624 5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640 4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688 1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704 3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720 4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736 1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752 5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768 2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784 2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800 3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816 5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832 1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848 3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864 5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880 1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896 5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912 2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928 3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944 2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960 3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976 3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992 3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008 4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040 2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056 4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072 3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088 5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104 1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120 5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152 1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184 4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200 1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216 4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232 1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264 3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280 4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296 5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328 3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360 2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 #last 512 #Everything below is of no interest for detection purpose 2522,1613,4812,5799,3345,3945,2523,5800,4162,5801,1637,4163,2471,4813,3946,5802, # 5392 2500,3034,3800,5803,5804,2195,4814,5805,2163,5806,5807,5808,5809,5810,5811,5812, # 5408 5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828, # 5424 5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844, # 5440 5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860, # 5456 5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872,5873,5874,5875,5876, # 5472 5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888,5889,5890,5891,5892, # 5488 5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,5906,5907,5908, # 5504 5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,5921,5922,5923,5924, # 5520 5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5938,5939,5940, # 5536 5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952,5953,5954,5955,5956, # 5552 5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5970,5971,5972, # 5568 5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984,5985,5986,5987,5988, # 5584 5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004, # 5600 6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020, # 5616 6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036, # 5632 6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052, # 5648 6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068, # 5664 6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084, # 5680 6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100, # 5696 6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116, # 5712 6117,6118,6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,6132, # 5728 6133,6134,6135,6136,6137,6138,6139,6140,6141,6142,6143,6144,6145,6146,6147,6148, # 5744 6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,6164, # 5760 6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,6180, # 5776 6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196, # 5792 6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212, # 5808 6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,3670,6224,6225,6226,6227, # 5824 6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243, # 5840 6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259, # 5856 6260,6261,6262,6263,6264,6265,6266,6267,6268,6269,6270,6271,6272,6273,6274,6275, # 5872 6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,4815,6286,6287,6288,6289,6290, # 5888 6291,6292,4816,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305, # 5904 6306,6307,6308,6309,6310,6311,4817,4818,6312,6313,6314,6315,6316,6317,6318,4819, # 5920 6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334, # 5936 6335,6336,6337,4820,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349, # 5952 6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365, # 5968 6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381, # 5984 6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,6396,6397, # 6000 6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,3441,6411,6412, # 6016 6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,4440,6426,6427, # 6032 6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443, # 6048 6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,4821,6455,6456,6457,6458, # 6064 6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,6473,6474, # 6080 6475,6476,6477,3947,3948,6478,6479,6480,6481,3272,4441,6482,6483,6484,6485,4442, # 6096 6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,4822,6497,6498,6499,6500, # 6112 6501,6502,6503,6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516, # 6128 6517,6518,6519,6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532, # 6144 6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548, # 6160 6549,6550,6551,6552,6553,6554,6555,6556,2784,6557,4823,6558,6559,6560,6561,6562, # 6176 6563,6564,6565,6566,6567,6568,6569,3949,6570,6571,6572,4824,6573,6574,6575,6576, # 6192 6577,6578,6579,6580,6581,6582,6583,4825,6584,6585,6586,3950,2785,6587,6588,6589, # 6208 6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6602,6603,6604,6605, # 6224 6606,6607,6608,6609,6610,6611,6612,4826,6613,6614,6615,4827,6616,6617,6618,6619, # 6240 6620,6621,6622,6623,6624,6625,4164,6626,6627,6628,6629,6630,6631,6632,6633,6634, # 6256 3547,6635,4828,6636,6637,6638,6639,6640,6641,6642,3951,2984,6643,6644,6645,6646, # 6272 6647,6648,6649,4165,6650,4829,6651,6652,4830,6653,6654,6655,6656,6657,6658,6659, # 6288 6660,6661,6662,4831,6663,6664,6665,6666,6667,6668,6669,6670,6671,4166,6672,4832, # 6304 3952,6673,6674,6675,6676,4833,6677,6678,6679,4167,6680,6681,6682,3198,6683,6684, # 6320 6685,6686,6687,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,4834,6698,6699, # 6336 6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715, # 6352 6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731, # 6368 6732,6733,6734,4443,6735,6736,6737,6738,6739,6740,6741,6742,6743,6744,6745,4444, # 6384 6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761, # 6400 6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777, # 6416 6778,6779,6780,6781,4168,6782,6783,3442,6784,6785,6786,6787,6788,6789,6790,6791, # 6432 4169,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806, # 6448 6807,6808,6809,6810,6811,4835,6812,6813,6814,4445,6815,6816,4446,6817,6818,6819, # 6464 6820,6821,6822,6823,6824,6825,6826,6827,6828,6829,6830,6831,6832,6833,6834,6835, # 6480 3548,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,4836,6847,6848,6849, # 6496 6850,6851,6852,6853,6854,3953,6855,6856,6857,6858,6859,6860,6861,6862,6863,6864, # 6512 6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,3199,6878,6879, # 6528 6880,6881,6882,4447,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894, # 6544 6895,6896,6897,6898,6899,6900,6901,6902,6903,6904,4170,6905,6906,6907,6908,6909, # 6560 6910,6911,6912,6913,6914,6915,6916,6917,6918,6919,6920,6921,6922,6923,6924,6925, # 6576 6926,6927,4837,6928,6929,6930,6931,6932,6933,6934,6935,6936,3346,6937,6938,4838, # 6592 6939,6940,6941,4448,6942,6943,6944,6945,6946,4449,6947,6948,6949,6950,6951,6952, # 6608 6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,6967,6968, # 6624 6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6981,6982,6983,6984, # 6640 6985,6986,6987,6988,6989,6990,6991,6992,6993,6994,3671,6995,6996,6997,6998,4839, # 6656 6999,7000,7001,7002,3549,7003,7004,7005,7006,7007,7008,7009,7010,7011,7012,7013, # 6672 7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,7028,7029, # 6688 7030,4840,7031,7032,7033,7034,7035,7036,7037,7038,4841,7039,7040,7041,7042,7043, # 6704 7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059, # 6720 7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,2985,7071,7072,7073,7074, # 6736 7075,7076,7077,7078,7079,7080,4842,7081,7082,7083,7084,7085,7086,7087,7088,7089, # 6752 7090,7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105, # 6768 7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,4450,7119,7120, # 6784 7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136, # 6800 7137,7138,7139,7140,7141,7142,7143,4843,7144,7145,7146,7147,7148,7149,7150,7151, # 6816 7152,7153,7154,7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167, # 6832 7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183, # 6848 7184,7185,7186,7187,7188,4171,4172,7189,7190,7191,7192,7193,7194,7195,7196,7197, # 6864 7198,7199,7200,7201,7202,7203,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213, # 6880 7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229, # 6896 7230,7231,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245, # 6912 7246,7247,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261, # 6928 7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277, # 6944 7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293, # 6960 7294,7295,7296,4844,7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308, # 6976 7309,7310,7311,7312,7313,7314,7315,7316,4451,7317,7318,7319,7320,7321,7322,7323, # 6992 7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339, # 7008 7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,4173,7354, # 7024 7355,4845,7356,7357,7358,7359,7360,7361,7362,7363,7364,7365,7366,7367,7368,7369, # 7040 7370,7371,7372,7373,7374,7375,7376,7377,7378,7379,7380,7381,7382,7383,7384,7385, # 7056 7386,7387,7388,4846,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400, # 7072 7401,7402,7403,7404,7405,3672,7406,7407,7408,7409,7410,7411,7412,7413,7414,7415, # 7088 7416,7417,7418,7419,7420,7421,7422,7423,7424,7425,7426,7427,7428,7429,7430,7431, # 7104 7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447, # 7120 7448,7449,7450,7451,7452,7453,4452,7454,3200,7455,7456,7457,7458,7459,7460,7461, # 7136 7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,4847,7475,7476, # 7152 7477,3133,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491, # 7168 7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,3347,7503,7504,7505,7506, # 7184 7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,4848, # 7200 7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537, # 7216 7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,3801,4849,7550,7551, # 7232 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, # 7248 7568,7569,3035,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582, # 7264 7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598, # 7280 7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614, # 7296 7615,7616,4850,7617,7618,3802,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628, # 7312 7629,7630,7631,7632,4851,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643, # 7328 7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659, # 7344 7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,4453,7671,7672,7673,7674, # 7360 7675,7676,7677,7678,7679,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690, # 7376 7691,7692,7693,7694,7695,7696,7697,3443,7698,7699,7700,7701,7702,4454,7703,7704, # 7392 7705,7706,7707,7708,7709,7710,7711,7712,7713,2472,7714,7715,7716,7717,7718,7719, # 7408 7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,3954,7732,7733,7734, # 7424 7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750, # 7440 3134,7751,7752,4852,7753,7754,7755,4853,7756,7757,7758,7759,7760,4174,7761,7762, # 7456 7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778, # 7472 7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794, # 7488 7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,4854,7806,7807,7808,7809, # 7504 7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825, # 7520 4855,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7536 7841,7842,7843,7844,7845,7846,7847,3955,7848,7849,7850,7851,7852,7853,7854,7855, # 7552 7856,7857,7858,7859,7860,3444,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870, # 7568 7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886, # 7584 7887,7888,7889,7890,7891,4175,7892,7893,7894,7895,7896,4856,4857,7897,7898,7899, # 7600 7900,2598,7901,7902,7903,7904,7905,7906,7907,7908,4455,7909,7910,7911,7912,7913, # 7616 7914,3201,7915,7916,7917,7918,7919,7920,7921,4858,7922,7923,7924,7925,7926,7927, # 7632 7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943, # 7648 7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7958,7959, # 7664 7960,7961,7962,7963,7964,7965,7966,7967,7968,7969,7970,7971,7972,7973,7974,7975, # 7680 7976,7977,7978,7979,7980,7981,4859,7982,7983,7984,7985,7986,7987,7988,7989,7990, # 7696 7991,7992,7993,7994,7995,7996,4860,7997,7998,7999,8000,8001,8002,8003,8004,8005, # 7712 8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,8016,4176,8017,8018,8019,8020, # 7728 8021,8022,8023,4861,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8034,8035, # 7744 8036,4862,4456,8037,8038,8039,8040,4863,8041,8042,8043,8044,8045,8046,8047,8048, # 7760 8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,8064, # 7776 8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080, # 7792 8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096, # 7808 8097,8098,8099,4864,4177,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110, # 7824 8111,8112,8113,8114,8115,8116,8117,8118,8119,8120,4178,8121,8122,8123,8124,8125, # 7840 8126,8127,8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141, # 7856 8142,8143,8144,8145,4865,4866,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155, # 7872 8156,8157,8158,8159,8160,8161,8162,8163,8164,8165,4179,8166,8167,8168,8169,8170, # 7888 8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,4457,8182,8183,8184,8185, # 7904 8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201, # 7920 8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213,8214,8215,8216,8217, # 7936 8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229,8230,8231,8232,8233, # 7952 8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245,8246,8247,8248,8249, # 7968 8250,8251,8252,8253,8254,8255,8256,3445,8257,8258,8259,8260,8261,8262,4458,8263, # 7984 8264,8265,8266,8267,8268,8269,8270,8271,8272,4459,8273,8274,8275,8276,3550,8277, # 8000 8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,4460,8290,8291,8292, # 8016 8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,4867, # 8032 8308,8309,8310,8311,8312,3551,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322, # 8048 8323,8324,8325,8326,4868,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337, # 8064 8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353, # 8080 8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,4869,4461,8364,8365,8366,8367, # 8096 8368,8369,8370,4870,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382, # 8112 8383,8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398, # 8128 8399,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,4871,8411,8412,8413, # 8144 8414,8415,8416,8417,8418,8419,8420,8421,8422,4462,8423,8424,8425,8426,8427,8428, # 8160 8429,8430,8431,8432,8433,2986,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443, # 8176 8444,8445,8446,8447,8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459, # 8192 8460,8461,8462,8463,8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475, # 8208 8476,8477,8478,4180,8479,8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490, # 8224 8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506, # 8240 8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522, # 8256 8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538, # 8272 8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554, # 8288 8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,4872,8565,8566,8567,8568,8569, # 8304 8570,8571,8572,8573,4873,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584, # 8320 8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597,8598,8599,8600, # 8336 8601,8602,8603,8604,8605,3803,8606,8607,8608,8609,8610,8611,8612,8613,4874,3804, # 8352 8614,8615,8616,8617,8618,8619,8620,8621,3956,8622,8623,8624,8625,8626,8627,8628, # 8368 8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,2865,8639,8640,8641,8642,8643, # 8384 8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,4463,8657,8658, # 8400 8659,4875,4876,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672, # 8416 8673,8674,8675,8676,8677,8678,8679,8680,8681,4464,8682,8683,8684,8685,8686,8687, # 8432 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, # 8448 8704,8705,8706,8707,8708,8709,2261,8710,8711,8712,8713,8714,8715,8716,8717,8718, # 8464 8719,8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,4181, # 8480 8734,8735,8736,8737,8738,8739,8740,8741,8742,8743,8744,8745,8746,8747,8748,8749, # 8496 8750,8751,8752,8753,8754,8755,8756,8757,8758,8759,8760,8761,8762,8763,4877,8764, # 8512 8765,8766,8767,8768,8769,8770,8771,8772,8773,8774,8775,8776,8777,8778,8779,8780, # 8528 8781,8782,8783,8784,8785,8786,8787,8788,4878,8789,4879,8790,8791,8792,4880,8793, # 8544 8794,8795,8796,8797,8798,8799,8800,8801,4881,8802,8803,8804,8805,8806,8807,8808, # 8560 8809,8810,8811,8812,8813,8814,8815,3957,8816,8817,8818,8819,8820,8821,8822,8823, # 8576 8824,8825,8826,8827,8828,8829,8830,8831,8832,8833,8834,8835,8836,8837,8838,8839, # 8592 8840,8841,8842,8843,8844,8845,8846,8847,4882,8848,8849,8850,8851,8852,8853,8854, # 8608 8855,8856,8857,8858,8859,8860,8861,8862,8863,8864,8865,8866,8867,8868,8869,8870, # 8624 8871,8872,8873,8874,8875,8876,8877,8878,8879,8880,8881,8882,8883,8884,3202,8885, # 8640 8886,8887,8888,8889,8890,8891,8892,8893,8894,8895,8896,8897,8898,8899,8900,8901, # 8656 8902,8903,8904,8905,8906,8907,8908,8909,8910,8911,8912,8913,8914,8915,8916,8917, # 8672 8918,8919,8920,8921,8922,8923,8924,4465,8925,8926,8927,8928,8929,8930,8931,8932, # 8688 4883,8933,8934,8935,8936,8937,8938,8939,8940,8941,8942,8943,2214,8944,8945,8946, # 8704 8947,8948,8949,8950,8951,8952,8953,8954,8955,8956,8957,8958,8959,8960,8961,8962, # 8720 8963,8964,8965,4884,8966,8967,8968,8969,8970,8971,8972,8973,8974,8975,8976,8977, # 8736 8978,8979,8980,8981,8982,8983,8984,8985,8986,8987,8988,8989,8990,8991,8992,4885, # 8752 8993,8994,8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005,9006,9007,9008, # 8768 9009,9010,9011,9012,9013,9014,9015,9016,9017,9018,9019,9020,9021,4182,9022,9023, # 8784 9024,9025,9026,9027,9028,9029,9030,9031,9032,9033,9034,9035,9036,9037,9038,9039, # 8800 9040,9041,9042,9043,9044,9045,9046,9047,9048,9049,9050,9051,9052,9053,9054,9055, # 8816 9056,9057,9058,9059,9060,9061,9062,9063,4886,9064,9065,9066,9067,9068,9069,4887, # 8832 9070,9071,9072,9073,9074,9075,9076,9077,9078,9079,9080,9081,9082,9083,9084,9085, # 8848 9086,9087,9088,9089,9090,9091,9092,9093,9094,9095,9096,9097,9098,9099,9100,9101, # 8864 9102,9103,9104,9105,9106,9107,9108,9109,9110,9111,9112,9113,9114,9115,9116,9117, # 8880 9118,9119,9120,9121,9122,9123,9124,9125,9126,9127,9128,9129,9130,9131,9132,9133, # 8896 9134,9135,9136,9137,9138,9139,9140,9141,3958,9142,9143,9144,9145,9146,9147,9148, # 8912 9149,9150,9151,4888,9152,9153,9154,9155,9156,9157,9158,9159,9160,9161,9162,9163, # 8928 9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,4889,9176,9177,9178, # 8944 9179,9180,9181,9182,9183,9184,9185,9186,9187,9188,9189,9190,9191,9192,9193,9194, # 8960 9195,9196,9197,9198,9199,9200,9201,9202,9203,4890,9204,9205,9206,9207,9208,9209, # 8976 9210,9211,9212,9213,9214,9215,9216,9217,9218,9219,9220,9221,9222,4466,9223,9224, # 8992 9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240, # 9008 9241,9242,9243,9244,9245,4891,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255, # 9024 9256,9257,4892,9258,9259,9260,9261,4893,4894,9262,9263,9264,9265,9266,9267,9268, # 9040 9269,9270,9271,9272,9273,4467,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283, # 9056 9284,9285,3673,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298, # 9072 9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314, # 9088 9315,9316,9317,9318,9319,9320,9321,9322,4895,9323,9324,9325,9326,9327,9328,9329, # 9104 9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345, # 9120 9346,9347,4468,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360, # 9136 9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,4896,9374,4469, # 9152 9375,9376,9377,9378,9379,4897,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389, # 9168 9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405, # 9184 9406,4470,9407,2751,9408,9409,3674,3552,9410,9411,9412,9413,9414,9415,9416,9417, # 9200 9418,9419,9420,9421,4898,9422,9423,9424,9425,9426,9427,9428,9429,3959,9430,9431, # 9216 9432,9433,9434,9435,9436,4471,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446, # 9232 9447,9448,9449,9450,3348,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461, # 9248 9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,4899,9473,9474,9475,9476, # 9264 9477,4900,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,3349,9489,9490, # 9280 9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506, # 9296 9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,4901,9521, # 9312 9522,9523,9524,9525,9526,4902,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536, # 9328 9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552, # 9344 9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568, # 9360 9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584, # 9376 3805,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599, # 9392 9600,9601,9602,4903,9603,9604,9605,9606,9607,4904,9608,9609,9610,9611,9612,9613, # 9408 9614,4905,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628, # 9424 9629,9630,9631,9632,4906,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643, # 9440 4907,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658, # 9456 9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,4183,9673, # 9472 9674,9675,9676,9677,4908,9678,9679,9680,9681,4909,9682,9683,9684,9685,9686,9687, # 9488 9688,9689,9690,4910,9691,9692,9693,3675,9694,9695,9696,2945,9697,9698,9699,9700, # 9504 9701,9702,9703,9704,9705,4911,9706,9707,9708,9709,9710,9711,9712,9713,9714,9715, # 9520 9716,9717,9718,9719,9720,9721,9722,9723,9724,9725,9726,9727,9728,9729,9730,9731, # 9536 9732,9733,9734,9735,4912,9736,9737,9738,9739,9740,4913,9741,9742,9743,9744,9745, # 9552 9746,9747,9748,9749,9750,9751,9752,9753,9754,9755,9756,9757,9758,4914,9759,9760, # 9568 9761,9762,9763,9764,9765,9766,9767,9768,9769,9770,9771,9772,9773,9774,9775,9776, # 9584 9777,9778,9779,9780,9781,9782,4915,9783,9784,9785,9786,9787,9788,9789,9790,9791, # 9600 9792,9793,4916,9794,9795,9796,9797,9798,9799,9800,9801,9802,9803,9804,9805,9806, # 9616 9807,9808,9809,9810,9811,9812,9813,9814,9815,9816,9817,9818,9819,9820,9821,9822, # 9632 9823,9824,9825,9826,9827,9828,9829,9830,9831,9832,9833,9834,9835,9836,9837,9838, # 9648 9839,9840,9841,9842,9843,9844,9845,9846,9847,9848,9849,9850,9851,9852,9853,9854, # 9664 9855,9856,9857,9858,9859,9860,9861,9862,9863,9864,9865,9866,9867,9868,4917,9869, # 9680 9870,9871,9872,9873,9874,9875,9876,9877,9878,9879,9880,9881,9882,9883,9884,9885, # 9696 9886,9887,9888,9889,9890,9891,9892,4472,9893,9894,9895,9896,9897,3806,9898,9899, # 9712 9900,9901,9902,9903,9904,9905,9906,9907,9908,9909,9910,9911,9912,9913,9914,4918, # 9728 9915,9916,9917,4919,9918,9919,9920,9921,4184,9922,9923,9924,9925,9926,9927,9928, # 9744 9929,9930,9931,9932,9933,9934,9935,9936,9937,9938,9939,9940,9941,9942,9943,9944, # 9760 9945,9946,4920,9947,9948,9949,9950,9951,9952,9953,9954,9955,4185,9956,9957,9958, # 9776 9959,9960,9961,9962,9963,9964,9965,4921,9966,9967,9968,4473,9969,9970,9971,9972, # 9792 9973,9974,9975,9976,9977,4474,9978,9979,9980,9981,9982,9983,9984,9985,9986,9987, # 9808 9988,9989,9990,9991,9992,9993,9994,9995,9996,9997,9998,9999,10000,10001,10002,10003, # 9824 10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019, # 9840 10020,10021,4922,10022,4923,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033, # 9856 10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,4924, # 9872 10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064, # 9888 10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080, # 9904 10081,10082,10083,10084,10085,10086,10087,4475,10088,10089,10090,10091,10092,10093,10094,10095, # 9920 10096,10097,4476,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110, # 9936 10111,2174,10112,10113,10114,10115,10116,10117,10118,10119,10120,10121,10122,10123,10124,10125, # 9952 10126,10127,10128,10129,10130,10131,10132,10133,10134,10135,10136,10137,10138,10139,10140,3807, # 9968 4186,4925,10141,10142,10143,10144,10145,10146,10147,4477,4187,10148,10149,10150,10151,10152, # 9984 10153,4188,10154,10155,10156,10157,10158,10159,10160,10161,4926,10162,10163,10164,10165,10166, #10000 10167,10168,10169,10170,10171,10172,10173,10174,10175,10176,10177,10178,10179,10180,10181,10182, #10016 10183,10184,10185,10186,10187,10188,10189,10190,10191,10192,3203,10193,10194,10195,10196,10197, #10032 10198,10199,10200,4478,10201,10202,10203,10204,4479,10205,10206,10207,10208,10209,10210,10211, #10048 10212,10213,10214,10215,10216,10217,10218,10219,10220,10221,10222,10223,10224,10225,10226,10227, #10064 10228,10229,10230,10231,10232,10233,10234,4927,10235,10236,10237,10238,10239,10240,10241,10242, #10080 10243,10244,10245,10246,10247,10248,10249,10250,10251,10252,10253,10254,10255,10256,10257,10258, #10096 10259,10260,10261,10262,10263,10264,10265,10266,10267,10268,10269,10270,10271,10272,10273,4480, #10112 4928,4929,10274,10275,10276,10277,10278,10279,10280,10281,10282,10283,10284,10285,10286,10287, #10128 10288,10289,10290,10291,10292,10293,10294,10295,10296,10297,10298,10299,10300,10301,10302,10303, #10144 10304,10305,10306,10307,10308,10309,10310,10311,10312,10313,10314,10315,10316,10317,10318,10319, #10160 10320,10321,10322,10323,10324,10325,10326,10327,10328,10329,10330,10331,10332,10333,10334,4930, #10176 10335,10336,10337,10338,10339,10340,10341,10342,4931,10343,10344,10345,10346,10347,10348,10349, #10192 10350,10351,10352,10353,10354,10355,3088,10356,2786,10357,10358,10359,10360,4189,10361,10362, #10208 10363,10364,10365,10366,10367,10368,10369,10370,10371,10372,10373,10374,10375,4932,10376,10377, #10224 10378,10379,10380,10381,10382,10383,10384,10385,10386,10387,10388,10389,10390,10391,10392,4933, #10240 10393,10394,10395,4934,10396,10397,10398,10399,10400,10401,10402,10403,10404,10405,10406,10407, #10256 10408,10409,10410,10411,10412,3446,10413,10414,10415,10416,10417,10418,10419,10420,10421,10422, #10272 10423,4935,10424,10425,10426,10427,10428,10429,10430,4936,10431,10432,10433,10434,10435,10436, #10288 10437,10438,10439,10440,10441,10442,10443,4937,10444,10445,10446,10447,4481,10448,10449,10450, #10304 10451,10452,10453,10454,10455,10456,10457,10458,10459,10460,10461,10462,10463,10464,10465,10466, #10320 10467,10468,10469,10470,10471,10472,10473,10474,10475,10476,10477,10478,10479,10480,10481,10482, #10336 10483,10484,10485,10486,10487,10488,10489,10490,10491,10492,10493,10494,10495,10496,10497,10498, #10352 10499,10500,10501,10502,10503,10504,10505,4938,10506,10507,10508,10509,10510,2552,10511,10512, #10368 10513,10514,10515,10516,3447,10517,10518,10519,10520,10521,10522,10523,10524,10525,10526,10527, #10384 10528,10529,10530,10531,10532,10533,10534,10535,10536,10537,10538,10539,10540,10541,10542,10543, #10400 4482,10544,4939,10545,10546,10547,10548,10549,10550,10551,10552,10553,10554,10555,10556,10557, #10416 10558,10559,10560,10561,10562,10563,10564,10565,10566,10567,3676,4483,10568,10569,10570,10571, #10432 10572,3448,10573,10574,10575,10576,10577,10578,10579,10580,10581,10582,10583,10584,10585,10586, #10448 10587,10588,10589,10590,10591,10592,10593,10594,10595,10596,10597,10598,10599,10600,10601,10602, #10464 10603,10604,10605,10606,10607,10608,10609,10610,10611,10612,10613,10614,10615,10616,10617,10618, #10480 10619,10620,10621,10622,10623,10624,10625,10626,10627,4484,10628,10629,10630,10631,10632,4940, #10496 10633,10634,10635,10636,10637,10638,10639,10640,10641,10642,10643,10644,10645,10646,10647,10648, #10512 10649,10650,10651,10652,10653,10654,10655,10656,4941,10657,10658,10659,2599,10660,10661,10662, #10528 10663,10664,10665,10666,3089,10667,10668,10669,10670,10671,10672,10673,10674,10675,10676,10677, #10544 10678,10679,10680,4942,10681,10682,10683,10684,10685,10686,10687,10688,10689,10690,10691,10692, #10560 10693,10694,10695,10696,10697,4485,10698,10699,10700,10701,10702,10703,10704,4943,10705,3677, #10576 10706,10707,10708,10709,10710,10711,10712,4944,10713,10714,10715,10716,10717,10718,10719,10720, #10592 10721,10722,10723,10724,10725,10726,10727,10728,4945,10729,10730,10731,10732,10733,10734,10735, #10608 10736,10737,10738,10739,10740,10741,10742,10743,10744,10745,10746,10747,10748,10749,10750,10751, #10624 10752,10753,10754,10755,10756,10757,10758,10759,10760,10761,4946,10762,10763,10764,10765,10766, #10640 10767,4947,4948,10768,10769,10770,10771,10772,10773,10774,10775,10776,10777,10778,10779,10780, #10656 10781,10782,10783,10784,10785,10786,10787,10788,10789,10790,10791,10792,10793,10794,10795,10796, #10672 10797,10798,10799,10800,10801,10802,10803,10804,10805,10806,10807,10808,10809,10810,10811,10812, #10688 10813,10814,10815,10816,10817,10818,10819,10820,10821,10822,10823,10824,10825,10826,10827,10828, #10704 10829,10830,10831,10832,10833,10834,10835,10836,10837,10838,10839,10840,10841,10842,10843,10844, #10720 10845,10846,10847,10848,10849,10850,10851,10852,10853,10854,10855,10856,10857,10858,10859,10860, #10736 10861,10862,10863,10864,10865,10866,10867,10868,10869,10870,10871,10872,10873,10874,10875,10876, #10752 10877,10878,4486,10879,10880,10881,10882,10883,10884,10885,4949,10886,10887,10888,10889,10890, #10768 10891,10892,10893,10894,10895,10896,10897,10898,10899,10900,10901,10902,10903,10904,10905,10906, #10784 10907,10908,10909,10910,10911,10912,10913,10914,10915,10916,10917,10918,10919,4487,10920,10921, #10800 10922,10923,10924,10925,10926,10927,10928,10929,10930,10931,10932,4950,10933,10934,10935,10936, #10816 10937,10938,10939,10940,10941,10942,10943,10944,10945,10946,10947,10948,10949,4488,10950,10951, #10832 10952,10953,10954,10955,10956,10957,10958,10959,4190,10960,10961,10962,10963,10964,10965,10966, #10848 10967,10968,10969,10970,10971,10972,10973,10974,10975,10976,10977,10978,10979,10980,10981,10982, #10864 10983,10984,10985,10986,10987,10988,10989,10990,10991,10992,10993,10994,10995,10996,10997,10998, #10880 10999,11000,11001,11002,11003,11004,11005,11006,3960,11007,11008,11009,11010,11011,11012,11013, #10896 11014,11015,11016,11017,11018,11019,11020,11021,11022,11023,11024,11025,11026,11027,11028,11029, #10912 11030,11031,11032,4951,11033,11034,11035,11036,11037,11038,11039,11040,11041,11042,11043,11044, #10928 11045,11046,11047,4489,11048,11049,11050,11051,4952,11052,11053,11054,11055,11056,11057,11058, #10944 4953,11059,11060,11061,11062,11063,11064,11065,11066,11067,11068,11069,11070,11071,4954,11072, #10960 11073,11074,11075,11076,11077,11078,11079,11080,11081,11082,11083,11084,11085,11086,11087,11088, #10976 11089,11090,11091,11092,11093,11094,11095,11096,11097,11098,11099,11100,11101,11102,11103,11104, #10992 11105,11106,11107,11108,11109,11110,11111,11112,11113,11114,11115,3808,11116,11117,11118,11119, #11008 11120,11121,11122,11123,11124,11125,11126,11127,11128,11129,11130,11131,11132,11133,11134,4955, #11024 11135,11136,11137,11138,11139,11140,11141,11142,11143,11144,11145,11146,11147,11148,11149,11150, #11040 11151,11152,11153,11154,11155,11156,11157,11158,11159,11160,11161,4956,11162,11163,11164,11165, #11056 11166,11167,11168,11169,11170,11171,11172,11173,11174,11175,11176,11177,11178,11179,11180,4957, #11072 11181,11182,11183,11184,11185,11186,4958,11187,11188,11189,11190,11191,11192,11193,11194,11195, #11088 11196,11197,11198,11199,11200,3678,11201,11202,11203,11204,11205,11206,4191,11207,11208,11209, #11104 11210,11211,11212,11213,11214,11215,11216,11217,11218,11219,11220,11221,11222,11223,11224,11225, #11120 11226,11227,11228,11229,11230,11231,11232,11233,11234,11235,11236,11237,11238,11239,11240,11241, #11136 11242,11243,11244,11245,11246,11247,11248,11249,11250,11251,4959,11252,11253,11254,11255,11256, #11152 11257,11258,11259,11260,11261,11262,11263,11264,11265,11266,11267,11268,11269,11270,11271,11272, #11168 11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288, #11184 11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304, #11200 11305,11306,11307,11308,11309,11310,11311,11312,11313,11314,3679,11315,11316,11317,11318,4490, #11216 11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334, #11232 11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,4960,11348,11349, #11248 11350,11351,11352,11353,11354,11355,11356,11357,11358,11359,11360,11361,11362,11363,11364,11365, #11264 11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,3961,4961,11378,11379, #11280 11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395, #11296 11396,11397,4192,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410, #11312 11411,4962,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425, #11328 11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441, #11344 11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457, #11360 11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,4963,11470,11471,4491, #11376 11472,11473,11474,11475,4964,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486, #11392 11487,11488,11489,11490,11491,11492,4965,11493,11494,11495,11496,11497,11498,11499,11500,11501, #11408 11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517, #11424 11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,3962,11530,11531,11532, #11440 11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548, #11456 11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564, #11472 4193,4194,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578, #11488 11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,4966,4195,11592, #11504 11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,3090,11605,11606,11607, #11520 11608,11609,11610,4967,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622, #11536 11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638, #11552 11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654, #11568 11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670, #11584 11671,11672,11673,11674,4968,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685, #11600 11686,11687,11688,11689,11690,11691,11692,11693,3809,11694,11695,11696,11697,11698,11699,11700, #11616 11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716, #11632 11717,11718,3553,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,4969, #11648 11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,4492,11741,11742,11743,11744,11745, #11664 11746,11747,11748,11749,11750,11751,11752,4970,11753,11754,11755,11756,11757,11758,11759,11760, #11680 11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776, #11696 11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,4971,11791, #11712 11792,11793,11794,11795,11796,11797,4972,11798,11799,11800,11801,11802,11803,11804,11805,11806, #11728 11807,11808,11809,11810,4973,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821, #11744 11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,3680,3810,11835, #11760 11836,4974,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850, #11776 11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866, #11792 11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882, #11808 11883,11884,4493,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897, #11824 11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913, #11840 11914,11915,4975,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928, #11856 11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944, #11872 11945,11946,11947,11948,11949,4976,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959, #11888 11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975, #11904 11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,4196,11988,11989,11990, #11920 11991,11992,4977,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005, #11936 12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021, #11952 12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037, #11968 12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053, #11984 12054,12055,12056,12057,12058,12059,12060,12061,4978,12062,12063,12064,12065,12066,12067,12068, #12000 12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084, #12016 12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100, #12032 12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116, #12048 12117,12118,12119,12120,12121,12122,12123,4979,12124,12125,12126,12127,12128,4197,12129,12130, #12064 12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146, #12080 12147,12148,12149,12150,12151,12152,12153,12154,4980,12155,12156,12157,12158,12159,12160,4494, #12096 12161,12162,12163,12164,3811,12165,12166,12167,12168,12169,4495,12170,12171,4496,12172,12173, #12112 12174,12175,12176,3812,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188, #12128 12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204, #12144 12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220, #12160 12221,4981,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235, #12176 4982,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,4983,12246,12247,12248,12249, #12192 4984,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264, #12208 4985,12265,4497,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278, #12224 12279,12280,12281,12282,12283,12284,12285,12286,12287,4986,12288,12289,12290,12291,12292,12293, #12240 12294,12295,12296,2473,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308, #12256 12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,3963,12320,12321,12322,12323, #12272 12324,12325,12326,12327,12328,12329,12330,12331,12332,4987,12333,12334,12335,12336,12337,12338, #12288 12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354, #12304 12355,12356,12357,12358,12359,3964,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369, #12320 12370,3965,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384, #12336 12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400, #12352 12401,12402,12403,12404,12405,12406,12407,12408,4988,12409,12410,12411,12412,12413,12414,12415, #12368 12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431, #12384 12432,12433,12434,12435,12436,12437,12438,3554,12439,12440,12441,12442,12443,12444,12445,12446, #12400 12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462, #12416 12463,12464,4989,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477, #12432 12478,12479,12480,4990,12481,12482,12483,12484,12485,12486,12487,12488,12489,4498,12490,12491, #12448 12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507, #12464 12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523, #12480 12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539, #12496 12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,4991,12552,12553,12554, #12512 12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570, #12528 12571,12572,12573,12574,12575,12576,12577,12578,3036,12579,12580,12581,12582,12583,3966,12584, #12544 12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600, #12560 12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616, #12576 12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632, #12592 12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,4499,12647, #12608 12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663, #12624 12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679, #12640 12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695, #12656 12696,12697,12698,4992,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710, #12672 12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726, #12688 12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742, #12704 12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758, #12720 12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774, #12736 12775,12776,12777,12778,4993,2175,12779,12780,12781,12782,12783,12784,12785,12786,4500,12787, #12752 12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803, #12768 12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819, #12784 12820,12821,12822,12823,12824,12825,12826,4198,3967,12827,12828,12829,12830,12831,12832,12833, #12800 12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849, #12816 12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,4199,12862,12863,12864, #12832 12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880, #12848 12881,12882,12883,12884,12885,12886,12887,4501,12888,12889,12890,12891,12892,12893,12894,12895, #12864 12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911, #12880 12912,4994,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926, #12896 12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942, #12912 12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,1772,12957, #12928 12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973, #12944 12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989, #12960 12990,12991,12992,12993,12994,12995,12996,12997,4502,12998,4503,12999,13000,13001,13002,13003, #12976 4504,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018, #12992 13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,3449,13030,13031,13032,13033, #13008 13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049, #13024 13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065, #13040 13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081, #13056 13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097, #13072 13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113, #13088 13114,13115,13116,13117,13118,3968,13119,4995,13120,13121,13122,13123,13124,13125,13126,13127, #13104 4505,13128,13129,13130,13131,13132,13133,13134,4996,4506,13135,13136,13137,13138,13139,4997, #13120 13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155, #13136 13156,13157,13158,13159,4998,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170, #13152 13171,13172,13173,13174,13175,13176,4999,13177,13178,13179,13180,13181,13182,13183,13184,13185, #13168 13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201, #13184 13202,13203,13204,13205,13206,5000,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216, #13200 13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,4200,5001,13228,13229,13230, #13216 13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,3969,13241,13242,13243,13244,3970, #13232 13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260, #13248 13261,13262,13263,13264,13265,13266,13267,13268,3450,13269,13270,13271,13272,13273,13274,13275, #13264 13276,5002,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290, #13280 13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,3813,13303,13304,13305, #13296 13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321, #13312 13322,13323,13324,13325,13326,13327,13328,4507,13329,13330,13331,13332,13333,13334,13335,13336, #13328 13337,13338,13339,13340,13341,5003,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351, #13344 13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367, #13360 5004,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382, #13376 13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398, #13392 13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414, #13408 13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430, #13424 13431,13432,4508,13433,13434,13435,4201,13436,13437,13438,13439,13440,13441,13442,13443,13444, #13440 13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,5005,13458,13459, #13456 13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,4509,13471,13472,13473,13474, #13472 13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490, #13488 13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506, #13504 13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522, #13520 13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538, #13536 13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554, #13552 13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570, #13568 13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586, #13584 13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602, #13600 13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618, #13616 13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634, #13632 13635,13636,13637,13638,13639,13640,13641,13642,5006,13643,13644,13645,13646,13647,13648,13649, #13648 13650,13651,5007,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664, #13664 13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680, #13680 13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696, #13696 13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712, #13712 13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728, #13728 13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744, #13744 13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760, #13760 13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,3273,13775, #13776 13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791, #13792 13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807, #13808 13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823, #13824 13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839, #13840 13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855, #13856 13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871, #13872 13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887, #13888 13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903, #13904 13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919, #13920 13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935, #13936 13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951, #13952 13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967, #13968 13968,13969,13970,13971,13972) #13973 # flake8: noqa
gpl-3.0
darith27/wagtail
wagtail/tests/testapp/migrations/0005_streampage.py
22
1043
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wagtail.wagtailcore.fields import wagtail.wagtailcore.blocks import wagtail.wagtailimages.blocks class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0001_squashed_0016_change_page_url_path_to_text_field'), ('tests', '0004_streammodel_richtext'), ] operations = [ migrations.CreateModel( name='StreamPage', fields=[ ('page_ptr', models.OneToOneField(auto_created=True, to='wagtailcore.Page', serialize=False, parent_link=True, primary_key=True)), ('body', wagtail.wagtailcore.fields.StreamField((('text', wagtail.wagtailcore.blocks.CharBlock()), ('rich_text', wagtail.wagtailcore.blocks.RichTextBlock()), ('image', wagtail.wagtailimages.blocks.ImageChooserBlock())))), ], options={ 'abstract': False, }, bases=('wagtailcore.page',), ), ]
bsd-3-clause
sohail-aspose/Aspose_Words_Cloud
SDKs/Aspose.Words_Cloud_SDK_for_Python/asposewordscloud/WordsApi.py
4
224530
#!/usr/bin/env python import sys import os import urllib import json import re from models import * from ApiClient import ApiException class WordsApi(object): def __init__(self, apiClient): self.apiClient = apiClient def GetDocumentBookmarkByName(self, name, bookmarkName, **kwargs): """Read document bookmark data by its name. Args: name (str): The document name. (required) bookmarkName (str): The bookmark name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: BookmarkResponse """ allParams = dict.fromkeys(['name', 'bookmarkName', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentBookmarkByName" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/bookmarks/{bookmarkName}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'bookmarkName' in allParams and allParams['bookmarkName'] is not None: resourcePath = resourcePath.replace("{" + "bookmarkName" + "}" , str(allParams['bookmarkName'])) else: resourcePath = re.sub("[&?]bookmarkName.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'BookmarkResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentBookmarks(self, name, **kwargs): """Read document bookmarks common info. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: BookmarksResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentBookmarks" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/bookmarks/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'BookmarksResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostUpdateDocumentBookmark(self, name, bookmarkName, body, **kwargs): """Update document bookmark. Args: name (str): The document name. (required) bookmarkName (str): The bookmark name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (BookmarkData): with new bookmark data. (required) Returns: BookmarkResponse """ allParams = dict.fromkeys(['name', 'bookmarkName', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostUpdateDocumentBookmark" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/bookmarks/{bookmarkName}/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'bookmarkName' in allParams and allParams['bookmarkName'] is not None: resourcePath = resourcePath.replace("{" + "bookmarkName" + "}" , str(allParams['bookmarkName'])) else: resourcePath = re.sub("[&?]bookmarkName.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'BookmarkResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocument(self, name, **kwargs): """RRead document common info. Args: name (str): The file name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentWithFormat(self, name, format, **kwargs): """Export the document into the specified format. Args: name (str): The file name. (required) format (str): The destination format. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) outPath (str): Path to save result (optional) Returns: ResponseMessage """ allParams = dict.fromkeys(['name', 'format', 'storage', 'folder', 'outPath']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentWithFormat" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/?appSid={appSid}&amp;toFormat={toFormat}&amp;storage={storage}&amp;folder={folder}&amp;outPath={outPath}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'format' in allParams and allParams['format'] is not None: resourcePath = resourcePath.replace("{" + "format" + "}" , str(allParams['format'])) else: resourcePath = re.sub("[&?]format.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'outPath' in allParams and allParams['outPath'] is not None: resourcePath = resourcePath.replace("{" + "outPath" + "}" , str(allParams['outPath'])) else: resourcePath = re.sub("[&?]outPath.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostAppendDocument(self, name, body, **kwargs): """Append documents to original document. Args: name (str): Original document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): Original document storage. (optional) folder (str): Original document folder. (optional) body (DocumentEntryList): with a list of documents to append. (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostAppendDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/appendDocument/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostExecuteTemplate(self, name, file, **kwargs): """Populate document template with data. Args: name (str): The template document name. (required) cleanup (str): Clean up options. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) useWholeParagraphAsRegion (bool): Gets or sets a value indicating whether paragraph with TableStart or TableEnd field should be fully included into mail merge region or particular range between TableStart and TableEnd fields. The default value is true. (optional) withRegions (bool): Merge with regions or not. True by default (optional) file (File): (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'cleanup', 'filename', 'storage', 'folder', 'useWholeParagraphAsRegion', 'withRegions', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostExecuteTemplate" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/executeTemplate/?appSid={appSid}&amp;cleanup={cleanup}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}&amp;useWholeParagraphAsRegion={useWholeParagraphAsRegion}&amp;withRegions={withRegions}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'cleanup' in allParams and allParams['cleanup'] is not None: resourcePath = resourcePath.replace("{" + "cleanup" + "}" , str(allParams['cleanup'])) else: resourcePath = re.sub("[&?]cleanup.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'useWholeParagraphAsRegion' in allParams and allParams['useWholeParagraphAsRegion'] is not None: resourcePath = resourcePath.replace("{" + "useWholeParagraphAsRegion" + "}" , str(allParams['useWholeParagraphAsRegion'])) else: resourcePath = re.sub("[&?]useWholeParagraphAsRegion.*?(?=&|\\?|$)", "", resourcePath) if 'withRegions' in allParams and allParams['withRegions'] is not None: resourcePath = resourcePath.replace("{" + "withRegions" + "}" , str(allParams['withRegions'])) else: resourcePath = re.sub("[&?]withRegions.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostInsertPageNumbers(self, name, body, **kwargs): """Insert document page numbers. Args: name (str): A document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (PageNumber): with the page numbers settings. (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostInsertPageNumbers" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/insertPageNumbers/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostLoadWebDocument(self, body, **kwargs): """Load new document from web into the file with any supported format of data. Args: body (LoadWebDocumentData): The property with new value. (required) Returns: SaveResponse """ allParams = dict.fromkeys([]) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostLoadWebDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/loadWebDocument/?appSid={appSid}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaveResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostRunTask(self, **kwargs): """Run tasks Args: Returns: ResponseMessage """ allParams = dict.fromkeys([]) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostRunTask" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/tasks/?appSid={appSid}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostSplitDocument(self, name, **kwargs): """Split document. Args: name (str): Original document name. (required) format (str): Format to split. (optional) ffrom (int): Start page. (optional) to (int): End page. (optional) zipOutput (bool): ZipOutput or not. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SplitDocumentResponse """ allParams = dict.fromkeys(['name', 'format', 'ffrom', 'to', 'zipOutput', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostSplitDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/split/?appSid={appSid}&amp;toFormat={toFormat}&amp;from={from}&amp;to={to}&amp;zipOutput={zipOutput}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'format' in allParams and allParams['format'] is not None: resourcePath = resourcePath.replace("{" + "format" + "}" , str(allParams['format'])) else: resourcePath = re.sub("[&?]format.*?(?=&|\\?|$)", "", resourcePath) if 'ffrom' in allParams and allParams['ffrom'] is not None: resourcePath = resourcePath.replace("{" + "from" + "}" , str(allParams['ffrom'])) else: resourcePath = re.sub("[&?]from.*?(?=&|\\?|$)", "", resourcePath) if 'to' in allParams and allParams['to'] is not None: resourcePath = resourcePath.replace("{" + "to" + "}" , str(allParams['to'])) else: resourcePath = re.sub("[&?]to.*?(?=&|\\?|$)", "", resourcePath) if 'zipOutput' in allParams and allParams['zipOutput'] is not None: resourcePath = resourcePath.replace("{" + "zipOutput" + "}" , str(allParams['zipOutput'])) else: resourcePath = re.sub("[&?]zipOutput.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SplitDocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutConvertDocument(self, file, **kwargs): """Convert document from request content to format specified. Args: format (str): Format to convert. (optional) outPath (str): (optional) file (File): (required) Returns: ResponseMessage """ allParams = dict.fromkeys(['format', 'outPath', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutConvertDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/convert/?appSid={appSid}&amp;toFormat={toFormat}&amp;outPath={outPath}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'format' in allParams and allParams['format'] is not None: resourcePath = resourcePath.replace("{" + "format" + "}" , str(allParams['format'])) else: resourcePath = re.sub("[&?]format.*?(?=&|\\?|$)", "", resourcePath) if 'outPath' in allParams and allParams['outPath'] is not None: resourcePath = resourcePath.replace("{" + "outPath" + "}" , str(allParams['outPath'])) else: resourcePath = re.sub("[&?]outPath.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutDocumentFieldNames(self, **kwargs): """Read document field names. Args: useNonMergeFields (bool): (optional) Returns: FieldNamesResponse """ allParams = dict.fromkeys(['useNonMergeFields']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutDocumentFieldNames" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/mailMergeFieldNames/?appSid={appSid}&amp;useNonMergeFields={useNonMergeFields}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'useNonMergeFields' in allParams and allParams['useNonMergeFields'] is not None: resourcePath = resourcePath.replace("{" + "useNonMergeFields" + "}" , str(allParams['useNonMergeFields'])) else: resourcePath = re.sub("[&?]useNonMergeFields.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FieldNamesResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutExecuteMailMergeOnline(self, withRegions, file, data, **kwargs): """Execute document mail merge online. Args: withRegions (bool): With regions flag. (required) cleanup (str): Clean up options. (optional) file (File): (required) data (File): (required) Returns: ResponseMessage """ allParams = dict.fromkeys(['withRegions', 'cleanup', 'file', 'data']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutExecuteMailMergeOnline" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/executeMailMerge/?withRegions={withRegions}&amp;appSid={appSid}&amp;cleanup={cleanup}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'withRegions' in allParams and allParams['withRegions'] is not None: resourcePath = resourcePath.replace("{" + "withRegions" + "}" , str(allParams['withRegions'])) else: resourcePath = re.sub("[&?]withRegions.*?(?=&|\\?|$)", "", resourcePath) if 'cleanup' in allParams and allParams['cleanup'] is not None: resourcePath = resourcePath.replace("{" + "cleanup" + "}" , str(allParams['cleanup'])) else: resourcePath = re.sub("[&?]cleanup.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = [ ('file', (os.path.basename(file), open(file, 'rb'), 'application/octet-stream')), ('data', (os.path.basename(data), open(data, 'rb'), 'application/xml')) ] bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = None postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutExecuteTemplateOnline(self, file, **kwargs): """Populate document template with data online. Args: cleanup (str): Clean up options. (optional) useWholeParagraphAsRegion (bool): Gets or sets a value indicating whether paragraph with TableStart or TableEnd field should be fully included into mail merge region or particular range between TableStart and TableEnd fields. The default value is true. (optional) withRegions (bool): Merge with regions or not. True by default (optional) file (File): (required) Returns: ResponseMessage """ allParams = dict.fromkeys(['cleanup', 'useWholeParagraphAsRegion', 'withRegions', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutExecuteTemplateOnline" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/executeTemplate/?appSid={appSid}&amp;cleanup={cleanup}&amp;useWholeParagraphAsRegion={useWholeParagraphAsRegion}&amp;withRegions={withRegions}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'cleanup' in allParams and allParams['cleanup'] is not None: resourcePath = resourcePath.replace("{" + "cleanup" + "}" , str(allParams['cleanup'])) else: resourcePath = re.sub("[&?]cleanup.*?(?=&|\\?|$)", "", resourcePath) if 'useWholeParagraphAsRegion' in allParams and allParams['useWholeParagraphAsRegion'] is not None: resourcePath = resourcePath.replace("{" + "useWholeParagraphAsRegion" + "}" , str(allParams['useWholeParagraphAsRegion'])) else: resourcePath = re.sub("[&?]useWholeParagraphAsRegion.*?(?=&|\\?|$)", "", resourcePath) if 'withRegions' in allParams and allParams['withRegions'] is not None: resourcePath = resourcePath.replace("{" + "withRegions" + "}" , str(allParams['withRegions'])) else: resourcePath = re.sub("[&?]withRegions.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteDocumentFields(self, name, **kwargs): """Remove fields from document. Args: name (str): The file name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteDocumentFields" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/fields/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostUpdateDocumentFields(self, name, **kwargs): """Update (reevaluate) fields in document. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostUpdateDocumentFields" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/updateFields/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteDocumentProperty(self, name, propertyName, **kwargs): """Delete document property. Args: name (str): The document name. (required) propertyName (str): The property name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): Document's storage. (optional) folder (str): Document's folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'propertyName', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteDocumentProperty" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/documentProperties/{propertyName}/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'propertyName' in allParams and allParams['propertyName'] is not None: resourcePath = resourcePath.replace("{" + "propertyName" + "}" , str(allParams['propertyName'])) else: resourcePath = re.sub("[&?]propertyName.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentProperties(self, name, **kwargs): """Read document properties info. Args: name (str): The document's name. (required) storage (str): The document's storage. (optional) folder (str): The document's folder. (optional) Returns: DocumentPropertiesResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentProperties" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/documentProperties/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentPropertiesResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentProperty(self, name, propertyName, **kwargs): """Read document property info by the property name. Args: name (str): The document name. (required) propertyName (str): The property name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: DocumentPropertyResponse """ allParams = dict.fromkeys(['name', 'propertyName', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentProperty" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/documentProperties/{propertyName}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'propertyName' in allParams and allParams['propertyName'] is not None: resourcePath = resourcePath.replace("{" + "propertyName" + "}" , str(allParams['propertyName'])) else: resourcePath = re.sub("[&?]propertyName.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentPropertyResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutUpdateDocumentProperty(self, name, propertyName, body, **kwargs): """Add new or update existing document property. Args: name (str): The document name. (required) propertyName (str): The property name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): Document's storage. (optional) folder (str): Document's folder. (optional) body (DocumentProperty): The property with new value. (required) Returns: DocumentPropertyResponse """ allParams = dict.fromkeys(['name', 'propertyName', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutUpdateDocumentProperty" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/documentProperties/{propertyName}/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'propertyName' in allParams and allParams['propertyName'] is not None: resourcePath = resourcePath.replace("{" + "propertyName" + "}" , str(allParams['propertyName'])) else: resourcePath = re.sub("[&?]propertyName.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentPropertyResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteUnprotectDocument(self, name, body, **kwargs): """Unprotect document. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (ProtectionRequest): with protection settings. (required) Returns: ProtectionDataResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteUnprotectDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/protection/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ProtectionDataResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentProtection(self, name, **kwargs): """Read document protection common info. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: ProtectionDataResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentProtection" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/protection/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ProtectionDataResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostChangeDocumentProtection(self, name, body, **kwargs): """Change document protection. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (ProtectionRequest): with protection settings. (required) Returns: ProtectionDataResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostChangeDocumentProtection" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/protection/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ProtectionDataResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutProtectDocument(self, name, body, **kwargs): """Protect document. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (ProtectionRequest): with protection settings. (required) Returns: ProtectionDataResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutProtectDocument" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/protection/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ProtectionDataResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostDocumentSaveAs(self, name, body, **kwargs): """Convert document to tiff with detailed settings and save result to storage. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (SaveOptionsData): Save options. (required) Returns: SaveResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostDocumentSaveAs" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/SaveAs/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaveResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutDocumentSaveAsTiff(self, name, body, **kwargs): """Convert document to tiff with detailed settings and save result to storage. Args: name (str): The document name. (required) resultFile (str): The resulting file name. (optional) useAntiAliasing (bool): Use antialiasing flag. (optional) useHighQualityRendering (bool): Use high quality flag. (optional) imageBrightness (float): Brightness for the generated images. (optional) imageColorMode (str): Color mode for the generated images. (optional) imageContrast (float): The contrast for the generated images. (optional) numeralFormat (str): The images numeral format. (optional) pageCount (int): Number of pages to render. (optional) pageIndex (int): Page index to start rendering. (optional) paperColor (str): Background image color. (optional) pixelFormat (str): The pixel format of generated images. (optional) resolution (float): The resolution of generated images. (optional) scale (float): Zoom factor for generated images. (optional) tiffCompression (str): The compression tipe. (optional) dmlRenderingMode (str): Optional, default is Fallback. (optional) dmlEffectsRenderingMode (str): Optional, default is Simplified. (optional) tiffBinarizationMethod (str): Optional, Tiff binarization method, possible values are: FloydSteinbergDithering, Threshold. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) zipOutput (bool): Optional. A value determining zip output or not. (optional) body (TiffSaveOptionsData): Tiff save options. (required) Returns: SaveResponse """ allParams = dict.fromkeys(['name', 'resultFile', 'useAntiAliasing', 'useHighQualityRendering', 'imageBrightness', 'imageColorMode', 'imageContrast', 'numeralFormat', 'pageCount', 'pageIndex', 'paperColor', 'pixelFormat', 'resolution', 'scale', 'tiffCompression', 'dmlRenderingMode', 'dmlEffectsRenderingMode', 'tiffBinarizationMethod', 'storage', 'folder', 'zipOutput', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutDocumentSaveAsTiff" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/SaveAs/tiff/?appSid={appSid}&amp;resultFile={resultFile}&amp;useAntiAliasing={useAntiAliasing}&amp;useHighQualityRendering={useHighQualityRendering}&amp;imageBrightness={imageBrightness}&amp;imageColorMode={imageColorMode}&amp;imageContrast={imageContrast}&amp;numeralFormat={numeralFormat}&amp;pageCount={pageCount}&amp;pageIndex={pageIndex}&amp;paperColor={paperColor}&amp;pixelFormat={pixelFormat}&amp;resolution={resolution}&amp;scale={scale}&amp;tiffCompression={tiffCompression}&amp;dmlRenderingMode={dmlRenderingMode}&amp;dmlEffectsRenderingMode={dmlEffectsRenderingMode}&amp;tiffBinarizationMethod={tiffBinarizationMethod}&amp;storage={storage}&amp;folder={folder}&amp;zipOutput={zipOutput}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'resultFile' in allParams and allParams['resultFile'] is not None: resourcePath = resourcePath.replace("{" + "resultFile" + "}" , str(allParams['resultFile'])) else: resourcePath = re.sub("[&?]resultFile.*?(?=&|\\?|$)", "", resourcePath) if 'useAntiAliasing' in allParams and allParams['useAntiAliasing'] is not None: resourcePath = resourcePath.replace("{" + "useAntiAliasing" + "}" , str(allParams['useAntiAliasing'])) else: resourcePath = re.sub("[&?]useAntiAliasing.*?(?=&|\\?|$)", "", resourcePath) if 'useHighQualityRendering' in allParams and allParams['useHighQualityRendering'] is not None: resourcePath = resourcePath.replace("{" + "useHighQualityRendering" + "}" , str(allParams['useHighQualityRendering'])) else: resourcePath = re.sub("[&?]useHighQualityRendering.*?(?=&|\\?|$)", "", resourcePath) if 'imageBrightness' in allParams and allParams['imageBrightness'] is not None: resourcePath = resourcePath.replace("{" + "imageBrightness" + "}" , str(allParams['imageBrightness'])) else: resourcePath = re.sub("[&?]imageBrightness.*?(?=&|\\?|$)", "", resourcePath) if 'imageColorMode' in allParams and allParams['imageColorMode'] is not None: resourcePath = resourcePath.replace("{" + "imageColorMode" + "}" , str(allParams['imageColorMode'])) else: resourcePath = re.sub("[&?]imageColorMode.*?(?=&|\\?|$)", "", resourcePath) if 'imageContrast' in allParams and allParams['imageContrast'] is not None: resourcePath = resourcePath.replace("{" + "imageContrast" + "}" , str(allParams['imageContrast'])) else: resourcePath = re.sub("[&?]imageContrast.*?(?=&|\\?|$)", "", resourcePath) if 'numeralFormat' in allParams and allParams['numeralFormat'] is not None: resourcePath = resourcePath.replace("{" + "numeralFormat" + "}" , str(allParams['numeralFormat'])) else: resourcePath = re.sub("[&?]numeralFormat.*?(?=&|\\?|$)", "", resourcePath) if 'pageCount' in allParams and allParams['pageCount'] is not None: resourcePath = resourcePath.replace("{" + "pageCount" + "}" , str(allParams['pageCount'])) else: resourcePath = re.sub("[&?]pageCount.*?(?=&|\\?|$)", "", resourcePath) if 'pageIndex' in allParams and allParams['pageIndex'] is not None: resourcePath = resourcePath.replace("{" + "pageIndex" + "}" , str(allParams['pageIndex'])) else: resourcePath = re.sub("[&?]pageIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paperColor' in allParams and allParams['paperColor'] is not None: resourcePath = resourcePath.replace("{" + "paperColor" + "}" , str(allParams['paperColor'])) else: resourcePath = re.sub("[&?]paperColor.*?(?=&|\\?|$)", "", resourcePath) if 'pixelFormat' in allParams and allParams['pixelFormat'] is not None: resourcePath = resourcePath.replace("{" + "pixelFormat" + "}" , str(allParams['pixelFormat'])) else: resourcePath = re.sub("[&?]pixelFormat.*?(?=&|\\?|$)", "", resourcePath) if 'resolution' in allParams and allParams['resolution'] is not None: resourcePath = resourcePath.replace("{" + "resolution" + "}" , str(allParams['resolution'])) else: resourcePath = re.sub("[&?]resolution.*?(?=&|\\?|$)", "", resourcePath) if 'scale' in allParams and allParams['scale'] is not None: resourcePath = resourcePath.replace("{" + "scale" + "}" , str(allParams['scale'])) else: resourcePath = re.sub("[&?]scale.*?(?=&|\\?|$)", "", resourcePath) if 'tiffCompression' in allParams and allParams['tiffCompression'] is not None: resourcePath = resourcePath.replace("{" + "tiffCompression" + "}" , str(allParams['tiffCompression'])) else: resourcePath = re.sub("[&?]tiffCompression.*?(?=&|\\?|$)", "", resourcePath) if 'dmlRenderingMode' in allParams and allParams['dmlRenderingMode'] is not None: resourcePath = resourcePath.replace("{" + "dmlRenderingMode" + "}" , str(allParams['dmlRenderingMode'])) else: resourcePath = re.sub("[&?]dmlRenderingMode.*?(?=&|\\?|$)", "", resourcePath) if 'dmlEffectsRenderingMode' in allParams and allParams['dmlEffectsRenderingMode'] is not None: resourcePath = resourcePath.replace("{" + "dmlEffectsRenderingMode" + "}" , str(allParams['dmlEffectsRenderingMode'])) else: resourcePath = re.sub("[&?]dmlEffectsRenderingMode.*?(?=&|\\?|$)", "", resourcePath) if 'tiffBinarizationMethod' in allParams and allParams['tiffBinarizationMethod'] is not None: resourcePath = resourcePath.replace("{" + "tiffBinarizationMethod" + "}" , str(allParams['tiffBinarizationMethod'])) else: resourcePath = re.sub("[&?]tiffBinarizationMethod.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'zipOutput' in allParams and allParams['zipOutput'] is not None: resourcePath = resourcePath.replace("{" + "zipOutput" + "}" , str(allParams['zipOutput'])) else: resourcePath = re.sub("[&?]zipOutput.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaveResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentStatistics(self, name, **kwargs): """Read document statistics. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: StatDataResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentStatistics" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/statistics/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'StatDataResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteDocumentWatermark(self, name, **kwargs): """Delete watermark (for deleting last watermark from the document). Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteDocumentWatermark" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/watermark/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostInsertDocumentWatermarkImage(self, name, file, **kwargs): """Insert document watermark image. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) rotationAngle (float): The watermark rotation angle. (optional) image (str): The image file server full name. If the name is empty the image is expected in request content. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) file (File): (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'rotationAngle', 'image', 'storage', 'folder', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostInsertDocumentWatermarkImage" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/watermark/insertImage/?appSid={appSid}&amp;filename={filename}&amp;rotationAngle={rotationAngle}&amp;image={image}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'rotationAngle' in allParams and allParams['rotationAngle'] is not None: resourcePath = resourcePath.replace("{" + "rotationAngle" + "}" , str(allParams['rotationAngle'])) else: resourcePath = re.sub("[&?]rotationAngle.*?(?=&|\\?|$)", "", resourcePath) if 'image' in allParams and allParams['image'] is not None: resourcePath = resourcePath.replace("{" + "image" + "}" , str(allParams['image'])) else: resourcePath = re.sub("[&?]image.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostInsertDocumentWatermarkText(self, name, body, **kwargs): """Insert document watermark text. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) text (str): The text to insert. (optional) rotationAngle (float): The text rotation angle. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (WatermarkText): with the watermark data. If the parameter is provided the query string parameters are ignored. (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'text', 'rotationAngle', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostInsertDocumentWatermarkText" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/watermark/insertText/?appSid={appSid}&amp;filename={filename}&amp;text={text}&amp;rotationAngle={rotationAngle}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'text' in allParams and allParams['text'] is not None: resourcePath = resourcePath.replace("{" + "text" + "}" , str(allParams['text'])) else: resourcePath = re.sub("[&?]text.*?(?=&|\\?|$)", "", resourcePath) if 'rotationAngle' in allParams and allParams['rotationAngle'] is not None: resourcePath = resourcePath.replace("{" + "rotationAngle" + "}" , str(allParams['rotationAngle'])) else: resourcePath = re.sub("[&?]rotationAngle.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentDrawingObjectByIndex(self, name, objectIndex, **kwargs): """Read document drawing object common info by its index or convert to format specified. Args: name (str): The document name. (required) objectIndex (int): The drawing object index. (required) storage (str): The document storage. (optional) folder (str): The document folder full path. (optional) Returns: DrawingObjectResponse """ allParams = dict.fromkeys(['name', 'objectIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentDrawingObjectByIndex" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/drawingObjects/{objectIndex}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'objectIndex' in allParams and allParams['objectIndex'] is not None: resourcePath = resourcePath.replace("{" + "objectIndex" + "}" , str(allParams['objectIndex'])) else: resourcePath = re.sub("[&?]objectIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DrawingObjectResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentDrawingObjectByIndexWithFormat(self, name, objectIndex, format, **kwargs): """Read document drawing object common info by its index or convert to format specified. Args: name (str): The document name. (required) objectIndex (int): The drawing object index. (required) format (str): The format to convert (if specified). (required) storage (str): The document storage. (optional) folder (str): The document folder full path. (optional) Returns: ResponseMessage """ allParams = dict.fromkeys(['name', 'objectIndex', 'format', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentDrawingObjectByIndexWithFormat" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/drawingObjects/{objectIndex}/?appSid={appSid}&amp;toFormat={toFormat}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'objectIndex' in allParams and allParams['objectIndex'] is not None: resourcePath = resourcePath.replace("{" + "objectIndex" + "}" , str(allParams['objectIndex'])) else: resourcePath = re.sub("[&?]objectIndex.*?(?=&|\\?|$)", "", resourcePath) if 'format' in allParams and allParams['format'] is not None: resourcePath = resourcePath.replace("{" + "format" + "}" , str(allParams['format'])) else: resourcePath = re.sub("[&?]format.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentDrawingObjectImageData(self, name, objectIndex, **kwargs): """Read drawing object image data. Args: name (str): The document name. (required) objectIndex (int): The drawing object index. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: ResponseMessage """ allParams = dict.fromkeys(['name', 'objectIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentDrawingObjectImageData" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/drawingObjects/{objectIndex}/imageData/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'objectIndex' in allParams and allParams['objectIndex'] is not None: resourcePath = resourcePath.replace("{" + "objectIndex" + "}" , str(allParams['objectIndex'])) else: resourcePath = re.sub("[&?]objectIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentDrawingObjectOleData(self, name, objectIndex, **kwargs): """Get drawing object OLE data. Args: name (str): The document name. (required) objectIndex (int): The object index. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: ResponseMessage """ allParams = dict.fromkeys(['name', 'objectIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentDrawingObjectOleData" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/drawingObjects/{objectIndex}/oleData/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'objectIndex' in allParams and allParams['objectIndex'] is not None: resourcePath = resourcePath.replace("{" + "objectIndex" + "}" , str(allParams['objectIndex'])) else: resourcePath = re.sub("[&?]objectIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/octet-stream' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ResponseMessage', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentDrawingObjects(self, name, **kwargs): """Read document drawing objects common info. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: DrawingObjectsResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentDrawingObjects" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/drawingObjects/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DrawingObjectsResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteFormField(self, name, sectionIndex, paragraphIndex, formfieldIndex, **kwargs): """Removes form field from document. Args: name (str): The document name. (required) sectionIndex (int): Section index. (required) paragraphIndex (int): Paragraph index. (required) formfieldIndex (int): Form field index. (required) destFileName (str): Destination file name. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'paragraphIndex', 'formfieldIndex', 'destFileName', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteFormField" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/paragraphs/{paragraphIndex}/formfields/{formfieldIndex}/?appSid={appSid}&amp;destFileName={destFileName}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paragraphIndex' in allParams and allParams['paragraphIndex'] is not None: resourcePath = resourcePath.replace("{" + "paragraphIndex" + "}" , str(allParams['paragraphIndex'])) else: resourcePath = re.sub("[&?]paragraphIndex.*?(?=&|\\?|$)", "", resourcePath) if 'formfieldIndex' in allParams and allParams['formfieldIndex'] is not None: resourcePath = resourcePath.replace("{" + "formfieldIndex" + "}" , str(allParams['formfieldIndex'])) else: resourcePath = re.sub("[&?]formfieldIndex.*?(?=&|\\?|$)", "", resourcePath) if 'destFileName' in allParams and allParams['destFileName'] is not None: resourcePath = resourcePath.replace("{" + "destFileName" + "}" , str(allParams['destFileName'])) else: resourcePath = re.sub("[&?]destFileName.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetFormField(self, name, sectionIndex, paragraphIndex, formfieldIndex, **kwargs): """Returns representation of an one of the form field. Args: name (str): The document name. (required) sectionIndex (int): Section index. (required) paragraphIndex (int): Paragraph index. (required) formfieldIndex (int): Form field index. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: FormFieldResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'paragraphIndex', 'formfieldIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetFormField" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/paragraphs/{paragraphIndex}/formfields/{formfieldIndex}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paragraphIndex' in allParams and allParams['paragraphIndex'] is not None: resourcePath = resourcePath.replace("{" + "paragraphIndex" + "}" , str(allParams['paragraphIndex'])) else: resourcePath = re.sub("[&?]paragraphIndex.*?(?=&|\\?|$)", "", resourcePath) if 'formfieldIndex' in allParams and allParams['formfieldIndex'] is not None: resourcePath = resourcePath.replace("{" + "formfieldIndex" + "}" , str(allParams['formfieldIndex'])) else: resourcePath = re.sub("[&?]formfieldIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FormFieldResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostFormField(self, name, sectionIndex, paragraphIndex, formfieldIndex, body, **kwargs): """Updates form field's properties, returns updated form field's data. Args: name (str): The document name. (required) sectionIndex (int): Section index. (required) paragraphIndex (int): Paragraph index. (required) formfieldIndex (int): Form field index. (required) destFileName (str): Destination file name. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (FormField): From field data. (required) Returns: FormFieldResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'paragraphIndex', 'formfieldIndex', 'destFileName', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostFormField" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/paragraphs/{paragraphIndex}/formfields/{formfieldIndex}/?appSid={appSid}&amp;destFileName={destFileName}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paragraphIndex' in allParams and allParams['paragraphIndex'] is not None: resourcePath = resourcePath.replace("{" + "paragraphIndex" + "}" , str(allParams['paragraphIndex'])) else: resourcePath = re.sub("[&?]paragraphIndex.*?(?=&|\\?|$)", "", resourcePath) if 'formfieldIndex' in allParams and allParams['formfieldIndex'] is not None: resourcePath = resourcePath.replace("{" + "formfieldIndex" + "}" , str(allParams['formfieldIndex'])) else: resourcePath = re.sub("[&?]formfieldIndex.*?(?=&|\\?|$)", "", resourcePath) if 'destFileName' in allParams and allParams['destFileName'] is not None: resourcePath = resourcePath.replace("{" + "destFileName" + "}" , str(allParams['destFileName'])) else: resourcePath = re.sub("[&?]destFileName.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FormFieldResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PutFormField(self, name, sectionIndex, paragraphIndex, body, **kwargs): """Adds form field to paragraph, returns added form field's data. Args: name (str): The document name. (required) sectionIndex (int): Section index. (required) paragraphIndex (int): Paragraph index. (required) insertBeforeNode (str): Form field will be inserted before node with index. (optional) destFileName (str): Destination file name. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (FormField): From field data. (required) Returns: FormFieldResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'paragraphIndex', 'insertBeforeNode', 'destFileName', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PutFormField" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/paragraphs/{paragraphIndex}/formfields/?appSid={appSid}&amp;insertBeforeNode={insertBeforeNode}&amp;destFileName={destFileName}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paragraphIndex' in allParams and allParams['paragraphIndex'] is not None: resourcePath = resourcePath.replace("{" + "paragraphIndex" + "}" , str(allParams['paragraphIndex'])) else: resourcePath = re.sub("[&?]paragraphIndex.*?(?=&|\\?|$)", "", resourcePath) if 'insertBeforeNode' in allParams and allParams['insertBeforeNode'] is not None: resourcePath = resourcePath.replace("{" + "insertBeforeNode" + "}" , str(allParams['insertBeforeNode'])) else: resourcePath = re.sub("[&?]insertBeforeNode.*?(?=&|\\?|$)", "", resourcePath) if 'destFileName' in allParams and allParams['destFileName'] is not None: resourcePath = resourcePath.replace("{" + "destFileName" + "}" , str(allParams['destFileName'])) else: resourcePath = re.sub("[&?]destFileName.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'PUT' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FormFieldResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteHeadersFooters(self, name, **kwargs): """Delete document headers and footers. Args: name (str): The document name. (required) headersFootersTypes (str): List of types of headers and footers. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'headersFootersTypes', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteHeadersFooters" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/headersfooters/?appSid={appSid}&amp;headersFootersTypes={headersFootersTypes}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'headersFootersTypes' in allParams and allParams['headersFootersTypes'] is not None: resourcePath = resourcePath.replace("{" + "headersFootersTypes" + "}" , str(allParams['headersFootersTypes'])) else: resourcePath = re.sub("[&?]headersFootersTypes.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentHyperlinkByIndex(self, name, hyperlinkIndex, **kwargs): """Read document hyperlink by its index. Args: name (str): The document name. (required) hyperlinkIndex (int): The hyperlink index. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: HyperlinkResponse """ allParams = dict.fromkeys(['name', 'hyperlinkIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentHyperlinkByIndex" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/hyperlinks/{hyperlinkIndex}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'hyperlinkIndex' in allParams and allParams['hyperlinkIndex'] is not None: resourcePath = resourcePath.replace("{" + "hyperlinkIndex" + "}" , str(allParams['hyperlinkIndex'])) else: resourcePath = re.sub("[&?]hyperlinkIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'HyperlinkResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentHyperlinks(self, name, **kwargs): """Read document hyperlinks common info. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: HyperlinksResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentHyperlinks" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/hyperlinks/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'HyperlinksResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteDocumentMacros(self, name, **kwargs): """Remove macros from document. Args: name (str): The file name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteDocumentMacros" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/macros/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentFieldNames(self, name, **kwargs): """Read document field names. Args: name (str): The document name. (required) useNonMergeFields (bool): (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: FieldNamesResponse """ allParams = dict.fromkeys(['name', 'useNonMergeFields', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentFieldNames" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/mailMergeFieldNames/?appSid={appSid}&amp;useNonMergeFields={useNonMergeFields}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'useNonMergeFields' in allParams and allParams['useNonMergeFields'] is not None: resourcePath = resourcePath.replace("{" + "useNonMergeFields" + "}" , str(allParams['useNonMergeFields'])) else: resourcePath = re.sub("[&?]useNonMergeFields.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FieldNamesResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostDocumentExecuteMailMerge(self, name, withRegions, file, **kwargs): """Execute document mail merge operation. Args: name (str): The document name. (required) withRegions (bool): With regions flag. (required) mailMergeDataFile (str): Mail merge data. (optional) cleanup (str): Clean up options. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) useWholeParagraphAsRegion (bool): Gets or sets a value indicating whether paragraph with TableStart or TableEnd field should be fully included into mail merge region or particular range between TableStart and TableEnd fields. The default value is true. (optional) file (File): (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'withRegions', 'mailMergeDataFile', 'cleanup', 'filename', 'storage', 'folder', 'useWholeParagraphAsRegion', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostDocumentExecuteMailMerge" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/executeMailMerge/{withRegions}/?appSid={appSid}&amp;mailMergeDataFile={mailMergeDataFile}&amp;cleanup={cleanup}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}&amp;useWholeParagraphAsRegion={useWholeParagraphAsRegion}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'withRegions' in allParams and allParams['withRegions'] is not None: resourcePath = resourcePath.replace("{" + "withRegions" + "}" , str(allParams['withRegions'])) else: resourcePath = re.sub("[&?]withRegions.*?(?=&|\\?|$)", "", resourcePath) if 'mailMergeDataFile' in allParams and allParams['mailMergeDataFile'] is not None: resourcePath = resourcePath.replace("{" + "mailMergeDataFile" + "}" , str(allParams['mailMergeDataFile'])) else: resourcePath = re.sub("[&?]mailMergeDataFile.*?(?=&|\\?|$)", "", resourcePath) if 'cleanup' in allParams and allParams['cleanup'] is not None: resourcePath = resourcePath.replace("{" + "cleanup" + "}" , str(allParams['cleanup'])) else: resourcePath = re.sub("[&?]cleanup.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'useWholeParagraphAsRegion' in allParams and allParams['useWholeParagraphAsRegion'] is not None: resourcePath = resourcePath.replace("{" + "useWholeParagraphAsRegion" + "}" , str(allParams['useWholeParagraphAsRegion'])) else: resourcePath = re.sub("[&?]useWholeParagraphAsRegion.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteParagraphFields(self, name, index, **kwargs): """Remove fields from paragraph. Args: name (str): The file name. (required) index (int): Paragraph index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'index', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteParagraphFields" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/{index}/fields/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'index' in allParams and allParams['index'] is not None: resourcePath = resourcePath.replace("{" + "index" + "}" , str(allParams['index'])) else: resourcePath = re.sub("[&?]index.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentParagraph(self, name, index, **kwargs): """This resource represents one of the paragraphs contained in the document. Args: name (str): The document name. (required) index (int): Paragraph index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: ParagraphResponse """ allParams = dict.fromkeys(['name', 'index', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentParagraph" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/{index}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'index' in allParams and allParams['index'] is not None: resourcePath = resourcePath.replace("{" + "index" + "}" , str(allParams['index'])) else: resourcePath = re.sub("[&?]index.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ParagraphResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentParagraphRun(self, name, index, runIndex, **kwargs): """This resource represents one of the paragraphs contained in the document. Args: name (str): The document name. (required) index (int): Paragraph index (required) runIndex (int): Run index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: RunResponse """ allParams = dict.fromkeys(['name', 'index', 'runIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentParagraphRun" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/{index}/runs/{runIndex}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'index' in allParams and allParams['index'] is not None: resourcePath = resourcePath.replace("{" + "index" + "}" , str(allParams['index'])) else: resourcePath = re.sub("[&?]index.*?(?=&|\\?|$)", "", resourcePath) if 'runIndex' in allParams and allParams['runIndex'] is not None: resourcePath = resourcePath.replace("{" + "runIndex" + "}" , str(allParams['runIndex'])) else: resourcePath = re.sub("[&?]runIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'RunResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentParagraphRunFont(self, name, index, runIndex, **kwargs): """This resource represents one of the paragraphs contained in the document. Args: name (str): The document name. (required) index (int): Paragraph index (required) runIndex (int): Run index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: FontResponse """ allParams = dict.fromkeys(['name', 'index', 'runIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentParagraphRunFont" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/{index}/runs/{runIndex}/font/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'index' in allParams and allParams['index'] is not None: resourcePath = resourcePath.replace("{" + "index" + "}" , str(allParams['index'])) else: resourcePath = re.sub("[&?]index.*?(?=&|\\?|$)", "", resourcePath) if 'runIndex' in allParams and allParams['runIndex'] is not None: resourcePath = resourcePath.replace("{" + "runIndex" + "}" , str(allParams['runIndex'])) else: resourcePath = re.sub("[&?]runIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FontResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentParagraphs(self, name, **kwargs): """Return a list of paragraphs that are contained in the document. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: ParagraphLinkCollectionResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentParagraphs" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ParagraphLinkCollectionResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostDocumentParagraphRunFont(self, name, index, runIndex, body, **kwargs): """This resource represents one of the paragraphs contained in the document. Args: name (str): The document name. (required) index (int): Paragraph index (required) runIndex (int): Run index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) body (Font): Font dto object (required) Returns: FontResponse """ allParams = dict.fromkeys(['name', 'index', 'runIndex', 'storage', 'folder', 'filename', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostDocumentParagraphRunFont" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/paragraphs/{index}/runs/{runIndex}/font/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}&amp;filename={filename}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'index' in allParams and allParams['index'] is not None: resourcePath = resourcePath.replace("{" + "index" + "}" , str(allParams['index'])) else: resourcePath = re.sub("[&?]index.*?(?=&|\\?|$)", "", resourcePath) if 'runIndex' in allParams and allParams['runIndex'] is not None: resourcePath = resourcePath.replace("{" + "runIndex" + "}" , str(allParams['runIndex'])) else: resourcePath = re.sub("[&?]runIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'FontResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def AcceptAllRevisions(self, name, **kwargs): """Accept all revisions in document Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: RevisionsModificationResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method AcceptAllRevisions" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/revisions/acceptAll/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'RevisionsModificationResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def RejectAllRevisions(self, name, **kwargs): """Reject all revisions in document Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: RevisionsModificationResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method RejectAllRevisions" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/revisions/rejectAll/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'RevisionsModificationResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteSectionFields(self, name, sectionIndex, **kwargs): """Remove fields from section. Args: name (str): The file name. (required) sectionIndex (int): Section index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteSectionFields" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/fields/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def DeleteSectionParagraphFields(self, name, sectionIndex, paragraphIndex, **kwargs): """Remove fields from section paragraph. Args: name (str): The file name. (required) sectionIndex (int): Section index (required) paragraphIndex (int): Paragraph index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SaaSposeResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'paragraphIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method DeleteSectionParagraphFields" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/paragraphs/{paragraphIndex}/fields/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'paragraphIndex' in allParams and allParams['paragraphIndex'] is not None: resourcePath = resourcePath.replace("{" + "paragraphIndex" + "}" , str(allParams['paragraphIndex'])) else: resourcePath = re.sub("[&?]paragraphIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'DELETE' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SaaSposeResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetSection(self, name, sectionIndex, **kwargs): """Get document section by index. Args: name (str): The document name. (required) sectionIndex (int): Section index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SectionResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetSection" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) print "resourcePath" + resourcePath if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) print "resourcePath" + resourcePath if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SectionResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetSectionPageSetup(self, name, sectionIndex, **kwargs): """Get page setup of section. Args: name (str): The document name. (required) sectionIndex (int): Section index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SectionPageSetupResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetSectionPageSetup" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/pageSetup/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SectionPageSetupResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetSections(self, name, **kwargs): """Return a list of sections that are contained in the document. Args: name (str): The document name. (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) Returns: SectionLinkCollectionResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetSections" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SectionLinkCollectionResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def UpdateSectionPageSetup(self, name, sectionIndex, body, **kwargs): """Update page setup of section. Args: name (str): The document name. (required) sectionIndex (int): Section index (required) storage (str): The document storage. (optional) folder (str): The document folder. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. (optional) body (PageSetup): Page setup properties dto (required) Returns: SectionPageSetupResponse """ allParams = dict.fromkeys(['name', 'sectionIndex', 'storage', 'folder', 'filename', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method UpdateSectionPageSetup" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/sections/{sectionIndex}/pageSetup/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}&amp;filename={filename}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'sectionIndex' in allParams and allParams['sectionIndex'] is not None: resourcePath = resourcePath.replace("{" + "sectionIndex" + "}" , str(allParams['sectionIndex'])) else: resourcePath = re.sub("[&?]sectionIndex.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'SectionPageSetupResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def GetDocumentTextItems(self, name, **kwargs): """Read document text items. Args: name (str): The document name. (required) storage (str): Document's storage. (optional) folder (str): Document's folder. (optional) Returns: TextItemsResponse """ allParams = dict.fromkeys(['name', 'storage', 'folder']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method GetDocumentTextItems" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/textItems/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'GET' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'TextItemsResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostReplaceText(self, name, body, **kwargs): """Replace document text. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (ReplaceTextRequest): with the replace operation settings. (required) Returns: ReplaceTextResponse """ allParams = dict.fromkeys(['name', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostReplaceText" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/replaceText/?appSid={appSid}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'ReplaceTextResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostInsertWatermarkImage(self, name, file, **kwargs): """Insert document watermark image. Args: name (str): The document name. (required) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) rotationAngle (float): The watermark rotation angle. (optional) image (str): The image file server full name. If the name is empty the image is expected in request content. (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) file (File): (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'filename', 'rotationAngle', 'image', 'storage', 'folder', 'file']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostInsertWatermarkImage" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/insertWatermarkImage/?appSid={appSid}&amp;filename={filename}&amp;rotationAngle={rotationAngle}&amp;image={image}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'rotationAngle' in allParams and allParams['rotationAngle'] is not None: resourcePath = resourcePath.replace("{" + "rotationAngle" + "}" , str(allParams['rotationAngle'])) else: resourcePath = re.sub("[&?]rotationAngle.*?(?=&|\\?|$)", "", resourcePath) if 'image' in allParams and allParams['image'] is not None: resourcePath = resourcePath.replace("{" + "image" + "}" , str(allParams['image'])) else: resourcePath = re.sub("[&?]image.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { 'file':open(file, 'rb')} bodyParam = None headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'multipart/form-data' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content) def PostInsertWatermarkText(self, name, body, **kwargs): """Insert document watermark text. Args: name (str): The document name. (required) text (str): The text to insert. (optional) rotationAngle (float): The text rotation angle. (optional) filename (str): Result name of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document (optional) storage (str): The document storage. (optional) folder (str): The document folder. (optional) body (WatermarkText): with the watermark data. If the parameter is provided the query string parameters are ignored. (required) Returns: DocumentResponse """ allParams = dict.fromkeys(['name', 'text', 'rotationAngle', 'filename', 'storage', 'folder', 'body']) params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s' to method PostInsertWatermarkText" % key) params[key] = val for (key, val) in params.iteritems(): if key in allParams: allParams[key] = val resourcePath = '/words/{name}/insertWatermarkText/?appSid={appSid}&amp;text={text}&amp;rotationAngle={rotationAngle}&amp;filename={filename}&amp;storage={storage}&amp;folder={folder}' resourcePath = resourcePath.replace('&amp;','&').replace("/?","?").replace("toFormat={toFormat}","format={format}").replace("{path}","{Path}") if 'name' in allParams and allParams['name'] is not None: resourcePath = resourcePath.replace("{" + "name" + "}" , str(allParams['name'])) else: resourcePath = re.sub("[&?]name.*?(?=&|\\?|$)", "", resourcePath) if 'text' in allParams and allParams['text'] is not None: resourcePath = resourcePath.replace("{" + "text" + "}" , str(allParams['text'])) else: resourcePath = re.sub("[&?]text.*?(?=&|\\?|$)", "", resourcePath) if 'rotationAngle' in allParams and allParams['rotationAngle'] is not None: resourcePath = resourcePath.replace("{" + "rotationAngle" + "}" , str(allParams['rotationAngle'])) else: resourcePath = re.sub("[&?]rotationAngle.*?(?=&|\\?|$)", "", resourcePath) if 'filename' in allParams and allParams['filename'] is not None: resourcePath = resourcePath.replace("{" + "filename" + "}" , str(allParams['filename'])) else: resourcePath = re.sub("[&?]filename.*?(?=&|\\?|$)", "", resourcePath) if 'storage' in allParams and allParams['storage'] is not None: resourcePath = resourcePath.replace("{" + "storage" + "}" , str(allParams['storage'])) else: resourcePath = re.sub("[&?]storage.*?(?=&|\\?|$)", "", resourcePath) if 'folder' in allParams and allParams['folder'] is not None: resourcePath = resourcePath.replace("{" + "folder" + "}" , str(allParams['folder'])) else: resourcePath = re.sub("[&?]folder.*?(?=&|\\?|$)", "", resourcePath) method = 'POST' queryParams = {} headerParams = {} formParams = {} files = { } bodyParam = body headerParams['Accept'] = 'application/xml,application/json' headerParams['Content-Type'] = 'application/json' postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, postData, headerParams, files=files) try: if response.status_code in [200,201,202]: responseObject = self.apiClient.pre_deserialize(response.content, 'DocumentResponse', response.headers['content-type']) return responseObject else: raise ApiException(response.status_code,response.content) except Exception: raise ApiException(response.status_code,response.content)
mit
jamespcole/home-assistant
homeassistant/components/http/auth.py
8
7249
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeassistant.core import callback from homeassistant.util import dt as dt_util from .const import ( KEY_AUTHENTICATED, KEY_HASS_USER, KEY_REAL_IP, ) _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD = 'api_password' DATA_SIGN_SECRET = 'http.auth.sign_secret' SIGN_QUERY_PARAM = 'authSig' @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format(path, SIGN_QUERY_PARAM, jwt.encode({ 'iss': refresh_token_id, 'path': path, 'iat': now, 'exp': now + expiration, }, secret, algorithm='HS256').decode()) @callback def setup_auth(hass, app): """Create auth middleware for the app.""" old_auth_warning = set() support_legacy = hass.auth.support_legacy if support_legacy: _LOGGER.warning("legacy_api_password support has been enabled.") trusted_networks = [] for prv in hass.auth.auth_providers: if prv.type == 'trusted_networks': trusted_networks += prv.trusted_networks async def async_validate_auth_header(request): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ try: auth_type, auth_val = \ request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) except ValueError: # If no space in authorization header return False if auth_type == 'Bearer': refresh_token = await hass.auth.async_validate_access_token( auth_val) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True if auth_type == 'Basic' and support_legacy: decoded = base64.b64decode(auth_val).decode('utf-8') try: username, password = decoded.split(':', 1) except ValueError: # If no ':' in decoded return False if username != 'homeassistant': return False user = await legacy_api_password.async_validate_password( hass, password) if user is None: return False request[KEY_HASS_USER] = user _LOGGER.info( 'Basic auth with api_password is going to deprecate,' ' please use a bearer token to access %s from %s', request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) return True return False async def async_validate_signed_request(request): """Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=['HS256'], options={'verify_iss': False} ) except jwt.InvalidTokenError: return False if claims['path'] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims['iss']) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True async def async_validate_trusted_networks(request): """Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] if not any(ip_addr in trusted_network for trusted_network in trusted_networks): return False user = await hass.auth.async_get_owner() if user is None: return False request[KEY_HASS_USER] = user return True async def async_validate_legacy_api_password(request, password): """Validate api_password.""" user = await legacy_api_password.async_validate_password( hass, password) if user is None: return False request[KEY_HASS_USER] = user return True @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers or DATA_API_PASSWORD in request.query): if request.path not in old_auth_warning: _LOGGER.log( logging.INFO if support_legacy else logging.WARNING, 'api_password is going to deprecate. You need to use a' ' bearer token to access %s from %s', request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) if (hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header(request)): # it included both use_auth and api_password Basic auth authenticated = True # We first start with a string check to avoid parsing query params # for every request. elif (request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request)): authenticated = True elif (trusted_networks and await async_validate_trusted_networks(request)): if request.path not in old_auth_warning: # When removing this, don't forget to remove the print logic # in http/view.py request['deprecate_warning_message'] = \ 'Access from trusted networks without auth token is ' \ 'going to be removed in Home Assistant 0.96. Configure ' \ 'the trusted networks auth provider or use long-lived ' \ 'access tokens to access {} from {}'.format( request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) authenticated = True elif (support_legacy and HTTP_HEADER_HA_AUTH in request.headers and await async_validate_legacy_api_password( request, request.headers[HTTP_HEADER_HA_AUTH])): authenticated = True elif (support_legacy and DATA_API_PASSWORD in request.query and await async_validate_legacy_api_password( request, request.query[DATA_API_PASSWORD])): authenticated = True request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware)
apache-2.0
jideobs/twilioAngular
venv/lib/python2.7/site-packages/pip/_vendor/html5lib/treewalkers/lxmletree.py
436
5992
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type from lxml import etree from ..treebuilders.etree import tag_regexp from . import _base from .. import ihatexml def ensure_str(s): if s is None: return None elif isinstance(s, text_type): return s else: return s.decode("utf-8", "strict") class Root(object): def __init__(self, et): self.elementtree = et self.children = [] if et.docinfo.internalDTD: self.children.append(Doctype(self, ensure_str(et.docinfo.root_name), ensure_str(et.docinfo.public_id), ensure_str(et.docinfo.system_url))) root = et.getroot() node = root while node.getprevious() is not None: node = node.getprevious() while node is not None: self.children.append(node) node = node.getnext() self.text = None self.tail = None def __getitem__(self, key): return self.children[key] def getnext(self): return None def __len__(self): return 1 class Doctype(object): def __init__(self, root_node, name, public_id, system_id): self.root_node = root_node self.name = name self.public_id = public_id self.system_id = system_id self.text = None self.tail = None def getnext(self): return self.root_node.children[1] class FragmentRoot(Root): def __init__(self, children): self.children = [FragmentWrapper(self, child) for child in children] self.text = self.tail = None def getnext(self): return None class FragmentWrapper(object): def __init__(self, fragment_root, obj): self.root_node = fragment_root self.obj = obj if hasattr(self.obj, 'text'): self.text = ensure_str(self.obj.text) else: self.text = None if hasattr(self.obj, 'tail'): self.tail = ensure_str(self.obj.tail) else: self.tail = None def __getattr__(self, name): return getattr(self.obj, name) def getnext(self): siblings = self.root_node.children idx = siblings.index(self) if idx < len(siblings) - 1: return siblings[idx + 1] else: return None def __getitem__(self, key): return self.obj[key] def __bool__(self): return bool(self.obj) def getparent(self): return None def __str__(self): return str(self.obj) def __unicode__(self): return str(self.obj) def __len__(self): return len(self.obj) class TreeWalker(_base.NonRecursiveTreeWalker): def __init__(self, tree): if hasattr(tree, "getroot"): tree = Root(tree) elif isinstance(tree, list): tree = FragmentRoot(tree) _base.NonRecursiveTreeWalker.__init__(self, tree) self.filter = ihatexml.InfosetFilter() def getNodeDetails(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), "Text nodes are text or tail, found %s" % key return _base.TEXT, ensure_str(getattr(node, key)) elif isinstance(node, Root): return (_base.DOCUMENT,) elif isinstance(node, Doctype): return _base.DOCTYPE, node.name, node.public_id, node.system_id elif isinstance(node, FragmentWrapper) and not hasattr(node, "tag"): return _base.TEXT, node.obj elif node.tag == etree.Comment: return _base.COMMENT, ensure_str(node.text) elif node.tag == etree.Entity: return _base.ENTITY, ensure_str(node.text)[1:-1] # strip &; else: # This is assumed to be an ordinary element match = tag_regexp.match(ensure_str(node.tag)) if match: namespace, tag = match.groups() else: namespace = None tag = ensure_str(node.tag) attrs = {} for name, value in list(node.attrib.items()): name = ensure_str(name) value = ensure_str(value) match = tag_regexp.match(name) if match: attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value return (_base.ELEMENT, namespace, self.filter.fromXmlName(tag), attrs, len(node) > 0 or node.text) def getFirstChild(self, node): assert not isinstance(node, tuple), "Text nodes have no children" assert len(node) or node.text, "Node has no children" if node.text: return (node, "text") else: return node[0] def getNextSibling(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), "Text nodes are text or tail, found %s" % key if key == "text": # XXX: we cannot use a "bool(node) and node[0] or None" construct here # because node[0] might evaluate to False if it has no child element if len(node): return node[0] else: return None else: # tail return node.getnext() return (node, "tail") if node.tail else node.getnext() def getParentNode(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), "Text nodes are text or tail, found %s" % key if key == "text": return node # else: fallback to "normal" processing return node.getparent()
mit
apocalypsebg/odoo
addons/lunch/__openerp__.py
267
2542
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Lunch Orders', 'author': 'OpenERP SA', 'version': '0.2', 'depends': ['base', 'report'], 'category' : 'Tools', 'summary': 'Lunch Order, Meal, Food', 'description': """ The base module to manage lunch. ================================ Many companies order sandwiches, pizzas and other, from usual suppliers, for their employees to offer them more facilities. However lunches management within the company requires proper administration especially when the number of employees or suppliers is important. The “Lunch Order” module has been developed to make this management easier but also to offer employees more tools and usability. In addition to a full meal and supplier management, this module offers the possibility to display warning and provides quick order selection based on employee’s preferences. If you want to save your employees' time and avoid them to always have coins in their pockets, this module is essential. """, 'data': [ 'security/lunch_security.xml', 'lunch_view.xml', 'wizard/lunch_order_view.xml', 'wizard/lunch_validation_view.xml', 'wizard/lunch_cancel_view.xml', 'lunch_report.xml', 'report/report_lunch_order_view.xml', 'security/ir.model.access.csv', 'views/report_lunchorder.xml', 'views/lunch.xml', ], 'demo': ['lunch_demo.xml',], 'installable': True, 'website': 'https://www.odoo.com/page/employees', 'application' : True, 'certificate' : '001292377792581874189', }
agpl-3.0
tortugueta/multilayers
examples/radcenter_distribution.py
1
8087
# -*- coding: utf-8 -*- """ Name : radcenter_distribution Author : Joan Juvert <trust.no.one.51@gmail.com> Version : 1.0 Description : This script calculates the influence of the distribution of : radiative centers in the active layer on the observed : spectrum. Copyright 2012 Joan Juvert This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import multilayers as ml import numpy as np import bphysics as bp import scipy.integrate as integ import argparse as ap import sys import pdb # Argument parsing parser = ap.ArgumentParser( description = "This script calculates the effect of the " + \ "distribution of radiative centers in the active layer on " + \ "the modificator to the spectrum. The observation angle is " + \ "a fixed parameter. Optionally, the output can be plotted " + \ "and output to the standard output or to a file. The matrix " + \ "containing the values of F(z, lambda) can be saved to a file " + \ "and recovered in a following run of the program to avoid " + \ "recalculating it in case we want to calculate the effect of " + \ "different distributions on the same system.") parser.add_argument( "--graph", help = "Plot the results", action = "store_true") parser.add_argument( "-o", "--output", help = "Dump the results to a file") parser.add_argument( "-s", "--savematrix", help = "Save the matrix with the F(z, lambda) values to a file") parser.add_argument( "-l", "--loadmatrix", help = "Load the matrix with the F(z, lambda) values from a file") args = parser.parse_args() # Load the depth distribution of radiative centers. Note that the origin # and units of z must be the same as in the multilayer.The distribution # should be normalized to 1. print("Loading the distribution...") path = "/home/joan/Dropbox/CNM/projectes/simulations_report/figures/" + \ "rcdistributions/" distribution = bp.rdfile(path + "gaussian_m25_s07.dat", usecols = [0, 1])[1] print("Done") print("Checking the distribution...") integral = integ.simps(distribution[:, 1], distribution[:, 0], 0) np.testing.assert_almost_equal(integral, 1, 2) print("Done") # If we load the values of F(z, lambda) calculated in a previous # execution we do not need to build the multilayer and repeat the # calculation of the F function. Notice that the values of z at which # the new distribution is sampled should be the same as the previous # one. if args.loadmatrix: print("Loading matrix...") fmatrix = np.load(args.loadmatrix) zlist = fmatrix['zlist'] np.testing.assert_array_equal(zlist, distribution[:, 0]) wlist = fmatrix['wlist'] angle = fmatrix['angle'] fte = fmatrix['fte'] ftm = fmatrix['ftm'] print("Done") else: # Create the materials print("Loading materials... ") silicon = ml.Medium("silicon.dat") air = ml.Medium("air.dat") sio2 = ml.Medium("sio2.dat") poly = ml.Medium("polysilicon.dat") print("Done") # Set the fixed parameters. angle = np.deg2rad(0) # Create the multilayer print("Building multilayer and allocating memory... ") thicknesses = [300, 50] multilayer = ml.Multilayer([ air, [poly, thicknesses[0]], [sio2, thicknesses[1]], silicon]) # Define the wavelengths and z coordinates at which F will be calculated # and allocate memory for the results. We will use a structured array to # store the values of F(z, lambda). wstep = 1 wmin = multilayer.getMinMaxWlength()[0] wmax = multilayer.getMinMaxWlength()[1] wlist = np.arange(wmin, wmax, wstep) zlist = distribution[:, 0] ftype = np.dtype([ ('fx', np.complex128), ('fy', np.complex128), ('fz', np.complex128)]) resmatrix = np.empty((zlist.size, wlist.size), dtype = ftype) print("Done") # I(wavelength, theta) = s(wavelength) * F'(wavelength, theta), where # F'(wav, theta) = integral[z](|F|^2 * rcdist(z). Therefore, we # calculate the new spectrum as a modification to the original spectrum. # The modification factor F'(wav, theta) is an integral over z. # First calculate |Fy|^2 for te and |Fx*cos^2 + Fz*sin^2|^2 for tm. We # do fx and fz in one loop and fy in another independent loop to avoid # recalculating the characteristic matrix at every iteration due to the # change of polarization. print("Calculating F...") for (widx, wlength) in enumerate(wlist): percent = (float(widx) / wlist.size) * 100 print("%.2f%%" % percent) for (zidx, z) in enumerate(zlist): resmatrix[zidx][widx]['fx'] = multilayer.calculateFx(z, wlength, angle) resmatrix[zidx][widx]['fz'] = multilayer.calculateFz(z, wlength, angle) for (zidx, z) in enumerate(zlist): resmatrix[zidx][widx]['fy'] = multilayer.calculateFy(z, wlength, angle) # We are probably more interesed on the effect of the multilayer on the # energy rather than the electric field. What we want is |Fy(z)|^2 for # TE waves and |Fx(z) cosA^2 + Fz(z) sinA^2|^2 for TM waves. ftm = np.absolute( resmatrix['fx'] * np.cos(angle) ** 2 + \ resmatrix['fz'] * np.sin(angle) ** 2) ** 2 fte = np.absolute(resmatrix['fy']) ** 2 print("Done") # Notice that until now we have not used the distribution of the # radiative ceneters, but the calculation of ftm and fte is costly. # If requested, we can save fte and ftm to a file. In a following # execution of the script, the matrix can be loaded from the file # instead of recalculated. if args.savematrix: print("Saving matrix...") np.savez(args.savematrix, fte = fte, ftm = ftm, zlist = zlist, wlist = wlist, angle = angle) print("Done") # Build or load the original spectrum. It should be sampled at the same # wavelengths defined in wlist. If we are interested only in the # modificator to the spectrum, not in the modified spectrum, we can # leave it at 1. original_spec = 1 # Multiply each F(z, lambda) by the distribution. print("Integrating...") distval = distribution[:, 1].reshape(distribution[:, 1].size, 1) fte_mplied = fte * distval ftm_mplied = ftm * distval fte_int = integ.simps(fte_mplied, zlist, axis = 0) ftm_int = integ.simps(ftm_mplied, zlist, axis = 0) spectrum_modte = original_spec * fte_int spectrum_modtm = original_spec * ftm_int print("Done") # Dump data to file or stdout comments = "# F_TE = |Fy^2|^2\n" + \ "# F_TM = |Fx * cosA^2 + Fz * sinA^2|^2\n" + \ "# Modified spectrum for TE and TM waves for a\n" + \ "# distributions of the radiative centers.\n" + \ "# wlength\tF_TE\tF_TM" if args.output: bp.wdfile(args.output, comments, np.array([wlist, spectrum_modte, spectrum_modtm]).T, '%.6e') else: print(comments) for i in xrange(wlist.size): print("%.6e\t%.6e\t%.6e" % (wlist[i], spectrum_modte[i], spectrum_modtm[i])) # Plot data if requested if args.graph: import matplotlib.pyplot as plt plt.plot(wlist, spectrum_modte, label='TE', color = 'r') plt.plot(wlist, spectrum_modtm, label='TM', color = 'b') plt.xlabel('Wavelength (nm)') plt.ylabel('Energy ratio') plt.grid() plt.legend(loc=2) plt.title('%.1f rad' % angle) plt.show() plt.close()
gpl-3.0
linaro-technologies/jobserv
jobserv/storage/local_storage.py
1
3989
# Copyright (C) 2017 Linaro Limited # Author: Andy Doan <andy.doan@linaro.org> import hmac import os import mimetypes import shutil from flask import Blueprint, request, send_file, url_for from jobserv.jsend import get_or_404 from jobserv.models import Build, Project, Run from jobserv.settings import INTERNAL_API_KEY, LOCAL_ARTIFACTS_DIR from jobserv.storage.base import BaseStorage blueprint = Blueprint('local_storage', __name__, url_prefix='/local-storage') class Storage(BaseStorage): blueprint = blueprint def __init__(self): super().__init__() self.artifacts = LOCAL_ARTIFACTS_DIR def _get_local(self, storage_path): assert storage_path[0] != '/' path = os.path.join(self.artifacts, storage_path) dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) return path def _create_from_string(self, storage_path, contents): path = self._get_local(storage_path) with open(path, 'w') as f: f.write(contents) def _create_from_file(self, storage_path, filename, content_type): path = self._get_local(storage_path) with open(filename, 'rb') as fin, open(path, 'wb') as fout: shutil.copyfileobj(fin, fout) def _get_as_string(self, storage_path): assert storage_path[0] != '/' path = os.path.join(self.artifacts, storage_path) with open(path, 'r') as f: return f.read() def list_artifacts(self, run): path = '%s/%s/%s/' % ( run.build.project.name, run.build.build_id, run.name) path = os.path.join(self.artifacts, path) for base, _, names in os.walk(path): for name in names: if name != '.rundef.json': yield os.path.join(base, name)[len(path):] def get_download_response(self, request, run, path): try: p = os.path.join(self.artifacts, self._get_run_path(run), path) mt = mimetypes.guess_type(p)[0] return send_file(open(p, 'rb'), mimetype=mt) except FileNotFoundError: return 'File not found', 404 def _generate_put_url(self, run, path, expiration, content_type): p = os.path.join(self.artifacts, self._get_run_path(run), path) msg = '%s,%s,%s' % ('PUT', p, content_type) sig = hmac.new(INTERNAL_API_KEY, msg.encode(), 'sha1').hexdigest() return url_for( 'local_storage.run_upload_artifact', sig=sig, proj=run.build.project.name, build_id=run.build.build_id, run=run.name, path=path, _external=True) def _get_run(proj, build_id, run): p = get_or_404(Project.query.filter_by(name=proj)) b = get_or_404(Build.query.filter_by(project=p, build_id=build_id)) return Run.query.filter_by( name=run ).filter( Run.build.has(Build.id == b.id) ).first_or_404() @blueprint.route('/<sig>/<proj>/builds/<int:build_id>/runs/<run>/<path:path>', methods=('PUT',)) def run_upload_artifact(sig, proj, build_id, run, path): run = _get_run(proj, build_id, run) # validate the signature ls = Storage() p = os.path.join(ls.artifacts, ls._get_run_path(run), path) msg = '%s,%s,%s' % (request.method, p, request.headers.get('Content-Type')) computed = hmac.new(INTERNAL_API_KEY, msg.encode(), 'sha1').hexdigest() if not hmac.compare_digest(sig, computed): return 'Invalid signature', 401 dirname = os.path.dirname(p) try: # we could have 2 uploads trying this, so just do it this way to avoid # race conditions os.makedirs(dirname) except FileExistsError: pass # stream the contents to disk with open(p, 'wb') as f: chunk_size = 4096 while True: chunk = request.stream.read(chunk_size) if len(chunk) == 0: break f.write(chunk) return 'ok'
agpl-3.0
ygenc/onlineLDA
onlineldavb_new/build/scipy/build/lib.macosx-10.6-intel-2.7/scipy/weave/blitz_tools.py
11
4789
import parser import sys import ast_tools import slice_handler import size_check import converters import numpy import copy import inline_tools from inline_tools import attempt_function_call function_catalog = inline_tools.function_catalog function_cache = inline_tools.function_cache def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0,**kw): # this could call inline, but making a copy of the # code here is more efficient for several reasons. global function_catalog # this grabs the local variables from the *previous* call # frame -- that is the locals from the function that called # inline. call_frame = sys._getframe().f_back if local_dict is None: local_dict = call_frame.f_locals if global_dict is None: global_dict = call_frame.f_globals # 1. Check the sizes of the arrays and make sure they are compatible. # This is expensive, so unsetting the check_size flag can save a lot # of time. It also can cause core-dumps if the sizes of the inputs # aren't compatible. if check_size and not size_check.check_expr(expr,local_dict,global_dict): raise ValueError("inputs failed to pass size check.") # 2. try local cache try: results = apply(function_cache[expr],(local_dict,global_dict)) return results except: pass try: results = attempt_function_call(expr,local_dict,global_dict) # 3. build the function except ValueError: # This section is pretty much the only difference # between blitz and inline ast = parser.suite(expr) ast_list = ast.tolist() expr_code = ast_to_blitz_expr(ast_list) arg_names = ast_tools.harvest_variables(ast_list) module_dir = global_dict.get('__file__',None) #func = inline_tools.compile_function(expr_code,arg_names, # local_dict,global_dict, # module_dir,auto_downcast = 1) func = inline_tools.compile_function(expr_code,arg_names,local_dict, global_dict,module_dir, compiler='gcc',auto_downcast=1, verbose = verbose, type_converters = converters.blitz, **kw) function_catalog.add_function(expr,func,module_dir) try: results = attempt_function_call(expr,local_dict,global_dict) except ValueError: print 'warning: compilation failed. Executing as python code' exec expr in global_dict, local_dict def ast_to_blitz_expr(ast_seq): """ Convert an ast_sequence to a blitz expression. """ # Don't overwrite orignal sequence in call to transform slices. ast_seq = copy.deepcopy(ast_seq) slice_handler.transform_slices(ast_seq) # Build the actual program statement from ast_seq expr = ast_tools.ast_to_string(ast_seq) # Now find and replace specific symbols to convert this to # a blitz++ compatible statement. # I'm doing this with string replacement here. It could # also be done on the actual ast tree (and probably should from # a purest standpoint...). # this one isn't necessary but it helps code readability # and compactness. It requires that # Range _all = blitz::Range::all(); # be included in the generated code. # These could all alternatively be done to the ast in # build_slice_atom() expr = expr.replace('slice(_beg,_end)', '_all' ) expr = expr.replace('slice', 'blitz::Range' ) expr = expr.replace('[','(') expr = expr.replace(']', ')' ) expr = expr.replace('_stp', '1' ) # Instead of blitz::fromStart and blitz::toEnd. This requires # the following in the generated code. # Range _beg = blitz::fromStart; # Range _end = blitz::toEnd; #expr = expr.replace('_beg', 'blitz::fromStart' ) #expr = expr.replace('_end', 'blitz::toEnd' ) return expr + ';\n' def test_function(): expr = "ex[:,1:,1:] = k + ca_x[:,1:,1:] * ex[:,1:,1:]" \ "+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,1:])"\ "- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])" #ast = parser.suite('a = (b + c) * sin(d)') ast = parser.suite(expr) k = 1. ex = numpy.ones((1,1,1),dtype=numpy.float32) ca_x = numpy.ones((1,1,1),dtype=numpy.float32) cb_y_x = numpy.ones((1,1,1),dtype=numpy.float32) cb_z_x = numpy.ones((1,1,1),dtype=numpy.float32) hz = numpy.ones((1,1,1),dtype=numpy.float32) hy = numpy.ones((1,1,1),dtype=numpy.float32) blitz(expr)
gpl-3.0
jadref/buffer_bci
python/echoClient/eventForwarder.py
1
2911
#!/usr/bin/env python3 bufferpath = "../../python/signalProc" fieldtripPath="../../dataAcq/buffer/python" import os, sys, random, math, time, socket, struct sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),bufferpath)) import bufhelp sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),fieldtripPath)) import FieldTrip # Configuration of buffer buffer1_hostname='localhost' buffer1_port=1972 # Configuration of forwarding buffer buffer2_hostname=None buffer2_port=None # holder for the buffer2 connection ftc2=None # flag to stop running when used from another function running=True def connectBuffers(buffer1_hostname,buffer1_port,buffer2_hostname,buffer2_port): if buffer1_hostname==buffer2_hostname and buffer1_port==buffer2_port : print("WARNING:: fowarding to the same port may result in infinite loops!!!!") #Connect to Buffer2 -- do this first so the global state is for ftc1 print("Connecting to " + buffer2_hostname + ":" + str(buffer2_port)) (ftc2,hdr2) = bufhelp.connect(buffer2_hostname,buffer2_port) print("Connected"); print(hdr2) #Connect to Buffer1 print("Connecting to " + buffer1_hostname + ":" + str(buffer1_port)) (ftc1,hdr1) = bufhelp.connect(buffer1_hostname,buffer1_port) print("Connected!"); print(hdr1) return (ftc1,ftc2) # Receive events from the buffer1 and send them to buffer2 def forwardBufferEvents(ftc1,ftc2): global running global ftc ftc=ftc1 while ( running ): events = bufhelp.buffer_newevents() for evt in events: print(str(evt.sample) + ": " + str(evt)) evt.sample=-1 ftc2.putEvents(evt) def guiGetBuffer2(): print("GUI info not supported yet!!") return; import tkinter as tk master = tk.Tk() tk.Label(master, text="HostName").grid(row=0) tk.Label(master, text="Port").grid(row=1) e1 = tk.Entry(master) e2 = tk.Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) master.mainloop() if __name__ == "__main__": if len(sys.argv)>0: # called with options, i.e. commandline buffer2_hostname = sys.argv[1] if len(sys.argv)>1: try: buffer2_port = int(sys.argv[2]) except: print('Error: second argument (%s) must be a valid (=integer) port number'%sys.argv[2]) sys.exit(1) if buffer2_hostname is None : (buffer2_hostname,buffer2_port)=guiGetBuffer2() (ftc1,ftc2)=connectBuffers(buffer1_hostname,buffer1_port,buffer2_hostname,buffer2_port) forwardBufferEvents(ftc1,ftc2)
gpl-3.0
attilahorvath/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/port/http_lock_unittest.py
124
5481
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # # THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from http_lock import HttpLock import os # Used for os.getpid() import unittest2 as unittest from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.executive_mock import MockExecutive # FIXME: These tests all touch the real disk, but could be written to a MockFileSystem instead. class HttpLockTestWithRealFileSystem(unittest.TestCase): # FIXME: Unit tests do not use an __init__ method, but rather setUp and tearDown methods. def __init__(self, testFunc): self.http_lock = HttpLock(None, "WebKitTestHttpd.lock.", "WebKitTest.lock") self.filesystem = self.http_lock._filesystem # FIXME: We should be passing in a MockFileSystem instead. self.lock_file_path_prefix = self.filesystem.join(self.http_lock._lock_path, self.http_lock._lock_file_prefix) self.lock_file_name = self.lock_file_path_prefix + "0" self.guard_lock_file = self.http_lock._guard_lock_file self.clean_all_lockfile() unittest.TestCase.__init__(self, testFunc) def clean_all_lockfile(self): if self.filesystem.exists(self.guard_lock_file): self.filesystem.remove(self.guard_lock_file) lock_list = self.filesystem.glob(self.lock_file_path_prefix + '*') for file_name in lock_list: self.filesystem.remove(file_name) def assertEqual(self, first, second): if first != second: self.clean_all_lockfile() unittest.TestCase.assertEqual(self, first, second) def _check_lock_file(self): if self.filesystem.exists(self.lock_file_name): pid = os.getpid() lock_file_pid = self.filesystem.read_text_file(self.lock_file_name) self.assertEqual(pid, int(lock_file_pid)) return True return False def test_lock_lifecycle(self): self.http_lock._create_lock_file() self.assertEqual(True, self._check_lock_file()) self.assertEqual(1, self.http_lock._next_lock_number()) self.http_lock.cleanup_http_lock() self.assertEqual(False, self._check_lock_file()) self.assertEqual(0, self.http_lock._next_lock_number()) class HttpLockTest(unittest.TestCase): def setUp(self): self.filesystem = MockFileSystem() self.http_lock = HttpLock(None, "WebKitTestHttpd.lock.", "WebKitTest.lock", filesystem=self.filesystem, executive=MockExecutive()) # FIXME: Shouldn't we be able to get these values from the http_lock object directly? self.lock_file_path_prefix = self.filesystem.join(self.http_lock._lock_path, self.http_lock._lock_file_prefix) self.lock_file_name = self.lock_file_path_prefix + "0" def test_current_lock_pid(self): # FIXME: Once Executive wraps getpid, we can mock this and not use a real pid. current_pid = os.getpid() self.http_lock._filesystem.write_text_file(self.lock_file_name, str(current_pid)) self.assertEqual(self.http_lock._current_lock_pid(), current_pid) def test_extract_lock_number(self): lock_file_list = ( self.lock_file_path_prefix + "00", self.lock_file_path_prefix + "9", self.lock_file_path_prefix + "001", self.lock_file_path_prefix + "021", ) expected_number_list = (0, 9, 1, 21) for lock_file, expected in zip(lock_file_list, expected_number_list): self.assertEqual(self.http_lock._extract_lock_number(lock_file), expected) def test_lock_file_list(self): self.http_lock._filesystem = MockFileSystem({ self.lock_file_path_prefix + "6": "", self.lock_file_path_prefix + "1": "", self.lock_file_path_prefix + "4": "", self.lock_file_path_prefix + "3": "", }) expected_file_list = [ self.lock_file_path_prefix + "1", self.lock_file_path_prefix + "3", self.lock_file_path_prefix + "4", self.lock_file_path_prefix + "6", ] self.assertEqual(self.http_lock._lock_file_list(), expected_file_list)
bsd-3-clause
ksh/gpitrainingv2
common/safe_dom.py
13
4961
"""Classes to build sanitized HTML.""" __author__ = 'John Orr (jorr@google.com)' import cgi import re def escape(strg): return cgi.escape(strg, quote=1).replace("'", '&#39;').replace('`', '&#96;') class Node(object): """Base class for the sanitizing module.""" @property def sanitized(self): raise NotImplementedError() def __str__(self): return self.sanitized class NodeList(object): """Holds a list of Nodes and can bulk sanitize them.""" def __init__(self): self.list = [] def __len__(self): return len(self.list) def append(self, node): assert node is not None, 'Cannot add an empty value to the node list' self.list.append(node) return self @property def sanitized(self): sanitized_list = [] for node in self.list: sanitized_list.append(node.sanitized) return ''.join(sanitized_list) def __str__(self): return self.sanitized class Text(Node): """Holds untrusted text which will be sanitized when accessed.""" def __init__(self, unsafe_string): self._value = unsafe_string @property def sanitized(self): return escape(self._value) class Element(Node): """Embodies an HTML element which will be sanitized when accessed.""" _ALLOWED_NAME_PATTERN = re.compile('^[a-zA-Z][a-zA-Z0-9]*$') _VOID_ELEMENTS = frozenset([ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr']) def __init__(self, tag_name, **attr): """Initializes an element with given tag name and attributes. Tag name will be restricted to alpha chars, attribute names will be quote-escaped. Args: tag_name: the name of the element, which must match _ALLOWED_NAME_PATTERN. **attr: the names and value of the attributes. Names must match _ALLOWED_NAME_PATTERN and values will be quote-escaped. """ assert Element._ALLOWED_NAME_PATTERN.match(tag_name), ( 'tag name %s is not allowed' % tag_name) for attr_name in attr: assert Element._ALLOWED_NAME_PATTERN.match(attr_name), ( 'attribute name %s is not allowed' % attr_name) self._tag_name = tag_name self._attr = attr self._children = [] def add_attribute(self, **attr): for attr_name, value in attr.items(): assert Element._ALLOWED_NAME_PATTERN.match(attr_name), ( 'attribute name %s is not allowed' % attr_name) self._attr[attr_name] = value return self def add_child(self, node): self._children.append(node) return self def add_children(self, node_list): self._children += node_list.list return self def add_text(self, text): return self.add_child(Text(text)) @property def sanitized(self): """Santize the element and its descendants.""" assert Element._ALLOWED_NAME_PATTERN.match(self._tag_name), ( 'tag name %s is not allowed' % self._tag_name) buff = '<' + self._tag_name for attr_name, value in sorted(self._attr.items()): if attr_name == 'className': attr_name = 'class' if value is None: value = '' buff += ' %s="%s"' % ( attr_name, escape(value)) if self._children: buff += '>' for child in self._children: buff += child.sanitized buff += '</%s>' % self._tag_name elif self._tag_name.lower() in Element._VOID_ELEMENTS: buff += '/>' else: buff += '></%s>' % self._tag_name return buff class ScriptElement(Element): """Represents an HTML <script> element.""" def __init__(self, **attr): super(ScriptElement, self).__init__('script', **attr) def add_child(self, unused_node): raise ValueError() def add_children(self, unused_nodes): raise ValueError() def add_text(self, text): """Add the script body.""" class Script(Node): def __init__(self, script): self._script = script @property def sanitized(self): if '</script>' in self._script: raise ValueError('End script tag forbidden') return self._script self._children.append(Script(text)) class Entity(Node): """Holds an XML entity.""" ENTITY_PATTERN = re.compile('^&([a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+);$') def __init__(self, entity): assert Entity.ENTITY_PATTERN.match(entity) self._entity = entity @property def sanitized(self): assert Entity.ENTITY_PATTERN.match(self._entity) return self._entity
apache-2.0
elopez/linux
tools/perf/scripts/python/syscall-counts.py
1996
1700
# system call counts # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts.py [comm]\n"; for_comm = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_syscall_totals() def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): raw_syscalls__sys_enter(**locals()) def print_syscall_totals(): if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "-----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): print "%-40s %10d\n" % (syscall_name(id), val),
gpl-2.0
AutorestCI/azure-sdk-for-python
azure-mgmt-containerregistry/setup.py
2
2823
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import re import os.path from io import open from setuptools import find_packages, setup try: from azure_bdist_wheel import cmdclass except ImportError: from distutils import log as logger logger.warn("Wheel is not available, disabling bdist_wheel hook") cmdclass = {} # Change the PACKAGE_NAME only to change folder and different name PACKAGE_NAME = "azure-mgmt-containerregistry" PACKAGE_PPRINT_NAME = "Container Registry" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace('-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # azure v0.x is not compatible with this package # azure v0.x used to have a __version__ attribute (newer versions don't) try: import azure try: ver = azure.__version__ raise Exception( 'This package is incompatible with azure=={}. '.format(ver) + 'Uninstall it with "pip uninstall azure".' ) except AttributeError: pass except ImportError: pass # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, 'version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.rst', encoding='utf-8') as f: readme = f.read() with open('HISTORY.rst', encoding='utf-8') as f: history = f.read() setup( name=PACKAGE_NAME, version=version, description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), long_description=readme + '\n\n' + history, license='MIT License', author='Microsoft Corporation', author_email='azpysdkhelp@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', ], zip_safe=False, packages=find_packages(exclude=["tests"]), install_requires=[ 'msrestazure~=0.4.11', 'azure-common~=1.1', ], cmdclass=cmdclass )
mit
13xforever/webserver
admin/plugins/evhost.py
5
1821
# -*- coding: utf-8 -*- # # Cheroke-admin # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2001-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # import CTK URL_APPLY = '/plugin/evhost/apply' NOTE_CHECK_DROOT = N_("Check the dynamically generated Document Root, and use the general Document Root if it doesn't exist.") NOTE_REHOST = N_("The Document Root directory will be built dynamically. The following variables are accepted:<br/>") +\ "${domain}, ${domain_md5}, ${tld}, ${domain_no_tld}, ${root_domain}, ${subdomain1}, ${subdomain2}." HELPS = [('config_virtual_servers_evhost', _("Advanced Virtual Hosting"))] class Plugin_evhost (CTK.Plugin): def __init__ (self, key): CTK.Plugin.__init__ (self, key) # GUI table = CTK.PropsAuto (URL_APPLY) table.Add (_("Dynamic Document Root"), CTK.TextCfg('%s!tpl_document_root'%(key)), _(NOTE_REHOST)) table.Add (_("Check Document Root"), CTK.CheckCfgText('%s!check_document_root'%(key), True, _('Check')), _(NOTE_CHECK_DROOT)) self += table # URL mapping CTK.publish ('^%s'%(URL_APPLY), CTK.cfg_apply_post, method="POST")
gpl-2.0
MTG/essentia
test/src/unittests/tonal/test_tonicindianartmusic.py
1
7198
#!/usr/bin/env python # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Afextentro General Public License as published by the Free # Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the Afextentro GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from essentia_test import * from numpy import sin, float32, pi, arange, mean, log2, floor, ceil, math, concatenate import numpy as np class TestTonicIndianArtMusic(TestCase): def testInvalidParam(self): self.assertConfigureFails(TonicIndianArtMusic(), { 'binResolution': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'frameSize': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'binResolution': 0 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'frameSize': 0 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'harmonicWeight': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'harmonicWeight': 0 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'harmonicWeight': 1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'hopSize': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'magnitudeCompression': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'magnitudeCompression': 2 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'magnitudeThreshold': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'maxTonicFrequency': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'minTonicFrequency': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'numberHarmonics': 0 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'numberHarmonics': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'numberSaliencePeaks': 0}) self.assertConfigureFails(TonicIndianArtMusic(), { 'numberSaliencePeaks': 16}) self.assertConfigureFails(TonicIndianArtMusic(), { 'referenceFrequency': -1 }) self.assertConfigureFails(TonicIndianArtMusic(), { 'sampleRate': -1 }) def testEmpty(self): self.assertRaises(RuntimeError, lambda: TonicIndianArtMusic()([])) def testSilence(self): # test 1 second of silence silence = np.zeros(44100) self.assertRaises(RuntimeError, lambda: TonicIndianArtMusic()(silence)) def testOnes(self): # Not a realistic test but useful for sanity checks/ regression checks. referenceTonic = 108.86 tonic = TonicIndianArtMusic()(ones(1024)) self.assertAlmostEqualFixedPrecision(tonic, referenceTonic, 2) # Full reference set of values can be sourced from dataset # Download https://compmusic.upf.edu/carnatic-varnam-dataset # See file "tonics.yaml" # # vignesh: 138.59 # This tonic corresponds to the following mp3 file. # "23582__gopalkoduri__carnatic-varnam-by-vignesh-in-abhogi-raaga.mp3' # # copy this file into essentia/test/audio/recorded. def testRegressionVignesh(self): audio = MonoLoader(filename = join(testdata.audio_dir, 'recorded/223582__gopalkoduri__carnatic-varnam-by-vignesh-in-abhogi-raaga.mp3'), sampleRate = 44100)() # Reference tonic from YAML file is 138.59. The measured is "138.8064422607422" referenceTonic = 138.59 tonic = TonicIndianArtMusic()(audio) self.assertAlmostEqualFixedPrecision(tonic, referenceTonic, 0) def testRegression(self): # Regression test using existing vignesh audio file in "essentia/test/audio/recorded" audio = MonoLoader(filename = join(testdata.audio_dir, 'recorded/vignesh.wav'), sampleRate = 44100)() referenceTonic = 102.74 tonic = TonicIndianArtMusic()(audio) self.assertAlmostEqualFixedPrecision( tonic, referenceTonic, 2) start_zero = np.zeros(int(44100)) end_zero = np.zeros(int(44100)) # Check result is the same with appended silences of constant length real_audio = np.hstack([start_zero, audio, end_zero]) tonic = TonicIndianArtMusic()(real_audio) self.assertAlmostEqualFixedPrecision(tonic, referenceTonic, 2) def testMinMaxMismatch(self): self.assertRaises(RuntimeError, lambda: TonicIndianArtMusic(minTonicFrequency=100,maxTonicFrequency=11)(ones(4096))) def testBelowMinimumTonic(self): signalSize = 15 * 2048 # generate test signal 99 Hz, and put minTonicFreq as 100 Hz in the TonicIndianArtMusic x = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 99* 2*math.pi) self.assertRaises(EssentiaException, lambda: TonicIndianArtMusic(minTonicFrequency=100,maxTonicFrequency=375)(x)) def testAboveMaxTonic(self): signalSize = 15 * 2048 # generate test signal 101 Hz, and put maxTonicFreq as 100 Hz in the TonicIndianArtMusic x = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 101* 2*math.pi) self.assertRaises(RuntimeError, lambda: TonicIndianArtMusic(minTonicFrequency=99,maxTonicFrequency=100)(x)) def testRegressionSyntheticSignal(self): # generate a test signal concatenating different frequencies signalSize = 15 * 2048 # Concat 3 sine waves together of different frequencies x = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 124 * 2*math.pi) y = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 100 * 2*math.pi) z = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 80 * 2*math.pi) mix = concatenate([x, y, z]) # tiam = acronym for "Tonic Indian Art Music" tiam = TonicIndianArtMusic(minTonicFrequency=50, maxTonicFrequency=111) tonic = tiam(mix) # Check that tonic is above minTonicFrequency self.assertGreater(tonic, 50) # Check that tonic is below highest frequency in signal self.assertGreater(124, tonic) ### Make a (unharmonic) chord x = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 124 * 2*math.pi) y = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 100 * 2*math.pi) z = 0.5 * numpy.sin((array(range(signalSize))/44100.) * 80 * 2*math.pi) chord = x+y+z tiam = TonicIndianArtMusic(minTonicFrequency=50, maxTonicFrequency=111) tonic = tiam(chord) # Check that tonic is above min frequency in signal self.assertGreater(tonic, 80) # Check that tonic is below highest frequency in signal self.assertGreater(124, tonic) suite = allTests(TestTonicIndianArtMusic) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)
agpl-3.0
shanot/imp
modules/saxs/test/test_surface.py
1
3121
from __future__ import print_function import IMP import IMP.test import IMP.atom import IMP.core import IMP.saxs import os import time class Tests(IMP.test.TestCase): def test_surface_area(self): """Check protein surface computation""" m = IMP.Model() #! read PDB mp = IMP.atom.read_pdb(self.get_input_file_name('6lyz.pdb'), m, IMP.atom.NonWaterNonHydrogenPDBSelector()) IMP.atom.add_radii(mp) #! select atom particles from the model particles = IMP.atom.get_by_type(mp, IMP.atom.ATOM_TYPE) #! calculate surface aceesability s = IMP.saxs.SolventAccessibleSurface() surface_area = s.get_solvent_accessibility(IMP.core.XYZRs(particles)) #! sum up total_area = 0.0 for area in surface_area: total_area += area # print 'Area = ' + str(total_area) self.assertAlmostEqual(total_area, 37.728, delta=0.1) def test_surface_area2(self): """Atom radii and probe radius parameters that work for SOAP""" m = IMP.Model() #! read PDB mp = IMP.atom.read_pdb(self.get_input_file_name('6lyz.pdb'), m, IMP.atom.NonWaterNonHydrogenPDBSelector()) IMP.atom.add_radii(mp) #! select atom particles from the model particles = IMP.atom.get_by_type(mp, IMP.atom.ATOM_TYPE) for p in particles: xyzrp = IMP.core.XYZR(p) xyzrp.set_radius(0.7 * xyzrp.get_radius()) #! calculate surface aceesability s = IMP.saxs.SolventAccessibleSurface() surface_area = s.get_solvent_accessibility( IMP.core.XYZRs(particles), 1.4) #! sum up total_area = 0.0 for area in surface_area: total_area += area print('Area = ' + str(total_area)) self.assertAlmostEqual(total_area, 73.53, delta=0.1) def test_corner_case(self): """Check the surface area handle points on boundary""" # this test could be simplified probably, but it is fast enough # if we move to non-grid based SA, it should go away ensemble = ["./433.pdb", "./434.pdb"] m = IMP.Model() #! read PDBs for struc in ensemble: print(" ... Fitting structure %s" % struc) mp = IMP.atom.read_pdb(self.get_input_file_name(struc), m, IMP.atom.NonWaterNonHydrogenPDBSelector()) #! select particles from the model particles = IMP.atom.get_by_type(mp, IMP.atom.ATOM_TYPE) #! add radius for water layer computation ft = IMP.saxs.get_default_form_factor_table() for i in range(0, len(particles)): radius = ft.get_radius(particles[i]) IMP.core.XYZR(particles[i]).set_radius(radius) # compute surface accessibility s = IMP.saxs.SolventAccessibleSurface() surface_area = s.get_solvent_accessibility( IMP.core.XYZRs(particles)) if __name__ == '__main__': IMP.test.main()
gpl-3.0
adamlwgriffiths/Pyglet
experimental/directshow.py
28
1798
#!/usr/bin/python # $Id:$ # Play an audio file with DirectShow. Tested ok with MP3, WMA, MID, WAV, AU. # Caveats: # - Requires a filename (not from memory or stream yet). Looks like we need # to manually implement a filter which provides an output IPin. Lot of # work. # - Theoretically can traverse the graph to get the output filter, which by # default is supposed to implement IDirectSound3DBuffer, for positioned # sounds. Untested. # - Requires comtypes. Can work around this in future by implementing the # small subset of comtypes ourselves (or including a snapshot of comtypes in # pyglet). import ctypes from comtypes import client import sys import time filename = sys.argv[1] qedit = client.GetModule('qedit.dll') # DexterLib quartz = client.GetModule('quartz.dll') # CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' filter_graph = client.CreateObject(CLSID_FilterGraph, interface=qedit.IFilterGraph) filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) filter_builder.RenderFile(filename, None) enum = filter_graph.EnumFilters() filter, count = enum.Next(1) while filter: filter_name = u''.join( [unichr(c) for c in filter.QueryFilterInfo().achName]).strip(u'\0') if 'DirectSound' in filter_name: output_filter = filter else: del filter filter, count = enum.Next(1) del enum media_control = filter_graph.QueryInterface(quartz.IMediaControl) media_control.Run() try: # Look at IMediaEvent interface for EOS notification while True: time.sleep(1) except KeyboardInterrupt: pass # Need these because finalisers don't have enough context to clean up after # themselves when script exits. del media_control del filter_builder del filter_graph
bsd-3-clause
alianmohammad/pd-gem5-latest
src/arch/mips/MipsISA.py
61
2521
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # 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 copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andreas Sandberg from m5.SimObject import SimObject from m5.params import * from m5.proxy import * class MipsISA(SimObject): type = 'MipsISA' cxx_class = 'MipsISA::ISA' cxx_header = "arch/mips/isa.hh" system = Param.System(Parent.any, "System this ISA object belongs to") num_threads = Param.UInt8(1, "Maximum number this ISA can handle") num_vpes = Param.UInt8(1, "Maximum number of vpes this ISA can handle")
bsd-3-clause
switchboardOp/ansible
test/units/modules/network/f5/test_bigip_provision.py
47
4904
# -*- coding: utf-8 -*- # # Copyright 2017 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, Mock from ansible.module_utils import basic from ansible.module_utils._text import to_bytes from ansible.module_utils.f5_utils import AnsibleF5Client try: from library.bigip_provision import Parameters from library.bigip_provision import ModuleManager from library.bigip_provision import ArgumentSpec except ImportError: try: from ansible.modules.network.f5.bigip_provision import Parameters from ansible.modules.network.f5.bigip_provision import ModuleManager from ansible.modules.network.f5.bigip_provision import ArgumentSpec except ImportError: raise SkipTest("F5 Ansible modules require the f5-sdk Python library") fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def set_module_args(args): args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( module='gtm', password='password', server='localhost', user='admin' ) p = Parameters(args) assert p.module == 'gtm' @patch('ansible.module_utils.f5_utils.AnsibleF5Client._get_mgmt_root', return_value=True) class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_provision_one_module_default_level(self, *args): # Configure the arguments that would be sent to the Ansible module set_module_args(dict( module='gtm', password='passsword', server='localhost', user='admin' )) # Configure the parameters that would be returned by querying the # remote device current = Parameters( dict( module='gtm', level='none' ) ) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) mm = ModuleManager(client) # Override methods to force specific logic in the module to happen mm.update_on_device = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) # this forced sleeping can cause these tests to take 15 # or more seconds to run. This is deliberate. mm._is_mprov_running_on_device = Mock(side_effect=[True, False, False, False, False]) results = mm.exec_module() assert results['changed'] is True assert results['level'] == 'nominal' def test_provision_all_modules(self, *args): modules = [ 'afm', 'am', 'sam', 'asm', 'avr', 'fps', 'gtm', 'lc', 'ltm', 'pem', 'swg', 'ilx', 'apm', ] for module in modules: # Configure the arguments that would be sent to the Ansible module set_module_args(dict( module=module, password='passsword', server='localhost', user='admin' )) with patch('ansible.module_utils.basic.AnsibleModule.fail_json') as mo: AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) mo.assert_not_called()
gpl-3.0
ozgurakgun/minion
mini-scripts/testallconstraints.py
1
3983
#!/usr/bin/python # Generate two minion input files, run them then compare dumptree outputs to # detect bugs in constraint propagators. import sys, os, getopt from constraint_test_common import * from multiprocessing import Pool, Manager import random #from sendemail import * import time (optargs, other)=getopt.gnu_getopt(sys.argv, "", ["minion=", "numtests=", "email", "fullprop", "64bit", "procs=", "seed=", "conslist="]) if len(other)>1: print("Usage: testallconstraints.py [--minion=<location of minion binary>] [--numtests=...] [--email] [--procs=...] [--seed=...] [--conslist=...]") sys.exit(1) # This one tests all the constraints in the following list. conslist=[] # equality constraints conslist+=["diseq", "eq", "gaceq"] # alldiffs conslist+=["alldiff", "gacalldiff", "alldiffmatrix"] # capacity constraints conslist+=["gcc", "gccweak", "occurrence", "occurrenceleq", "occurrencegeq"] #element constraints conslist+=["element", "element_undefzero", "watchelement", "watchelement_undefzero"] conslist+=["watchelement_one", "element_one"] # arithmetic constraints conslist+=["modulo", "modulo_undefzero", "pow", "minuseq", "product", "div", "div_undefzero", "abs"] conslist+=["watchsumleq", "watchsumgeq", "watchvecneq", "hamming", "not-hamming"] conslist+=["weightedsumleq", "weightedsumgeq"] conslist+=["litsumgeq"] # should test table to test reifytable? and reifyimplytable conslist+=["sumgeq", "sumleq", "weightedsumleq", "weightedsumgeq"] conslist+=["ineq"] conslist+=["difference"] conslist+=["negativetable", "lighttable"] # symmetry-breaking constraints conslist+=["lexleq", "lexless", "lexleq_rv", "lexleq_quick", "lexless_quick"] conslist+=["max", "min"] conslist+=["watchneq", "watchless"] conslist+=["w-inset", "w-inintervalset", "w-notinset", "w-inrange", "w-notinrange", "w-literal", "w-notliteral"] conslist+=["watchsumgeq", "litsumgeq", "watchneq", "watchless", "not-hamming"] conslist+=["not-hamming"] conslist+=["gacschema", "haggisgac", "haggisgac-stable", "str2plus", "shortstr2", "shortctuplestr2", "mddc"] conslist+=["nvalueleq", "nvaluegeq"] # add reifyimply variant of all constraints, # and reify variant of all except those in reifyexceptions it=conslist[:] for c in it: conslist+=["reifyimply"+c] conslist+=["reify"+c] numtests=100 minionbin="bin/minion" email=False fullprop=False # compare the constraint against itself with fullprop. Needs DEBUG=1. bit64=False procs=1 seed=12345 for i in optargs: (a1, a2)=i if a1=="--minion": minionbin=a2 elif a1=="--numtests": numtests=int(a2) elif a1=="--email": email=True elif a1=="--fullprop": fullprop=True elif a1=="--64bit": bit64=True elif a1=="--procs": procs=int(a2) elif a1=="--seed": seed=int(a2) elif a1=="--conslist": conslist=a2.split(",") def runtest(consname): cachename = consname starttime=time.time() sys.stdout.flush() random.seed(seed) reify=False reifyimply=False if consname[0:10]=="reifyimply": reifyimply=True consname=consname[10:] if consname[0:5]=="reify": reify=True consname=consname[5:] consname=consname.replace("-", "__minus__") testobj=eval("test"+consname+"()") testobj.solver=minionbin for testnum in range(numtests): options = {'reify': reify, 'reifyimply': reifyimply, 'fullprop': fullprop, 'printcmd': False, 'fixlength':False, 'getsatisfyingassignment':True} if not testobj.runtest(options): print("Failed when testing %s"%cachename) sys.stdout.flush() return False print("Completed testing %s, duration: %d"%(cachename, time.time()-starttime)) return True if __name__ == '__main__': p = Pool(procs) retval = p.map(runtest, conslist) if all(retval): print("Success") exit(0) else: print("Failure") exit(1)
gpl-2.0
Bashar/django
tests/null_fk/models.py
166
1323
""" Regression tests for proper working of ForeignKey(null=True). """ from django.db import models from django.utils.encoding import python_2_unicode_compatible class SystemDetails(models.Model): details = models.TextField() class SystemInfo(models.Model): system_details = models.ForeignKey(SystemDetails) system_name = models.CharField(max_length=32) class Forum(models.Model): system_info = models.ForeignKey(SystemInfo) forum_name = models.CharField(max_length=32) @python_2_unicode_compatible class Post(models.Model): forum = models.ForeignKey(Forum, null=True) title = models.CharField(max_length=32) def __str__(self): return self.title @python_2_unicode_compatible class Comment(models.Model): post = models.ForeignKey(Post, null=True) comment_text = models.CharField(max_length=250) class Meta: ordering = ('comment_text',) def __str__(self): return self.comment_text # Ticket 15823 class Item(models.Model): title = models.CharField(max_length=100) class PropertyValue(models.Model): label = models.CharField(max_length=100) class Property(models.Model): item = models.ForeignKey(Item, related_name='props') key = models.CharField(max_length=100) value = models.ForeignKey(PropertyValue, null=True)
bsd-3-clause
40123112/w17exam
static/Brython3.1.1-20150328-091302/Lib/binascii.py
620
24585
"""A pure Python implementation of binascii. Rather slow and buggy in corner cases. PyPy provides an RPython version too. """ # borrowed from https://bitbucket.org/pypy/pypy/src/f2bf94943a41/lib_pypy/binascii.py class Error(Exception): pass class Done(Exception): pass class Incomplete(Exception): pass def a2b_uu(s): if not s: return '' length = (ord(s[0]) - 0x20) % 64 def quadruplets_gen(s): while s: try: yield ord(s[0]), ord(s[1]), ord(s[2]), ord(s[3]) except IndexError: s += ' ' yield ord(s[0]), ord(s[1]), ord(s[2]), ord(s[3]) return s = s[4:] try: result = [''.join( [chr((A - 0x20) << 2 | (((B - 0x20) >> 4) & 0x3)), chr(((B - 0x20) & 0xf) << 4 | (((C - 0x20) >> 2) & 0xf)), chr(((C - 0x20) & 0x3) << 6 | ((D - 0x20) & 0x3f)) ]) for A, B, C, D in quadruplets_gen(s[1:].rstrip())] except ValueError: raise Error('Illegal char') result = ''.join(result) trailingdata = result[length:] if trailingdata.strip('\x00'): raise Error('Trailing garbage') result = result[:length] if len(result) < length: result += ((length - len(result)) * '\x00') return bytes(result, __BRYTHON__.charset) def b2a_uu(s): length = len(s) if length > 45: raise Error('At most 45 bytes at once') def triples_gen(s): while s: try: yield ord(s[0]), ord(s[1]), ord(s[2]) except IndexError: s += '\0\0' yield ord(s[0]), ord(s[1]), ord(s[2]) return s = s[3:] result = [''.join( [chr(0x20 + (( A >> 2 ) & 0x3F)), chr(0x20 + (((A << 4) | ((B >> 4) & 0xF)) & 0x3F)), chr(0x20 + (((B << 2) | ((C >> 6) & 0x3)) & 0x3F)), chr(0x20 + (( C ) & 0x3F))]) for A, B, C in triples_gen(s)] return chr(ord(' ') + (length & 0o77)) + ''.join(result) + '\n' table_a2b_base64 = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25, 'a': 26, 'b': 27, 'c': 28, 'd': 29, 'e': 30, 'f': 31, 'g': 32, 'h': 33, 'i': 34, 'j': 35, 'k': 36, 'l': 37, 'm': 38, 'n': 39, 'o': 40, 'p': 41, 'q': 42, 'r': 43, 's': 44, 't': 45, 'u': 46, 'v': 47, 'w': 48, 'x': 49, 'y': 50, 'z': 51, '0': 52, '1': 53, '2': 54, '3': 55, '4': 56, '5': 57, '6': 58, '7': 59, '8': 60, '9': 61, '+': 62, '/': 63, '=': 0, } def a2b_base64(s): if not isinstance(s, (str, bytes)): raise TypeError("expected string, got %r" % (s,)) s = s.rstrip() # clean out all invalid characters, this also strips the final '=' padding # check for correct padding def next_valid_char(s, pos): for i in range(pos + 1, len(s)): c = s[i] if c < '\x7f': try: table_a2b_base64[c] return c except KeyError: pass return None quad_pos = 0 leftbits = 0 leftchar = 0 res = [] for i, c in enumerate(s): if isinstance(c, int): c = chr(c) if c > '\x7f' or c == '\n' or c == '\r' or c == ' ': continue if c == '=': if quad_pos < 2 or (quad_pos == 2 and next_valid_char(s, i) != '='): continue else: leftbits = 0 break try: next_c = table_a2b_base64[c] except KeyError: continue quad_pos = (quad_pos + 1) & 0x03 leftchar = (leftchar << 6) | next_c leftbits += 6 if leftbits >= 8: leftbits -= 8 res.append((leftchar >> leftbits & 0xff)) leftchar &= ((1 << leftbits) - 1) if leftbits != 0: raise Error('Incorrect padding') return bytes(''.join([chr(i) for i in res]),__BRYTHON__.charset) table_b2a_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"\ "0123456789+/" def b2a_base64(s): length = len(s) final_length = length % 3 def triples_gen(s): while s: try: yield s[0], s[1], s[2] except IndexError: s += b'\0\0' yield s[0], s[1], s[2] return s = s[3:] a = triples_gen(s[ :length - final_length]) result = [''.join( [table_b2a_base64[( A >> 2 ) & 0x3F], table_b2a_base64[((A << 4) | ((B >> 4) & 0xF)) & 0x3F], table_b2a_base64[((B << 2) | ((C >> 6) & 0x3)) & 0x3F], table_b2a_base64[( C ) & 0x3F]]) for A, B, C in a] final = s[length - final_length:] if final_length == 0: snippet = '' elif final_length == 1: a = ord(final[0]) snippet = table_b2a_base64[(a >> 2 ) & 0x3F] + \ table_b2a_base64[(a << 4 ) & 0x3F] + '==' else: a = ord(final[0]) b = ord(final[1]) snippet = table_b2a_base64[(a >> 2) & 0x3F] + \ table_b2a_base64[((a << 4) | (b >> 4) & 0xF) & 0x3F] + \ table_b2a_base64[(b << 2) & 0x3F] + '=' return bytes(''.join(result) + snippet + '\n',__BRYTHON__.charset) def a2b_qp(s, header=False): inp = 0 odata = [] while inp < len(s): if s[inp] == '=': inp += 1 if inp >= len(s): break # Soft line breaks if (s[inp] == '\n') or (s[inp] == '\r'): if s[inp] != '\n': while inp < len(s) and s[inp] != '\n': inp += 1 if inp < len(s): inp += 1 elif s[inp] == '=': # broken case from broken python qp odata.append('=') inp += 1 elif s[inp] in hex_numbers and s[inp + 1] in hex_numbers: ch = chr(int(s[inp:inp+2], 16)) inp += 2 odata.append(ch) else: odata.append('=') elif header and s[inp] == '_': odata.append(' ') inp += 1 else: odata.append(s[inp]) inp += 1 return bytes(''.join(odata), __BRYTHON__.charset) def b2a_qp(data, quotetabs=False, istext=True, header=False): """quotetabs=True means that tab and space characters are always quoted. istext=False means that \r and \n are treated as regular characters header=True encodes space characters with '_' and requires real '_' characters to be quoted. """ MAXLINESIZE = 76 # See if this string is using CRLF line ends lf = data.find('\n') crlf = lf > 0 and data[lf-1] == '\r' inp = 0 linelen = 0 odata = [] while inp < len(data): c = data[inp] if (c > '~' or c == '=' or (header and c == '_') or (c == '.' and linelen == 0 and (inp+1 == len(data) or data[inp+1] == '\n' or data[inp+1] == '\r')) or (not istext and (c == '\r' or c == '\n')) or ((c == '\t' or c == ' ') and (inp + 1 == len(data))) or (c <= ' ' and c != '\r' and c != '\n' and (quotetabs or (not quotetabs and (c != '\t' and c != ' '))))): linelen += 3 if linelen >= MAXLINESIZE: odata.append('=') if crlf: odata.append('\r') odata.append('\n') linelen = 3 odata.append('=' + two_hex_digits(ord(c))) inp += 1 else: if (istext and (c == '\n' or (inp+1 < len(data) and c == '\r' and data[inp+1] == '\n'))): linelen = 0 # Protect against whitespace on end of line if (len(odata) > 0 and (odata[-1] == ' ' or odata[-1] == '\t')): ch = ord(odata[-1]) odata[-1] = '=' odata.append(two_hex_digits(ch)) if crlf: odata.append('\r') odata.append('\n') if c == '\r': inp += 2 else: inp += 1 else: if (inp + 1 < len(data) and data[inp+1] != '\n' and (linelen + 1) >= MAXLINESIZE): odata.append('=') if crlf: odata.append('\r') odata.append('\n') linelen = 0 linelen += 1 if header and c == ' ': c = '_' odata.append(c) inp += 1 return ''.join(odata) hex_numbers = '0123456789ABCDEF' def hex(n): if n == 0: return '0' if n < 0: n = -n sign = '-' else: sign = '' arr = [] def hex_gen(n): """ Yield a nibble at a time. """ while n: yield n % 0x10 n = n / 0x10 for nibble in hex_gen(n): arr = [hex_numbers[nibble]] + arr return sign + ''.join(arr) def two_hex_digits(n): return hex_numbers[n / 0x10] + hex_numbers[n % 0x10] def strhex_to_int(s): i = 0 for c in s: i = i * 0x10 + hex_numbers.index(c) return i hqx_encoding = '!"#$%&\'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr' DONE = 0x7f SKIP = 0x7e FAIL = 0x7d table_a2b_hqx = [ #^@ ^A ^B ^C ^D ^E ^F ^G FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, #\b \t \n ^K ^L \r ^N ^O FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, #^P ^Q ^R ^S ^T ^U ^V ^W FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, #^X ^Y ^Z ^[ ^\ ^] ^^ ^_ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, # ! " # $ % & ' FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, #( ) * + , - . / 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, #0 1 2 3 4 5 6 7 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, #8 9 : ; < = > ? 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, #@ A B C D E F G 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, #H I J K L M N O 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, #P Q R S T U V W 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, #X Y Z [ \ ] ^ _ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, #` a b c d e f g 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, #h i j k l m n o 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, #p q r s t u v w 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, #x y z { | } ~ ^? FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, ] def a2b_hqx(s): result = [] def quadruples_gen(s): t = [] for c in s: res = table_a2b_hqx[ord(c)] if res == SKIP: continue elif res == FAIL: raise Error('Illegal character') elif res == DONE: yield t raise Done else: t.append(res) if len(t) == 4: yield t t = [] yield t done = 0 try: for snippet in quadruples_gen(s): length = len(snippet) if length == 4: result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) result.append(chr(((snippet[2] & 0x03) << 6) | (snippet[3]))) elif length == 3: result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) elif length == 2: result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) except Done: done = 1 except Error: raise return (''.join(result), done) # should this return a bytes object? #return (bytes(''.join(result), __BRYTHON__.charset), done) def b2a_hqx(s): result =[] def triples_gen(s): while s: try: yield ord(s[0]), ord(s[1]), ord(s[2]) except IndexError: yield tuple([ord(c) for c in s]) s = s[3:] for snippet in triples_gen(s): length = len(snippet) if length == 3: result.append( hqx_encoding[(snippet[0] & 0xfc) >> 2]) result.append(hqx_encoding[ ((snippet[0] & 0x03) << 4) | ((snippet[1] & 0xf0) >> 4)]) result.append(hqx_encoding[ (snippet[1] & 0x0f) << 2 | ((snippet[2] & 0xc0) >> 6)]) result.append(hqx_encoding[snippet[2] & 0x3f]) elif length == 2: result.append( hqx_encoding[(snippet[0] & 0xfc) >> 2]) result.append(hqx_encoding[ ((snippet[0] & 0x03) << 4) | ((snippet[1] & 0xf0) >> 4)]) result.append(hqx_encoding[ (snippet[1] & 0x0f) << 2]) elif length == 1: result.append( hqx_encoding[(snippet[0] & 0xfc) >> 2]) result.append(hqx_encoding[ ((snippet[0] & 0x03) << 4)]) return ''.join(result) crctab_hqx = [ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, ] def crc_hqx(s, crc): for c in s: crc = ((crc << 8) & 0xff00) ^ crctab_hqx[((crc >> 8) & 0xff) ^ ord(c)] return crc def rlecode_hqx(s): """ Run length encoding for binhex4. The CPython implementation does not do run length encoding of \x90 characters. This implementation does. """ if not s: return '' result = [] prev = s[0] count = 1 # Add a dummy character to get the loop to go one extra round. # The dummy must be different from the last character of s. # In the same step we remove the first character, which has # already been stored in prev. if s[-1] == '!': s = s[1:] + '?' else: s = s[1:] + '!' for c in s: if c == prev and count < 255: count += 1 else: if count == 1: if prev != '\x90': result.append(prev) else: result.extend(['\x90', '\x00']) elif count < 4: if prev != '\x90': result.extend([prev] * count) else: result.extend(['\x90', '\x00'] * count) else: if prev != '\x90': result.extend([prev, '\x90', chr(count)]) else: result.extend(['\x90', '\x00', '\x90', chr(count)]) count = 1 prev = c return ''.join(result) def rledecode_hqx(s): s = s.split('\x90') result = [s[0]] prev = s[0] for snippet in s[1:]: count = ord(snippet[0]) if count > 0: result.append(prev[-1] * (count-1)) prev = snippet else: result.append('\x90') prev = '\x90' result.append(snippet[1:]) return ''.join(result) crc_32_tab = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ] def crc32(s, crc=0): result = 0 crc = ~int(crc) & 0xffffffff #crc = ~long(crc) & 0xffffffffL for c in s: crc = crc_32_tab[(crc ^ int(ord(c))) & 0xff] ^ (crc >> 8) #crc = crc_32_tab[(crc ^ long(ord(c))) & 0xffL] ^ (crc >> 8) #/* Note: (crc >> 8) MUST zero fill on left result = crc ^ 0xffffffff if result > 2**31: result = ((result + 2**31) % 2**32) - 2**31 return result def b2a_hex(s): result = [] for char in s: c = (ord(char) >> 4) & 0xf if c > 9: c = c + ord('a') - 10 else: c = c + ord('0') result.append(chr(c)) c = ord(char) & 0xf if c > 9: c = c + ord('a') - 10 else: c = c + ord('0') result.append(chr(c)) return ''.join(result) hexlify = b2a_hex table_hex = [ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 ] def a2b_hex(t): result = [] def pairs_gen(s): while s: try: yield table_hex[ord(s[0])], table_hex[ord(s[1])] except IndexError: if len(s): raise TypeError('Odd-length string') return s = s[2:] for a, b in pairs_gen(t): if a < 0 or b < 0: raise TypeError('Non-hexadecimal digit found') result.append(chr((a << 4) + b)) return bytes(''.join(result), __BRYTHON__.charset) unhexlify = a2b_hex
agpl-3.0
rabramley/telomere
app/model/batch.py
1
2972
from app import db from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.sql import select, func from app.model.outstandingError import OutstandingError import numpy import decimal class Batch(db.Model): id = db.Column(db.Integer, primary_key=True) robot = db.Column(db.String(20)) temperature = db.Column(db.Numeric(precision=3, scale=1)) datetime = db.Column(db.DateTime()) userId = db.Column(db.Integer, db.ForeignKey('user.id')) version_id = db.Column(db.Integer, nullable=False) plateName = db.Column(db.String(50)) halfPlate = db.Column(db.String(1)) humidity = db.Column(db.Integer()) primerBatch = db.Column(db.Integer()) enzymeBatch = db.Column(db.Integer()) rotorGene = db.Column(db.Integer()) operatorUserId = db.Column(db.Integer, db.ForeignKey('user.id')) batchFailureReason = db.Column(db.Integer()) processType = db.Column(db.String(20)) __mapper_args__ = { "version_id_col": version_id } def __init__(self, *args, **kwargs): self.id = kwargs.get('id') self.robot = kwargs.get('robot') self.temperature = kwargs.get('temperature') self.datetime = kwargs.get('datetime') self.userId = kwargs.get('userId') self.plateName = kwargs.get('plateName') self.halfPlate = kwargs.get('halfPlate') self.humidity = kwargs.get('humidity') self.primerBatch = kwargs.get('primerBatch') self.enzymeBatch = kwargs.get('enzymeBatch') self.rotorGene = kwargs.get('rotorGene') self.operatorUserId = kwargs.get('operatorUserId') self.batchFailureReason = kwargs.get('batchFailureReason') self.processType = kwargs.get('processType') @hybrid_property def outstandingErrorCount(self): return len(self.outstandingErrors) @outstandingErrorCount.expression def outstandingErrorCount(cls): return (select([func.count(OutstandingError.id)]). where(OutstandingError.batchId == cls.id). label("outstandingErrorCount") ) def get_measurements_for_sample_code(self, sampleCode): return [m for m in self.measurements if m.sample.sampleCode == sampleCode] def has_no_pool_samples(self): return not any(m.sample.is_pool_sample() for m in self.measurements) def has_no_non_pool_samples(self): return not any(not m.sample.is_pool_sample() for m in self.measurements) def has_invalid_pool_ts_average(self): poolTsValues = [ decimal.Decimal(m.ts) for m in self.measurements if m.ts is not None and m.sample.is_pool_sample()] averagePoolTs = numpy.mean(poolTsValues) return averagePoolTs < 0.99 or averagePoolTs > 1.01 def is_duplicate(self): return self.processType == "Duplicate" def is_replate(self): return self.processType == "Re-Plate" def is_initial(self): return self.processType == "Initial"
mit
DarioGT/OMS-PluginXML
org.modelsphere.sms/lib/jython-2.2.1/Lib/uu.py
1
6092
#! /usr/bin/env python # Copyright 1994 by Lance Ellinghouse # Cathedral City, California Republic, United States of America. # All Rights Reserved # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Lance Ellinghouse # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE # FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Modified by Jack Jansen, CWI, July 1995: # - Use binascii module to do the actual line-by-line conversion # between ascii and binary. This results in a 1000-fold speedup. The C # version is still 5 times faster, though. # - Arguments more compliant with python standard """Implementation of the UUencode and UUdecode functions. encode(in_file, out_file [,name, mode]) decode(in_file [, out_file, mode]) """ import binascii import os import sys from types import StringType __all__ = ["Error", "encode", "decode"] class Error(Exception): pass def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file)[0] except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') def decode(in_file, out_file=None, mode=None, quiet=0): """Decode uuencoded file""" # # Open the input file, if needed. # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): in_file = open(in_file) # # Read until a begin is encountered or we've exhausted the file # while 1: hdr = in_file.readline() if not hdr: raise Error, 'No valid begin line found in input file' if hdr[:5] != 'begin': continue hdrfields = hdr.split(" ", 2) if len(hdrfields) == 3 and hdrfields[0] == 'begin': try: int(hdrfields[1], 8) break except ValueError: pass if out_file is None: out_file = hdrfields[2].rstrip() if os.path.exists(out_file): raise Error, 'Cannot overwrite existing file: %s' % out_file if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # opened = False if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): fp = open(out_file, 'wb') try: os.path.chmod(out_file, mode) except AttributeError: pass out_file = fp opened = True # # Main decoding loop # s = in_file.readline() while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) except binascii.Error, v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = binascii.a2b_uu(s[:nbytes]) if not quiet: sys.stderr.write("Warning: %s\n" % str(v)) out_file.write(data) s = in_file.readline() if not s: raise Error, 'Truncated input file' if opened: out_file.close() def test(): """uuencode/uudecode main program""" import getopt dopt = 0 topt = 0 input = sys.stdin output = sys.stdout ok = 1 try: optlist, args = getopt.getopt(sys.argv[1:], 'dt') except getopt.error: ok = 0 if not ok or len(args) > 2: print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' print ' -d: Decode (in stead of encode)' print ' -t: data is text, encoded format unix-compatible text' sys.exit(1) for o, a in optlist: if o == '-d': dopt = 1 if o == '-t': topt = 1 if len(args) > 0: input = args[0] if len(args) > 1: output = args[1] if dopt: if topt: if isinstance(output, StringType): output = open(output, 'w') else: print sys.argv[0], ': cannot do -t to stdout' sys.exit(1) decode(input, output) else: if topt: if isinstance(input, StringType): input = open(input, 'r') else: print sys.argv[0], ': cannot do -t from stdin' sys.exit(1) encode(input, output) if __name__ == '__main__': test()
gpl-3.0
jhogg41/gm-o-matic
gom_server/gom_server/urls.py
1
1187
"""gom_server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers import core.router import char_attr.router router = routers.DefaultRouter() core.router.addRoutes(router) char_attr.router.addRoutes(router) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest-framework')), url(r'^', include(router.urls)), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration', include('rest_auth.registration.urls')), ]
bsd-2-clause
GitHublong/hue
desktop/core/src/desktop/migrations/0010_auto__add_document2__chg_field_userpreferences_key__chg_field_userpref.py
35
13246
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Document2' db.create_table('desktop_document2', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('owner', self.gf('django.db.models.fields.related.ForeignKey')(related_name='doc2_owner', to=orm['auth.User'])), ('name', self.gf('django.db.models.fields.CharField')(default='', max_length=255)), ('description', self.gf('django.db.models.fields.TextField')(default='')), ('uuid', self.gf('django.db.models.fields.CharField')(default='', max_length=32, db_index=True)), ('type', self.gf('django.db.models.fields.CharField')(default='', max_length=32, db_index=True)), ('data', self.gf('django.db.models.fields.TextField')(default='{}')), ('extra', self.gf('django.db.models.fields.TextField')(default='')), ('last_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)), ('version', self.gf('django.db.models.fields.SmallIntegerField')(default=1, db_index=True)), ('is_history', self.gf('django.db.models.fields.BooleanField')(default=False, db_index=True)), )) db.send_create_signal('desktop', ['Document2']) # Adding M2M table for field tags on 'Document2' m2m_table_name = db.shorten_name('desktop_document2_tags') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('from_document2', models.ForeignKey(orm['desktop.document2'], null=False)), ('to_document2', models.ForeignKey(orm['desktop.document2'], null=False)) )) db.create_unique(m2m_table_name, ['from_document2_id', 'to_document2_id']) # Adding M2M table for field dependencies on 'Document2' m2m_table_name = db.shorten_name('desktop_document2_dependencies') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('from_document2', models.ForeignKey(orm['desktop.document2'], null=False)), ('to_document2', models.ForeignKey(orm['desktop.document2'], null=False)) )) db.create_unique(m2m_table_name, ['from_document2_id', 'to_document2_id']) # Changing field 'UserPreferences.key' db.alter_column('desktop_userpreferences', 'key', self.gf('django.db.models.fields.CharField')(default='', max_length=20)) # Changing field 'UserPreferences.value' db.alter_column('desktop_userpreferences', 'value', self.gf('django.db.models.fields.TextField')(default='', max_length=4096)) # Changing field 'DocumentPermission.perms' db.alter_column('desktop_documentpermission', 'perms', self.gf('django.db.models.fields.TextField')()) # Changing field 'DocumentTag.tag' db.alter_column('desktop_documenttag', 'tag', self.gf('django.db.models.fields.SlugField')(default='', max_length=50)) # Changing field 'Document.extra' db.alter_column('desktop_document', 'extra', self.gf('django.db.models.fields.TextField')()) # Changing field 'Document.name' db.alter_column('desktop_document', 'name', self.gf('django.db.models.fields.CharField')(max_length=255)) # Changing field 'Document.description' db.alter_column('desktop_document', 'description', self.gf('django.db.models.fields.TextField')()) def backwards(self, orm): # Deleting model 'Document2' db.delete_table('desktop_document2') # Removing M2M table for field tags on 'Document2' db.delete_table(db.shorten_name('desktop_document2_tags')) # Removing M2M table for field dependencies on 'Document2' db.delete_table(db.shorten_name('desktop_document2_dependencies')) # Changing field 'UserPreferences.key' db.alter_column('desktop_userpreferences', 'key', self.gf('django.db.models.fields.CharField')(max_length=20, null=True)) # Changing field 'UserPreferences.value' db.alter_column('desktop_userpreferences', 'value', self.gf('django.db.models.fields.TextField')(max_length=4096, null=True)) # Changing field 'DocumentPermission.perms' db.alter_column('desktop_documentpermission', 'perms', self.gf('django.db.models.fields.TextField')(null=True)) # Changing field 'DocumentTag.tag' db.alter_column('desktop_documenttag', 'tag', self.gf('django.db.models.fields.SlugField')(max_length=50, null=True)) # Changing field 'Document.extra' db.alter_column('desktop_document', 'extra', self.gf('django.db.models.fields.TextField')(null=True)) # Changing field 'Document.name' db.alter_column('desktop_document', 'name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True)) # Changing field 'Document.description' db.alter_column('desktop_document', 'description', self.gf('django.db.models.fields.TextField')(null=True)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'desktop.document': { 'Meta': {'object_name': 'Document'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'description': ('django.db.models.fields.TextField', [], {'default': "''"}), 'extra': ('django.db.models.fields.TextField', [], {'default': "''"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'doc_owner'", 'to': "orm['auth.User']"}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['desktop.DocumentTag']", 'db_index': 'True', 'symmetrical': 'False'}), 'version': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}) }, 'desktop.document2': { 'Meta': {'object_name': 'Document2'}, 'data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}), 'dependencies': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'dependencies_rel_+'", 'db_index': 'True', 'to': "orm['desktop.Document2']"}), 'description': ('django.db.models.fields.TextField', [], {'default': "''"}), 'extra': ('django.db.models.fields.TextField', [], {'default': "''"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_history': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'doc2_owner'", 'to': "orm['auth.User']"}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'tags_rel_+'", 'db_index': 'True', 'to': "orm['desktop.Document2']"}), 'type': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'db_index': 'True'}), 'uuid': ('django.db.models.fields.CharField', [], {'default': "'6f8fe9aff12d44d0a2b01c863822dfa1'", 'max_length': '32', 'db_index': 'True'}), 'version': ('django.db.models.fields.SmallIntegerField', [], {'default': '1', 'db_index': 'True'}) }, 'desktop.documentpermission': { 'Meta': {'object_name': 'DocumentPermission'}, 'doc': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['desktop.Document']"}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'to': "orm['auth.Group']", 'db_table': "'documentpermission_groups'", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'perms': ('django.db.models.fields.TextField', [], {'default': "'read'"}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'db_index': 'True', 'to': "orm['auth.User']", 'db_table': "'documentpermission_users'", 'symmetrical': 'False'}) }, 'desktop.documenttag': { 'Meta': {'object_name': 'DocumentTag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'tag': ('django.db.models.fields.SlugField', [], {'max_length': '50'}) }, 'desktop.settings': { 'Meta': {'object_name': 'Settings'}, 'collect_usage': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tours_and_tutorials': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}) }, 'desktop.userpreferences': { 'Meta': {'object_name': 'UserPreferences'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'value': ('django.db.models.fields.TextField', [], {'max_length': '4096'}) } } complete_apps = ['desktop']
apache-2.0