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 |
|---|---|---|---|---|---|
oihane/server-tools | users_ldap_populate/model/populate_wizard.py | 43 | 1787 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2012 Therp BV (<http://therp.nl>).
#
# 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 orm, fields
class CompanyLDAPPopulateWizard(orm.TransientModel):
_name = 'res.company.ldap.populate_wizard'
_description = 'Populate users from LDAP'
_columns = {
'name': fields.char('Name', size=16),
'ldap_id': fields.many2one(
'res.company.ldap', 'LDAP Configuration'),
'users_created': fields.integer(
'Number of users created', readonly=True),
}
def create(self, cr, uid, vals, context=None):
ldap_pool = self.pool.get('res.company.ldap')
if 'ldap_id' in vals:
vals['users_created'] = ldap_pool.action_populate(
cr, uid, vals['ldap_id'], context=context)
return super(CompanyLDAPPopulateWizard, self).create(
cr, uid, vals, context=None)
| agpl-3.0 |
rakuco/crosswalk | tools/reflection_generator/code_generator.py | 7 | 1212 | # Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class CodeGenerator(object):
"""Basic class of code generator"""
def __init__(self, java_data, class_loader):
self._java_data = java_data
self._class_loader = class_loader
self._generated_code = ''
self._generated_class_name = ''
def RunTask(self):
pass
def GetJavaData(self, clazz):
return self._class_loader.GetJavaData(clazz)
def IsInternalClass(self, clazz):
return self._class_loader.IsInternalClass(clazz)
def GenerateDoc(self, doc):
return self._class_loader.GenerateDoc(doc)
def GetGeneratedCode(self):
return self._generated_code
def GetGeneratedClassFileName(self):
return self._generated_class_name + '.java'
def GenerateImportRules(self):
imports = ''
for imported in self._java_data.imports:
import_string = 'import ' + imported + ";\n"
imports += import_string
# Add the reflection helper import.
imports += '\n'
imports += 'import java.lang.reflect.Constructor;\n'
imports += 'import java.lang.reflect.Method;\n'
return imports
| bsd-3-clause |
frappe/frappe | frappe/website/doctype/website_route_meta/test_website_route_meta.py | 1 | 1119 | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and Contributors
# See license.txt
import frappe
import unittest
from frappe.utils import set_request
from frappe.website.serve import get_response
test_dependencies = ['Blog Post']
class TestWebsiteRouteMeta(unittest.TestCase):
def test_meta_tag_generation(self):
blogs = frappe.get_all('Blog Post', fields=['name', 'route'],
filters={'published': 1, 'route': ('!=', '')}, limit=1)
blog = blogs[0]
# create meta tags for this route
doc = frappe.new_doc('Website Route Meta')
doc.append('meta_tags', {
'key': 'type',
'value': 'blog_post'
})
doc.append('meta_tags', {
'key': 'og:title',
'value': 'My Blog'
})
doc.name = blog.route
doc.insert()
# set request on this route
set_request(path=blog.route)
response = get_response()
self.assertTrue(response.status_code, 200)
html = response.get_data().decode()
self.assertTrue('''<meta name="type" content="blog_post">''' in html)
self.assertTrue('''<meta property="og:title" content="My Blog">''' in html)
def tearDown(self):
frappe.db.rollback()
| mit |
jamesbroadhead/pyyaml | lib3/yaml/loader.py | 277 | 1138 |
__all__ = ['BaseLoader', 'SafeLoader', 'Loader']
from .reader import *
from .scanner import *
from .parser import *
from .composer import *
from .constructor import *
from .resolver import *
class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
BaseConstructor.__init__(self)
BaseResolver.__init__(self)
class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
SafeConstructor.__init__(self)
Resolver.__init__(self)
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self)
| mit |
proxysh/Safejumper-for-Desktop | buildmac/Resources/env/lib/python2.7/site-packages/twisted/web/server.py | 12 | 24816 | # -*- test-case-name: twisted.web.test.test_web -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This is a web-server which integrates with the twisted.internet
infrastructure.
"""
from __future__ import division, absolute_import
import copy
import os
try:
from urllib import quote
except ImportError:
from urllib.parse import quote as _quote
def quote(string, *args, **kwargs):
return _quote(
string.decode('charmap'), *args, **kwargs).encode('charmap')
import zlib
from binascii import hexlify
from zope.interface import implementer
from twisted.python.compat import _PY3, networkString, nativeString, intToBytes
if _PY3:
class Copyable:
"""
Fake mixin, until twisted.spread is ported.
"""
else:
from twisted.spread.pb import Copyable, ViewPoint
from twisted.internet import address, interfaces
from twisted.web import iweb, http, util
from twisted.web.http import unquote
from twisted.python import log, reflect, failure, components
from twisted import copyright
from twisted.web import resource
from twisted.web.error import UnsupportedMethod
from incremental import Version
from twisted.python.deprecate import deprecatedModuleAttribute
from twisted.python.compat import escape
NOT_DONE_YET = 1
__all__ = [
'supportedMethods',
'Request',
'Session',
'Site',
'version',
'NOT_DONE_YET',
'GzipEncoderFactory'
]
# backwards compatibility
deprecatedModuleAttribute(
Version("Twisted", 12, 1, 0),
"Please use twisted.web.http.datetimeToString instead",
"twisted.web.server",
"date_time_string")
deprecatedModuleAttribute(
Version("Twisted", 12, 1, 0),
"Please use twisted.web.http.stringToDatetime instead",
"twisted.web.server",
"string_date_time")
date_time_string = http.datetimeToString
string_date_time = http.stringToDatetime
# Support for other methods may be implemented on a per-resource basis.
supportedMethods = (b'GET', b'HEAD', b'POST')
def _addressToTuple(addr):
if isinstance(addr, address.IPv4Address):
return ('INET', addr.host, addr.port)
elif isinstance(addr, address.UNIXAddress):
return ('UNIX', addr.name)
else:
return tuple(addr)
@implementer(iweb.IRequest)
class Request(Copyable, http.Request, components.Componentized):
"""
An HTTP request.
@ivar defaultContentType: A C{bytes} giving the default I{Content-Type}
value to send in responses if no other value is set. L{None} disables
the default.
@ivar _insecureSession: The L{Session} object representing state that will
be transmitted over plain-text HTTP.
@ivar _secureSession: The L{Session} object representing the state that
will be transmitted only over HTTPS.
"""
defaultContentType = b"text/html"
site = None
appRootURL = None
__pychecker__ = 'unusednames=issuer'
_inFakeHead = False
_encoder = None
def __init__(self, *args, **kw):
http.Request.__init__(self, *args, **kw)
components.Componentized.__init__(self)
def getStateToCopyFor(self, issuer):
x = self.__dict__.copy()
del x['transport']
# XXX refactor this attribute out; it's from protocol
# del x['server']
del x['channel']
del x['content']
del x['site']
self.content.seek(0, 0)
x['content_data'] = self.content.read()
x['remote'] = ViewPoint(issuer, self)
# Address objects aren't jellyable
x['host'] = _addressToTuple(x['host'])
x['client'] = _addressToTuple(x['client'])
# Header objects also aren't jellyable.
x['requestHeaders'] = list(x['requestHeaders'].getAllRawHeaders())
return x
# HTML generation helpers
def sibLink(self, name):
"""
Return the text that links to a sibling of the requested resource.
"""
if self.postpath:
return (len(self.postpath)*b"../") + name
else:
return name
def childLink(self, name):
"""
Return the text that links to a child of the requested resource.
"""
lpp = len(self.postpath)
if lpp > 1:
return ((lpp-1)*b"../") + name
elif lpp == 1:
return name
else: # lpp == 0
if len(self.prepath) and self.prepath[-1]:
return self.prepath[-1] + b'/' + name
else:
return name
def process(self):
"""
Process a request.
"""
# get site from channel
self.site = self.channel.site
# set various default headers
self.setHeader(b'server', version)
self.setHeader(b'date', http.datetimeToString())
# Resource Identification
self.prepath = []
self.postpath = list(map(unquote, self.path[1:].split(b'/')))
try:
resrc = self.site.getResourceFor(self)
if resource._IEncodingResource.providedBy(resrc):
encoder = resrc.getEncoder(self)
if encoder is not None:
self._encoder = encoder
self.render(resrc)
except:
self.processingFailed(failure.Failure())
def write(self, data):
"""
Write data to the transport (if not responding to a HEAD request).
@param data: A string to write to the response.
"""
if not self.startedWriting:
# Before doing the first write, check to see if a default
# Content-Type header should be supplied.
modified = self.code != http.NOT_MODIFIED
contentType = self.responseHeaders.getRawHeaders(b'content-type')
if (modified and contentType is None and
self.defaultContentType is not None
):
self.responseHeaders.setRawHeaders(
b'content-type', [self.defaultContentType])
# Only let the write happen if we're not generating a HEAD response by
# faking out the request method. Note, if we are doing that,
# startedWriting will never be true, and the above logic may run
# multiple times. It will only actually change the responseHeaders
# once though, so it's still okay.
if not self._inFakeHead:
if self._encoder:
data = self._encoder.encode(data)
http.Request.write(self, data)
def finish(self):
"""
Override C{http.Request.finish} for possible encoding.
"""
if self._encoder:
data = self._encoder.finish()
if data:
http.Request.write(self, data)
return http.Request.finish(self)
def render(self, resrc):
"""
Ask a resource to render itself.
@param resrc: a L{twisted.web.resource.IResource}.
"""
try:
body = resrc.render(self)
except UnsupportedMethod as e:
allowedMethods = e.allowedMethods
if (self.method == b"HEAD") and (b"GET" in allowedMethods):
# We must support HEAD (RFC 2616, 5.1.1). If the
# resource doesn't, fake it by giving the resource
# a 'GET' request and then return only the headers,
# not the body.
log.msg("Using GET to fake a HEAD request for %s" %
(resrc,))
self.method = b"GET"
self._inFakeHead = True
body = resrc.render(self)
if body is NOT_DONE_YET:
log.msg("Tried to fake a HEAD request for %s, but "
"it got away from me." % resrc)
# Oh well, I guess we won't include the content length.
else:
self.setHeader(b'content-length', intToBytes(len(body)))
self._inFakeHead = False
self.method = b"HEAD"
self.write(b'')
self.finish()
return
if self.method in (supportedMethods):
# We MUST include an Allow header
# (RFC 2616, 10.4.6 and 14.7)
self.setHeader(b'Allow', b', '.join(allowedMethods))
s = ('''Your browser approached me (at %(URI)s) with'''
''' the method "%(method)s". I only allow'''
''' the method%(plural)s %(allowed)s here.''' % {
'URI': escape(nativeString(self.uri)),
'method': nativeString(self.method),
'plural': ((len(allowedMethods) > 1) and 's') or '',
'allowed': ', '.join(
[nativeString(x) for x in allowedMethods])
})
epage = resource.ErrorPage(http.NOT_ALLOWED,
"Method Not Allowed", s)
body = epage.render(self)
else:
epage = resource.ErrorPage(
http.NOT_IMPLEMENTED, "Huh?",
"I don't know how to treat a %s request." %
(escape(self.method.decode("charmap")),))
body = epage.render(self)
# end except UnsupportedMethod
if body == NOT_DONE_YET:
return
if not isinstance(body, bytes):
body = resource.ErrorPage(
http.INTERNAL_SERVER_ERROR,
"Request did not return bytes",
"Request: " + util._PRE(reflect.safe_repr(self)) + "<br />" +
"Resource: " + util._PRE(reflect.safe_repr(resrc)) + "<br />" +
"Value: " + util._PRE(reflect.safe_repr(body))).render(self)
if self.method == b"HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader(b'content-length',
intToBytes(len(body)))
self.write(b'')
else:
self.setHeader(b'content-length',
intToBytes(len(body)))
self.write(body)
self.finish()
def processingFailed(self, reason):
log.err(reason)
if self.site.displayTracebacks:
body = (b"<html><head><title>web.Server Traceback"
b" (most recent call last)</title></head>"
b"<body><b>web.Server Traceback"
b" (most recent call last):</b>\n\n" +
util.formatFailure(reason) +
b"\n\n</body></html>\n")
else:
body = (b"<html><head><title>Processing Failed"
b"</title></head><body>"
b"<b>Processing Failed</b></body></html>")
self.setResponseCode(http.INTERNAL_SERVER_ERROR)
self.setHeader(b'content-type', b"text/html")
self.setHeader(b'content-length', intToBytes(len(body)))
self.write(body)
self.finish()
return reason
def view_write(self, issuer, data):
"""Remote version of write; same interface.
"""
self.write(data)
def view_finish(self, issuer):
"""Remote version of finish; same interface.
"""
self.finish()
def view_addCookie(self, issuer, k, v, **kwargs):
"""Remote version of addCookie; same interface.
"""
self.addCookie(k, v, **kwargs)
def view_setHeader(self, issuer, k, v):
"""Remote version of setHeader; same interface.
"""
self.setHeader(k, v)
def view_setLastModified(self, issuer, when):
"""Remote version of setLastModified; same interface.
"""
self.setLastModified(when)
def view_setETag(self, issuer, tag):
"""Remote version of setETag; same interface.
"""
self.setETag(tag)
def view_setResponseCode(self, issuer, code, message=None):
"""
Remote version of setResponseCode; same interface.
"""
self.setResponseCode(code, message)
def view_registerProducer(self, issuer, producer, streaming):
"""Remote version of registerProducer; same interface.
(requires a remote producer.)
"""
self.registerProducer(_RemoteProducerWrapper(producer), streaming)
def view_unregisterProducer(self, issuer):
self.unregisterProducer()
### these calls remain local
_secureSession = None
_insecureSession = None
@property
def session(self):
"""
If a session has already been created or looked up with
L{Request.getSession}, this will return that object. (This will always
be the session that matches the security of the request; so if
C{forceNotSecure} is used on a secure request, this will not return
that session.)
@return: the session attribute
@rtype: L{Session} or L{None}
"""
if self.isSecure():
return self._secureSession
else:
return self._insecureSession
def getSession(self, sessionInterface=None, forceNotSecure=False):
"""
Check if there is a session cookie, and if not, create it.
By default, the cookie with be secure for HTTPS requests and not secure
for HTTP requests. If for some reason you need access to the insecure
cookie from a secure request you can set C{forceNotSecure = True}.
@param forceNotSecure: Should we retrieve a session that will be
transmitted over HTTP, even if this L{Request} was delivered over
HTTPS?
@type forceNotSecure: L{bool}
"""
# Make sure we aren't creating a secure session on a non-secure page
secure = self.isSecure() and not forceNotSecure
if not secure:
cookieString = b"TWISTED_SESSION"
sessionAttribute = "_insecureSession"
else:
cookieString = b"TWISTED_SECURE_SESSION"
sessionAttribute = "_secureSession"
session = getattr(self, sessionAttribute)
# Session management
if not session:
cookiename = b"_".join([cookieString] + self.sitepath)
sessionCookie = self.getCookie(cookiename)
if sessionCookie:
try:
session = self.site.getSession(sessionCookie)
except KeyError:
pass
# if it still hasn't been set, fix it up.
if not session:
session = self.site.makeSession()
self.addCookie(cookiename, session.uid, path=b"/",
secure=secure)
session.touch()
setattr(self, sessionAttribute, session)
if sessionInterface:
return session.getComponent(sessionInterface)
return session
def _prePathURL(self, prepath):
port = self.getHost().port
if self.isSecure():
default = 443
else:
default = 80
if port == default:
hostport = ''
else:
hostport = ':%d' % port
prefix = networkString('http%s://%s%s/' % (
self.isSecure() and 's' or '',
nativeString(self.getRequestHostname()),
hostport))
path = b'/'.join([quote(segment, safe=b'') for segment in prepath])
return prefix + path
def prePathURL(self):
return self._prePathURL(self.prepath)
def URLPath(self):
from twisted.python import urlpath
return urlpath.URLPath.fromRequest(self)
def rememberRootURL(self):
"""
Remember the currently-processed part of the URL for later
recalling.
"""
url = self._prePathURL(self.prepath[:-1])
self.appRootURL = url
def getRootURL(self):
"""
Get a previously-remembered URL.
"""
return self.appRootURL
@implementer(iweb._IRequestEncoderFactory)
class GzipEncoderFactory(object):
"""
@cvar compressLevel: The compression level used by the compressor, default
to 9 (highest).
@since: 12.3
"""
compressLevel = 9
def encoderForRequest(self, request):
"""
Check the headers if the client accepts gzip encoding, and encodes the
request if so.
"""
acceptHeaders = request.requestHeaders.getRawHeaders(
'accept-encoding', [])
supported = ','.join(acceptHeaders).split(',')
if 'gzip' in supported:
encoding = request.responseHeaders.getRawHeaders(
'content-encoding')
if encoding:
encoding = '%s,gzip' % ','.join(encoding)
else:
encoding = 'gzip'
request.responseHeaders.setRawHeaders('content-encoding',
[encoding])
return _GzipEncoder(self.compressLevel, request)
@implementer(iweb._IRequestEncoder)
class _GzipEncoder(object):
"""
An encoder which supports gzip.
@ivar _zlibCompressor: The zlib compressor instance used to compress the
stream.
@ivar _request: A reference to the originating request.
@since: 12.3
"""
_zlibCompressor = None
def __init__(self, compressLevel, request):
self._zlibCompressor = zlib.compressobj(
compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
self._request = request
def encode(self, data):
"""
Write to the request, automatically compressing data on the fly.
"""
if not self._request.startedWriting:
# Remove the content-length header, we can't honor it
# because we compress on the fly.
self._request.responseHeaders.removeHeader(b'content-length')
return self._zlibCompressor.compress(data)
def finish(self):
"""
Finish handling the request request, flushing any data from the zlib
buffer.
"""
remain = self._zlibCompressor.flush()
self._zlibCompressor = None
return remain
class _RemoteProducerWrapper:
def __init__(self, remote):
self.resumeProducing = remote.remoteMethod("resumeProducing")
self.pauseProducing = remote.remoteMethod("pauseProducing")
self.stopProducing = remote.remoteMethod("stopProducing")
class Session(components.Componentized):
"""
A user's session with a system.
This utility class contains no functionality, but is used to
represent a session.
@ivar uid: A unique identifier for the session.
@type uid: L{bytes}
@ivar _reactor: An object providing L{IReactorTime} to use for scheduling
expiration.
@ivar sessionTimeout: timeout of a session, in seconds.
"""
sessionTimeout = 900
_expireCall = None
def __init__(self, site, uid, reactor=None):
"""
Initialize a session with a unique ID for that session.
"""
components.Componentized.__init__(self)
if reactor is None:
from twisted.internet import reactor
self._reactor = reactor
self.site = site
self.uid = uid
self.expireCallbacks = []
self.touch()
self.sessionNamespaces = {}
def startCheckingExpiration(self):
"""
Start expiration tracking.
@return: L{None}
"""
self._expireCall = self._reactor.callLater(
self.sessionTimeout, self.expire)
def notifyOnExpire(self, callback):
"""
Call this callback when the session expires or logs out.
"""
self.expireCallbacks.append(callback)
def expire(self):
"""
Expire/logout of the session.
"""
del self.site.sessions[self.uid]
for c in self.expireCallbacks:
c()
self.expireCallbacks = []
if self._expireCall and self._expireCall.active():
self._expireCall.cancel()
# Break reference cycle.
self._expireCall = None
def touch(self):
"""
Notify session modification.
"""
self.lastModified = self._reactor.seconds()
if self._expireCall is not None:
self._expireCall.reset(self.sessionTimeout)
version = networkString("TwistedWeb/%s" % (copyright.version,))
@implementer(interfaces.IProtocolNegotiationFactory)
class Site(http.HTTPFactory):
"""
A web site: manage log, sessions, and resources.
@ivar counter: increment value used for generating unique sessions ID.
@ivar requestFactory: A factory which is called with (channel)
and creates L{Request} instances. Default to L{Request}.
@ivar displayTracebacks: if set, Twisted internal errors are displayed on
rendered pages. Default to C{True}.
@ivar sessionFactory: factory for sessions objects. Default to L{Session}.
@ivar sessionCheckTime: Deprecated. See L{Session.sessionTimeout} instead.
"""
counter = 0
requestFactory = Request
displayTracebacks = True
sessionFactory = Session
sessionCheckTime = 1800
_entropy = os.urandom
def __init__(self, resource, requestFactory=None, *args, **kwargs):
"""
@param resource: The root of the resource hierarchy. All request
traversal for requests received by this factory will begin at this
resource.
@type resource: L{IResource} provider
@param requestFactory: Overwrite for default requestFactory.
@type requestFactory: C{callable} or C{class}.
@see: L{twisted.web.http.HTTPFactory.__init__}
"""
http.HTTPFactory.__init__(self, *args, **kwargs)
self.sessions = {}
self.resource = resource
if requestFactory is not None:
self.requestFactory = requestFactory
def _openLogFile(self, path):
from twisted.python import logfile
return logfile.LogFile(os.path.basename(path), os.path.dirname(path))
def __getstate__(self):
d = self.__dict__.copy()
d['sessions'] = {}
return d
def _mkuid(self):
"""
(internal) Generate an opaque, unique ID for a user's session.
"""
self.counter = self.counter + 1
return hexlify(self._entropy(32))
def makeSession(self):
"""
Generate a new Session instance, and store it for future reference.
"""
uid = self._mkuid()
session = self.sessions[uid] = self.sessionFactory(self, uid)
session.startCheckingExpiration()
return session
def getSession(self, uid):
"""
Get a previously generated session.
@param uid: Unique ID of the session.
@type uid: L{bytes}.
@raise: L{KeyError} if the session is not found.
"""
return self.sessions[uid]
def buildProtocol(self, addr):
"""
Generate a channel attached to this site.
"""
channel = http.HTTPFactory.buildProtocol(self, addr)
channel.requestFactory = self.requestFactory
channel.site = self
return channel
isLeaf = 0
def render(self, request):
"""
Redirect because a Site is always a directory.
"""
request.redirect(request.prePathURL() + b'/')
request.finish()
def getChildWithDefault(self, pathEl, request):
"""
Emulate a resource's getChild method.
"""
request.site = self
return self.resource.getChildWithDefault(pathEl, request)
def getResourceFor(self, request):
"""
Get a resource for a request.
This iterates through the resource hierarchy, calling
getChildWithDefault on each resource it finds for a path element,
stopping when it hits an element where isLeaf is true.
"""
request.site = self
# Sitepath is used to determine cookie names between distributed
# servers and disconnected sites.
request.sitepath = copy.copy(request.prepath)
return resource.getChildForRequest(self.resource, request)
# IProtocolNegotiationFactory
def acceptableProtocols(self):
"""
Protocols this server can speak.
"""
baseProtocols = [b'http/1.1']
if http.H2_ENABLED:
baseProtocols.insert(0, b'h2')
return baseProtocols
| gpl-2.0 |
GinnyN/Team-Fortress-RPG-Generators | django/conf/locale/en_GB/formats.py | 99 | 2044 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j M Y' # '25 Oct 2006'
TIME_FORMAT = 'P' # '2:30 pm'
DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 pm'
YEAR_MONTH_FORMAT = 'F Y' # 'October 2006'
MONTH_DAY_FORMAT = 'j F' # '25 October'
SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006'
SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 pm'
FIRST_DAY_OF_WEEK = 0 # Sunday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = (
'%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06'
'%Y-%m-%d', # '2006-10-25'
# '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
# '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
# '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
# '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
)
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
)
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59'
'%d/%m/%Y %H:%M', # '25/10/2006 14:30'
'%d/%m/%Y', # '25/10/2006'
'%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59'
'%d/%m/%y %H:%M', # '25/10/06 14:30'
'%d/%m/%y', # '25/10/06'
)
DECIMAL_SEPARATOR = '.'
THOUSAND_SEPARATOR = ','
NUMBER_GROUPING = 3
| bsd-3-clause |
mnahm5/django-estore | Lib/site-packages/boto/opsworks/__init__.py | 135 | 1657 | # Copyright (c) 2014 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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 boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the Amazon OpsWorks service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.opsworks.layer1 import OpsWorksConnection
return get_regions('opsworks', connection_cls=OpsWorksConnection)
def connect_to_region(region_name, **kw_params):
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None
| mit |
ycaihua/kbengine | kbe/res/scripts/common/Lib/pty.py | 120 | 4763 | """Pseudo terminal utilities."""
# Bugs: No signal handling. Doesn't set slave termios and window size.
# Only tested on Linux.
# See: W. Richard Stevens. 1992. Advanced Programming in the
# UNIX Environment. Chapter 19.
# Author: Steen Lumholt -- with additions by Guido.
from select import select
import os
import tty
__all__ = ["openpty","fork","spawn"]
STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2
CHILD = 0
def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_fd
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = os.ttyname(slave_fd)
os.close(slave_fd)
return master_fd, slave_name
return _open_terminal()
def _open_terminal():
"""Open pty master and return (master_fd, tty_name)."""
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
pty_name = '/dev/pty' + x + y
try:
fd = os.open(pty_name, os.O_RDWR)
except OSError:
continue
return (fd, '/dev/tty' + x + y)
raise OSError('out of pty devices')
def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
pass
return result
def fork():
"""fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal."""
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() already set us session leader
pass
return pid, fd
master_fd, slave_fd = openpty()
pid = os.fork()
if pid == CHILD:
# Establish a new session.
os.setsid()
os.close(master_fd)
# Slave becomes stdin/stdout/stderr of child.
os.dup2(slave_fd, STDIN_FILENO)
os.dup2(slave_fd, STDOUT_FILENO)
os.dup2(slave_fd, STDERR_FILENO)
if (slave_fd > STDERR_FILENO):
os.close (slave_fd)
# Explicitly open the tty to make it become a controlling tty.
tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
os.close(tmp_fd)
else:
os.close(slave_fd)
# Parent and child process.
return pid, master_fd
def _writen(fd, data):
"""Write all the data to a descriptor."""
while data:
n = os.write(fd, data)
data = data[n:]
def _read(fd):
"""Default read function."""
return os.read(fd, 1024)
def _copy(master_fd, master_read=_read, stdin_read=_read):
"""Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read)"""
fds = [master_fd, STDIN_FILENO]
while True:
rfds, wfds, xfds = select(fds, [], [])
if master_fd in rfds:
data = master_read(master_fd)
if not data: # Reached EOF.
fds.remove(master_fd)
else:
os.write(STDOUT_FILENO, data)
if STDIN_FILENO in rfds:
data = stdin_read(STDIN_FILENO)
if not data:
fds.remove(STDIN_FILENO)
else:
_writen(master_fd, data)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except OSError:
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
return os.waitpid(pid, 0)[1]
| lgpl-3.0 |
jazztpt/edx-platform | common/djangoapps/cache_toolbox/model.py | 239 | 1680 | """
Caching model instances
-----------------------
``cache_model`` adds utility methods to a model to obtain ``ForeignKey``
instances via the cache.
Usage
~~~~~
::
from django.db import models
from django.contrib.auth.models import User
class Foo(models.Model):
name = models.CharField(length=20)
cache_model(Foo)
::
>>> a = Foo.objects.create(name='a')
>>> a
<Foo: >
>>> Foo.get_cached(a.pk) # Cache miss
<Foo: >
>>> a = Foo.get_cached(a.pk) # Cache hit
>>> a.name
u'a'
Instances returned from ``get_cached`` are real model instances::
>>> a = Foo.get_cached(a.pk) # Cache hit
>>> type(a)
<class '__main__.models.A'>
>>> a.pk
1L
Invalidation
~~~~~~~~~~~~
Invalidation is performed automatically upon saving or deleting a ``Foo``
instance::
>>> a = Foo.objects.create(name='a')
>>> a.name = 'b'
>>> a.save()
>>> a = Foo.get_cached(a.pk)
>>> a.name
u'b'
>>> a.delete()
>>> a = Foo.get_cached(a.pk)
... Foo.DoesNotExist
"""
from django.db.models.signals import post_save, post_delete
from .core import get_instance, delete_instance
def cache_model(model, timeout=None):
if hasattr(model, 'get_cached'):
# Already patched
return
def clear_cache(sender, instance, *args, **kwargs):
delete_instance(sender, instance)
post_save.connect(clear_cache, sender=model, weak=False)
post_delete.connect(clear_cache, sender=model, weak=False)
@classmethod
def get(cls, pk, using=None):
if pk is None:
return None
return get_instance(cls, pk, timeout, using)
model.get_cached = get
| agpl-3.0 |
vadimtk/chrome4sdp | tools/telemetry/third_party/webpagereplay/trafficshaper.py | 31 | 6415 | #!/usr/bin/env python
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import platformsettings
import re
# Mac has broken bandwitdh parsing, so double check the values.
# On Mac OS X 10.6, "KBit/s" actually uses "KByte/s".
BANDWIDTH_PATTERN = r'0|\d+[KM]?(bit|Byte)/s'
class TrafficShaperException(Exception):
pass
class BandwidthValueError(TrafficShaperException):
def __init__(self, value): # pylint: disable=super-init-not-called
self.value = value
def __str__(self):
return 'Value, "%s", does not match regex: %s' % (
self.value, BANDWIDTH_PATTERN)
class TrafficShaper(object):
"""Manages network traffic shaping."""
# Pick webpagetest-compatible values (details: http://goo.gl/oghTg).
_UPLOAD_PIPE = '10' # Enforces overall upload bandwidth.
_UPLOAD_QUEUE = '10' # Shares upload bandwidth among source ports.
_UPLOAD_RULE = '5000' # Specifies when the upload queue is used.
_DOWNLOAD_PIPE = '11' # Enforces overall download bandwidth.
_DOWNLOAD_QUEUE = '11' # Shares download bandwidth among destination ports.
_DOWNLOAD_RULE = '5100' # Specifies when the download queue is used.
_QUEUE_SLOTS = 100 # Number of packets to queue.
_BANDWIDTH_RE = re.compile(BANDWIDTH_PATTERN)
def __init__(self,
dont_use=None,
host='127.0.0.1',
ports=None,
up_bandwidth='0',
down_bandwidth='0',
delay_ms='0',
packet_loss_rate='0',
init_cwnd='0',
use_loopback=True):
"""Start shaping traffic.
Args:
host: a host string (name or IP) for the web proxy.
ports: a list of ports to shape traffic on.
up_bandwidth: Upload bandwidth
down_bandwidth: Download bandwidth
Bandwidths measured in [K|M]{bit/s|Byte/s}. '0' means unlimited.
delay_ms: Propagation delay in milliseconds. '0' means no delay.
packet_loss_rate: Packet loss rate in range [0..1]. '0' means no loss.
init_cwnd: the initial cwnd setting. '0' means no change.
use_loopback: True iff shaping is done on the loopback (or equiv) adapter.
"""
assert dont_use is None # Force args to be named.
self.host = host
self.ports = ports
self.up_bandwidth = up_bandwidth
self.down_bandwidth = down_bandwidth
self.delay_ms = delay_ms
self.packet_loss_rate = packet_loss_rate
self.init_cwnd = init_cwnd
self.use_loopback = use_loopback
if not self._BANDWIDTH_RE.match(self.up_bandwidth):
raise BandwidthValueError(self.up_bandwidth)
if not self._BANDWIDTH_RE.match(self.down_bandwidth):
raise BandwidthValueError(self.down_bandwidth)
self.is_shaping = False
def __enter__(self):
if self.use_loopback:
platformsettings.setup_temporary_loopback_config()
if self.init_cwnd != '0':
platformsettings.set_temporary_tcp_init_cwnd(self.init_cwnd)
try:
ipfw_list = platformsettings.ipfw('list')
if not ipfw_list.startswith('65535 '):
logging.warn('ipfw has existing rules:\n%s', ipfw_list)
self._delete_rules(ipfw_list)
except Exception:
pass
if (self.up_bandwidth == '0' and self.down_bandwidth == '0' and
self.delay_ms == '0' and self.packet_loss_rate == '0'):
logging.info('Skipped shaping traffic.')
return
if not self.ports:
raise TrafficShaperException('No ports on which to shape traffic.')
ports = ','.join(str(p) for p in self.ports)
half_delay_ms = int(self.delay_ms) / 2 # split over up/down links
try:
# Configure upload shaping.
platformsettings.ipfw(
'pipe', self._UPLOAD_PIPE,
'config',
'bw', self.up_bandwidth,
'delay', half_delay_ms,
)
platformsettings.ipfw(
'queue', self._UPLOAD_QUEUE,
'config',
'pipe', self._UPLOAD_PIPE,
'plr', self.packet_loss_rate,
'queue', self._QUEUE_SLOTS,
'mask', 'src-port', '0xffff',
)
platformsettings.ipfw(
'add', self._UPLOAD_RULE,
'queue', self._UPLOAD_QUEUE,
'ip',
'from', 'any',
'to', self.host,
self.use_loopback and 'out' or 'in',
'dst-port', ports,
)
self.is_shaping = True
# Configure download shaping.
platformsettings.ipfw(
'pipe', self._DOWNLOAD_PIPE,
'config',
'bw', self.down_bandwidth,
'delay', half_delay_ms,
)
platformsettings.ipfw(
'queue', self._DOWNLOAD_QUEUE,
'config',
'pipe', self._DOWNLOAD_PIPE,
'plr', self.packet_loss_rate,
'queue', self._QUEUE_SLOTS,
'mask', 'dst-port', '0xffff',
)
platformsettings.ipfw(
'add', self._DOWNLOAD_RULE,
'queue', self._DOWNLOAD_QUEUE,
'ip',
'from', self.host,
'to', 'any',
'out',
'src-port', ports,
)
logging.info('Started shaping traffic')
except Exception:
logging.error('Unable to shape traffic.')
raise
def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb):
if self.is_shaping:
try:
self._delete_rules()
logging.info('Stopped shaping traffic')
except Exception:
logging.error('Unable to stop shaping traffic.')
raise
def _delete_rules(self, ipfw_list=None):
if ipfw_list is None:
ipfw_list = platformsettings.ipfw('list')
existing_rules = set(
r.split()[0].lstrip('0') for r in ipfw_list.splitlines())
delete_rules = [r for r in (self._DOWNLOAD_RULE, self._UPLOAD_RULE)
if r in existing_rules]
if delete_rules:
platformsettings.ipfw('delete', *delete_rules)
| bsd-3-clause |
aaleotti-unimore/ComicsScraper | lib/html5lib/treebuilders/etree_lxml.py | 353 | 14161 | """Module for supporting the lxml.etree library. The idea here is to use as much
of the native library as possible, without using fragile hacks like custom element
names that break between releases. The downside of this is that we cannot represent
all possible trees; specifically the following are known to cause problems:
Text or comments as siblings of the root element
Docypes with no name
When any of these things occur, we emit a DataLossWarning
"""
from __future__ import absolute_import, division, unicode_literals
# pylint:disable=protected-access
import warnings
import re
import sys
from . import base
from ..constants import DataLossWarning
from .. import constants
from . import etree as etree_builders
from .. import _ihatexml
import lxml.etree as etree
fullTree = True
tag_regexp = re.compile("{([^}]*)}(.*)")
comment_type = etree.Comment("asd").tag
class DocumentType(object):
def __init__(self, name, publicId, systemId):
self.name = name
self.publicId = publicId
self.systemId = systemId
class Document(object):
def __init__(self):
self._elementTree = None
self._childNodes = []
def appendChild(self, element):
self._elementTree.getroot().addnext(element._element)
def _getChildNodes(self):
return self._childNodes
childNodes = property(_getChildNodes)
def testSerializer(element):
rv = []
infosetFilter = _ihatexml.InfosetFilter(preventDoubleDashComments=True)
def serializeElement(element, indent=0):
if not hasattr(element, "tag"):
if hasattr(element, "getroot"):
# Full tree case
rv.append("#document")
if element.docinfo.internalDTD:
if not (element.docinfo.public_id or
element.docinfo.system_url):
dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name
else:
dtd_str = """<!DOCTYPE %s "%s" "%s">""" % (
element.docinfo.root_name,
element.docinfo.public_id,
element.docinfo.system_url)
rv.append("|%s%s" % (' ' * (indent + 2), dtd_str))
next_element = element.getroot()
while next_element.getprevious() is not None:
next_element = next_element.getprevious()
while next_element is not None:
serializeElement(next_element, indent + 2)
next_element = next_element.getnext()
elif isinstance(element, str) or isinstance(element, bytes):
# Text in a fragment
assert isinstance(element, str) or sys.version_info[0] == 2
rv.append("|%s\"%s\"" % (' ' * indent, element))
else:
# Fragment case
rv.append("#document-fragment")
for next_element in element:
serializeElement(next_element, indent + 2)
elif element.tag == comment_type:
rv.append("|%s<!-- %s -->" % (' ' * indent, element.text))
if hasattr(element, "tail") and element.tail:
rv.append("|%s\"%s\"" % (' ' * indent, element.tail))
else:
assert isinstance(element, etree._Element)
nsmatch = etree_builders.tag_regexp.match(element.tag)
if nsmatch is not None:
ns = nsmatch.group(1)
tag = nsmatch.group(2)
prefix = constants.prefixes[ns]
rv.append("|%s<%s %s>" % (' ' * indent, prefix,
infosetFilter.fromXmlName(tag)))
else:
rv.append("|%s<%s>" % (' ' * indent,
infosetFilter.fromXmlName(element.tag)))
if hasattr(element, "attrib"):
attributes = []
for name, value in element.attrib.items():
nsmatch = tag_regexp.match(name)
if nsmatch is not None:
ns, name = nsmatch.groups()
name = infosetFilter.fromXmlName(name)
prefix = constants.prefixes[ns]
attr_string = "%s %s" % (prefix, name)
else:
attr_string = infosetFilter.fromXmlName(name)
attributes.append((attr_string, value))
for name, value in sorted(attributes):
rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))
if element.text:
rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text))
indent += 2
for child in element:
serializeElement(child, indent)
if hasattr(element, "tail") and element.tail:
rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail))
serializeElement(element, 0)
return "\n".join(rv)
def tostring(element):
"""Serialize an element and its child nodes to a string"""
rv = []
def serializeElement(element):
if not hasattr(element, "tag"):
if element.docinfo.internalDTD:
if element.docinfo.doctype:
dtd_str = element.docinfo.doctype
else:
dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name
rv.append(dtd_str)
serializeElement(element.getroot())
elif element.tag == comment_type:
rv.append("<!--%s-->" % (element.text,))
else:
# This is assumed to be an ordinary element
if not element.attrib:
rv.append("<%s>" % (element.tag,))
else:
attr = " ".join(["%s=\"%s\"" % (name, value)
for name, value in element.attrib.items()])
rv.append("<%s %s>" % (element.tag, attr))
if element.text:
rv.append(element.text)
for child in element:
serializeElement(child)
rv.append("</%s>" % (element.tag,))
if hasattr(element, "tail") and element.tail:
rv.append(element.tail)
serializeElement(element)
return "".join(rv)
class TreeBuilder(base.TreeBuilder):
documentClass = Document
doctypeClass = DocumentType
elementClass = None
commentClass = None
fragmentClass = Document
implementation = etree
def __init__(self, namespaceHTMLElements, fullTree=False):
builder = etree_builders.getETreeModule(etree, fullTree=fullTree)
infosetFilter = self.infosetFilter = _ihatexml.InfosetFilter(preventDoubleDashComments=True)
self.namespaceHTMLElements = namespaceHTMLElements
class Attributes(dict):
def __init__(self, element, value=None):
if value is None:
value = {}
self._element = element
dict.__init__(self, value) # pylint:disable=non-parent-init-called
for key, value in self.items():
if isinstance(key, tuple):
name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1]))
else:
name = infosetFilter.coerceAttribute(key)
self._element._element.attrib[name] = value
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
if isinstance(key, tuple):
name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1]))
else:
name = infosetFilter.coerceAttribute(key)
self._element._element.attrib[name] = value
class Element(builder.Element):
def __init__(self, name, namespace):
name = infosetFilter.coerceElement(name)
builder.Element.__init__(self, name, namespace=namespace)
self._attributes = Attributes(self)
def _setName(self, name):
self._name = infosetFilter.coerceElement(name)
self._element.tag = self._getETreeTag(
self._name, self._namespace)
def _getName(self):
return infosetFilter.fromXmlName(self._name)
name = property(_getName, _setName)
def _getAttributes(self):
return self._attributes
def _setAttributes(self, attributes):
self._attributes = Attributes(self, attributes)
attributes = property(_getAttributes, _setAttributes)
def insertText(self, data, insertBefore=None):
data = infosetFilter.coerceCharacters(data)
builder.Element.insertText(self, data, insertBefore)
def appendChild(self, child):
builder.Element.appendChild(self, child)
class Comment(builder.Comment):
def __init__(self, data):
data = infosetFilter.coerceComment(data)
builder.Comment.__init__(self, data)
def _setData(self, data):
data = infosetFilter.coerceComment(data)
self._element.text = data
def _getData(self):
return self._element.text
data = property(_getData, _setData)
self.elementClass = Element
self.commentClass = Comment
# self.fragmentClass = builder.DocumentFragment
base.TreeBuilder.__init__(self, namespaceHTMLElements)
def reset(self):
base.TreeBuilder.reset(self)
self.insertComment = self.insertCommentInitial
self.initial_comments = []
self.doctype = None
def testSerializer(self, element):
return testSerializer(element)
def getDocument(self):
if fullTree:
return self.document._elementTree
else:
return self.document._elementTree.getroot()
def getFragment(self):
fragment = []
element = self.openElements[0]._element
if element.text:
fragment.append(element.text)
fragment.extend(list(element))
if element.tail:
fragment.append(element.tail)
return fragment
def insertDoctype(self, token):
name = token["name"]
publicId = token["publicId"]
systemId = token["systemId"]
if not name:
warnings.warn("lxml cannot represent empty doctype", DataLossWarning)
self.doctype = None
else:
coercedName = self.infosetFilter.coerceElement(name)
if coercedName != name:
warnings.warn("lxml cannot represent non-xml doctype", DataLossWarning)
doctype = self.doctypeClass(coercedName, publicId, systemId)
self.doctype = doctype
def insertCommentInitial(self, data, parent=None):
assert parent is None or parent is self.document
assert self.document._elementTree is None
self.initial_comments.append(data)
def insertCommentMain(self, data, parent=None):
if (parent == self.document and
self.document._elementTree.getroot()[-1].tag == comment_type):
warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning)
super(TreeBuilder, self).insertComment(data, parent)
def insertRoot(self, token):
"""Create the document root"""
# Because of the way libxml2 works, it doesn't seem to be possible to
# alter information like the doctype after the tree has been parsed.
# Therefore we need to use the built-in parser to create our initial
# tree, after which we can add elements like normal
docStr = ""
if self.doctype:
assert self.doctype.name
docStr += "<!DOCTYPE %s" % self.doctype.name
if (self.doctype.publicId is not None or
self.doctype.systemId is not None):
docStr += (' PUBLIC "%s" ' %
(self.infosetFilter.coercePubid(self.doctype.publicId or "")))
if self.doctype.systemId:
sysid = self.doctype.systemId
if sysid.find("'") >= 0 and sysid.find('"') >= 0:
warnings.warn("DOCTYPE system cannot contain single and double quotes", DataLossWarning)
sysid = sysid.replace("'", 'U00027')
if sysid.find("'") >= 0:
docStr += '"%s"' % sysid
else:
docStr += "'%s'" % sysid
else:
docStr += "''"
docStr += ">"
if self.doctype.name != token["name"]:
warnings.warn("lxml cannot represent doctype with a different name to the root element", DataLossWarning)
docStr += "<THIS_SHOULD_NEVER_APPEAR_PUBLICLY/>"
root = etree.fromstring(docStr)
# Append the initial comments:
for comment_token in self.initial_comments:
comment = self.commentClass(comment_token["data"])
root.addprevious(comment._element)
# Create the root document and add the ElementTree to it
self.document = self.documentClass()
self.document._elementTree = root.getroottree()
# Give the root element the right name
name = token["name"]
namespace = token.get("namespace", self.defaultNamespace)
if namespace is None:
etree_tag = name
else:
etree_tag = "{%s}%s" % (namespace, name)
root.tag = etree_tag
# Add the root element to the internal child/open data structures
root_element = self.elementClass(name, namespace)
root_element._element = root
self.document._childNodes.append(root_element)
self.openElements.append(root_element)
# Reset to the default insert comment function
self.insertComment = self.insertCommentMain
| apache-2.0 |
milki/password-store | contrib/importers/keepass2pass.py | 26 | 4832 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Stefan Simroth <stefan.simroth@gmail.com>. All Rights Reserved.
# Based on the script for KeepassX by Juhamatti Niemelä <iiska@iki.fi>.
# This file is licensed under the GPLv2+. Please see COPYING for more information.
#
# Usage:
# ./keepass2pass.py -f export.xml
# By default, takes the name of the root element and puts all passwords in there, but you can disable this:
# ./keepass2pass.py -f export.xml -r ""
# Or you can use another root folder:
# ./keepass2pass.py -f export.xml -r foo
#
# Features:
# * This script can handle duplicates and will merge them.
# * Besides the password also the fields 'UserName', 'URL' and 'Notes' (comment) will be inserted.
# * You get a warning if an entry has no password, but it will still insert it.
import getopt, sys
from subprocess import Popen, PIPE
from xml.etree import ElementTree
def pass_import_entry(path, data):
""" Import new password entry to password-store using pass insert command """
proc = Popen(['pass', 'insert', '--multiline', path], stdin=PIPE, stdout=PIPE)
proc.communicate(data.encode('utf8'))
proc.wait()
def get_value(elements, node_text):
for element in elements:
for child in element.findall('Key'):
if child.text == node_text:
return element.find('Value').text
return ''
def path_for(element, path=''):
""" Generate path name from elements title and current path """
if element.tag == 'Entry':
title = get_value(element.findall("String"), "Title")
elif element.tag == 'Group':
title = element.find('Name').text
else: title = ''
if path == '': return title
else: return '/'.join([path, title])
def password_data(element, path=''):
""" Return password data and additional info if available from password entry element. """
data = ""
password = get_value(element.findall('String'), 'Password')
if password is not None: data = password + "\n"
else:
print "[WARN] No password: %s" % path_for(element, path)
for field in ['UserName', 'URL', 'Notes']:
value = get_value(element, field)
if value is not None and not len(value) == 0:
data = "%s%s: %s\n" % (data, field, value)
return data
def import_entry(entries, element, path=''):
element_path = path_for(element, path)
if entries.has_key(element_path):
print "[INFO] Duplicate needs merging: %s" % element_path
existing_data = entries[element_path]
data = "%s---------\nPassword: %s" % (existing_data, password_data(element))
else:
data = password_data(element, path)
entries[element_path] = data
def import_group(entries, element, path=''):
""" Import all entries and sub-groups from given group """
npath = path_for(element, path)
for group in element.findall('Group'):
import_group(entries, group, npath)
for entry in element.findall('Entry'):
import_entry(entries, entry, npath)
def import_passwords(xml_file, root_path=None):
""" Parse given Keepass2 XML file and import password groups from it """
print "[>>>>] Importing passwords from file %s" % xml_file
print "[INFO] Root path: %s" % root_path
entries = dict()
with open(xml_file) as xml:
text = xml.read()
xml_tree = ElementTree.XML(text)
root = xml_tree.find('Root')
root_group = root.find('Group')
import_group(entries,root_group,'')
if root_path is None: root_path = root_group.find('Name').text
groups = root_group.findall('Group')
for group in groups:
import_group(entries, group, root_path)
password_count = 0
for path, data in sorted(entries.iteritems()):
sys.stdout.write("[>>>>] Importing %s ... " % path.encode("utf-8"))
pass_import_entry(path, data)
sys.stdout.write("OK\n")
password_count += 1
print "[ OK ] Done. Imported %i passwords." % password_count
def usage():
""" Print usage """
print "Usage: %s -f XML_FILE" % (sys.argv[0])
print "Optional:"
print " -r ROOT_PATH Different root path to use than the one in xml file, use \"\" for none"
def main(argv):
try:
opts, args = getopt.gnu_getopt(argv, "f:r:")
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit(2)
xml_file = None
root_path = None
for opt, arg in opts:
if opt in "-f":
xml_file = arg
if opt in "-r":
root_path = arg
if xml_file is not None:
import_passwords(xml_file, root_path)
else:
usage()
sys.exit(2)
if __name__ == '__main__':
main(sys.argv[1:])
| gpl-2.0 |
camptocamp/c2c-rd-addons | chricar_account_period_sum/wizard/__init__.py | 4 | 1182 | # -*- coding: utf-8 -*-
# ChriCar Beteiligungs- und Beratungs- GmbH
# 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 Affero General Public License
# as published by the Free Software Foundation; either version 2
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
import chart
| agpl-3.0 |
eadgarchen/tensorflow | tensorflow/contrib/ffmpeg/decode_audio_op_test.py | 33 | 8176 | # 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 third_party.tensorflow.contrib.ffmpeg.decode_audio_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import six
from tensorflow.contrib import ffmpeg
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import resource_loader
from tensorflow.python.platform import test
class DecodeAudioOpTest(test.TestCase):
def _loadFileAndTest(self, filename, file_format, duration_sec,
samples_per_second, channel_count,
samples_per_second_tensor=None, feed_dict=None):
"""Loads an audio file and validates the output tensor.
Args:
filename: The filename of the input file.
file_format: The format of the input file.
duration_sec: The duration of the audio contained in the file in seconds.
samples_per_second: The desired sample rate in the output tensor.
channel_count: The desired channel count in the output tensor.
samples_per_second_tensor: The value to pass to the corresponding
parameter in the instantiated `decode_audio` op. If not
provided, will default to a constant value of
`samples_per_second`. Useful for providing a placeholder.
feed_dict: Used when evaluating the `decode_audio` op. If not
provided, will be empty. Useful when providing a placeholder for
`samples_per_second_tensor`.
"""
if samples_per_second_tensor is None:
samples_per_second_tensor = samples_per_second
with self.test_session():
path = os.path.join(resource_loader.get_data_files_path(), 'testdata',
filename)
with open(path, 'rb') as f:
contents = f.read()
audio_op = ffmpeg.decode_audio(
contents,
file_format=file_format,
samples_per_second=samples_per_second_tensor,
channel_count=channel_count)
audio = audio_op.eval(feed_dict=feed_dict or {})
self.assertEqual(len(audio.shape), 2)
self.assertNear(
duration_sec * samples_per_second,
audio.shape[0],
# Duration should be specified within 10%:
0.1 * audio.shape[0])
self.assertEqual(audio.shape[1], channel_count)
def testMonoMp3(self):
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000, 1)
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000, 2)
def testMonoMp4Mp3Codec(self):
# mp3 compressed audio streams in mp4 container.
self._loadFileAndTest('mono_16khz_mp3.mp4', 'mp4', 2.77, 20000, 1)
self._loadFileAndTest('mono_16khz_mp3.mp4', 'mp4', 2.77, 20000, 2)
def testMonoMp4AacCodec(self):
# aac compressed audio streams in mp4 container.
self._loadFileAndTest('mono_32khz_aac.mp4', 'mp4', 2.77, 20000, 1)
self._loadFileAndTest('mono_32khz_aac.mp4', 'mp4', 2.77, 20000, 2)
def testStereoMp3(self):
self._loadFileAndTest('stereo_48khz.mp3', 'mp3', 0.79, 50000, 1)
self._loadFileAndTest('stereo_48khz.mp3', 'mp3', 0.79, 20000, 2)
def testStereoMp4Mp3Codec(self):
# mp3 compressed audio streams in mp4 container.
self._loadFileAndTest('stereo_48khz_mp3.mp4', 'mp4', 0.79, 50000, 1)
self._loadFileAndTest('stereo_48khz_mp3.mp4', 'mp4', 0.79, 20000, 2)
def testStereoMp4AacCodec(self):
# aac compressed audio streams in mp4 container.
self._loadFileAndTest('stereo_48khz_aac.mp4', 'mp4', 0.79, 50000, 1)
self._loadFileAndTest('stereo_48khz_aac.mp4', 'mp4', 0.79, 20000, 2)
def testMonoWav(self):
self._loadFileAndTest('mono_10khz.wav', 'wav', 0.57, 5000, 1)
self._loadFileAndTest('mono_10khz.wav', 'wav', 0.57, 10000, 4)
def testOgg(self):
self._loadFileAndTest('mono_10khz.ogg', 'ogg', 0.57, 10000, 1)
def testInvalidFile(self):
with self.test_session():
contents = 'invalid file'
audio_op = ffmpeg.decode_audio(
contents,
file_format='wav',
samples_per_second=10000,
channel_count=2)
audio = audio_op.eval()
self.assertEqual(audio.shape, (0, 0))
def testSampleRatePlaceholder(self):
placeholder = array_ops.placeholder(dtypes.int32)
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000, 1,
samples_per_second_tensor=placeholder,
feed_dict={placeholder: 20000})
def testSampleRateBadType(self):
placeholder = array_ops.placeholder(dtypes.float32)
with self.assertRaises(TypeError):
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000.0, 1,
samples_per_second_tensor=placeholder,
feed_dict={placeholder: 20000.0})
def testSampleRateBadValue_Zero(self):
placeholder = array_ops.placeholder(dtypes.int32)
with six.assertRaisesRegex(self, Exception,
r'samples_per_second must be positive'):
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000.0, 1,
samples_per_second_tensor=placeholder,
feed_dict={placeholder: 0})
def testSampleRateBadValue_Negative(self):
placeholder = array_ops.placeholder(dtypes.int32)
with six.assertRaisesRegex(self, Exception,
r'samples_per_second must be positive'):
self._loadFileAndTest('mono_16khz.mp3', 'mp3', 0.57, 20000.0, 1,
samples_per_second_tensor=placeholder,
feed_dict={placeholder: -2})
def testInvalidFileFormat(self):
with six.assertRaisesRegex(self, Exception,
r'file_format must be one of'):
self._loadFileAndTest('mono_16khz.mp3', 'docx', 0.57, 20000, 1)
def testStaticShapeInference_ConstantChannelCount(self):
with self.test_session():
audio_op = ffmpeg.decode_audio(b'~~~ wave ~~~',
file_format='wav',
samples_per_second=44100,
channel_count=2)
self.assertEqual([None, 2], audio_op.shape.as_list())
def testStaticShapeInference_NonConstantChannelCount(self):
with self.test_session():
channel_count = array_ops.placeholder(dtypes.int32)
audio_op = ffmpeg.decode_audio(b'~~~ wave ~~~',
file_format='wav',
samples_per_second=44100,
channel_count=channel_count)
self.assertEqual([None, None], audio_op.shape.as_list())
def testStaticShapeInference_ZeroChannelCountInvalid(self):
with self.test_session():
with six.assertRaisesRegex(self, Exception,
r'channel_count must be positive'):
ffmpeg.decode_audio(b'~~~ wave ~~~',
file_format='wav',
samples_per_second=44100,
channel_count=0)
def testStaticShapeInference_NegativeChannelCountInvalid(self):
with self.test_session():
with six.assertRaisesRegex(self, Exception,
r'channel_count must be positive'):
ffmpeg.decode_audio(b'~~~ wave ~~~',
file_format='wav',
samples_per_second=44100,
channel_count=-2)
if __name__ == '__main__':
test.main()
| apache-2.0 |
iamutkarshtiwari/kivy | kivy/uix/dropdown.py | 20 | 11854 | '''
Drop-Down List
==============
.. versionadded:: 1.4.0
A versatile drop-down list that can be used with custom widgets. It allows you
to display a list of widgets under a displayed widget. Unlike other toolkits,
the list of widgets can contain any type of widget: simple buttons,
images etc.
The positioning of the drop-down list is fully automatic: we will always try to
place the dropdown list in a way that the user can select an item in the list.
Basic example
-------------
A button with a dropdown list of 10 possible values. All the buttons within the
dropdown list will trigger the dropdown :meth:`DropDown.select` method. After
being called, the main button text will display the selection of the
dropdown. ::
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
# create a dropdown with 10 buttons
dropdown = DropDown()
for index in range(10):
# when adding widgets, we need to specify the height manually (disabling
# the size_hint_y) so the dropdown can calculate the area it needs.
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
# then add the button inside the dropdown
dropdown.add_widget(btn)
# create a big main button
mainbutton = Button(text='Hello', size_hint=(None, None))
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=dropdown.open)
# one last thing, listen for the selection in the dropdown list and
# assign the data to the button text.
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
runTouchApp(mainbutton)
Extending dropdown in Kv
------------------------
You could create a dropdown directly from your kv::
#:kivy 1.4.0
<CustomDropDown>:
Button:
text: 'My first Item'
size_hint_y: None
height: 44
on_release: root.select('item1')
Label:
text: 'Unselectable item'
size_hint_y: None
height: 44
Button:
text: 'My second Item'
size_hint_y: None
height: 44
on_release: root.select('item2')
And then, create the associated python class and use it::
class CustomDropDown(DropDown):
pass
dropdown = CustomDropDown()
mainbutton = Button(text='Hello', size_hint=(None, None))
mainbutton.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
'''
__all__ = ('DropDown', )
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty
from kivy.core.window import Window
from kivy.lang import Builder
_grid_kv = '''
GridLayout:
size_hint_y: None
height: self.minimum_size[1]
cols: 1
'''
class DropDownException(Exception):
'''DropDownException class.
'''
pass
class DropDown(ScrollView):
'''DropDown class. See module documentation for more information.
:Events:
`on_select`: data
Fired when a selection is done. The data of the selection is passed
in as the first argument and is what you pass in the :meth:`select`
method as the first argument.
`on_dismiss`:
.. versionadded:: 1.8.0
Fired when the DropDown is dismissed, either on selection or on
touching outside the widget.
'''
auto_width = BooleanProperty(True)
'''By default, the width of the dropdown will be the same as the width of
the attached widget. Set to False if you want to provide your own width.
'''
max_height = NumericProperty(None, allownone=True)
'''Indicate the maximum height that the dropdown can take. If None, it will
take the maximum height available until the top or bottom of the screen
is reached.
:attr:`max_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to None.
'''
dismiss_on_select = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
selection has been done. Set to False to prevent the dismiss.
:attr:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
'''
auto_dismiss = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
touch happens outside of it, this option allow to disable this
feature
:attr:`auto_dismiss` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
.. versionadded:: 1.8.0
'''
attach_to = ObjectProperty(allownone=True)
'''(internal) Property that will be set to the widget to which the
drop down list is attached.
The :meth:`open` method will automatically set this property whilst
:meth:`dismiss` will set it back to None.
'''
container = ObjectProperty()
'''(internal) Property that will be set to the container of the dropdown
list. It is a :class:`~kivy.uix.gridlayout.GridLayout` by default.
'''
__events__ = ('on_select', 'on_dismiss')
def __init__(self, **kwargs):
self._win = None
if 'container' not in kwargs:
c = self.container = Builder.load_string(_grid_kv)
else:
c = None
kwargs.setdefault('do_scroll_x', False)
if 'size_hint' not in kwargs:
kwargs.setdefault('size_hint_x', None)
kwargs.setdefault('size_hint_y', None)
super(DropDown, self).__init__(**kwargs)
if c is not None:
super(DropDown, self).add_widget(c)
self.on_container(self, c)
Window.bind(
on_key_down=self.on_key_down,
size=self._reposition)
self.fbind('size', self._reposition)
def on_key_down(self, instance, key, scancode, codepoint, modifiers):
if key == 27 and self.get_parent_window():
self.dismiss()
return True
def on_container(self, instance, value):
if value is not None:
self.container.bind(minimum_size=self._container_minimum_size)
def open(self, widget):
'''Open the dropdown list and attach it to a specific widget.
Depending on the position of the widget within the window and
the height of the dropdown, the dropdown might be above or below
that widget.
'''
# ensure we are not already attached
if self.attach_to is not None:
self.dismiss()
# we will attach ourself to the main window, so ensure the
# widget we are looking for have a window
self._win = widget.get_parent_window()
if self._win is None:
raise DropDownException(
'Cannot open a dropdown list on a hidden widget')
self.attach_to = widget
widget.bind(pos=self._reposition, size=self._reposition)
self._reposition()
# attach ourself to the main window
self._win.add_widget(self)
def dismiss(self, *largs):
'''Remove the dropdown widget from the window and detach it from
the attached widget.
'''
if self.parent:
self.parent.remove_widget(self)
if self.attach_to:
self.attach_to.unbind(pos=self._reposition, size=self._reposition)
self.attach_to = None
self.dispatch('on_dismiss')
def on_dismiss(self):
pass
def select(self, data):
'''Call this method to trigger the `on_select` event with the `data`
selection. The `data` can be anything you want.
'''
self.dispatch('on_select', data)
if self.dismiss_on_select:
self.dismiss()
def on_select(self, data):
pass
def _container_minimum_size(self, instance, size):
if self.max_height:
self.height = min(size[1], self.max_height)
self.do_scroll_y = size[1] > self.max_height
else:
self.height = size[1]
self.do_scroll_y = True
def add_widget(self, *largs):
if self.container:
return self.container.add_widget(*largs)
return super(DropDown, self).add_widget(*largs)
def remove_widget(self, *largs):
if self.container:
return self.container.remove_widget(*largs)
return super(DropDown, self).remove_widget(*largs)
def clear_widgets(self):
if self.container:
return self.container.clear_widgets()
return super(DropDown, self).clear_widgets()
def on_touch_down(self, touch):
if super(DropDown, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos):
return True
if self.attach_to and self.attach_to.collide_point(*touch.pos):
return True
if self.auto_dismiss:
self.dismiss()
def on_touch_up(self, touch):
if super(DropDown, self).on_touch_up(touch):
return True
if 'button' in touch.profile and touch.button.startswith('scroll'):
return
if self.auto_dismiss:
self.dismiss()
def _reposition(self, *largs):
# calculate the coordinate of the attached widget in the window
# coordinate system
win = self._win
widget = self.attach_to
if not widget or not win:
return
wx, wy = widget.to_window(*widget.pos)
wright, wtop = widget.to_window(widget.right, widget.top)
# set width and x
if self.auto_width:
self.width = wright - wx
# ensure the dropdown list doesn't get out on the X axis, with a
# preference to 0 in case the list is too wide.
x = wx
if x + self.width > win.width:
x = win.width - self.width
if x < 0:
x = 0
self.x = x
# determine if we display the dropdown upper or lower to the widget
h_bottom = wy - self.height
h_top = win.height - (wtop + self.height)
if h_bottom > 0:
self.top = wy
self.height = self.container.minimum_height
elif h_top > 0:
self.y = wtop
self.height = self.container.minimum_height
else:
# none of both top/bottom have enough place to display the
# widget at the current size. Take the best side, and fit to
# it.
height = max(h_bottom, h_top)
if height == h_bottom:
self.top = wy
self.height = wy
else:
self.y = wtop
self.height = win.height - wtop
if __name__ == '__main__':
from kivy.uix.button import Button
from kivy.base import runTouchApp
def show_dropdown(button, *largs):
dp = DropDown()
dp.bind(on_select=lambda instance, x: setattr(button, 'text', x))
for i in range(10):
item = Button(text='hello %d' % i, size_hint_y=None, height=44)
item.bind(on_release=lambda btn: dp.select(btn.text))
dp.add_widget(item)
dp.open(button)
def touch_move(instance, touch):
instance.center = touch.pos
btn = Button(text='SHOW', size_hint=(None, None), pos=(300, 200))
btn.bind(on_release=show_dropdown, on_touch_move=touch_move)
runTouchApp(btn)
| mit |
wikier/apache-marmotta-tutorial-iswc2014 | media/media-tutorial-webapp/src/main/webapp/tutorial/bower_components/bootstrap/test-infra/s3_cache.py | 1700 | 3523 | #!/usr/bin/env python2.7
from __future__ import absolute_import, unicode_literals, print_function, division
from sys import argv
from os import environ, stat, remove as _delete_file
from os.path import isfile, dirname, basename, abspath
from hashlib import sha256
from subprocess import check_call as run
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.exception import S3ResponseError
NEED_TO_UPLOAD_MARKER = '.need-to-upload'
BYTES_PER_MB = 1024 * 1024
try:
BUCKET_NAME = environ['TWBS_S3_BUCKET']
except KeyError:
raise SystemExit("TWBS_S3_BUCKET environment variable not set!")
def _sha256_of_file(filename):
hasher = sha256()
with open(filename, 'rb') as input_file:
hasher.update(input_file.read())
file_hash = hasher.hexdigest()
print('sha256({}) = {}'.format(filename, file_hash))
return file_hash
def _delete_file_quietly(filename):
try:
_delete_file(filename)
except (OSError, IOError):
pass
def _tarball_size(directory):
kib = stat(_tarball_filename_for(directory)).st_size // BYTES_PER_MB
return "{} MiB".format(kib)
def _tarball_filename_for(directory):
return abspath('./{}.tar.gz'.format(basename(directory)))
def _create_tarball(directory):
print("Creating tarball of {}...".format(directory))
run(['tar', '-czf', _tarball_filename_for(directory), '-C', dirname(directory), basename(directory)])
def _extract_tarball(directory):
print("Extracting tarball of {}...".format(directory))
run(['tar', '-xzf', _tarball_filename_for(directory), '-C', dirname(directory)])
def download(directory):
_delete_file_quietly(NEED_TO_UPLOAD_MARKER)
try:
print("Downloading {} tarball from S3...".format(friendly_name))
key.get_contents_to_filename(_tarball_filename_for(directory))
except S3ResponseError as err:
open(NEED_TO_UPLOAD_MARKER, 'a').close()
print(err)
raise SystemExit("Cached {} download failed!".format(friendly_name))
print("Downloaded {}.".format(_tarball_size(directory)))
_extract_tarball(directory)
print("{} successfully installed from cache.".format(friendly_name))
def upload(directory):
_create_tarball(directory)
print("Uploading {} tarball to S3... ({})".format(friendly_name, _tarball_size(directory)))
key.set_contents_from_filename(_tarball_filename_for(directory))
print("{} cache successfully updated.".format(friendly_name))
_delete_file_quietly(NEED_TO_UPLOAD_MARKER)
if __name__ == '__main__':
# Uses environment variables:
# AWS_ACCESS_KEY_ID -- AWS Access Key ID
# AWS_SECRET_ACCESS_KEY -- AWS Secret Access Key
argv.pop(0)
if len(argv) != 4:
raise SystemExit("USAGE: s3_cache.py <download | upload> <friendly name> <dependencies file> <directory>")
mode, friendly_name, dependencies_file, directory = argv
conn = S3Connection()
bucket = conn.lookup(BUCKET_NAME, validate=False)
if bucket is None:
raise SystemExit("Could not access bucket!")
dependencies_file_hash = _sha256_of_file(dependencies_file)
key = Key(bucket, dependencies_file_hash)
key.storage_class = 'REDUCED_REDUNDANCY'
if mode == 'download':
download(directory)
elif mode == 'upload':
if isfile(NEED_TO_UPLOAD_MARKER): # FIXME
upload(directory)
else:
print("No need to upload anything.")
else:
raise SystemExit("Unrecognized mode {!r}".format(mode))
| apache-2.0 |
muffl0n/ansible-modules-core | windows/win_msi.py | 114 | 1747 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>, and others
#
# 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/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_msi
version_added: "1.7"
short_description: Installs and uninstalls Windows MSI files
description:
- Installs or uninstalls a Windows MSI file that is already located on the
target server
options:
path:
description:
- File system path to the MSI file to install
required: true
state:
description:
- Whether the MSI file should be installed or uninstalled
choices:
- present
- absent
default: present
creates:
description:
- Path to a file created by installing the MSI to prevent from
attempting to reinstall the package on every run
author: "Matt Martz (@sivel)"
'''
EXAMPLES = '''
# Install an MSI file
- win_msi: path=C:\\\\7z920-x64.msi
# Uninstall an MSI file
- win_msi: path=C:\\\\7z920-x64.msi state=absent
'''
| gpl-3.0 |
tmpgit/intellij-community | python/lib/Lib/site-packages/django/contrib/gis/maps/google/__init__.py | 603 | 2648 | """
This module houses the GoogleMap object, used for generating
the needed javascript to embed Google Maps in a Web page.
Google(R) is a registered trademark of Google, Inc. of Mountain View, California.
Example:
* In the view:
return render_to_response('template.html', {'google' : GoogleMap(key="abcdefg")})
* In the template:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
{{ google.xhtml }}
<head>
<title>Google Maps via GeoDjango</title>
{{ google.style }}
{{ google.scripts }}
</head>
{{ google.body }}
<div id="{{ google.dom_id }}" style="width:600px;height:400px;"></div>
</body>
</html>
Note: If you want to be more explicit in your templates, the following are
equivalent:
{{ google.body }} => "<body {{ google.onload }} {{ google.onunload }}>"
{{ google.xhtml }} => "<html xmlns="http://www.w3.org/1999/xhtml" {{ google.xmlns }}>"
{{ google.style }} => "<style>{{ google.vml_css }}</style>"
Explanation:
- The `xhtml` property provides the correct XML namespace needed for
Google Maps to operate in IE using XHTML. Google Maps on IE uses
VML to draw polylines. Returns, by default:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
- The `style` property provides the correct style tag for the CSS
properties required by Google Maps on IE:
<style type="text/css">v\:* {behavior:url(#default#VML);}</style>
- The `scripts` property provides the necessary <script> tags for
including the Google Maps javascript, as well as including the
generated javascript.
- The `body` property provides the correct attributes for the
body tag to load the generated javascript. By default, returns:
<body onload="gmap_load()" onunload="GUnload()">
- The `dom_id` property returns the DOM id for the map. Defaults to "map".
The following attributes may be set or customized in your local settings:
* GOOGLE_MAPS_API_KEY: String of your Google Maps API key. These are tied to
to a domain. May be obtained from http://www.google.com/apis/maps/
* GOOGLE_MAPS_API_VERSION (optional): Defaults to using "2.x"
* GOOGLE_MAPS_URL (optional): Must have a substitution ('%s') for the API
version.
"""
from django.contrib.gis.maps.google.gmap import GoogleMap, GoogleMapSet
from django.contrib.gis.maps.google.overlays import GEvent, GIcon, GMarker, GPolygon, GPolyline
from django.contrib.gis.maps.google.zoom import GoogleZoom
| apache-2.0 |
ashutrix03/inteygrate_flaskapp-master | build/lib/yowsup/layers/protocol_groups/protocolentities/iq_groups_subject.py | 61 | 1076 | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class SubjectGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq type="set" id="{{id}}" xmlns="w:g2", to={{group_jid}}">
<subject>
{{NEW_VAL}}
</subject>
</iq>
'''
def __init__(self, jid, subject, _id = None):
super(SubjectGroupsIqProtocolEntity, self).__init__(to = jid, _id = _id, _type = "set")
self.setProps(subject)
def setProps(self, subject):
self.subject = subject
def toProtocolTreeNode(self):
node = super(SubjectGroupsIqProtocolEntity, self).toProtocolTreeNode()
node.addChild(ProtocolTreeNode("subject",{}, None, self.subject))
return node
@staticmethod
def fromProtocolTreeNode(node):
entity = super(SubjectGroupsIqProtocolEntity, SubjectGroupsIqProtocolEntity).fromProtocolTreeNode(node)
entity.__class__ = SubjectGroupsIqProtocolEntity
entity.setProps(node.getChild("subject").getData())
return entity
| gpl-3.0 |
ianctse/pvlib-python | pvlib/test/test_clearsky.py | 1 | 6604 | import logging
pvl_logger = logging.getLogger('pvlib')
import numpy as np
import pandas as pd
from nose.tools import raises
from numpy.testing import assert_almost_equal
from pandas.util.testing import assert_frame_equal, assert_series_equal
from pvlib.location import Location
from pvlib import clearsky
from pvlib import solarposition
from . import requires_scipy
# setup times and location to be tested.
tus = Location(32.2, -111, 'US/Arizona', 700)
times = pd.date_range(start='2014-06-24', end='2014-06-25', freq='3h')
times_localized = times.tz_localize(tus.tz)
ephem_data = solarposition.get_solarposition(times_localized, tus.latitude,
tus.longitude)
@requires_scipy
def test_ineichen_required():
# the clearsky function should call lookup_linke_turbidity by default
expected = pd.DataFrame(
np.array([[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 51.47811191, 265.33462162, 84.48262202],
[ 105.008507 , 832.29100407, 682.67761951],
[ 121.97988054, 901.31821834, 1008.02102657],
[ 112.57957512, 867.76297247, 824.61702926],
[ 76.69672675, 588.8462898 , 254.5808329 ],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ]]),
columns=['dhi', 'dni', 'ghi'],
index=times_localized)
out = clearsky.ineichen(times_localized, tus.latitude, tus.longitude)
assert_frame_equal(expected, out)
def test_ineichen_supply_linke():
expected = pd.DataFrame(np.array(
[[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 40.16490879, 321.71856556, 80.12815294],
[ 95.14336873, 876.49252839, 703.47605855],
[ 118.4587024 , 939.81646535, 1042.34480815],
[ 105.36645492, 909.11265773, 851.32459694],
[ 61.91187639, 647.35889938, 257.42691896],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ]]),
columns=['dhi', 'dni', 'ghi'],
index=times_localized)
out = clearsky.ineichen(times_localized, tus.latitude, tus.longitude,
altitude=tus.altitude,
linke_turbidity=3)
assert_frame_equal(expected, out)
def test_ineichen_solpos():
clearsky.ineichen(times_localized, tus.latitude, tus.longitude,
linke_turbidity=3,
solarposition_method='ephemeris')
def test_ineichen_airmass():
expected = pd.DataFrame(
np.array([[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 53.90422388, 257.01655613, 85.87406435],
[ 101.34055688, 842.92925705, 686.39337307],
[ 117.7573735 , 909.70367947, 1012.04184961],
[ 108.6233401 , 877.30589626, 828.49118038],
[ 75.23108133, 602.06895546, 257.10961202],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ]]),
columns=['dhi', 'dni', 'ghi'],
index=times_localized)
out = clearsky.ineichen(times_localized, tus.latitude, tus.longitude,
linke_turbidity=3,
airmass_model='simple')
assert_frame_equal(expected, out)
@requires_scipy
def test_lookup_linke_turbidity():
times = pd.date_range(start='2014-06-24', end='2014-06-25',
freq='12h', tz=tus.tz)
# expect same value on 2014-06-24 0000 and 1200, and
# diff value on 2014-06-25
expected = pd.Series(np.array([3.10126582, 3.10126582, 3.11443038]),
index=times)
out = clearsky.lookup_linke_turbidity(times, tus.latitude, tus.longitude)
assert_series_equal(expected, out)
@requires_scipy
def test_lookup_linke_turbidity_nointerp():
times = pd.date_range(start='2014-06-24', end='2014-06-25',
freq='12h', tz=tus.tz)
# expect same value for all days
expected = pd.Series(np.array([3., 3., 3.]), index=times)
out = clearsky.lookup_linke_turbidity(times, tus.latitude, tus.longitude,
interp_turbidity=False)
assert_series_equal(expected, out)
@requires_scipy
def test_lookup_linke_turbidity_months():
times = pd.date_range(start='2014-04-01', end='2014-07-01',
freq='1M', tz=tus.tz)
expected = pd.Series(np.array([2.8943038, 2.97316456, 3.18025316]),
index=times)
out = clearsky.lookup_linke_turbidity(times, tus.latitude,
tus.longitude)
assert_series_equal(expected, out)
@requires_scipy
def test_lookup_linke_turbidity_nointerp_months():
times = pd.date_range(start='2014-04-10', end='2014-07-10',
freq='1M', tz=tus.tz)
expected = pd.Series(np.array([2.85, 2.95, 3.]), index=times)
out = clearsky.lookup_linke_turbidity(times, tus.latitude, tus.longitude,
interp_turbidity=False)
assert_series_equal(expected, out)
# changing the dates shouldn't matter if interp=False
times = pd.date_range(start='2014-04-05', end='2014-07-05',
freq='1M', tz=tus.tz)
out = clearsky.lookup_linke_turbidity(times, tus.latitude, tus.longitude,
interp_turbidity=False)
assert_series_equal(expected, out)
def test_haurwitz():
expected = pd.DataFrame(np.array([[0.],
[0.],
[82.85934048],
[699.74514735],
[1016.50198354],
[838.32103769],
[271.90853863],
[0.],
[0.]]),
columns=['ghi'], index=times_localized)
out = clearsky.haurwitz(ephem_data['zenith'])
assert_frame_equal(expected, out)
| bsd-3-clause |
jetskijoe/SickGear | lib/sqlalchemy/dialects/postgresql/pypostgresql.py | 79 | 2169 | # postgresql/pypostgresql.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: postgresql+pypostgresql
:name: py-postgresql
:dbapi: pypostgresql
:connectstring: postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...]
:url: http://python.projects.pgfoundry.org/
"""
from ... import util
from ... import types as sqltypes
from .base import PGDialect, PGExecutionContext
from ... import processors
class PGNumeric(sqltypes.Numeric):
def bind_processor(self, dialect):
return processors.to_str
def result_processor(self, dialect, coltype):
if self.asdecimal:
return None
else:
return processors.to_float
class PGExecutionContext_pypostgresql(PGExecutionContext):
pass
class PGDialect_pypostgresql(PGDialect):
driver = 'pypostgresql'
supports_unicode_statements = True
supports_unicode_binds = True
description_encoding = None
default_paramstyle = 'pyformat'
# requires trunk version to support sane rowcounts
# TODO: use dbapi version information to set this flag appropriately
supports_sane_rowcount = True
supports_sane_multi_rowcount = False
execution_ctx_cls = PGExecutionContext_pypostgresql
colspecs = util.update_copy(
PGDialect.colspecs,
{
sqltypes.Numeric: PGNumeric,
# prevents PGNumeric from being used
sqltypes.Float: sqltypes.Float,
}
)
@classmethod
def dbapi(cls):
from postgresql.driver import dbapi20
return dbapi20
def create_connect_args(self, url):
opts = url.translate_connect_args(username='user')
if 'port' in opts:
opts['port'] = int(opts['port'])
else:
opts['port'] = 5432
opts.update(url.query)
return ([], opts)
def is_disconnect(self, e, connection, cursor):
return "connection is closed" in str(e)
dialect = PGDialect_pypostgresql
| gpl-3.0 |
jalavik/invenio | invenio/legacy/websession/scripts/inveniogc.py | 13 | 1080 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2007, 2008, 2010, 2011, 2013 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Guest user sessions garbage collector. To be run via cron once per day. (say)
"""
__revision__ = "$Id$"
from invenio.base.factory import with_app_context
@with_app_context()
def main():
from invenio.legacy.websession.inveniogc import main as gc_main
return gc_main()
| gpl-2.0 |
omry/omegaconf | setup.py | 1 | 2119 | # type: ignore
"""
OmegaConf setup
Instructions:
# Build:
rm -rf dist/ omegaconf.egg-info/
python setup.py sdist bdist_wheel
# Upload:
twine upload dist/*
"""
import pathlib
import pkg_resources
import setuptools
from build_helpers.build_helpers import (
ANTLRCommand,
BuildPyCommand,
CleanCommand,
DevelopCommand,
SDistCommand,
find_version,
)
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
install_requires = [
str(requirement)
for requirement in pkg_resources.parse_requirements(requirements_txt)
]
with open("README.md", "r") as fh:
LONG_DESC = fh.read()
setuptools.setup(
cmdclass={
"antlr": ANTLRCommand,
"clean": CleanCommand,
"sdist": SDistCommand,
"build_py": BuildPyCommand,
"develop": DevelopCommand,
},
name="omegaconf",
version=find_version("omegaconf", "version.py"),
author="Omry Yadan",
author_email="omry@yadan.net",
description="A flexible configuration library",
long_description=LONG_DESC,
long_description_content_type="text/markdown",
setup_requires=["pytest-runner"],
tests_require=["pytest"],
url="https://github.com/omry/omegaconf",
keywords="yaml configuration config",
packages=[
"omegaconf",
"omegaconf.grammar",
"omegaconf.grammar.gen",
"omegaconf.resolvers",
"omegaconf.resolvers.oc",
"pydevd_plugins",
"pydevd_plugins.extensions",
],
python_requires=">=3.6",
classifiers=[
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
],
install_requires=install_requires,
package_data={"omegaconf": ["py.typed"]},
)
| bsd-3-clause |
iain-buclaw-sociomantic/carbon | lib/carbon/carbon_pb2.py | 2 | 4757 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: carbon.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='carbon.proto',
package='carbon',
syntax='proto3',
serialized_pb=_b('\n\x0c\x63\x61rbon.proto\x12\x06\x63\x61rbon\")\n\x05Point\x12\x11\n\ttimestamp\x18\x01 \x01(\r\x12\r\n\x05value\x18\x02 \x01(\x01\"7\n\x06Metric\x12\x0e\n\x06metric\x18\x01 \x01(\t\x12\x1d\n\x06points\x18\x02 \x03(\x0b\x32\r.carbon.Point\"*\n\x07Payload\x12\x1f\n\x07metrics\x18\x01 \x03(\x0b\x32\x0e.carbon.Metricb\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_POINT = _descriptor.Descriptor(
name='Point',
full_name='carbon.Point',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='timestamp', full_name='carbon.Point.timestamp', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='carbon.Point.value', index=1,
number=2, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=24,
serialized_end=65,
)
_METRIC = _descriptor.Descriptor(
name='Metric',
full_name='carbon.Metric',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='metric', full_name='carbon.Metric.metric', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='points', full_name='carbon.Metric.points', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=67,
serialized_end=122,
)
_PAYLOAD = _descriptor.Descriptor(
name='Payload',
full_name='carbon.Payload',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='metrics', full_name='carbon.Payload.metrics', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=124,
serialized_end=166,
)
_METRIC.fields_by_name['points'].message_type = _POINT
_PAYLOAD.fields_by_name['metrics'].message_type = _METRIC
DESCRIPTOR.message_types_by_name['Point'] = _POINT
DESCRIPTOR.message_types_by_name['Metric'] = _METRIC
DESCRIPTOR.message_types_by_name['Payload'] = _PAYLOAD
Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict(
DESCRIPTOR = _POINT,
__module__ = 'carbon_pb2'
# @@protoc_insertion_point(class_scope:carbon.Point)
))
_sym_db.RegisterMessage(Point)
Metric = _reflection.GeneratedProtocolMessageType('Metric', (_message.Message,), dict(
DESCRIPTOR = _METRIC,
__module__ = 'carbon_pb2'
# @@protoc_insertion_point(class_scope:carbon.Metric)
))
_sym_db.RegisterMessage(Metric)
Payload = _reflection.GeneratedProtocolMessageType('Payload', (_message.Message,), dict(
DESCRIPTOR = _PAYLOAD,
__module__ = 'carbon_pb2'
# @@protoc_insertion_point(class_scope:carbon.Payload)
))
_sym_db.RegisterMessage(Payload)
# @@protoc_insertion_point(module_scope)
| apache-2.0 |
joequery/django | tests/lookup/models.py | 235 | 2178 | """
The lookup API
This demonstrates features of the database API.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class Alarm(models.Model):
desc = models.CharField(max_length=100)
time = models.TimeField()
def __str__(self):
return '%s (%s)' % (self.time, self.desc)
class Author(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name', )
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True)
class Meta:
ordering = ('-pub_date', 'headline')
def __str__(self):
return self.headline
class Tag(models.Model):
articles = models.ManyToManyField(Article)
name = models.CharField(max_length=100)
class Meta:
ordering = ('name', )
@python_2_unicode_compatible
class Season(models.Model):
year = models.PositiveSmallIntegerField()
gt = models.IntegerField(null=True, blank=True)
def __str__(self):
return six.text_type(self.year)
@python_2_unicode_compatible
class Game(models.Model):
season = models.ForeignKey(Season, models.CASCADE, related_name='games')
home = models.CharField(max_length=100)
away = models.CharField(max_length=100)
def __str__(self):
return "%s at %s" % (self.away, self.home)
@python_2_unicode_compatible
class Player(models.Model):
name = models.CharField(max_length=100)
games = models.ManyToManyField(Game, related_name='players')
def __str__(self):
return self.name
# To test __search lookup a fulltext index is needed. This
# is only available when using MySQL 5.6, or when using MyISAM
# tables. As 5.6 isn't common yet, lets use MyISAM table for
# testing. The table is manually created by the test method.
class MyISAMArticle(models.Model):
headline = models.CharField(max_length=100)
class Meta:
db_table = 'myisam_article'
managed = False
| bsd-3-clause |
akloster/bokeh | bokeh/charts/_data_adapter.py | 43 | 8802 | """This is the Bokeh charts interface. It gives you a high level API to build
complex plot is a simple way.
This is the ChartObject class, a minimal prototype class to build more chart
types on top of it. It provides the mechanisms to support the shared chained
methods.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import absolute_import
from six import string_types
from collections import OrderedDict
from ..properties import bokeh_integer_types, Datetime
try:
import numpy as np
except ImportError:
np = None
try:
import pandas as pd
except ImportError:
pd = None
try:
import blaze
except ImportError:
blaze=None
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
DEFAULT_INDEX_ALIASES = list('abcdefghijklmnopqrstuvz1234567890')
DEFAULT_INDEX_ALIASES += list(zip(DEFAULT_INDEX_ALIASES, DEFAULT_INDEX_ALIASES))
class DataAdapter(object):
"""
Adapter object used to normalize Charts inputs to a common interface.
Supported inputs are dict, list, tuple, np.ndarray and pd.DataFrame.
"""
def __init__(self, data, index=None, columns=None, force_alias=True):
self.__values = data
self._values = self.validate_values(data)
self.convert_index_to_int = False
self._columns_map = {}
self.convert_items_to_dict = False
if columns is None and force_alias:
# no column 'labels' defined for data... in this case we use
# default names
keys = getattr(self._values, 'keys', None)
if callable(keys):
columns = list(keys())
elif keys is None:
columns = list(map(str, range(len(data))))
else:
columns = list(keys)
if columns:
self._columns = columns
# define a mapping between the real keys to access data and the aliases
# we have defined using 'columns'
self._columns_map = dict(zip(columns, self.keys()))
if index is not None:
self._index = index
self.convert_items_to_dict = True
elif force_alias:
_index = getattr(self._values, 'index', None)
# check because if it is a callable self._values is not a
# dataframe (probably a list)
if _index is None:
indexes = self.index
if isinstance(indexes[0], int):
self._index = DEFAULT_INDEX_ALIASES[:][:len(self.values()[0])]
self.convert_items_to_dict = True
elif not callable(_index):
self._index = list(_index)
self.convert_items_to_dict = True
else:
self._index = DEFAULT_INDEX_ALIASES[:][:len(self.values()[0])]
self.convert_items_to_dict = True
@staticmethod
def is_number(value):
numbers = (float, ) + bokeh_integer_types
return isinstance(value, numbers)
@staticmethod
def is_datetime(value):
try:
dt = Datetime(value)
dt # shut up pyflakes
return True
except ValueError:
return False
@staticmethod
def validate_values(values):
if np and isinstance(values, np.ndarray):
if len(values.shape) == 1:
return np.array([values])
else:
return values
elif pd and isinstance(values, pd.DataFrame):
return values
elif isinstance(values, (dict, OrderedDict)):
if all(DataAdapter.is_number(x) for x in values.values()):
return values
return values
elif isinstance(values, (list, tuple)):
if all(DataAdapter.is_number(x) for x in values):
return [values]
return values
elif hasattr(values, '__array__'):
values = pd.DataFrame(np.asarray(values))
return values
# TODO: Improve this error message..
raise TypeError("Input type not supported! %s" % values)
def index_converter(self, x):
key = self._columns_map.get(x, x)
if self.convert_index_to_int:
key = int(key)
return key
def keys(self):
# assuming it's a dict or dataframe
keys = getattr(self._values, "keys", None)
if callable(keys):
return list(keys())
elif keys is None:
self.convert_index_to_int = True
indexes = range(len(self._values))
return list(map(str, indexes))
else:
return list(keys)
def __len__(self):
return len(self.values())
def __iter__(self):
for k in self.keys():
yield k
def __getitem__(self, key):
val = self._values[self.index_converter(key)]
# if we have "index aliases" we need to remap the values...
if self.convert_items_to_dict:
val = dict(zip(self._index, val))
return val
def values(self):
return self.normalize_values(self._values)
@staticmethod
def normalize_values(values):
_values = getattr(values, "values", None)
if callable(_values):
return list(_values())
elif _values is None:
return values
else:
# assuming it's a dataframe, in that case it returns transposed
# values compared to it's dict equivalent..
return list(_values.T)
def items(self):
return [(key, self[key]) for key in self]
def iterkeys(self):
return iter(self)
def itervalues(self):
for k in self:
yield self[k]
def iteritems(self):
for k in self:
yield (k, self[k])
@property
def columns(self):
try:
return self._columns
except AttributeError:
return list(self.keys())
@property
def index(self):
try:
return self._index
except AttributeError:
index = getattr(self._values, "index", None)
if not callable(index) and index is not None:
# guess it's a pandas dataframe..
return index
# no, it's not. So it's probably a list so let's get the
# values and check
values = self.values()
if isinstance(values, dict):
return list(values.keys())
else:
first_el = self.values()[0]
if isinstance(first_el, dict):
indexes = list(first_el.keys())
else:
indexes = range(0, len(self.values()[0]))
self._index = indexes
return indexes
#-----------------------------------------------------------------------------
# Convenience methods
#-----------------------------------------------------------------------------
@staticmethod
def get_index_and_data(values, index=None):
"""Parse values (that must be one of the DataAdapter supported
input types) and create an separate/create index and data
depending on values type and index.
Args:
values (iterable): container that holds data to be plotted using
on the Chart classes
Returns:
A tuple of (index, values), where: ``index`` is an iterable that
represents the data index and ``values`` is an iterable containing
the values to be plotted.
"""
_values = DataAdapter(values, force_alias=False)
if hasattr(values, 'keys'):
if index is not None:
if isinstance(index, string_types):
xs = _values[index]
else:
xs = index
else:
try:
xs = _values.index
except AttributeError:
xs = values.index
else:
if index is None:
xs = _values.index
elif isinstance(index, string_types):
xs = _values[index]
else:
xs = index
return xs, _values
| bsd-3-clause |
maheshp/novatest | tools/install_venv_common.py | 18 | 7806 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
"""Provides methods needed by installation script for OpenStack development
virtual environments.
Synced in from openstack-common
"""
import argparse
import os
import subprocess
import sys
class InstallVenv(object):
def __init__(self, root, venv, pip_requires, test_requires, py_version,
project):
self.root = root
self.venv = venv
self.pip_requires = pip_requires
self.test_requires = test_requires
self.py_version = py_version
self.project = project
def die(self, message, *args):
print >> sys.stderr, message % args
sys.exit(1)
def check_python_version(self):
if sys.version_info < (2, 6):
self.die("Need Python Version >= 2.6")
def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
"""Runs a command in an out-of-process shell.
Returns the output of that command. Working directory is self.root.
"""
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
return (output, proc.returncode)
def run_command(self, cmd, redirect_output=True, check_exit_code=True):
return self.run_command_with_code(cmd, redirect_output,
check_exit_code)[0]
def get_distro(self):
if (os.path.exists('/etc/fedora-release') or
os.path.exists('/etc/redhat-release')):
return Fedora(self.root, self.venv, self.pip_requires,
self.test_requires, self.py_version, self.project)
else:
return Distro(self.root, self.venv, self.pip_requires,
self.test_requires, self.py_version, self.project)
def check_dependencies(self):
self.get_distro().install_virtualenv()
def create_virtualenv(self, no_site_packages=True):
"""Creates the virtual environment and installs PIP.
Creates the virtual environment and installs PIP only into the
virtual environment.
"""
if not os.path.isdir(self.venv):
print 'Creating venv...',
if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages',
self.venv])
else:
self.run_command(['virtualenv', '-q', self.venv])
print 'done.'
print 'Installing pip in venv...',
if not self.run_command(['tools/with_venv.sh', 'easy_install',
'pip>1.0']).strip():
self.die("Failed to install pip.")
print 'done.'
else:
print "venv already exists..."
pass
def pip_install(self, *args):
self.run_command(['tools/with_venv.sh',
'pip', 'install', '--upgrade'] + list(args),
redirect_output=False)
def install_dependencies(self):
print 'Installing dependencies with pip (this can take a while)...'
# First things first, make sure our venv has the latest pip and
# distribute.
# NOTE: we keep pip at version 1.1 since the most recent version causes
# the .venv creation to fail. See:
# https://bugs.launchpad.net/nova/+bug/1047120
self.pip_install('pip==1.1')
self.pip_install('distribute')
# Install greenlet by hand - just listing it in the requires file does
# not
# get it installed in the right order
self.pip_install('greenlet')
self.pip_install('-r', self.pip_requires)
self.pip_install('-r', self.test_requires)
def post_process(self):
self.get_distro().post_process()
def parse_args(self, argv):
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--no-site-packages',
action='store_true',
help="Do not inherit packages from global Python "
"install")
return parser.parse_args(argv[1:])
class Distro(InstallVenv):
def check_cmd(self, cmd):
return bool(self.run_command(['which', cmd],
check_exit_code=False).strip())
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if self.check_cmd('easy_install'):
print 'Installing virtualenv via easy_install...',
if self.run_command(['easy_install', 'virtualenv']):
print 'Succeeded'
return
else:
print 'Failed'
self.die('ERROR: virtualenv not found.\n\n%s development'
' requires virtualenv, please install it using your'
' favorite package management tool' % self.project)
def post_process(self):
"""Any distribution-specific post-processing gets done here.
In particular, this is useful for applying patches to code inside
the venv.
"""
pass
class Fedora(Distro):
"""This covers all Fedora-based distributions.
Includes: Fedora, RHEL, CentOS, Scientific Linux
"""
def check_pkg(self, pkg):
return self.run_command_with_code(['rpm', '-q', pkg],
check_exit_code=False)[1] == 0
def yum_install(self, pkg, **kwargs):
print "Attempting to install '%s' via yum" % pkg
self.run_command(['sudo', 'yum', 'install', '-y', pkg], **kwargs)
def apply_patch(self, originalfile, patchfile):
self.run_command(['patch', '-N', originalfile, patchfile],
check_exit_code=False)
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if not self.check_pkg('python-virtualenv'):
self.yum_install('python-virtualenv', check_exit_code=False)
super(Fedora, self).install_virtualenv()
def post_process(self):
"""Workaround for a bug in eventlet.
This currently affects RHEL6.1, but the fix can safely be
applied to all RHEL and Fedora distributions.
This can be removed when the fix is applied upstream.
Nova: https://bugs.launchpad.net/nova/+bug/884915
Upstream: https://bitbucket.org/which_linden/eventlet/issue/89
"""
# Install "patch" program if it's not there
if not self.check_pkg('patch'):
self.yum_install('patch')
# Apply the eventlet patch
self.apply_patch(os.path.join(self.venv, 'lib', self.py_version,
'site-packages',
'eventlet/green/subprocess.py'),
'contrib/redhat-eventlet.patch')
| apache-2.0 |
openvapour/ryu | ryu/services/protocols/bgp/api/jsonrpc.py | 24 | 3129 | # Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
#
# 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 json
from ryu.base import app_manager
from ryu.lib import hub
from ryu.app.wsgi import route, websocket, ControllerBase, WSGIApplication
from ryu.app.wsgi import rpc_public, WebSocketRPCServer
from ryu.services.protocols.bgp.api.base import call
from ryu.services.protocols.bgp.api.base import PREFIX
from ryu.services.protocols.bgp.rtconf.common import LOCAL_AS
from ryu.services.protocols.bgp.rtconf.common import ROUTER_ID
from ryu.services.protocols.bgp.rtconf import neighbors
bgp_instance_name = 'bgp_api_app'
url = '/bgp/ws'
class BgpWSJsonRpc(app_manager.RyuApp):
_CONTEXTS = {
'wsgi': WSGIApplication,
}
def __init__(self, *args, **kwargs):
super(BgpWSJsonRpc, self).__init__(*args, **kwargs)
wsgi = kwargs['wsgi']
wsgi.register(
BgpWSJsonRpcController,
data={bgp_instance_name: self},
)
self._ws_manager = wsgi.websocketmanager
@rpc_public('core.start')
def _core_start(self, as_number=64512, router_id='10.0.0.1'):
common_settings = {}
common_settings[LOCAL_AS] = as_number
common_settings[ROUTER_ID] = str(router_id)
waiter = hub.Event()
call('core.start', waiter=waiter, **common_settings)
waiter.wait()
return {}
@rpc_public('neighbor.create')
def _neighbor_create(self, ip_address='192.168.177.32',
remote_as=64513):
bgp_neighbor = {}
bgp_neighbor[neighbors.IP_ADDRESS] = str(ip_address)
bgp_neighbor[neighbors.REMOTE_AS] = remote_as
call('neighbor.create', **bgp_neighbor)
return {}
@rpc_public('network.add')
def _prefix_add(self, prefix='10.20.0.0/24'):
networks = {}
networks[PREFIX] = str(prefix)
call('network.add', **networks)
return {}
@rpc_public('neighbors.get')
def _neighbors_get(self):
return call('neighbors.get')
@rpc_public('show.rib')
def _show_rib(self, family='ipv4'):
show = {}
show['params'] = ['rib', family]
return call('operator.show', **show)
class BgpWSJsonRpcController(ControllerBase):
def __init__(self, req, link, data, **config):
super(BgpWSJsonRpcController, self).__init__(
req, link, data, **config)
self.bgp_api_app = data[bgp_instance_name]
@websocket('bgp', url)
def _websocket_handler(self, ws):
rpc_server = WebSocketRPCServer(ws, self.bgp_api_app)
rpc_server.serve_forever()
| apache-2.0 |
Changaco/oh-mainline | vendor/packages/Django/tests/modeltests/invalid_models/invalid_models/models.py | 51 | 30225 | #encoding=utf-8
"""
26. Invalid models
This example exists purely to point out errors in models.
"""
from __future__ import unicode_literals
from django.db import connection, models
class FieldErrors(models.Model):
charfield = models.CharField()
charfield2 = models.CharField(max_length=-1)
charfield3 = models.CharField(max_length="bad")
decimalfield = models.DecimalField()
decimalfield2 = models.DecimalField(max_digits=-1, decimal_places=-1)
decimalfield3 = models.DecimalField(max_digits="bad", decimal_places="bad")
decimalfield4 = models.DecimalField(max_digits=9, decimal_places=10)
decimalfield5 = models.DecimalField(max_digits=10, decimal_places=10)
filefield = models.FileField()
choices = models.CharField(max_length=10, choices='bad')
choices2 = models.CharField(max_length=10, choices=[(1, 2, 3), (1, 2, 3)])
index = models.CharField(max_length=10, db_index='bad')
field_ = models.CharField(max_length=10)
nullbool = models.BooleanField(null=True)
class Target(models.Model):
tgt_safe = models.CharField(max_length=10)
clash1 = models.CharField(max_length=10)
clash2 = models.CharField(max_length=10)
clash1_set = models.CharField(max_length=10)
class Clash1(models.Model):
src_safe = models.CharField(max_length=10)
foreign = models.ForeignKey(Target)
m2m = models.ManyToManyField(Target)
class Clash2(models.Model):
src_safe = models.CharField(max_length=10)
foreign_1 = models.ForeignKey(Target, related_name='id')
foreign_2 = models.ForeignKey(Target, related_name='src_safe')
m2m_1 = models.ManyToManyField(Target, related_name='id')
m2m_2 = models.ManyToManyField(Target, related_name='src_safe')
class Target2(models.Model):
clash3 = models.CharField(max_length=10)
foreign_tgt = models.ForeignKey(Target)
clashforeign_set = models.ForeignKey(Target)
m2m_tgt = models.ManyToManyField(Target)
clashm2m_set = models.ManyToManyField(Target)
class Clash3(models.Model):
src_safe = models.CharField(max_length=10)
foreign_1 = models.ForeignKey(Target2, related_name='foreign_tgt')
foreign_2 = models.ForeignKey(Target2, related_name='m2m_tgt')
m2m_1 = models.ManyToManyField(Target2, related_name='foreign_tgt')
m2m_2 = models.ManyToManyField(Target2, related_name='m2m_tgt')
class ClashForeign(models.Model):
foreign = models.ForeignKey(Target2)
class ClashM2M(models.Model):
m2m = models.ManyToManyField(Target2)
class SelfClashForeign(models.Model):
src_safe = models.CharField(max_length=10)
selfclashforeign = models.CharField(max_length=10)
selfclashforeign_set = models.ForeignKey("SelfClashForeign")
foreign_1 = models.ForeignKey("SelfClashForeign", related_name='id')
foreign_2 = models.ForeignKey("SelfClashForeign", related_name='src_safe')
class ValidM2M(models.Model):
src_safe = models.CharField(max_length=10)
validm2m = models.CharField(max_length=10)
# M2M fields are symmetrical by default. Symmetrical M2M fields
# on self don't require a related accessor, so many potential
# clashes are avoided.
validm2m_set = models.ManyToManyField("self")
m2m_1 = models.ManyToManyField("self", related_name='id')
m2m_2 = models.ManyToManyField("self", related_name='src_safe')
m2m_3 = models.ManyToManyField('self')
m2m_4 = models.ManyToManyField('self')
class SelfClashM2M(models.Model):
src_safe = models.CharField(max_length=10)
selfclashm2m = models.CharField(max_length=10)
# Non-symmetrical M2M fields _do_ have related accessors, so
# there is potential for clashes.
selfclashm2m_set = models.ManyToManyField("self", symmetrical=False)
m2m_1 = models.ManyToManyField("self", related_name='id', symmetrical=False)
m2m_2 = models.ManyToManyField("self", related_name='src_safe', symmetrical=False)
m2m_3 = models.ManyToManyField('self', symmetrical=False)
m2m_4 = models.ManyToManyField('self', symmetrical=False)
class Model(models.Model):
"But it's valid to call a model Model."
year = models.PositiveIntegerField() # 1960
make = models.CharField(max_length=10) # Aston Martin
name = models.CharField(max_length=10) # DB 4 GT
class Car(models.Model):
colour = models.CharField(max_length=5)
model = models.ForeignKey(Model)
class MissingRelations(models.Model):
rel1 = models.ForeignKey("Rel1")
rel2 = models.ManyToManyField("Rel2")
class MissingManualM2MModel(models.Model):
name = models.CharField(max_length=5)
missing_m2m = models.ManyToManyField(Model, through="MissingM2MModel")
class Person(models.Model):
name = models.CharField(max_length=5)
class Group(models.Model):
name = models.CharField(max_length=5)
primary = models.ManyToManyField(Person, through="Membership", related_name="primary")
secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary")
tertiary = models.ManyToManyField(Person, through="RelationshipDoubleFK", related_name="tertiary")
class GroupTwo(models.Model):
name = models.CharField(max_length=5)
primary = models.ManyToManyField(Person, through="Membership")
secondary = models.ManyToManyField(Group, through="MembershipMissingFK")
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
not_default_or_null = models.CharField(max_length=5)
class MembershipMissingFK(models.Model):
person = models.ForeignKey(Person)
class PersonSelfRefM2M(models.Model):
name = models.CharField(max_length=5)
friends = models.ManyToManyField('self', through="Relationship")
too_many_friends = models.ManyToManyField('self', through="RelationshipTripleFK")
class PersonSelfRefM2MExplicit(models.Model):
name = models.CharField(max_length=5)
friends = models.ManyToManyField('self', through="ExplicitRelationship", symmetrical=True)
class Relationship(models.Model):
first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set")
second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set")
date_added = models.DateTimeField()
class ExplicitRelationship(models.Model):
first = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_from_set")
second = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_to_set")
date_added = models.DateTimeField()
class RelationshipTripleFK(models.Model):
first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set_2")
second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set_2")
third = models.ForeignKey(PersonSelfRefM2M, related_name="too_many_by_far")
date_added = models.DateTimeField()
class RelationshipDoubleFK(models.Model):
first = models.ForeignKey(Person, related_name="first_related_name")
second = models.ForeignKey(Person, related_name="second_related_name")
third = models.ForeignKey(Group, related_name="rel_to_set")
date_added = models.DateTimeField()
class AbstractModel(models.Model):
name = models.CharField(max_length=10)
class Meta:
abstract = True
class AbstractRelationModel(models.Model):
fk1 = models.ForeignKey('AbstractModel')
fk2 = models.ManyToManyField('AbstractModel')
class UniqueM2M(models.Model):
""" Model to test for unique ManyToManyFields, which are invalid. """
unique_people = models.ManyToManyField(Person, unique=True)
class NonUniqueFKTarget1(models.Model):
""" Model to test for non-unique FK target in yet-to-be-defined model: expect an error """
tgt = models.ForeignKey('FKTarget', to_field='bad')
class UniqueFKTarget1(models.Model):
""" Model to test for unique FK target in yet-to-be-defined model: expect no error """
tgt = models.ForeignKey('FKTarget', to_field='good')
class FKTarget(models.Model):
bad = models.IntegerField()
good = models.IntegerField(unique=True)
class NonUniqueFKTarget2(models.Model):
""" Model to test for non-unique FK target in previously seen model: expect an error """
tgt = models.ForeignKey(FKTarget, to_field='bad')
class UniqueFKTarget2(models.Model):
""" Model to test for unique FK target in previously seen model: expect no error """
tgt = models.ForeignKey(FKTarget, to_field='good')
class NonExistingOrderingWithSingleUnderscore(models.Model):
class Meta:
ordering = ("does_not_exist",)
class InvalidSetNull(models.Model):
fk = models.ForeignKey('self', on_delete=models.SET_NULL)
class InvalidSetDefault(models.Model):
fk = models.ForeignKey('self', on_delete=models.SET_DEFAULT)
class UnicodeForeignKeys(models.Model):
"""Foreign keys which can translate to ascii should be OK, but fail if
they're not."""
good = models.ForeignKey('FKTarget')
also_good = models.ManyToManyField('FKTarget', related_name='unicode2')
# In Python 3 this should become legal, but currently causes unicode errors
# when adding the errors in core/management/validation.py
#bad = models.ForeignKey('★')
class PrimaryKeyNull(models.Model):
my_pk_field = models.IntegerField(primary_key=True, null=True)
class OrderByPKModel(models.Model):
"""
Model to test that ordering by pk passes validation.
Refs #8291
"""
name = models.CharField(max_length=100, blank=True)
class Meta:
ordering = ('pk',)
class SwappableModel(models.Model):
"""A model that can be, but isn't swapped out.
References to this model *shoudln't* raise any validation error.
"""
name = models.CharField(max_length=100)
class Meta:
swappable = 'TEST_SWAPPABLE_MODEL'
class SwappedModel(models.Model):
"""A model that is swapped out.
References to this model *should* raise a validation error.
Requires TEST_SWAPPED_MODEL to be defined in the test environment;
this is guaranteed by the test runner using @override_settings.
The foreign keys and m2m relations on this model *shouldn't*
install related accessors, so there shouldn't be clashes with
the equivalent names on the replacement.
"""
name = models.CharField(max_length=100)
foreign = models.ForeignKey(Target, related_name='swappable_fk_set')
m2m = models.ManyToManyField(Target, related_name='swappable_m2m_set')
class Meta:
swappable = 'TEST_SWAPPED_MODEL'
class ReplacementModel(models.Model):
"""A replacement model for swapping purposes."""
name = models.CharField(max_length=100)
foreign = models.ForeignKey(Target, related_name='swappable_fk_set')
m2m = models.ManyToManyField(Target, related_name='swappable_m2m_set')
class BadSwappableValue(models.Model):
"""A model that can be swapped out; during testing, the swappable
value is not of the format app.model
"""
name = models.CharField(max_length=100)
class Meta:
swappable = 'TEST_SWAPPED_MODEL_BAD_VALUE'
class BadSwappableModel(models.Model):
"""A model that can be swapped out; during testing, the swappable
value references an unknown model.
"""
name = models.CharField(max_length=100)
class Meta:
swappable = 'TEST_SWAPPED_MODEL_BAD_MODEL'
class HardReferenceModel(models.Model):
fk_1 = models.ForeignKey(SwappableModel, related_name='fk_hardref1')
fk_2 = models.ForeignKey('invalid_models.SwappableModel', related_name='fk_hardref2')
fk_3 = models.ForeignKey(SwappedModel, related_name='fk_hardref3')
fk_4 = models.ForeignKey('invalid_models.SwappedModel', related_name='fk_hardref4')
m2m_1 = models.ManyToManyField(SwappableModel, related_name='m2m_hardref1')
m2m_2 = models.ManyToManyField('invalid_models.SwappableModel', related_name='m2m_hardref2')
m2m_3 = models.ManyToManyField(SwappedModel, related_name='m2m_hardref3')
m2m_4 = models.ManyToManyField('invalid_models.SwappedModel', related_name='m2m_hardref4')
class BadIndexTogether1(models.Model):
class Meta:
index_together = [
["field_that_does_not_exist"],
]
model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute that is a positive integer.
invalid_models.fielderrors: "charfield2": CharFields require a "max_length" attribute that is a positive integer.
invalid_models.fielderrors: "charfield3": CharFields require a "max_length" attribute that is a positive integer.
invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute that is a non-negative integer.
invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute that is a positive integer.
invalid_models.fielderrors: "decimalfield2": DecimalFields require a "decimal_places" attribute that is a non-negative integer.
invalid_models.fielderrors: "decimalfield2": DecimalFields require a "max_digits" attribute that is a positive integer.
invalid_models.fielderrors: "decimalfield3": DecimalFields require a "decimal_places" attribute that is a non-negative integer.
invalid_models.fielderrors: "decimalfield3": DecimalFields require a "max_digits" attribute that is a positive integer.
invalid_models.fielderrors: "decimalfield4": DecimalFields require a "max_digits" attribute value that is greater than or equal to the value of the "decimal_places" attribute.
invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute.
invalid_models.fielderrors: "choices": "choices" should be iterable (e.g., a tuple or list).
invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples.
invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples.
invalid_models.fielderrors: "index": "db_index" should be either None, True or False.
invalid_models.fielderrors: "field_": Field names cannot end with underscores, because this would lead to ambiguous queryset filters.
invalid_models.fielderrors: "nullbool": BooleanFields do not accept null values. Use a NullBooleanField instead.
invalid_models.clash1: Accessor for field 'foreign' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'.
invalid_models.clash1: Accessor for field 'foreign' clashes with related m2m field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'.
invalid_models.clash1: Reverse query name for field 'foreign' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'foreign'.
invalid_models.clash1: Accessor for m2m field 'm2m' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'.
invalid_models.clash1: Accessor for m2m field 'm2m' clashes with related field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'.
invalid_models.clash1: Reverse query name for m2m field 'm2m' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'm2m'.
invalid_models.clash2: Accessor for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash2: Accessor for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash2: Accessor for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash2: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash2: Accessor for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clash2: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clash3: Accessor for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash3: Accessor for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.clash3: Accessor for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash3: Accessor for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.clashforeign: Accessor for field 'foreign' clashes with field 'Target2.clashforeign_set'. Add a related_name argument to the definition for 'foreign'.
invalid_models.clashm2m: Accessor for m2m field 'm2m' clashes with m2m field 'Target2.clashm2m_set'. Add a related_name argument to the definition for 'm2m'.
invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
invalid_models.selfclashforeign: Accessor for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign_set'. Add a related_name argument to the definition for 'selfclashforeign_set'.
invalid_models.selfclashforeign: Reverse query name for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign'. Add a related_name argument to the definition for 'selfclashforeign_set'.
invalid_models.selfclashforeign: Accessor for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.selfclashforeign: Reverse query name for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'.
invalid_models.selfclashforeign: Accessor for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.selfclashforeign: Reverse query name for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'.
invalid_models.selfclashm2m: Reverse query name for m2m field 'selfclashm2m_set' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'selfclashm2m_set'.
invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'.
invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_3' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_3'.
invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_4' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_4'.
invalid_models.missingrelations: 'rel1' has a relation with model Rel1, which has either not been installed or is abstract.
invalid_models.missingrelations: 'rel2' has an m2m relation with model Rel2, which has either not been installed or is abstract.
invalid_models.grouptwo: 'primary' is a manually-defined m2m relation through model Membership, which does not have foreign keys to Person and GroupTwo
invalid_models.grouptwo: 'secondary' is a manually-defined m2m relation through model MembershipMissingFK, which does not have foreign keys to Group and GroupTwo
invalid_models.missingmanualm2mmodel: 'missing_m2m' specifies an m2m relation through model MissingM2MModel, which has not been installed
invalid_models.group: The model Group has two manually-defined m2m relations through the model Membership, which is not permitted. Please consider using an extra field on your intermediary model instead.
invalid_models.group: Intermediary model RelationshipDoubleFK has more than one foreign key to Person, which is ambiguous and is not permitted.
invalid_models.personselfrefm2m: Many-to-many fields with intermediate tables cannot be symmetrical.
invalid_models.personselfrefm2m: Intermediary model RelationshipTripleFK has more than two foreign keys to PersonSelfRefM2M, which is ambiguous and is not permitted.
invalid_models.personselfrefm2mexplicit: Many-to-many fields with intermediate tables cannot be symmetrical.
invalid_models.abstractrelationmodel: 'fk1' has a relation with model AbstractModel, which has either not been installed or is abstract.
invalid_models.abstractrelationmodel: 'fk2' has an m2m relation with model AbstractModel, which has either not been installed or is abstract.
invalid_models.uniquem2m: ManyToManyFields cannot be unique. Remove the unique argument on 'unique_people'.
invalid_models.nonuniquefktarget1: Field 'bad' under model 'FKTarget' must have a unique=True constraint.
invalid_models.nonuniquefktarget2: Field 'bad' under model 'FKTarget' must have a unique=True constraint.
invalid_models.nonexistingorderingwithsingleunderscore: "ordering" refers to "does_not_exist", a field that doesn't exist.
invalid_models.invalidsetnull: 'fk' specifies on_delete=SET_NULL, but cannot be null.
invalid_models.invalidsetdefault: 'fk' specifies on_delete=SET_DEFAULT, but has no default value.
invalid_models.hardreferencemodel: 'fk_3' defines a relation with the model 'invalid_models.SwappedModel', which has been swapped out. Update the relation to point at settings.TEST_SWAPPED_MODEL.
invalid_models.hardreferencemodel: 'fk_4' defines a relation with the model 'invalid_models.SwappedModel', which has been swapped out. Update the relation to point at settings.TEST_SWAPPED_MODEL.
invalid_models.hardreferencemodel: 'm2m_3' defines a relation with the model 'invalid_models.SwappedModel', which has been swapped out. Update the relation to point at settings.TEST_SWAPPED_MODEL.
invalid_models.hardreferencemodel: 'm2m_4' defines a relation with the model 'invalid_models.SwappedModel', which has been swapped out. Update the relation to point at settings.TEST_SWAPPED_MODEL.
invalid_models.badswappablevalue: TEST_SWAPPED_MODEL_BAD_VALUE is not of the form 'app_label.app_name'.
invalid_models.badswappablemodel: Model has been swapped out for 'not_an_app.Target' which has not been installed or is abstract.
invalid_models.badindextogether1: "index_together" refers to field_that_does_not_exist, a field that doesn't exist.
"""
if not connection.features.interprets_empty_strings_as_nulls:
model_errors += """invalid_models.primarykeynull: "my_pk_field": Primary key fields cannot have null=True.
"""
| agpl-3.0 |
CG-F16-16-Rutgers/steersuite-rutgers | steerstats/tools/deap/tools/selection.py | 19 | 7250 | from __future__ import division
import random
from functools import partial
from operator import attrgetter
######################################
# Selections #
######################################
def selRandom(individuals, k):
"""Select *k* individuals at random from the input *individuals* with
replacement. The list returned contains references to the input
*individuals*.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:returns: A list of selected individuals.
This function uses the :func:`~random.choice` function from the
python base :mod:`random` module.
"""
return [random.choice(individuals) for i in xrange(k)]
def selBest(individuals, k):
"""Select the *k* best individuals among the input *individuals*. The
list returned contains references to the input *individuals*.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:returns: A list containing the k best individuals.
"""
return sorted(individuals, key=attrgetter("fitness"), reverse=True)[:k]
def selWorst(individuals, k):
"""Select the *k* worst individuals among the input *individuals*. The
list returned contains references to the input *individuals*.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:returns: A list containing the k worst individuals.
"""
return sorted(individuals, key=attrgetter("fitness"))[:k]
def selTournament(individuals, k, tournsize):
"""Select *k* individuals from the input *individuals* using *k*
tournaments of *tournsize* individuals. The list returned contains
references to the input *individuals*.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:param tournsize: The number of individuals participating in each tournament.
:returns: A list of selected individuals.
This function uses the :func:`~random.choice` function from the python base
:mod:`random` module.
"""
chosen = []
for i in xrange(k):
aspirants = selRandom(individuals, tournsize)
chosen.append(max(aspirants, key=attrgetter("fitness")))
return chosen
def selRoulette(individuals, k):
"""Select *k* individuals from the input *individuals* using *k*
spins of a roulette. The selection is made by looking only at the first
objective of each individual. The list returned contains references to
the input *individuals*.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:returns: A list of selected individuals.
This function uses the :func:`~random.random` function from the python base
:mod:`random` module.
.. warning::
The roulette selection by definition cannot be used for minimization
or when the fitness can be smaller or equal to 0.
"""
s_inds = sorted(individuals, key=attrgetter("fitness"), reverse=True)
sum_fits = sum(ind.fitness.values[0] for ind in individuals)
chosen = []
for i in xrange(k):
u = random.random() * sum_fits
sum_ = 0
for ind in s_inds:
sum_ += ind.fitness.values[0]
if sum_ > u:
chosen.append(ind)
break
return chosen
def selDoubleTournament(individuals, k, fitness_size, parsimony_size, fitness_first):
"""Tournament selection which use the size of the individuals in order
to discriminate good solutions. This kind of tournament is obviously
useless with fixed-length representation, but has been shown to
significantly reduce excessive growth of individuals, especially in GP,
where it can be used as a bloat control technique (see
[Luke2002fighting]_). This selection operator implements the double
tournament technique presented in this paper.
The core principle is to use a normal tournament selection, but using a
special sample function to select aspirants, which is another tournament
based on the size of the individuals. To ensure that the selection
pressure is not too high, the size of the size tournament (the number
of candidates evaluated) can be a real number between 1 and 2. In this
case, the smaller individual among two will be selected with a probability
*size_tourn_size*/2. For instance, if *size_tourn_size* is set to 1.4,
then the smaller individual will have a 0.7 probability to be selected.
.. note::
In GP, it has been shown that this operator produces better results
when it is combined with some kind of a depth limit.
:param individuals: A list of individuals to select from.
:param k: The number of individuals to select.
:param fitness_size: The number of individuals participating in each \
fitness tournament
:param parsimony_size: The number of individuals participating in each \
size tournament. This value has to be a real number\
in the range [1,2], see above for details.
:param fitness_first: Set this to True if the first tournament done should \
be the fitness one (i.e. the fitness tournament producing aspirants for \
the size tournament). Setting it to False will behaves as the opposite \
(size tournament feeding fitness tournaments with candidates). It has been \
shown that this parameter does not have a significant effect in most cases\
(see [Luke2002fighting]_).
:returns: A list of selected individuals.
.. [Luke2002fighting] Luke and Panait, 2002, Fighting bloat with
nonparametric parsimony pressure
"""
assert (1 <= parsimony_size <= 2), "Parsimony tournament size has to be in the range [1, 2]."
def _sizeTournament(individuals, k, select):
chosen = []
for i in xrange(k):
# Select two individuals from the population
# The first individual has to be the shortest
prob = parsimony_size / 2.
ind1, ind2 = select(individuals, k=2)
if len(ind1) > len(ind2):
ind1, ind2 = ind2, ind1
elif len(ind1) == len(ind2):
# random selection in case of a tie
prob = 0.5
# Since size1 <= size2 then ind1 is selected
# with a probability prob
chosen.append(ind1 if random.random() < prob else ind2)
return chosen
def _fitTournament(individuals, k, select):
chosen = []
for i in xrange(k):
aspirants = select(individuals, k=fitness_size)
chosen.append(max(aspirants, key=attrgetter("fitness")))
return chosen
if fitness_first:
tfit = partial(_fitTournament, select=selRandom)
return _sizeTournament(individuals, k, tfit)
else:
tsize = partial(_sizeTournament, select=selRandom)
return _fitTournament(individuals, k, tsize)
__all__ = ['selRandom', 'selBest', 'selWorst', 'selRoulette',
'selTournament', 'selDoubleTournament'] | gpl-3.0 |
zverevalexei/trex-http-proxy | trex_client/external_libs/pyyaml-3.11/python2/yaml/emitter.py | 387 | 43298 |
# Emitter expects events obeying the following grammar:
# stream ::= STREAM-START document* STREAM-END
# document ::= DOCUMENT-START node DOCUMENT-END
# node ::= SCALAR | sequence | mapping
# sequence ::= SEQUENCE-START node* SEQUENCE-END
# mapping ::= MAPPING-START (node node)* MAPPING-END
__all__ = ['Emitter', 'EmitterError']
from error import YAMLError
from events import *
class EmitterError(YAMLError):
pass
class ScalarAnalysis(object):
def __init__(self, scalar, empty, multiline,
allow_flow_plain, allow_block_plain,
allow_single_quoted, allow_double_quoted,
allow_block):
self.scalar = scalar
self.empty = empty
self.multiline = multiline
self.allow_flow_plain = allow_flow_plain
self.allow_block_plain = allow_block_plain
self.allow_single_quoted = allow_single_quoted
self.allow_double_quoted = allow_double_quoted
self.allow_block = allow_block
class Emitter(object):
DEFAULT_TAG_PREFIXES = {
u'!' : u'!',
u'tag:yaml.org,2002:' : u'!!',
}
def __init__(self, stream, canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
# The stream should have the methods `write` and possibly `flush`.
self.stream = stream
# Encoding can be overriden by STREAM-START.
self.encoding = None
# Emitter is a state machine with a stack of states to handle nested
# structures.
self.states = []
self.state = self.expect_stream_start
# Current event and the event queue.
self.events = []
self.event = None
# The current indentation level and the stack of previous indents.
self.indents = []
self.indent = None
# Flow level.
self.flow_level = 0
# Contexts.
self.root_context = False
self.sequence_context = False
self.mapping_context = False
self.simple_key_context = False
# Characteristics of the last emitted character:
# - current position.
# - is it a whitespace?
# - is it an indention character
# (indentation space, '-', '?', or ':')?
self.line = 0
self.column = 0
self.whitespace = True
self.indention = True
# Whether the document requires an explicit document indicator
self.open_ended = False
# Formatting details.
self.canonical = canonical
self.allow_unicode = allow_unicode
self.best_indent = 2
if indent and 1 < indent < 10:
self.best_indent = indent
self.best_width = 80
if width and width > self.best_indent*2:
self.best_width = width
self.best_line_break = u'\n'
if line_break in [u'\r', u'\n', u'\r\n']:
self.best_line_break = line_break
# Tag prefixes.
self.tag_prefixes = None
# Prepared anchor and tag.
self.prepared_anchor = None
self.prepared_tag = None
# Scalar analysis and style.
self.analysis = None
self.style = None
def dispose(self):
# Reset the state attributes (to clear self-references)
self.states = []
self.state = None
def emit(self, event):
self.events.append(event)
while not self.need_more_events():
self.event = self.events.pop(0)
self.state()
self.event = None
# In some cases, we wait for a few next events before emitting.
def need_more_events(self):
if not self.events:
return True
event = self.events[0]
if isinstance(event, DocumentStartEvent):
return self.need_events(1)
elif isinstance(event, SequenceStartEvent):
return self.need_events(2)
elif isinstance(event, MappingStartEvent):
return self.need_events(3)
else:
return False
def need_events(self, count):
level = 0
for event in self.events[1:]:
if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
level += 1
elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
level -= 1
elif isinstance(event, StreamEndEvent):
level = -1
if level < 0:
return False
return (len(self.events) < count+1)
def increase_indent(self, flow=False, indentless=False):
self.indents.append(self.indent)
if self.indent is None:
if flow:
self.indent = self.best_indent
else:
self.indent = 0
elif not indentless:
self.indent += self.best_indent
# States.
# Stream handlers.
def expect_stream_start(self):
if isinstance(self.event, StreamStartEvent):
if self.event.encoding and not getattr(self.stream, 'encoding', None):
self.encoding = self.event.encoding
self.write_stream_start()
self.state = self.expect_first_document_start
else:
raise EmitterError("expected StreamStartEvent, but got %s"
% self.event)
def expect_nothing(self):
raise EmitterError("expected nothing, but got %s" % self.event)
# Document handlers.
def expect_first_document_start(self):
return self.expect_document_start(first=True)
def expect_document_start(self, first=False):
if isinstance(self.event, DocumentStartEvent):
if (self.event.version or self.event.tags) and self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
if self.event.version:
version_text = self.prepare_version(self.event.version)
self.write_version_directive(version_text)
self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
if self.event.tags:
handles = self.event.tags.keys()
handles.sort()
for handle in handles:
prefix = self.event.tags[handle]
self.tag_prefixes[prefix] = handle
handle_text = self.prepare_tag_handle(handle)
prefix_text = self.prepare_tag_prefix(prefix)
self.write_tag_directive(handle_text, prefix_text)
implicit = (first and not self.event.explicit and not self.canonical
and not self.event.version and not self.event.tags
and not self.check_empty_document())
if not implicit:
self.write_indent()
self.write_indicator(u'---', True)
if self.canonical:
self.write_indent()
self.state = self.expect_document_root
elif isinstance(self.event, StreamEndEvent):
if self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
self.write_stream_end()
self.state = self.expect_nothing
else:
raise EmitterError("expected DocumentStartEvent, but got %s"
% self.event)
def expect_document_end(self):
if isinstance(self.event, DocumentEndEvent):
self.write_indent()
if self.event.explicit:
self.write_indicator(u'...', True)
self.write_indent()
self.flush_stream()
self.state = self.expect_document_start
else:
raise EmitterError("expected DocumentEndEvent, but got %s"
% self.event)
def expect_document_root(self):
self.states.append(self.expect_document_end)
self.expect_node(root=True)
# Node handlers.
def expect_node(self, root=False, sequence=False, mapping=False,
simple_key=False):
self.root_context = root
self.sequence_context = sequence
self.mapping_context = mapping
self.simple_key_context = simple_key
if isinstance(self.event, AliasEvent):
self.expect_alias()
elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
self.process_anchor(u'&')
self.process_tag()
if isinstance(self.event, ScalarEvent):
self.expect_scalar()
elif isinstance(self.event, SequenceStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_sequence():
self.expect_flow_sequence()
else:
self.expect_block_sequence()
elif isinstance(self.event, MappingStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_mapping():
self.expect_flow_mapping()
else:
self.expect_block_mapping()
else:
raise EmitterError("expected NodeEvent, but got %s" % self.event)
def expect_alias(self):
if self.event.anchor is None:
raise EmitterError("anchor is not specified for alias")
self.process_anchor(u'*')
self.state = self.states.pop()
def expect_scalar(self):
self.increase_indent(flow=True)
self.process_scalar()
self.indent = self.indents.pop()
self.state = self.states.pop()
# Flow sequence handlers.
def expect_flow_sequence(self):
self.write_indicator(u'[', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_sequence_item
def expect_first_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
def expect_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
# Flow mapping handlers.
def expect_flow_mapping(self):
self.write_indicator(u'{', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_mapping_key
def expect_first_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
def expect_flow_mapping_value(self):
if self.canonical or self.column > self.best_width:
self.write_indent()
self.write_indicator(u':', True)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
# Block sequence handlers.
def expect_block_sequence(self):
indentless = (self.mapping_context and not self.indention)
self.increase_indent(flow=False, indentless=indentless)
self.state = self.expect_first_block_sequence_item
def expect_first_block_sequence_item(self):
return self.expect_block_sequence_item(first=True)
def expect_block_sequence_item(self, first=False):
if not first and isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
self.write_indicator(u'-', True, indention=True)
self.states.append(self.expect_block_sequence_item)
self.expect_node(sequence=True)
# Block mapping handlers.
def expect_block_mapping(self):
self.increase_indent(flow=False)
self.state = self.expect_first_block_mapping_key
def expect_first_block_mapping_key(self):
return self.expect_block_mapping_key(first=True)
def expect_block_mapping_key(self, first=False):
if not first and isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
if self.check_simple_key():
self.states.append(self.expect_block_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True, indention=True)
self.states.append(self.expect_block_mapping_value)
self.expect_node(mapping=True)
def expect_block_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
def expect_block_mapping_value(self):
self.write_indent()
self.write_indicator(u':', True, indention=True)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
# Checkers.
def check_empty_sequence(self):
return (isinstance(self.event, SequenceStartEvent) and self.events
and isinstance(self.events[0], SequenceEndEvent))
def check_empty_mapping(self):
return (isinstance(self.event, MappingStartEvent) and self.events
and isinstance(self.events[0], MappingEndEvent))
def check_empty_document(self):
if not isinstance(self.event, DocumentStartEvent) or not self.events:
return False
event = self.events[0]
return (isinstance(event, ScalarEvent) and event.anchor is None
and event.tag is None and event.implicit and event.value == u'')
def check_simple_key(self):
length = 0
if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
length += len(self.prepared_anchor)
if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
and self.event.tag is not None:
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(self.event.tag)
length += len(self.prepared_tag)
if isinstance(self.event, ScalarEvent):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
length += len(self.analysis.scalar)
return (length < 128 and (isinstance(self.event, AliasEvent)
or (isinstance(self.event, ScalarEvent)
and not self.analysis.empty and not self.analysis.multiline)
or self.check_empty_sequence() or self.check_empty_mapping()))
# Anchor, Tag, and Scalar processors.
def process_anchor(self, indicator):
if self.event.anchor is None:
self.prepared_anchor = None
return
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
if self.prepared_anchor:
self.write_indicator(indicator+self.prepared_anchor, True)
self.prepared_anchor = None
def process_tag(self):
tag = self.event.tag
if isinstance(self.event, ScalarEvent):
if self.style is None:
self.style = self.choose_scalar_style()
if ((not self.canonical or tag is None) and
((self.style == '' and self.event.implicit[0])
or (self.style != '' and self.event.implicit[1]))):
self.prepared_tag = None
return
if self.event.implicit[0] and tag is None:
tag = u'!'
self.prepared_tag = None
else:
if (not self.canonical or tag is None) and self.event.implicit:
self.prepared_tag = None
return
if tag is None:
raise EmitterError("tag is not specified")
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(tag)
if self.prepared_tag:
self.write_indicator(self.prepared_tag, True)
self.prepared_tag = None
def choose_scalar_style(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.event.style == '"' or self.canonical:
return '"'
if not self.event.style and self.event.implicit[0]:
if (not (self.simple_key_context and
(self.analysis.empty or self.analysis.multiline))
and (self.flow_level and self.analysis.allow_flow_plain
or (not self.flow_level and self.analysis.allow_block_plain))):
return ''
if self.event.style and self.event.style in '|>':
if (not self.flow_level and not self.simple_key_context
and self.analysis.allow_block):
return self.event.style
if not self.event.style or self.event.style == '\'':
if (self.analysis.allow_single_quoted and
not (self.simple_key_context and self.analysis.multiline)):
return '\''
return '"'
def process_scalar(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.style is None:
self.style = self.choose_scalar_style()
split = (not self.simple_key_context)
#if self.analysis.multiline and split \
# and (not self.style or self.style in '\'\"'):
# self.write_indent()
if self.style == '"':
self.write_double_quoted(self.analysis.scalar, split)
elif self.style == '\'':
self.write_single_quoted(self.analysis.scalar, split)
elif self.style == '>':
self.write_folded(self.analysis.scalar)
elif self.style == '|':
self.write_literal(self.analysis.scalar)
else:
self.write_plain(self.analysis.scalar, split)
self.analysis = None
self.style = None
# Analyzers.
def prepare_version(self, version):
major, minor = version
if major != 1:
raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
return u'%d.%d' % (major, minor)
def prepare_tag_handle(self, handle):
if not handle:
raise EmitterError("tag handle must not be empty")
if handle[0] != u'!' or handle[-1] != u'!':
raise EmitterError("tag handle must start and end with '!': %r"
% (handle.encode('utf-8')))
for ch in handle[1:-1]:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the tag handle: %r"
% (ch.encode('utf-8'), handle.encode('utf-8')))
return handle
def prepare_tag_prefix(self, prefix):
if not prefix:
raise EmitterError("tag prefix must not be empty")
chunks = []
start = end = 0
if prefix[0] == u'!':
end = 1
while end < len(prefix):
ch = prefix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?!:@&=+$,_.~*\'()[]':
end += 1
else:
if start < end:
chunks.append(prefix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(prefix[start:end])
return u''.join(chunks)
def prepare_tag(self, tag):
if not tag:
raise EmitterError("tag must not be empty")
if tag == u'!':
return tag
handle = None
suffix = tag
prefixes = self.tag_prefixes.keys()
prefixes.sort()
for prefix in prefixes:
if tag.startswith(prefix) \
and (prefix == u'!' or len(prefix) < len(tag)):
handle = self.tag_prefixes[prefix]
suffix = tag[len(prefix):]
chunks = []
start = end = 0
while end < len(suffix):
ch = suffix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?:@&=+$,_.~*\'()[]' \
or (ch == u'!' and handle != u'!'):
end += 1
else:
if start < end:
chunks.append(suffix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(suffix[start:end])
suffix_text = u''.join(chunks)
if handle:
return u'%s%s' % (handle, suffix_text)
else:
return u'!<%s>' % suffix_text
def prepare_anchor(self, anchor):
if not anchor:
raise EmitterError("anchor must not be empty")
for ch in anchor:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the anchor: %r"
% (ch.encode('utf-8'), anchor.encode('utf-8')))
return anchor
def analyze_scalar(self, scalar):
# Empty scalar is a special case.
if not scalar:
return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
allow_flow_plain=False, allow_block_plain=True,
allow_single_quoted=True, allow_double_quoted=True,
allow_block=False)
# Indicators and special characters.
block_indicators = False
flow_indicators = False
line_breaks = False
special_characters = False
# Important whitespace combinations.
leading_space = False
leading_break = False
trailing_space = False
trailing_break = False
break_space = False
space_break = False
# Check document indicators.
if scalar.startswith(u'---') or scalar.startswith(u'...'):
block_indicators = True
flow_indicators = True
# First character or preceded by a whitespace.
preceeded_by_whitespace = True
# Last character or followed by a whitespace.
followed_by_whitespace = (len(scalar) == 1 or
scalar[1] in u'\0 \t\r\n\x85\u2028\u2029')
# The previous character is a space.
previous_space = False
# The previous character is a break.
previous_break = False
index = 0
while index < len(scalar):
ch = scalar[index]
# Check for indicators.
if index == 0:
# Leading indicators are special characters.
if ch in u'#,[]{}&*!|>\'\"%@`':
flow_indicators = True
block_indicators = True
if ch in u'?:':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'-' and followed_by_whitespace:
flow_indicators = True
block_indicators = True
else:
# Some indicators cannot appear within a scalar as well.
if ch in u',?[]{}':
flow_indicators = True
if ch == u':':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'#' and preceeded_by_whitespace:
flow_indicators = True
block_indicators = True
# Check for line breaks, special, and unicode characters.
if ch in u'\n\x85\u2028\u2029':
line_breaks = True
if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'):
if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF':
unicode_characters = True
if not self.allow_unicode:
special_characters = True
else:
special_characters = True
# Detect important whitespace combinations.
if ch == u' ':
if index == 0:
leading_space = True
if index == len(scalar)-1:
trailing_space = True
if previous_break:
break_space = True
previous_space = True
previous_break = False
elif ch in u'\n\x85\u2028\u2029':
if index == 0:
leading_break = True
if index == len(scalar)-1:
trailing_break = True
if previous_space:
space_break = True
previous_space = False
previous_break = True
else:
previous_space = False
previous_break = False
# Prepare for the next character.
index += 1
preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029')
followed_by_whitespace = (index+1 >= len(scalar) or
scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029')
# Let's decide what styles are allowed.
allow_flow_plain = True
allow_block_plain = True
allow_single_quoted = True
allow_double_quoted = True
allow_block = True
# Leading and trailing whitespaces are bad for plain scalars.
if (leading_space or leading_break
or trailing_space or trailing_break):
allow_flow_plain = allow_block_plain = False
# We do not permit trailing spaces for block scalars.
if trailing_space:
allow_block = False
# Spaces at the beginning of a new line are only acceptable for block
# scalars.
if break_space:
allow_flow_plain = allow_block_plain = allow_single_quoted = False
# Spaces followed by breaks, as well as special character are only
# allowed for double quoted scalars.
if space_break or special_characters:
allow_flow_plain = allow_block_plain = \
allow_single_quoted = allow_block = False
# Although the plain scalar writer supports breaks, we never emit
# multiline plain scalars.
if line_breaks:
allow_flow_plain = allow_block_plain = False
# Flow indicators are forbidden for flow plain scalars.
if flow_indicators:
allow_flow_plain = False
# Block indicators are forbidden for block plain scalars.
if block_indicators:
allow_block_plain = False
return ScalarAnalysis(scalar=scalar,
empty=False, multiline=line_breaks,
allow_flow_plain=allow_flow_plain,
allow_block_plain=allow_block_plain,
allow_single_quoted=allow_single_quoted,
allow_double_quoted=allow_double_quoted,
allow_block=allow_block)
# Writers.
def flush_stream(self):
if hasattr(self.stream, 'flush'):
self.stream.flush()
def write_stream_start(self):
# Write BOM if needed.
if self.encoding and self.encoding.startswith('utf-16'):
self.stream.write(u'\uFEFF'.encode(self.encoding))
def write_stream_end(self):
self.flush_stream()
def write_indicator(self, indicator, need_whitespace,
whitespace=False, indention=False):
if self.whitespace or not need_whitespace:
data = indicator
else:
data = u' '+indicator
self.whitespace = whitespace
self.indention = self.indention and indention
self.column += len(data)
self.open_ended = False
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_indent(self):
indent = self.indent or 0
if not self.indention or self.column > indent \
or (self.column == indent and not self.whitespace):
self.write_line_break()
if self.column < indent:
self.whitespace = True
data = u' '*(indent-self.column)
self.column = indent
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_line_break(self, data=None):
if data is None:
data = self.best_line_break
self.whitespace = True
self.indention = True
self.line += 1
self.column = 0
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_version_directive(self, version_text):
data = u'%%YAML %s' % version_text
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
def write_tag_directive(self, handle_text, prefix_text):
data = u'%%TAG %s %s' % (handle_text, prefix_text)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
# Scalar streams.
def write_single_quoted(self, text, split=True):
self.write_indicator(u'\'', True)
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch is None or ch != u' ':
if start+1 == end and self.column > self.best_width and split \
and start != 0 and end != len(text):
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'':
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch == u'\'':
data = u'\'\''
self.column += 2
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end + 1
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
self.write_indicator(u'\'', False)
ESCAPE_REPLACEMENTS = {
u'\0': u'0',
u'\x07': u'a',
u'\x08': u'b',
u'\x09': u't',
u'\x0A': u'n',
u'\x0B': u'v',
u'\x0C': u'f',
u'\x0D': u'r',
u'\x1B': u'e',
u'\"': u'\"',
u'\\': u'\\',
u'\x85': u'N',
u'\xA0': u'_',
u'\u2028': u'L',
u'\u2029': u'P',
}
def write_double_quoted(self, text, split=True):
self.write_indicator(u'"', True)
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \
or not (u'\x20' <= ch <= u'\x7E'
or (self.allow_unicode
and (u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD'))):
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
if ch in self.ESCAPE_REPLACEMENTS:
data = u'\\'+self.ESCAPE_REPLACEMENTS[ch]
elif ch <= u'\xFF':
data = u'\\x%02X' % ord(ch)
elif ch <= u'\uFFFF':
data = u'\\u%04X' % ord(ch)
else:
data = u'\\U%08X' % ord(ch)
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end+1
if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \
and self.column+(end-start) > self.best_width and split:
data = text[start:end]+u'\\'
if start < end:
start = end
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_indent()
self.whitespace = False
self.indention = False
if text[start] == u' ':
data = u'\\'
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
end += 1
self.write_indicator(u'"', False)
def determine_block_hints(self, text):
hints = u''
if text:
if text[0] in u' \n\x85\u2028\u2029':
hints += unicode(self.best_indent)
if text[-1] not in u'\n\x85\u2028\u2029':
hints += u'-'
elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029':
hints += u'+'
return hints
def write_folded(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'>'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
leading_space = True
spaces = False
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if not leading_space and ch is not None and ch != u' ' \
and text[start] == u'\n':
self.write_line_break()
leading_space = (ch == u' ')
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
elif spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width:
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
spaces = (ch == u' ')
end += 1
def write_literal(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'|'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
else:
if ch is None or ch in u'\n\x85\u2028\u2029':
data = text[start:end]
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
def write_plain(self, text, split=True):
if self.root_context:
self.open_ended = True
if not text:
return
if not self.whitespace:
data = u' '
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.whitespace = False
self.indention = False
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width and split:
self.write_indent()
self.whitespace = False
self.indention = False
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
self.whitespace = False
self.indention = False
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
| mit |
aclevy/vcrpy | vcr/matchers.py | 2 | 2397 | import json
from six.moves import urllib, xmlrpc_client
from .util import CaseInsensitiveDict, read_body
import logging
log = logging.getLogger(__name__)
def method(r1, r2):
return r1.method == r2.method
def uri(r1, r2):
return r1.uri == r2.uri
def host(r1, r2):
return r1.host == r2.host
def scheme(r1, r2):
return r1.scheme == r2.scheme
def port(r1, r2):
return r1.port == r2.port
def path(r1, r2):
return r1.path == r2.path
def query(r1, r2):
return r1.query == r2.query
def raw_body(r1, r2):
return read_body(r1) == read_body(r2)
def _header_checker(value, header='Content-Type'):
def checker(headers):
return value in headers.get(header, '').lower()
return checker
def _transform_json(body):
# Request body is always a byte string, but json.loads() wants a text
# string. RFC 7159 says the default encoding is UTF-8 (although UTF-16
# and UTF-32 are also allowed: hmmmmm).
return json.loads(body.decode('utf-8'))
_xml_header_checker = _header_checker('text/xml')
_xmlrpc_header_checker = _header_checker('xmlrpc', header='User-Agent')
_checker_transformer_pairs = (
(_header_checker('application/x-www-form-urlencoded'), urllib.parse.parse_qs),
(_header_checker('application/json'), _transform_json),
(lambda request: _xml_header_checker(request) and _xmlrpc_header_checker(request), xmlrpc_client.loads),
)
def _identity(x):
return x
def _get_transformer(request):
headers = CaseInsensitiveDict(request.headers)
for checker, transformer in _checker_transformer_pairs:
if checker(headers): return transformer
else:
return _identity
def body(r1, r2):
transformer = _get_transformer(r1)
r2_transformer = _get_transformer(r2)
if transformer != r2_transformer:
transformer = _identity
return transformer(read_body(r1)) == transformer(read_body(r2))
def headers(r1, r2):
return r1.headers == r2.headers
def _log_matches(r1, r2, matches):
differences = [m for m in matches if not m[0]]
if differences:
log.debug(
"Requests {0} and {1} differ according to "
"the following matchers: {2}".format(r1, r2, differences)
)
def requests_match(r1, r2, matchers):
matches = [(m(r1, r2), m) for m in matchers]
_log_matches(r1, r2, matches)
return all([m[0] for m in matches])
| mit |
dmlc/tvm | tests/python/unittest/test_link_params.py | 1 | 15580 | # 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.
import collections
import ctypes
import json
import os
import re
import struct
import sys
import numpy as np
import pytest
import tvm
import tvm.relay
import tvm.testing
from tvm.contrib import utils
INPUT_SHAPE = (1, 3, 16, 16)
KERNEL_SHAPE = (3, 3, 3, 3)
# The data types that are linkable.
LINKABLE_DTYPES = (
[f"uint{b}" for b in (8, 16, 32, 64)]
+ [f"int{b}" for b in (8, 16, 32, 64)]
+ ["float32", "float64"]
)
def dtype_info(dtype):
"""Lookup numpy type info for the given string dtype (of LINKABLE_DTYPES above)."""
if "int" in dtype:
return np.iinfo(getattr(np, dtype))
else:
return np.finfo(getattr(np, dtype))
# Note: for debugging, set this to an integer (i.e. 1.0). Then all "random" tensors will become
# predictable
RANDOM_TENSOR_START = None
def _make_random_tensor(dtype, shape):
"""Create a random test tensor with given shape and dtype."""
global RAND_SEED
if RANDOM_TENSOR_START is not None:
to_return = np.arange(
RANDOM_TENSOR_START, RANDOM_TENSOR_START + np.prod(shape), dtype=dtype
).reshape(shape)
RAND_SEED += np.prod(shape)
return to_return
dinfo = dtype_info(dtype)
if "int" in dtype:
return np.random.randint(dinfo.min, dinfo.max, shape, dtype=dtype)
else:
to_return = np.random.uniform(0, dinfo.max, shape).astype(dtype)
np.reshape(to_return, np.prod(shape))[::2] *= -1
return to_return
def _lookup_sid(graph, name):
"""Lookup the storage id of a named parameter.
Arguments
---------
graph : dict
Parsed JSON graph.
name : str
Name of the tensor parameter to lookup.
Returns
-------
int :
The storage_id of the parameter.
"""
num_outputs_seen = 0
for i, n in enumerate(graph["nodes"]):
if n["name"] == name:
print("sid", name, graph["attrs"]["storage_id"][1], num_outputs_seen)
return graph["attrs"]["storage_id"][1][num_outputs_seen]
else:
if "attrs" in n and "num_outputs" in n["attrs"]:
num_outputs_seen += int(n["attrs"]["num_outputs"])
else:
num_outputs_seen += 1
raise KeyError(f"no such param: {name}")
def _get_ctypes_dtype(dt):
"""Return a ctypes c_* datatype given a string data type."""
if "int" in dt:
return getattr(ctypes, f"c_{dt}")
elif dt == "float32":
return ctypes.c_float
elif dt == "float64":
return ctypes.c_double
else:
assert False, f"unknown dtype: {dt}"
def _verify_linked_param(dtype, lib, mod, graph, name):
"""Directly read memory from the linked library to verify the linked parameter is correct."""
sid = _lookup_sid(graph, name)
# NOTE: query_imports=True because when loading a module from disk (i.e. for C backend),
# a GraphRuntimeFactory module is created instead of the module itself.
param_ptr = mod.get_function("_lookup_linked_param", True)(sid)
gen_param = lib.params[name]
arr_data = (_get_ctypes_dtype(dtype) * np.prod(gen_param.shape)).from_address(param_ptr.value)
arr = np.ndarray(shape=gen_param.shape, dtype=gen_param.dtype, buffer=arr_data, order="C")
if "int" in gen_param.dtype:
np.testing.assert_equal(gen_param.asnumpy(), arr)
else:
np.testing.assert_allclose(gen_param.asnumpy(), arr)
return dtype == gen_param.dtype
def _make_mod_and_params(dtype):
"""Create a Relay module and parameters to test the given datatype."""
param_decls = collections.OrderedDict()
param_init = {}
def _add_decl(name, dtype):
param_decls[name] = f"%{name} : Tensor[{KERNEL_SHAPE}, {dtype}]"
param_init[name] = _make_random_tensor(dtype, KERNEL_SHAPE)
# Add several parameters so that the number of parameters
_add_decl(f"{dtype}_a", dtype)
_add_decl(f"{dtype}_b", dtype)
mod_lines = [
'#[version = "0.0.5"]',
f"def @main(%rand_input : Tensor[{INPUT_SHAPE}, {dtype}], { ', '.join(param_decls.values()) } ) {{",
# This program ensures that GraphPlanMemory alternates between the same two storage IDs for a
# while. In doing this, it ensures that param %{dtype}_b will be placed into the graph at an
# index unequal to its storage_id. This ensures that GraphRuntimeCodegen encodes the storage_id
# and not the parameter index into the graph.
(
f' %0 = nn.conv2d(%rand_input, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", '
f'kernel_size=[3, 3], out_dtype="{dtype}");'
),
(
f' %1 = nn.conv2d(%0, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", '
f'kernel_size=[3, 3], out_dtype="{dtype}");'
),
(
f' %2 = nn.conv2d(%1, %{dtype}_a, data_layout="NCHW", kernel_layout="OIHW", '
f'kernel_size=[3, 3], out_dtype="{dtype}");'
),
(
f' %3 = nn.conv2d(%2, %{dtype}_b, data_layout="NCHW", kernel_layout="OIHW", '
f'kernel_size=[3, 3], out_dtype="{dtype}");'
),
" %3",
"}",
]
mod = tvm.parser.fromtext("\n".join(mod_lines))
return mod, param_init
@tvm.testing.requires_llvm
def test_llvm_link_params():
for dtype in LINKABLE_DTYPES:
mod, param_init = _make_mod_and_params(dtype)
rand_input = _make_random_tensor(dtype, INPUT_SHAPE)
main_func = mod["main"]
target = "llvm --runtime=c --system-lib --link-params"
with tvm.transform.PassContext(opt_level=3):
lib = tvm.relay.build(mod, target, params=param_init)
assert set(lib.params.keys()) == {"p0", "p1"} # NOTE: op folded
print("graph", lib.graph_json)
graph = json.loads(lib.graph_json)
for p in lib.params:
_verify_linked_param(dtype, lib, lib.lib, graph, p) or found_one
# Wrap in function to explicitly deallocate the runtime.
def _run_linked(lib):
graph_json, mod, _ = lib
graph_rt = tvm.contrib.graph_runtime.create(graph_json, mod, tvm.cpu(0))
graph_rt.set_input("rand_input", rand_input) # NOTE: params not required.
graph_rt.run()
return graph_rt.get_output(0)
linked_output = _run_linked(lib)
with tvm.transform.PassContext(opt_level=3):
lib = tvm.relay.build(mod, "llvm --system-lib", params=param_init)
def _run_unlinked(lib):
graph_json, mod, lowered_params = lib
graph_rt = tvm.contrib.graph_runtime.create(graph_json, mod, tvm.cpu(0))
graph_rt.set_input("rand_input", rand_input, **lowered_params)
graph_rt.run()
return graph_rt.get_output(0)
unlinked_output = _run_unlinked(lib)
if "int" in dtype:
np.testing.assert_equal(unlinked_output.asnumpy(), linked_output.asnumpy())
else:
np.testing.assert_allclose(unlinked_output.asnumpy(), linked_output.asnumpy())
def _get_c_datatype(dtype):
"""Translate LINKABLE_DTYPES element to c datatype."""
if "int" in dtype:
return f"{dtype}_t"
elif dtype == "float32":
return "float"
elif dtype == "float64":
return "double"
else:
assert False, f"unknown dtype {dtype}"
def _format_c_value(dtype, width, x):
if "int" in dtype:
hex_formatstr = f'{{:{"+" if dtype.startswith("int") else ""}#0{width}x}}'
return hex_formatstr.format(x)
elif "float" in dtype:
to_ret = float(x).hex()
if "inf" in to_ret:
return ("-" if x < 0 else "") + "INFINITY"
elif "nan" in to_ret:
return "NAN"
before, after = to_ret.split("p")
return f'{before.rstrip("0")}p{after}'
else:
assert False, f"don't know dtype {dtype}"
HEX_NUM_RE = re.compile(r"[+\-]?(?:(?:0x[0-9A-Fa-f.p+-]+)|(?:INFINITY)|(?:NAN))")
def test_c_link_params():
temp_dir = utils.tempdir()
for dtype in LINKABLE_DTYPES:
mod, param_init = _make_mod_and_params(dtype)
rand_input = _make_random_tensor(dtype, INPUT_SHAPE)
main_func = mod["main"]
target = "c --link-params"
with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}):
lib = tvm.relay.build(mod, target, params=param_init)
assert set(lib.params.keys()) == {"p0", "p1"} # NOTE: op folded
src = lib.lib.get_source()
lib.lib.save("test.c", "cc")
c_dtype = _get_c_datatype(dtype)
src_lines = src.split("\n")
param = lib.params["p0"].asnumpy().reshape(np.prod(KERNEL_SHAPE))
param_def = f"static const {c_dtype} __tvm_param__p0[{np.prod(param.shape)}] = {{"
for i, line in enumerate(src_lines):
if line == param_def:
i += 1
break
else:
assert False, f'did not find parameter definition "{param_def}":\n{src}'
cursor = 0
width = dtype_info(dtype).bits // 4 + 2
if dtype.startswith("int"):
width += 1 # Account for sign
while "};" not in src_lines[i]:
for match in HEX_NUM_RE.finditer(src_lines[i]):
assert match.group() == _format_c_value(dtype, width, param[cursor]), (
f'p0 byte {cursor}: want "{_format_c_value(dtype, width, param[cursor])}" got '
f'"{match.group(0)}"; full p0 follows:\n{src}'
)
cursor += 1
i += 1
assert cursor == np.prod(param.shape)
temp = utils.tempdir()
# Need a unique name per library to avoid dlopen caching the lib load.
lib_path = temp_dir.relpath(f"test-{dtype}-linked.so")
lib["remove_params"]().export_library(lib_path)
lib_mod = tvm.runtime.load_module(lib_path)
# lib_mod = lib_factory['default']()
graph = json.loads(lib.graph_json)
for p in lib.params:
_verify_linked_param(dtype, lib, lib_mod, graph, p)
# Wrap in function to explicitly deallocate the runtime.
def _run_linked(lib_mod):
graph_rt = tvm.contrib.graph_runtime.GraphModule(lib_mod["default"](tvm.cpu(0)))
graph_rt.set_input("rand_input", rand_input) # NOTE: params not required.
graph_rt.run()
return graph_rt.get_output(0)
linked_output = _run_linked(lib_mod)
linked_params = lib.params
with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}):
lib = tvm.relay.build(mod, "c", params=param_init)
_, _, params = lib
# Need a unique name per library to avoid dlopen caching the lib load.
lib_path = temp_dir.relpath(f"test-{dtype}-unlinked.so")
lib.export_library(lib_path)
lib_mod = tvm.runtime.load_module(lib_path)
def _run_unlinked(lib_mod):
graph_rt = tvm.contrib.graph_runtime.GraphModule(lib_mod["default"](tvm.cpu(0)))
graph_rt.set_input("rand_input", rand_input, **params)
graph_rt.run()
return graph_rt.get_output(0)
unlinked_output = _run_unlinked(lib_mod)
if "int" in dtype:
np.testing.assert_equal(unlinked_output.asnumpy(), linked_output.asnumpy())
else:
np.testing.assert_allclose(unlinked_output.asnumpy(), linked_output.asnumpy())
@tvm.testing.requires_micro
def test_crt_link_params():
import tvm.micro
for dtype in LINKABLE_DTYPES:
mod, param_init = _make_mod_and_params(dtype)
rand_input = _make_random_tensor(dtype, INPUT_SHAPE)
main_func = mod["main"]
target = "c -mcpu=native --system-lib --runtime=c --link-params"
with tvm.transform.PassContext(opt_level=3, config={"tir.disable_vectorize": True}):
graph_json, lib, params = tvm.relay.build(mod, target, params=param_init)
assert set(params.keys()) == {"p0", "p1"} # NOTE: op folded
workspace = tvm.micro.Workspace()
compiler = tvm.micro.DefaultCompiler(target=target)
opts = tvm.micro.default_options(os.path.join(tvm.micro.CRT_ROOT_DIR, "host"))
opts["bin_opts"]["ldflags"].append("-DTVM_HOST_USE_GRAPH_RUNTIME_MODULE")
micro_binary = tvm.micro.build_static_runtime(
# the x86 compiler *expects* you to give the exact same dictionary for both
# lib_opts and bin_opts. so the library compiler is mutating lib_opts and
# the binary compiler is expecting those mutations to be in bin_opts.
# TODO(weberlo) fix this very bizarre behavior
workspace,
compiler,
lib,
lib_opts=opts["bin_opts"],
bin_opts=opts["bin_opts"],
extra_libs=[
os.path.join(tvm.micro.CRT_ROOT_DIR, m)
for m in ("memory", "graph_runtime_module", "graph_runtime")
],
)
flasher_kw = {
"debug": False,
}
flasher = compiler.flasher(**flasher_kw)
with tvm.micro.Session(binary=micro_binary, flasher=flasher) as sess:
graph_rt = tvm.micro.session.create_local_graph_runtime(
graph_json, sess.get_system_lib(), sess.context
)
# NOTE: not setting params here.
graph_rt.set_input("rand_input", rand_input)
graph_rt.run()
linked_output = graph_rt.get_output(0).asnumpy()
with tvm.transform.PassContext(opt_level=3):
lib = tvm.relay.build(mod, "llvm --system-lib", params=param_init)
def _run_unlinked(lib):
graph_json, mod, lowered_params = lib
graph_rt = tvm.contrib.graph_runtime.create(graph_json, mod, tvm.cpu(0))
graph_rt.set_input("rand_input", rand_input, **lowered_params)
graph_rt.run()
return graph_rt.get_output(0).asnumpy()
unlinked_output = _run_unlinked(lib)
if "int" in dtype:
np.testing.assert_equal(unlinked_output, linked_output)
else:
np.testing.assert_allclose(unlinked_output, linked_output)
if __name__ == "__main__":
sys.exit(pytest.main([__file__] + sys.argv[1:]))
| apache-2.0 |
codekaki/odoo | openerp/report/render/makohtml2html/__init__.py | 76 | 1120 | # -*- 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 makohtml2html import parseNode
#.apidoc title: MAKO to HTML engine
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
prologic/fabtools | fabtools/require/shorewall.py | 10 | 7739 | """
Shorewall firewall
==================
"""
from fabric.api import hide, puts, settings, shell_env
from fabric.contrib.files import sed
from fabtools.files import watch
from fabtools.service import start, stop, restart
from fabtools.shorewall import (
Ping,
SSH,
HTTP,
HTTPS,
SMTP,
is_started,
is_stopped,
)
from fabtools.system import UnsupportedFamily, distrib_family
from fabtools.require.deb import package as require_deb_package
from fabtools.require.files import file
DEFAULT_ZONES = [
{
'name': 'fw',
'type': 'firewall',
},
{
'name': 'net',
'type': 'ipv4',
},
]
ZONE_HEADER = '#ZONE\tTYPE\tOPTIONS\tIN OPTIONS\tOUT OPTIONS\n'
ZONE_FORMAT = '%(name)s\t%(type)s\t%(options)s\t%(in_options)s\t%(out_options)s\n'
def _zone_config(zones):
"""
Zone configuration
"""
if zones is None:
zones = DEFAULT_ZONES
lines = [ZONE_HEADER]
for entry in zones:
entry.setdefault('options', '')
entry.setdefault('in_options', '')
entry.setdefault('out_options', '')
lines.append(ZONE_FORMAT % entry)
file('/etc/shorewall/zones', contents=''.join(lines), use_sudo=True)
DEFAULT_INTERFACES = [
{
'zone': 'net',
'interface': 'eth0',
},
]
INTERFACES_HEADER = '#ZONE\tINTERFACE\tBROADCAST\tOPTIONS\n'
INTERFACES_FORMAT = '%(zone)s\t%(interface)s\t%(broadcast)s\t%(options)s\n'
def _interfaces_config(interfaces):
"""
Interfaces configuration
"""
if interfaces is None:
interfaces = DEFAULT_INTERFACES
lines = [INTERFACES_HEADER]
for entry in interfaces:
entry.setdefault('zone', 'net')
entry.setdefault('broadcast', 'detect')
entry.setdefault('options', '')
lines.append(INTERFACES_FORMAT % entry)
file('/etc/shorewall/interfaces', contents=''.join(lines), use_sudo=True)
DEFAULT_POLICY = [
{
'source': '$FW',
'dest': 'net',
'policy': 'ACCEPT',
},
{
'source': 'net',
'dest': 'all',
'policy': 'DROP',
'log_level': 'info',
},
{
'source': 'all',
'dest': 'all',
'policy': 'REJECT',
'log_level': 'info',
},
]
POLICY_HEADER = '''\
#SOURCE\tDEST\tPOLICY\tLOG \tBURST:LIMIT
# \t \t \tLEVEL
'''
POLICY_FORMAT = '%(source)s\t%(dest)s\t%(policy)s\t%(log_level)s\t%(burst_limit)s\n'
def _policy_config(policy):
"""
Policy configuration
"""
if policy is None:
policy = DEFAULT_POLICY
lines = [POLICY_HEADER]
for entry in policy:
entry.setdefault('log_level', '')
entry.setdefault('burst_limit', '')
lines.append(POLICY_FORMAT % entry)
file('/etc/shorewall/policy', contents=''.join(lines), use_sudo=True)
DEFAULT_RULES = [
Ping(),
SSH(),
HTTP(),
HTTPS(),
SMTP(port=[25, 587]),
]
RULES_HEADER = '''\
#ACTION\tSOURCE\tDEST\tPROTO\tDEST \tSOURCE \tORIG\tRATE \tUSER/\tMARK\tCONN \tTIME
# \t \t \t \tPORT(S)\tPORT(S)\tDEST\tLIMIT\tGROUP\t \tLIMIT
'''
RULES_FORMAT = '%(action)s\t%(source)s\t%(dest)s\t%(proto)s\t%(dest_port)s\t%(source_port)s\t%(original_dest)s\t%(rate_limit)s\t%(user)s\t%(mark)s\t%(conn_limit)s\t%(time)s\n'
def _rules_config(rules):
"""
Policy configuration
"""
if rules is None:
rules = DEFAULT_RULES
lines = [RULES_HEADER]
for entry in rules:
entry.setdefault('proto', 'tcp')
entry.setdefault('dest_port', '-')
entry.setdefault('source_port', '-')
entry.setdefault('original_dest', '-')
entry.setdefault('rate_limit', '-')
entry.setdefault('user', '-')
entry.setdefault('mark', '-')
entry.setdefault('conn_limit', '-')
entry.setdefault('time', '-')
if isinstance(entry['dest_port'], list):
entry['dest_port'] = ','.join(map(str, entry['dest_port']))
if isinstance(entry['source_port'], list):
entry['source_port'] = ','.join(map(str, entry['source_port']))
lines.append(RULES_FORMAT % entry)
file('/etc/shorewall/rules', contents=''.join(lines), use_sudo=True)
ROUTESTOPPED_HEADER = '''\
#INTERFACE\tHOST(S)\tOPTIONS\tPROTO\tDEST \tSOURCE
# \t \t \t \tPORT(S)\tPORT(S)
'''
ROUTESTOPPED_FORMAT = '%(interface)s\t%(host)s\t%(options)s\t%(proto)s\t%(dest_port)s\t%(source_port)s\n'
def _routestopped_config(routestopped):
"""
Routestopped configuration
This lists the hosts that should be accessible
when the firewall is stopped or starting.
"""
if routestopped is None:
routestopped = []
lines = [ROUTESTOPPED_HEADER]
for entry in routestopped:
entry.setdefault('interface', 'eth0')
entry.setdefault('host', '0.0.0.0/0')
entry.setdefault('options', '-')
entry.setdefault('proto', '-')
entry.setdefault('dest_port', '-')
entry.setdefault('source_port', '-')
if isinstance(entry['host'], list):
entry['host'] = ','.join(entry['host'])
if isinstance(entry['options'], list):
entry['options'] = ','.join(entry['options'])
lines.append(ROUTESTOPPED_FORMAT % entry)
file('/etc/shorewall/routestopped', contents=''.join(lines), use_sudo=True)
MASQ_HEADER = '''\
#INTERFACE\tSOURCE\tADDRESS\tPROTO\tPORT(S)
'''
MASQ_FORMAT = '%(interface)s\t%(source)s\t%(address)s\t%(proto)s\t%(port)s\n'
def _masq_config(masq):
"""
Masquerading/SNAT configuration
"""
if masq is None:
masq = []
lines = [MASQ_HEADER]
for entry in masq:
entry.setdefault('interface', 'eth0')
entry.setdefault('address', '-')
entry.setdefault('proto', '-')
entry.setdefault('port', '-')
if isinstance(entry['source'], list):
entry['source'] = ','.join(entry['source'])
lines.append(MASQ_FORMAT % entry)
file('/etc/shorewall/masq', contents=''.join(lines), use_sudo=True)
CONFIG_FILES = [
'/etc/shorewall/interfaces',
'/etc/shorewall/masq',
'/etc/shorewall/policy',
'/etc/shorewall/routestopped',
'/etc/shorewall/rules',
'/etc/shorewall/zones',
]
def firewall(zones=None, interfaces=None, policy=None, rules=None,
routestopped=None, masq=None):
"""
Ensure that a firewall is configured.
Example::
from fabtools.shorewall import *
from fabtools import require
# We need a firewall with some custom rules
require.shorewall.firewall(
rules=[
Ping(),
SSH(),
HTTP(),
HTTPS(),
SMTP(),
rule(port=1234, source=hosts(['example.com'])),
]
)
"""
family = distrib_family()
if family != 'debian':
raise UnsupportedFamily(supported=['debian'])
require_deb_package('shorewall')
with watch(CONFIG_FILES) as config:
_zone_config(zones)
_interfaces_config(interfaces)
_policy_config(policy)
_rules_config(rules)
_routestopped_config(routestopped)
_masq_config(masq)
if config.changed:
puts("Shorewall configuration changed")
if is_started():
restart('shorewall')
with settings(hide('running'), shell_env()):
sed('/etc/default/shorewall', 'startup=0', 'startup=1', use_sudo=True)
def started():
"""
Ensure that the firewall is started.
"""
if not is_started():
start('shorewall')
def stopped():
"""
Ensure that the firewall is stopped.
"""
if not is_stopped():
stop('shorewall')
| bsd-2-clause |
frohoff/Empire | lib/modules/powershell/collection/inveigh.py | 2 | 10714 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-Inveigh',
'Author': ['Kevin Robertson'],
'Description': ('Inveigh is a Windows PowerShell LLMNR/mDNS/NBNS spoofer/man-in-the-middle tool. Note '
'that this module exposes only a subset of Inveigh\'s parameters. Inveigh can be used '
'through Empire\'s scriptimport and scriptcmd if additional parameters are needed.'),
'Background' : True,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : True,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'https://github.com/Kevin-Robertson/Inveigh'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
},
'ConsoleOutput' : {
'Description' : '(Low/Medium/Y) Default = Y: Enable/Disable real time console output. Medium and Low can be used to reduce output.',
'Required' : False,
'Value' : ''
},
'ConsoleStatus' : {
'Description' : 'Interval in minutes for displaying all unique captured hashes and credentials. This will display a clean list of captures in Empire.',
'Required' : False,
'Value' : ''
},
'ConsoleUnique' : {
'Description' : '(Y/N) Default = Y: Enable/Disable displaying challenge/response hashes for only unique IP, domain/hostname, and username combinations.',
'Required' : False,
'Value' : ''
},
'ElevatedPrivilege' : {
'Description' : '(Auto/Y/N) Default = Auto: Set the privilege mode. Auto will determine if Inveigh is running with elevated privilege. If so, options that require elevated privilege can be used.',
'Required' : False,
'Value' : ''
},
'HTTP' : {
'Description' : '(Y/N) Default = Y: Enable/Disable HTTP challenge/response capture.',
'Required' : False,
'Value' : ''
},
'HTTPAuth' : {
'Description' : '(Anonymous/Basic/NTLM/NTLMNoESS) HTTP listener authentication type. This setting does not apply to wpad.dat requests.',
'Required' : False,
'Value' : ''
},
'HTTPContentType' : {
'Description' : 'Content type for HTTP/Proxy responses. Does not apply to EXEs and wpad.dat. Set to "application/hta" for HTA files or when using HTA code with HTTPResponse.',
'Required' : False,
'Value' : ''
},
'HTTPResponse' : {
'Description' : 'Content to serve as the default HTTP/Proxy response. This response will not be used for wpad.dat requests. Use PowerShell escape characters and newlines where necessary. This paramater will be wrapped in double quotes by this module.',
'Required' : False,
'Value' : ''
},
'Inspect' : {
'Description' : '(Switch) Inspect LLMNR, mDNS, and NBNS traffic only.',
'Required' : False,
'Value' : ''
},
'IP' : {
'Description' : 'Local IP address for listening and packet sniffing. This IP address will also be used for LLMNR/mDNS/NBNS spoofing if the SpooferIP parameter is not set.',
'Required' : False,
'Value' : ''
},
'LLMNR' : {
'Description' : '(Y/N) Default = Y: Enable/Disable LLMNR spoofer.',
'Required' : False,
'Value' : ''
},
'mDNS' : {
'Description' : '(Y/N) Enable/Disable mDNS spoofer.',
'Required' : False,
'Value' : ''
},
'mDNSTypes' : {
'Description' : '(QU,QM) Default = QU: Comma separated list of mDNS types to spoof. Note that QM will send the response to 224.0.0.251.',
'Required' : False,
'Value' : ''
},
'NBNS' : {
'Description' : '(Y/N) Enable/Disable NBNS spoofer.',
'Required' : False,
'Value' : ''
},
'NBNSTypes' : {
'Description' : 'Default = 00,20: Comma separated list of NBNS types to spoof.',
'Required' : False,
'Value' : ''
},
'Proxy' : {
'Description' : '(Y/N) Enable/Disable Inveigh\'s proxy server authentication capture.',
'Required' : False,
'Value' : ''
},
'ProxyPort' : {
'Description' : 'Default = 8492: TCP port for the Inveigh\'s proxy listener.',
'Required' : False,
'Value' : ''
},
'RunCount' : {
'Description' : 'Number of NTLMv1/NTLMv2 captures to perform before auto-exiting.',
'Required' : False,
'Value' : ''
},
'RunTime' : {
'Description' : 'Run time duration in minutes.',
'Required' : True,
'Value' : ''
},
'SMB' : {
'Description' : '(Y/N) Default = Y: Enable/Disable SMB challenge/response capture.',
'Required' : False,
'Value' : ''
},
'SpooferIP' : {
'Description' : 'Response IP address for spoofing. This parameter is only necessary when redirecting victims to a system other than the Inveigh host.',
'Required' : False,
'Value' : ''
},
'SpooferHostsIgnore' : {
'Description' : 'Comma separated list of requested hostnames to ignore when spoofing.',
'Required' : False,
'Value' : ''
},
'SpooferHostsReply' : {
'Description' : 'Comma separated list of requested hostnames to respond to when spoofing.',
'Required' : False,
'Value' : ''
},
'SpooferIPsIgnore' : {
'Description' : 'Comma separated list of source IP addresses to ignore when spoofing.',
'Required' : False,
'Value' : ''
},
'SpooferIPsReply' : {
'Description' : 'Comma separated list of source IP addresses to respond to when spoofing.',
'Required' : False,
'Value' : ''
},
'SpooferLearning' : {
'Description' : '(Y/N) Enable/Disable LLMNR/NBNS valid host learning.',
'Required' : False,
'Value' : ''
},
'SpooferLearningDelay' : {
'Description' : 'Time in minutes that Inveigh will delay spoofing while valid hosts are being blacklisted through SpooferLearning.',
'Required' : False,
'Value' : ''
},
'SpooferRepeat' : {
'Description' : '(Y/N) Default = Y: Enable/Disable repeated LLMNR/NBNS spoofs to a victim system after one user challenge/response has been captured.',
'Required' : False,
'Value' : ''
},
'WPADAuth' : {
'Description' : '(Anonymous/Basic/NTLM/NTLMNoESS) HTTP listener authentication type for wpad.dat requests.',
'Required' : False,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self, obfuscate=False, obfuscationCommand=""):
# read in the common module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/collection/Invoke-Inveigh.ps1"
if obfuscate:
helpers.obfuscate_module(moduleSource=moduleSource, obfuscationCommand=obfuscationCommand)
moduleSource = moduleSource.replace("module_source", "obfuscated_module_source")
try:
f = open(moduleSource, 'r')
except:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
moduleCode = f.read()
f.close()
script = moduleCode
# set defaults for Empire
scriptEnd = "\n" + 'Invoke-Inveigh -Tool "2"'
for option,values in self.options.iteritems():
if option.lower() != "agent":
if values['Value'] and values['Value'] != '':
if values['Value'].lower() == "true":
# if we're just adding a switch
scriptEnd += " -" + str(option)
else:
if "," in str(values['Value']):
quoted = '"' + str(values['Value']).replace(',', '","') + '"'
scriptEnd += " -" + str(option) + " " + quoted
else:
scriptEnd += " -" + str(option) + " \"" + str(values['Value']) + "\""
if obfuscate:
scriptEnd = helpers.obfuscate(psScript=scriptEnd, obfuscationCommand=obfuscationCommand)
script += scriptEnd
return script
| bsd-3-clause |
sergiohgz/incubator-airflow | airflow/contrib/operators/__init__.py | 8 | 1900 | # -*- coding: utf-8 -*-
#
# 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.
#
# Contrib operators are not imported by default. They should be accessed
# directly: from airflow.contrib.operators.operator_module import Operator
import sys
import os as _os
# ------------------------------------------------------------------------
#
# #TODO #FIXME Airflow 2.0
#
# Old import machinary below.
#
# This is deprecated but should be kept until Airflow 2.0
# for compatibility.
#
# ------------------------------------------------------------------------
_operators = {
'ssh_operator': ['SSHOperator'],
'winrm_operator': ['WinRMOperator'],
'vertica_operator': ['VerticaOperator'],
'vertica_to_hive': ['VerticaToHiveTransfer'],
'qubole_operator': ['QuboleOperator'],
'spark_submit_operator': ['SparkSubmitOperator'],
'file_to_wasb': ['FileToWasbOperator'],
'fs_operator': ['FileSensor'],
'hive_to_dynamodb': ['HiveToDynamoDBTransferOperator']
}
if not _os.environ.get('AIRFLOW_USE_NEW_IMPORTS', False):
from airflow.utils.helpers import AirflowImporter
airflow_importer = AirflowImporter(sys.modules[__name__], _operators)
| apache-2.0 |
samsath/django-easydata | setup.py | 2 | 1938 | import os
from setuptools import setup
from setuptools import find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-easydata',
version='0.1',
packages=find_packages(),
include_package_data=True,
license='GNU License',
description='A Django app to publish your project data using ontologies.',
long_description=README,
author='Jose Manuel Llerena',
author_email='jose.llerecarmo@alum.uca.es',
keywords = ['ontology', 'rdf', 'rdfa', 'semantic web', 'django', 'microdata'],
package_dir={'easydata': 'easydata'},
package_data={'easydata': ['templates/*.html',
'templates/easydata/*.html',
'templates/easydata/informacion/*.html',
'templates/easydata/map/*.html',
'templates/easydata/modelo/*.html',
'templates/easydata/namespace/*.html',
'templates/easydata/templatetags/*.html',
'static/easydata/css/*.css',
'static/easydata/img/*.png',
'static/easydata/img/ui-theme/*.png',
'static/easydata/img/ui-theme/*.gif',
'static/easydata/js/*.js',
]
},
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
install_requires=[
"Django >= 1.4",
"rdflib == 4.0.1",
"pydot",
],
)
| gpl-3.0 |
snakeleon/YouCompleteMe-x86 | third_party/ycmd/third_party/python-future/src/libfuturize/fixes/fix_metaclass.py | 61 | 9568 | # coding: utf-8
"""Fixer for __metaclass__ = X -> (future.utils.with_metaclass(X)) methods.
The various forms of classef (inherits nothing, inherits once, inherints
many) don't parse the same in the CST so we look at ALL classes for
a __metaclass__ and if we find one normalize the inherits to all be
an arglist.
For one-liner classes ('class X: pass') there is no indent/dedent so
we normalize those into having a suite.
Moving the __metaclass__ into the classdef can also cause the class
body to be empty so there is some special casing for that as well.
This fixer also tries very hard to keep original indenting and spacing
in all those corner cases.
"""
# This is a derived work of Lib/lib2to3/fixes/fix_metaclass.py under the
# copyright of the Python Software Foundation, licensed under the Python
# Software Foundation License 2.
#
# Copyright notice:
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
# 2011, 2012, 2013 Python Software Foundation. All rights reserved.
#
# Full license text: http://docs.python.org/3.4/license.html
# Author: Jack Diederich, Daniel Neuhäuser
# Local imports
from lib2to3 import fixer_base
from lib2to3.pygram import token
from lib2to3.fixer_util import Name, syms, Node, Leaf, touch_import, Call, \
String, Comma, parenthesize
def has_metaclass(parent):
""" we have to check the cls_node without changing it.
There are two possiblities:
1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
"""
for node in parent.children:
if node.type == syms.suite:
return has_metaclass(node)
elif node.type == syms.simple_stmt and node.children:
expr_node = node.children[0]
if expr_node.type == syms.expr_stmt and expr_node.children:
left_side = expr_node.children[0]
if isinstance(left_side, Leaf) and \
left_side.value == '__metaclass__':
return True
return False
def fixup_parse_tree(cls_node):
""" one-line classes don't get a suite in the parse tree so we add
one to normalize the tree
"""
for node in cls_node.children:
if node.type == syms.suite:
# already in the preferred format, do nothing
return
# !%@#! oneliners have no suite node, we have to fake one up
for i, node in enumerate(cls_node.children):
if node.type == token.COLON:
break
else:
raise ValueError("No class suite and no ':'!")
# move everything into a suite node
suite = Node(syms.suite, [])
while cls_node.children[i+1:]:
move_node = cls_node.children[i+1]
suite.append_child(move_node.clone())
move_node.remove()
cls_node.append_child(suite)
node = suite
def fixup_simple_stmt(parent, i, stmt_node):
""" if there is a semi-colon all the parts count as part of the same
simple_stmt. We just want the __metaclass__ part so we move
everything efter the semi-colon into its own simple_stmt node
"""
for semi_ind, node in enumerate(stmt_node.children):
if node.type == token.SEMI: # *sigh*
break
else:
return
node.remove() # kill the semicolon
new_expr = Node(syms.expr_stmt, [])
new_stmt = Node(syms.simple_stmt, [new_expr])
while stmt_node.children[semi_ind:]:
move_node = stmt_node.children[semi_ind]
new_expr.append_child(move_node.clone())
move_node.remove()
parent.insert_child(i, new_stmt)
new_leaf1 = new_stmt.children[0].children[0]
old_leaf1 = stmt_node.children[0].children[0]
new_leaf1.prefix = old_leaf1.prefix
def remove_trailing_newline(node):
if node.children and node.children[-1].type == token.NEWLINE:
node.children[-1].remove()
def find_metas(cls_node):
# find the suite node (Mmm, sweet nodes)
for node in cls_node.children:
if node.type == syms.suite:
break
else:
raise ValueError("No class suite!")
# look for simple_stmt[ expr_stmt[ Leaf('__metaclass__') ] ]
for i, simple_node in list(enumerate(node.children)):
if simple_node.type == syms.simple_stmt and simple_node.children:
expr_node = simple_node.children[0]
if expr_node.type == syms.expr_stmt and expr_node.children:
# Check if the expr_node is a simple assignment.
left_node = expr_node.children[0]
if isinstance(left_node, Leaf) and \
left_node.value == u'__metaclass__':
# We found a assignment to __metaclass__.
fixup_simple_stmt(node, i, simple_node)
remove_trailing_newline(simple_node)
yield (node, i, simple_node)
def fixup_indent(suite):
""" If an INDENT is followed by a thing with a prefix then nuke the prefix
Otherwise we get in trouble when removing __metaclass__ at suite start
"""
kids = suite.children[::-1]
# find the first indent
while kids:
node = kids.pop()
if node.type == token.INDENT:
break
# find the first Leaf
while kids:
node = kids.pop()
if isinstance(node, Leaf) and node.type != token.DEDENT:
if node.prefix:
node.prefix = u''
return
else:
kids.extend(node.children[::-1])
class FixMetaclass(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
classdef<any*>
"""
def transform(self, node, results):
if not has_metaclass(node):
return
fixup_parse_tree(node)
# find metaclasses, keep the last one
last_metaclass = None
for suite, i, stmt in find_metas(node):
last_metaclass = stmt
stmt.remove()
text_type = node.children[0].type # always Leaf(nnn, 'class')
# figure out what kind of classdef we have
if len(node.children) == 7:
# Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite])
# 0 1 2 3 4 5 6
if node.children[3].type == syms.arglist:
arglist = node.children[3]
# Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite])
else:
parent = node.children[3].clone()
arglist = Node(syms.arglist, [parent])
node.set_child(3, arglist)
elif len(node.children) == 6:
# Node(classdef, ['class', 'name', '(', ')', ':', suite])
# 0 1 2 3 4 5
arglist = Node(syms.arglist, [])
node.insert_child(3, arglist)
elif len(node.children) == 4:
# Node(classdef, ['class', 'name', ':', suite])
# 0 1 2 3
arglist = Node(syms.arglist, [])
node.insert_child(2, Leaf(token.RPAR, u')'))
node.insert_child(2, arglist)
node.insert_child(2, Leaf(token.LPAR, u'('))
else:
raise ValueError("Unexpected class definition")
# now stick the metaclass in the arglist
meta_txt = last_metaclass.children[0].children[0]
meta_txt.value = 'metaclass'
orig_meta_prefix = meta_txt.prefix
# Was: touch_import(None, u'future.utils', node)
touch_import(u'future.utils', u'with_metaclass', node)
metaclass = last_metaclass.children[0].children[2].clone()
metaclass.prefix = u''
arguments = [metaclass]
if arglist.children:
if len(arglist.children) == 1:
base = arglist.children[0].clone()
base.prefix = u' '
else:
# Unfortunately six.with_metaclass() only allows one base
# class, so we have to dynamically generate a base class if
# there is more than one.
bases = parenthesize(arglist.clone())
bases.prefix = u' '
base = Call(Name('type'), [
String("'NewBase'"),
Comma(),
bases,
Comma(),
Node(
syms.atom,
[Leaf(token.LBRACE, u'{'), Leaf(token.RBRACE, u'}')],
prefix=u' '
)
], prefix=u' ')
arguments.extend([Comma(), base])
arglist.replace(Call(
Name(u'with_metaclass', prefix=arglist.prefix),
arguments
))
fixup_indent(suite)
# check for empty suite
if not suite.children:
# one-liner that was just __metaclass_
suite.remove()
pass_leaf = Leaf(text_type, u'pass')
pass_leaf.prefix = orig_meta_prefix
node.append_child(pass_leaf)
node.append_child(Leaf(token.NEWLINE, u'\n'))
elif len(suite.children) > 1 and \
(suite.children[-2].type == token.INDENT and
suite.children[-1].type == token.DEDENT):
# there was only one line in the class body and it was __metaclass__
pass_leaf = Leaf(text_type, u'pass')
suite.insert_child(-1, pass_leaf)
suite.insert_child(-1, Leaf(token.NEWLINE, u'\n'))
| gpl-3.0 |
MechCoder/sympy | sympy/physics/mechanics/tests/test_lagrange.py | 45 | 9336 | from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
RigidBody, LagrangesMethod, Particle,
inertia, Lagrangian)
from sympy import symbols, pi, sin, cos, tan, simplify, Function, \
Derivative, Matrix
def test_disc_on_an_incline_plane():
# Disc rolling on an inclined plane
# First the generalized coordinates are created. The mass center of the
# disc is located from top vertex of the inclined plane by the generalized
# coordinate 'y'. The orientation of the disc is defined by the angle
# 'theta'. The mass of the disc is 'm' and its radius is 'R'. The length of
# the inclined path is 'l', the angle of inclination is 'alpha'. 'g' is the
# gravitational constant.
y, theta = dynamicsymbols('y theta')
yd, thetad = dynamicsymbols('y theta', 1)
m, g, R, l, alpha = symbols('m g R l alpha')
# Next, we create the inertial reference frame 'N'. A reference frame 'A'
# is attached to the inclined plane. Finally a frame is created which is attached to the disk.
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [pi/2 - alpha, N.z])
B = A.orientnew('B', 'Axis', [-theta, A.z])
# Creating the disc 'D'; we create the point that represents the mass
# center of the disc and set its velocity. The inertia dyadic of the disc
# is created. Finally, we create the disc.
Do = Point('Do')
Do.set_vel(N, yd * A.x)
I = m * R**2 / 2 * B.z | B.z
D = RigidBody('D', Do, B, m, (I, Do))
# To construct the Lagrangian, 'L', of the disc, we determine its kinetic
# and potential energies, T and U, respectively. L is defined as the
# difference between T and U.
D.potential_energy = m * g * (l - y) * sin(alpha)
L = Lagrangian(N, D)
# We then create the list of generalized coordinates and constraint
# equations. The constraint arises due to the disc rolling without slip on
# on the inclined path. We then invoke the 'LagrangesMethod' class and
# supply it the necessary arguments and generate the equations of motion.
# The'rhs' method solves for the q_double_dots (i.e. the second derivative
# with respect to time of the generalized coordinates and the lagrange
# multiplers.
q = [y, theta]
hol_coneqs = [y - R * theta]
m = LagrangesMethod(L, q, hol_coneqs=hol_coneqs)
m.form_lagranges_equations()
rhs = m.rhs()
rhs.simplify()
assert rhs[2] == 2*g*sin(alpha)/3
def test_simp_pen():
# This tests that the equations generated by LagrangesMethod are identical
# to those obtained by hand calculations. The system under consideration is
# the simple pendulum.
# We begin by creating the generalized coordinates as per the requirements
# of LagrangesMethod. Also we created the associate symbols
# that characterize the system: 'm' is the mass of the bob, l is the length
# of the massless rigid rod connecting the bob to a point O fixed in the
# inertial frame.
q, u = dynamicsymbols('q u')
qd, ud = dynamicsymbols('q u ', 1)
l, m, g = symbols('l m g')
# We then create the inertial frame and a frame attached to the massless
# string following which we define the inertial angular velocity of the
# string.
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q, N.z])
A.set_ang_vel(N, qd * N.z)
# Next, we create the point O and fix it in the inertial frame. We then
# locate the point P to which the bob is attached. Its corresponding
# velocity is then determined by the 'two point formula'.
O = Point('O')
O.set_vel(N, 0)
P = O.locatenew('P', l * A.x)
P.v2pt_theory(O, N, A)
# The 'Particle' which represents the bob is then created and its
# Lagrangian generated.
Pa = Particle('Pa', P, m)
Pa.potential_energy = - m * g * l * cos(q)
L = Lagrangian(N, Pa)
# The 'LagrangesMethod' class is invoked to obtain equations of motion.
lm = LagrangesMethod(L, [q])
lm.form_lagranges_equations()
RHS = lm.rhs()
assert RHS[1] == -g*sin(q)/l
def test_nonminimal_pendulum():
q1, q2 = dynamicsymbols('q1:3')
q1d, q2d = dynamicsymbols('q1:3', level=1)
L, m, t = symbols('L, m, t')
g = 9.8
# Compose World Frame
N = ReferenceFrame('N')
pN = Point('N*')
pN.set_vel(N, 0)
# Create point P, the pendulum mass
P = pN.locatenew('P1', q1*N.x + q2*N.y)
P.set_vel(N, P.pos_from(pN).dt(N))
pP = Particle('pP', P, m)
# Constraint Equations
f_c = Matrix([q1**2 + q2**2 - L**2])
# Calculate the lagrangian, and form the equations of motion
Lag = Lagrangian(N, pP)
LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c,
forcelist=[(P, m*g*N.x)], frame=N)
LM.form_lagranges_equations()
# Check solution
lam1 = LM.lam_vec[0, 0]
eom_sol = Matrix([[m*Derivative(q1, t, t) - 9.8*m + 2*lam1*q1],
[m*Derivative(q2, t, t) + 2*lam1*q2]])
assert LM.eom == eom_sol
# Check multiplier solution
lam_sol = Matrix([(19.6*q1 + 2*q1d**2 + 2*q2d**2)/(4*q1**2/m + 4*q2**2/m)])
assert LM.solve_multipliers(sol_type='Matrix') == lam_sol
def test_dub_pen():
# The system considered is the double pendulum. Like in the
# test of the simple pendulum above, we begin by creating the generalized
# coordinates and the simple generalized speeds and accelerations which
# will be used later. Following this we create frames and points necessary
# for the kinematics. The procedure isn't explicitly explained as this is
# similar to the simple pendulum. Also this is documented on the pydy.org
# website.
q1, q2 = dynamicsymbols('q1 q2')
q1d, q2d = dynamicsymbols('q1 q2', 1)
q1dd, q2dd = dynamicsymbols('q1 q2', 2)
u1, u2 = dynamicsymbols('u1 u2')
u1d, u2d = dynamicsymbols('u1 u2', 1)
l, m, g = symbols('l m g')
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = N.orientnew('B', 'Axis', [q2, N.z])
A.set_ang_vel(N, q1d * A.z)
B.set_ang_vel(N, q2d * A.z)
O = Point('O')
P = O.locatenew('P', l * A.x)
R = P.locatenew('R', l * B.x)
O.set_vel(N, 0)
P.v2pt_theory(O, N, A)
R.v2pt_theory(P, N, B)
ParP = Particle('ParP', P, m)
ParR = Particle('ParR', R, m)
ParP.potential_energy = - m * g * l * cos(q1)
ParR.potential_energy = - m * g * l * cos(q1) - m * g * l * cos(q2)
L = Lagrangian(N, ParP, ParR)
lm = LagrangesMethod(L, [q1, q2])
lm.form_lagranges_equations()
assert simplify(l*m*(2*g*sin(q1) + l*sin(q1)*sin(q2)*q2dd
+ l*sin(q1)*cos(q2)*q2d**2 - l*sin(q2)*cos(q1)*q2d**2
+ l*cos(q1)*cos(q2)*q2dd + 2*l*q1dd) - lm.eom[0]) == 0
assert simplify(l*m*(g*sin(q2) + l*sin(q1)*sin(q2)*q1dd
- l*sin(q1)*cos(q2)*q1d**2 + l*sin(q2)*cos(q1)*q1d**2
+ l*cos(q1)*cos(q2)*q1dd + l*q2dd) - lm.eom[1]) == 0
def test_rolling_disc():
# Rolling Disc Example
# Here the rolling disc is formed from the contact point up, removing the
# need to introduce generalized speeds. Only 3 configuration and 3
# speed variables are need to describe this system, along with the
# disc's mass and radius, and the local gravity.
q1, q2, q3 = dynamicsymbols('q1 q2 q3')
q1d, q2d, q3d = dynamicsymbols('q1 q2 q3', 1)
r, m, g = symbols('r m g')
# The kinematics are formed by a series of simple rotations. Each simple
# rotation creates a new frame, and the next rotation is defined by the new
# frame's basis vectors. This example uses a 3-1-2 series of rotations, or
# Z, X, Y series of rotations. Angular velocity for this is defined using
# the second frame's basis (the lean frame).
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
# This is the translational kinematics. We create a point with no velocity
# in N; this is the contact point between the disc and ground. Next we form
# the position vector from the contact point to the disc's center of mass.
# Finally we form the velocity and acceleration of the disc.
C = Point('C')
C.set_vel(N, 0)
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
# Forming the inertia dyadic.
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
# Finally we form the equations of motion, using the same steps we did
# before. Supply the Lagrangian, the generalized speeds.
BodyD.potential_energy = - m * g * r * cos(q2)
Lag = Lagrangian(N, BodyD)
q = [q1, q2, q3]
q1 = Function('q1')
q2 = Function('q2')
q3 = Function('q3')
l = LagrangesMethod(Lag, q)
l.form_lagranges_equations()
RHS = l.rhs()
RHS.simplify()
t = symbols('t')
assert (l.mass_matrix[3:6] == [0, 5*m*r**2/4, 0])
assert RHS[4].simplify() == (
(-8*g*sin(q2(t)) + r*(5*sin(2*q2(t))*Derivative(q1(t), t) +
12*cos(q2(t))*Derivative(q3(t), t))*Derivative(q1(t), t))/(10*r))
assert RHS[5] == (-5*cos(q2(t))*Derivative(q1(t), t) + 6*tan(q2(t)
)*Derivative(q3(t), t) + 4*Derivative(q1(t), t)/cos(q2(t))
)*Derivative(q2(t), t)
| bsd-3-clause |
Fat-Zer/FreeCAD_sf_master | src/Mod/Path/PathScripts/PathUtilsGui.py | 12 | 4259 | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2019 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library 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 FreeCADGui
import PathGui as PGui # ensure Path/Gui/Resources are loaded
import PathScripts
import PathScripts.PathJobCmd as PathJobCmd
import PathScripts.PathUtils as PathUtils
class PathUtilsUserInput(object):
def selectedToolController(self):
tc = None
# check if a user has selected a tool controller in the tree.
# Return the first one and remove all from selection
for sel in FreeCADGui.Selection.getSelectionEx():
if hasattr(sel.Object, 'Proxy'):
if isinstance(sel.Object.Proxy, PathScripts.PathToolController.ToolController):
if tc is None:
tc = sel.Object
FreeCADGui.Selection.removeSelection(sel.Object)
return tc
def chooseToolController(self, controllers):
form = FreeCADGui.PySideUic.loadUi(":/panels/DlgTCChooser.ui")
mylist = [i.Label for i in controllers]
form.uiToolController.addItems(mylist)
r = form.exec_()
if not r:
return None
return [i for i in controllers if i.Label == form.uiToolController.currentText()][0]
def chooseJob(self, jobs):
job = None
selected = FreeCADGui.Selection.getSelection()
if 1 == len(selected) and selected[0] in jobs:
job = selected[0]
else:
modelSelected = []
for job in jobs:
if all([o in job.Model.Group for o in selected]):
modelSelected.append(job)
if 1 == len(modelSelected):
job = modelSelected[0]
else:
modelObjectSelected = []
for job in jobs:
if all([o in job.Proxy.baseObjects(job) for o in selected]):
modelObjectSelected.append(job)
if 1 == len(modelObjectSelected):
job = modelObjectSelected[0]
else:
form = FreeCADGui.PySideUic.loadUi(":/panels/DlgJobChooser.ui")
if modelObjectSelected:
mylist = [j.Label for j in modelObjectSelected]
else:
mylist = [j.Label for j in jobs]
form.cboProject.addItems(mylist)
r = form.exec_()
if r is False or r == 0:
return None
else:
job = [j for j in jobs if j.Label == form.cboProject.currentText()][0]
return job
def createJob(self):
return PathJobCmd.CommandJobCreate().Activated()
PathUtils.UserInput = PathUtilsUserInput()
| lgpl-2.1 |
JohnGriffiths/nipype | nipype/interfaces/fsl/tests/test_auto_InvWarp.py | 9 | 1542 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.fsl.utils import InvWarp
def test_InvWarp_inputs():
input_map = dict(absolute=dict(argstr='--abs',
xor=['relative'],
),
args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
inverse_warp=dict(argstr='--out=%s',
hash_files=False,
name_source=['warp'],
name_template='%s_inverse',
),
jacobian_max=dict(argstr='--jmax=%f',
),
jacobian_min=dict(argstr='--jmin=%f',
),
niter=dict(argstr='--niter=%d',
),
noconstraint=dict(argstr='--noconstraint',
),
output_type=dict(),
reference=dict(argstr='--ref=%s',
mandatory=True,
),
regularise=dict(argstr='--regularise=%f',
),
relative=dict(argstr='--rel',
xor=['absolute'],
),
terminal_output=dict(nohash=True,
),
warp=dict(argstr='--warp=%s',
mandatory=True,
),
)
inputs = InvWarp.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_InvWarp_outputs():
output_map = dict(inverse_warp=dict(),
)
outputs = InvWarp.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| bsd-3-clause |
theo-l/django | django/utils/lorem_ipsum.py | 130 | 4775 | """
Utility functions for generating "lorem ipsum" Latin text.
"""
import random
COMMON_P = (
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod '
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim '
'veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea '
'commodo consequat. Duis aute irure dolor in reprehenderit in voluptate '
'velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint '
'occaecat cupidatat non proident, sunt in culpa qui officia deserunt '
'mollit anim id est laborum.'
)
WORDS = (
'exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet',
'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi',
'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi',
'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos',
'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum',
'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus',
'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus',
'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum',
'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem',
'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus',
'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente',
'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet',
'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta',
'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima',
'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim',
'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores',
'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias',
'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea',
'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt',
'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate',
'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius',
'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos',
'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore',
'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo',
'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi',
'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam',
'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique',
'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere',
'maxime', 'corrupti',
)
COMMON_WORDS = (
'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt',
'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua',
)
def sentence():
"""
Return a randomly generated sentence of lorem ipsum text.
The first word is capitalized, and the sentence ends in either a period or
question mark. Commas are added at random.
"""
# Determine the number of comma-separated sections and number of words in
# each section for this sentence.
sections = [' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))]
s = ', '.join(sections)
# Convert to sentence case and add end punctuation.
return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.'))
def paragraph():
"""
Return a randomly generated paragraph of lorem ipsum text.
The paragraph consists of between 1 and 4 sentences, inclusive.
"""
return ' '.join(sentence() for i in range(random.randint(1, 4)))
def paragraphs(count, common=True):
"""
Return a list of paragraphs as returned by paragraph().
If `common` is True, then the first paragraph will be the standard
'lorem ipsum' paragraph. Otherwise, the first paragraph will be random
Latin text. Either way, subsequent paragraphs will be random Latin text.
"""
paras = []
for i in range(count):
if common and i == 0:
paras.append(COMMON_P)
else:
paras.append(paragraph())
return paras
def words(count, common=True):
"""
Return a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
'lorem ipsum' words. Otherwise, all words will be selected randomly.
"""
word_list = list(COMMON_WORDS) if common else []
c = len(word_list)
if count > c:
count -= c
while count > 0:
c = min(count, len(WORDS))
count -= c
word_list += random.sample(WORDS, c)
else:
word_list = word_list[:count]
return ' '.join(word_list)
| bsd-3-clause |
dknlght/dkodi | src/plugin.video.india4movie/resources/lib/api.py | 1 | 4287 | import resources.lib.util as util
import re
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup
from BeautifulSoup import SoupStrainer
class SiteApi():
MAIN_URL = 'http://www.india4movie.com/'
LONG_NAME = 'India 4 Movie'
def get_menu_category(self):
'''
Get main list of categories
'''
print 'Get list categories'
url = self.MAIN_URL
data = util.get_remote_data(url)
product = SoupStrainer('div', {'class': 'menu-secondary-container'})
soup = BeautifulStoneSoup(data, parseOnlyThese=product,
convertEntities=BeautifulSoup.XML_ENTITIES)
items = []
for item in soup.findAll('li'):
link = item.a['href'].encode('utf-8', 'ignore')
pk = item['id']
items.append({
'label': item.text,
'url': link,
'pk': pk,
})
return items
def get_menu_movies(self, url):
'''
Get movie titles for category
'''
print 'Get list movies: {url}'.format(url=url)
data = util.get_remote_data(url)
# Get list of movie titles
product = SoupStrainer('div', {'class': 'entry clearfix'})
soup = BeautifulStoneSoup(data, parseOnlyThese=product,
convertEntities=BeautifulSoup.XML_ENTITIES)
items = []
pk_regex = re.compile('\/([\w\-]+)\/')
for item in soup:
link = item.a['href'].encode('utf-8', 'ignore')
thumb = item.a.img['src'].encode('utf-8', 'ignore')
info = item.p.text
pk = pk_regex.search(item.a['href']).group(1)
items.append({
'label': item.text,
'url': link,
'thumb': thumb,
'info': info,
'pk': pk,
'is_playable': False
})
return items
def get_next_link(self, url):
'''
Get next page link
'''
print 'Get next page link: {url}'.format(url=url)
data = util.get_remote_data(url)
# Get list of movie titles
product = SoupStrainer('div', {'class': 'wp-pagenavi'})
soup = BeautifulStoneSoup(data, parseOnlyThese=product,
convertEntities=BeautifulSoup.XML_ENTITIES)
current_item = soup.find('span', {'class': 'current'})
if current_item:
next_item = current_item.findNextSibling()
item = {
'label': '[B]Next >> [/B]',
'url': next_item['href'],
'pk': next_item.text
}
return item
return None
def get_movie_links(self, url):
print 'Get movie links: {url}'.format(url=url)
data = util.get_remote_data(url)
product = SoupStrainer('a', href=re.compile("^http\:\/\/www\.power4link\.us"))
soup = BeautifulStoneSoup(data, parseOnlyThese=product,
convertEntities=BeautifulSoup.XML_ENTITIES)
items = []
pk_regex = re.compile('.*\/.*-(.*)\/')
for a in soup:
if a.text.startswith('Play'):
link = a['href'].encode('utf-8', 'ignore')
match = pk_regex.search(link)
if match:
label = match.group(1)
pk = label
items.append({
'label': label,
'url': link,
'pk': pk,
'is_playable': True
})
return items
def resolve_redirect(self, url):
print 'Resolving redirect: {url}'.format(url=url)
data = util.get_remote_data(url)
product = SoupStrainer('iframe')
soup = BeautifulStoneSoup(data, parseOnlyThese=product,
convertEntities=BeautifulSoup.XML_ENTITIES)
if soup.iframe:
return soup.iframe['src']
return None
| gpl-2.0 |
ToontownUprising/src | toontown/coghq/LawbotOfficeDiamondRoom_Battle00_Cogs.py | 10 | 1124 | from SpecImports import *
from toontown.toonbase import ToontownGlobals
CogParent = 10000
BattlePlace1 = 10000
BattleCellId = 0
BattleCells = {BattleCellId: {'parentEntId': BattlePlace1,
'pos': Point3(0, 0, 0)}}
CogData = [{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel,
'battleCell': BattleCellId,
'pos': Point3(-8, 4, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 1},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel + 1,
'battleCell': BattleCellId,
'pos': Point3(-3, 4, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 1},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel,
'battleCell': BattleCellId,
'pos': Point3(3, 4, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 1},
{'parentEntId': CogParent,
'boss': 0,
'level': ToontownGlobals.CashbotMintCogLevel + 1,
'battleCell': BattleCellId,
'pos': Point3(8, 4, 0),
'h': 180,
'behavior': 'stand',
'path': None,
'skeleton': 1}]
ReserveCogData = []
| mit |
nzavagli/UnrealPy | UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Lib/lib2to3/tests/test_fixers.py | 27 | 122213 | """ Test suite for the fixer modules """
# Python imports
import os
import unittest
from itertools import chain
from operator import itemgetter
# Local imports
from lib2to3 import pygram, pytree, refactor, fixer_util
from lib2to3.tests import support
class FixerTestCase(support.TestCase):
# Other test cases can subclass this class and replace "fixer_pkg" with
# their own.
def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None):
if fix_list is None:
fix_list = [self.fixer]
self.refactor = support.get_refactorer(fixer_pkg, fix_list, options)
self.fixer_log = []
self.filename = u"<string>"
for fixer in chain(self.refactor.pre_order,
self.refactor.post_order):
fixer.log = self.fixer_log
def _check(self, before, after):
before = support.reformat(before)
after = support.reformat(after)
tree = self.refactor.refactor_string(before, self.filename)
self.assertEqual(after, unicode(tree))
return tree
def check(self, before, after, ignore_warnings=False):
tree = self._check(before, after)
self.assertTrue(tree.was_changed)
if not ignore_warnings:
self.assertEqual(self.fixer_log, [])
def warns(self, before, after, message, unchanged=False):
tree = self._check(before, after)
self.assertIn(message, "".join(self.fixer_log))
if not unchanged:
self.assertTrue(tree.was_changed)
def warns_unchanged(self, before, message):
self.warns(before, before, message, unchanged=True)
def unchanged(self, before, ignore_warnings=False):
self._check(before, before)
if not ignore_warnings:
self.assertEqual(self.fixer_log, [])
def assert_runs_after(self, *names):
fixes = [self.fixer]
fixes.extend(names)
r = support.get_refactorer("lib2to3", fixes)
(pre, post) = r.get_fixers()
n = "fix_" + self.fixer
if post and post[-1].__class__.__module__.endswith(n):
# We're the last fixer to run
return
if pre and pre[-1].__class__.__module__.endswith(n) and not post:
# We're the last in pre and post is empty
return
self.fail("Fixer run order (%s) is incorrect; %s should be last."\
%(", ".join([x.__class__.__module__ for x in (pre+post)]), n))
class Test_ne(FixerTestCase):
fixer = "ne"
def test_basic(self):
b = """if x <> y:
pass"""
a = """if x != y:
pass"""
self.check(b, a)
def test_no_spaces(self):
b = """if x<>y:
pass"""
a = """if x!=y:
pass"""
self.check(b, a)
def test_chained(self):
b = """if x<>y<>z:
pass"""
a = """if x!=y!=z:
pass"""
self.check(b, a)
class Test_has_key(FixerTestCase):
fixer = "has_key"
def test_1(self):
b = """x = d.has_key("x") or d.has_key("y")"""
a = """x = "x" in d or "y" in d"""
self.check(b, a)
def test_2(self):
b = """x = a.b.c.d.has_key("x") ** 3"""
a = """x = ("x" in a.b.c.d) ** 3"""
self.check(b, a)
def test_3(self):
b = """x = a.b.has_key(1 + 2).__repr__()"""
a = """x = (1 + 2 in a.b).__repr__()"""
self.check(b, a)
def test_4(self):
b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4"""
a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4"""
self.check(b, a)
def test_5(self):
b = """x = a.has_key(f or g)"""
a = """x = (f or g) in a"""
self.check(b, a)
def test_6(self):
b = """x = a + b.has_key(c)"""
a = """x = a + (c in b)"""
self.check(b, a)
def test_7(self):
b = """x = a.has_key(lambda: 12)"""
a = """x = (lambda: 12) in a"""
self.check(b, a)
def test_8(self):
b = """x = a.has_key(a for a in b)"""
a = """x = (a for a in b) in a"""
self.check(b, a)
def test_9(self):
b = """if not a.has_key(b): pass"""
a = """if b not in a: pass"""
self.check(b, a)
def test_10(self):
b = """if not a.has_key(b).__repr__(): pass"""
a = """if not (b in a).__repr__(): pass"""
self.check(b, a)
def test_11(self):
b = """if not a.has_key(b) ** 2: pass"""
a = """if not (b in a) ** 2: pass"""
self.check(b, a)
class Test_apply(FixerTestCase):
fixer = "apply"
def test_1(self):
b = """x = apply(f, g + h)"""
a = """x = f(*g + h)"""
self.check(b, a)
def test_2(self):
b = """y = apply(f, g, h)"""
a = """y = f(*g, **h)"""
self.check(b, a)
def test_3(self):
b = """z = apply(fs[0], g or h, h or g)"""
a = """z = fs[0](*g or h, **h or g)"""
self.check(b, a)
def test_4(self):
b = """apply(f, (x, y) + t)"""
a = """f(*(x, y) + t)"""
self.check(b, a)
def test_5(self):
b = """apply(f, args,)"""
a = """f(*args)"""
self.check(b, a)
def test_6(self):
b = """apply(f, args, kwds,)"""
a = """f(*args, **kwds)"""
self.check(b, a)
# Test that complex functions are parenthesized
def test_complex_1(self):
b = """x = apply(f+g, args)"""
a = """x = (f+g)(*args)"""
self.check(b, a)
def test_complex_2(self):
b = """x = apply(f*g, args)"""
a = """x = (f*g)(*args)"""
self.check(b, a)
def test_complex_3(self):
b = """x = apply(f**g, args)"""
a = """x = (f**g)(*args)"""
self.check(b, a)
# But dotted names etc. not
def test_dotted_name(self):
b = """x = apply(f.g, args)"""
a = """x = f.g(*args)"""
self.check(b, a)
def test_subscript(self):
b = """x = apply(f[x], args)"""
a = """x = f[x](*args)"""
self.check(b, a)
def test_call(self):
b = """x = apply(f(), args)"""
a = """x = f()(*args)"""
self.check(b, a)
# Extreme case
def test_extreme(self):
b = """x = apply(a.b.c.d.e.f, args, kwds)"""
a = """x = a.b.c.d.e.f(*args, **kwds)"""
self.check(b, a)
# XXX Comments in weird places still get lost
def test_weird_comments(self):
b = """apply( # foo
f, # bar
args)"""
a = """f(*args)"""
self.check(b, a)
# These should *not* be touched
def test_unchanged_1(self):
s = """apply()"""
self.unchanged(s)
def test_unchanged_2(self):
s = """apply(f)"""
self.unchanged(s)
def test_unchanged_3(self):
s = """apply(f,)"""
self.unchanged(s)
def test_unchanged_4(self):
s = """apply(f, args, kwds, extras)"""
self.unchanged(s)
def test_unchanged_5(self):
s = """apply(f, *args, **kwds)"""
self.unchanged(s)
def test_unchanged_6(self):
s = """apply(f, *args)"""
self.unchanged(s)
def test_unchanged_7(self):
s = """apply(func=f, args=args, kwds=kwds)"""
self.unchanged(s)
def test_unchanged_8(self):
s = """apply(f, args=args, kwds=kwds)"""
self.unchanged(s)
def test_unchanged_9(self):
s = """apply(f, args, kwds=kwds)"""
self.unchanged(s)
def test_space_1(self):
a = """apply( f, args, kwds)"""
b = """f(*args, **kwds)"""
self.check(a, b)
def test_space_2(self):
a = """apply( f ,args,kwds )"""
b = """f(*args, **kwds)"""
self.check(a, b)
class Test_intern(FixerTestCase):
fixer = "intern"
def test_prefix_preservation(self):
b = """x = intern( a )"""
a = """import sys\nx = sys.intern( a )"""
self.check(b, a)
b = """y = intern("b" # test
)"""
a = """import sys\ny = sys.intern("b" # test
)"""
self.check(b, a)
b = """z = intern(a+b+c.d, )"""
a = """import sys\nz = sys.intern(a+b+c.d, )"""
self.check(b, a)
def test(self):
b = """x = intern(a)"""
a = """import sys\nx = sys.intern(a)"""
self.check(b, a)
b = """z = intern(a+b+c.d,)"""
a = """import sys\nz = sys.intern(a+b+c.d,)"""
self.check(b, a)
b = """intern("y%s" % 5).replace("y", "")"""
a = """import sys\nsys.intern("y%s" % 5).replace("y", "")"""
self.check(b, a)
# These should not be refactored
def test_unchanged(self):
s = """intern(a=1)"""
self.unchanged(s)
s = """intern(f, g)"""
self.unchanged(s)
s = """intern(*h)"""
self.unchanged(s)
s = """intern(**i)"""
self.unchanged(s)
s = """intern()"""
self.unchanged(s)
class Test_reduce(FixerTestCase):
fixer = "reduce"
def test_simple_call(self):
b = "reduce(a, b, c)"
a = "from functools import reduce\nreduce(a, b, c)"
self.check(b, a)
def test_bug_7253(self):
# fix_tuple_params was being bad and orphaning nodes in the tree.
b = "def x(arg): reduce(sum, [])"
a = "from functools import reduce\ndef x(arg): reduce(sum, [])"
self.check(b, a)
def test_call_with_lambda(self):
b = "reduce(lambda x, y: x + y, seq)"
a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)"
self.check(b, a)
def test_unchanged(self):
s = "reduce(a)"
self.unchanged(s)
s = "reduce(a, b=42)"
self.unchanged(s)
s = "reduce(a, b, c, d)"
self.unchanged(s)
s = "reduce(**c)"
self.unchanged(s)
s = "reduce()"
self.unchanged(s)
class Test_print(FixerTestCase):
fixer = "print"
def test_prefix_preservation(self):
b = """print 1, 1+1, 1+1+1"""
a = """print(1, 1+1, 1+1+1)"""
self.check(b, a)
def test_idempotency(self):
s = """print()"""
self.unchanged(s)
s = """print('')"""
self.unchanged(s)
def test_idempotency_print_as_function(self):
self.refactor.driver.grammar = pygram.python_grammar_no_print_statement
s = """print(1, 1+1, 1+1+1)"""
self.unchanged(s)
s = """print()"""
self.unchanged(s)
s = """print('')"""
self.unchanged(s)
def test_1(self):
b = """print 1, 1+1, 1+1+1"""
a = """print(1, 1+1, 1+1+1)"""
self.check(b, a)
def test_2(self):
b = """print 1, 2"""
a = """print(1, 2)"""
self.check(b, a)
def test_3(self):
b = """print"""
a = """print()"""
self.check(b, a)
def test_4(self):
# from bug 3000
b = """print whatever; print"""
a = """print(whatever); print()"""
self.check(b, a)
def test_5(self):
b = """print; print whatever;"""
a = """print(); print(whatever);"""
self.check(b, a)
def test_tuple(self):
b = """print (a, b, c)"""
a = """print((a, b, c))"""
self.check(b, a)
# trailing commas
def test_trailing_comma_1(self):
b = """print 1, 2, 3,"""
a = """print(1, 2, 3, end=' ')"""
self.check(b, a)
def test_trailing_comma_2(self):
b = """print 1, 2,"""
a = """print(1, 2, end=' ')"""
self.check(b, a)
def test_trailing_comma_3(self):
b = """print 1,"""
a = """print(1, end=' ')"""
self.check(b, a)
# >> stuff
def test_vargs_without_trailing_comma(self):
b = """print >>sys.stderr, 1, 2, 3"""
a = """print(1, 2, 3, file=sys.stderr)"""
self.check(b, a)
def test_with_trailing_comma(self):
b = """print >>sys.stderr, 1, 2,"""
a = """print(1, 2, end=' ', file=sys.stderr)"""
self.check(b, a)
def test_no_trailing_comma(self):
b = """print >>sys.stderr, 1+1"""
a = """print(1+1, file=sys.stderr)"""
self.check(b, a)
def test_spaces_before_file(self):
b = """print >> sys.stderr"""
a = """print(file=sys.stderr)"""
self.check(b, a)
def test_with_future_print_function(self):
s = "from __future__ import print_function\n" \
"print('Hai!', end=' ')"
self.unchanged(s)
b = "print 'Hello, world!'"
a = "print('Hello, world!')"
self.check(b, a)
class Test_exec(FixerTestCase):
fixer = "exec"
def test_prefix_preservation(self):
b = """ exec code in ns1, ns2"""
a = """ exec(code, ns1, ns2)"""
self.check(b, a)
def test_basic(self):
b = """exec code"""
a = """exec(code)"""
self.check(b, a)
def test_with_globals(self):
b = """exec code in ns"""
a = """exec(code, ns)"""
self.check(b, a)
def test_with_globals_locals(self):
b = """exec code in ns1, ns2"""
a = """exec(code, ns1, ns2)"""
self.check(b, a)
def test_complex_1(self):
b = """exec (a.b()) in ns"""
a = """exec((a.b()), ns)"""
self.check(b, a)
def test_complex_2(self):
b = """exec a.b() + c in ns"""
a = """exec(a.b() + c, ns)"""
self.check(b, a)
# These should not be touched
def test_unchanged_1(self):
s = """exec(code)"""
self.unchanged(s)
def test_unchanged_2(self):
s = """exec (code)"""
self.unchanged(s)
def test_unchanged_3(self):
s = """exec(code, ns)"""
self.unchanged(s)
def test_unchanged_4(self):
s = """exec(code, ns1, ns2)"""
self.unchanged(s)
class Test_repr(FixerTestCase):
fixer = "repr"
def test_prefix_preservation(self):
b = """x = `1 + 2`"""
a = """x = repr(1 + 2)"""
self.check(b, a)
def test_simple_1(self):
b = """x = `1 + 2`"""
a = """x = repr(1 + 2)"""
self.check(b, a)
def test_simple_2(self):
b = """y = `x`"""
a = """y = repr(x)"""
self.check(b, a)
def test_complex(self):
b = """z = `y`.__repr__()"""
a = """z = repr(y).__repr__()"""
self.check(b, a)
def test_tuple(self):
b = """x = `1, 2, 3`"""
a = """x = repr((1, 2, 3))"""
self.check(b, a)
def test_nested(self):
b = """x = `1 + `2``"""
a = """x = repr(1 + repr(2))"""
self.check(b, a)
def test_nested_tuples(self):
b = """x = `1, 2 + `3, 4``"""
a = """x = repr((1, 2 + repr((3, 4))))"""
self.check(b, a)
class Test_except(FixerTestCase):
fixer = "except"
def test_prefix_preservation(self):
b = """
try:
pass
except (RuntimeError, ImportError), e:
pass"""
a = """
try:
pass
except (RuntimeError, ImportError) as e:
pass"""
self.check(b, a)
def test_simple(self):
b = """
try:
pass
except Foo, e:
pass"""
a = """
try:
pass
except Foo as e:
pass"""
self.check(b, a)
def test_simple_no_space_before_target(self):
b = """
try:
pass
except Foo,e:
pass"""
a = """
try:
pass
except Foo as e:
pass"""
self.check(b, a)
def test_tuple_unpack(self):
b = """
def foo():
try:
pass
except Exception, (f, e):
pass
except ImportError, e:
pass"""
a = """
def foo():
try:
pass
except Exception as xxx_todo_changeme:
(f, e) = xxx_todo_changeme.args
pass
except ImportError as e:
pass"""
self.check(b, a)
def test_multi_class(self):
b = """
try:
pass
except (RuntimeError, ImportError), e:
pass"""
a = """
try:
pass
except (RuntimeError, ImportError) as e:
pass"""
self.check(b, a)
def test_list_unpack(self):
b = """
try:
pass
except Exception, [a, b]:
pass"""
a = """
try:
pass
except Exception as xxx_todo_changeme:
[a, b] = xxx_todo_changeme.args
pass"""
self.check(b, a)
def test_weird_target_1(self):
b = """
try:
pass
except Exception, d[5]:
pass"""
a = """
try:
pass
except Exception as xxx_todo_changeme:
d[5] = xxx_todo_changeme
pass"""
self.check(b, a)
def test_weird_target_2(self):
b = """
try:
pass
except Exception, a.foo:
pass"""
a = """
try:
pass
except Exception as xxx_todo_changeme:
a.foo = xxx_todo_changeme
pass"""
self.check(b, a)
def test_weird_target_3(self):
b = """
try:
pass
except Exception, a().foo:
pass"""
a = """
try:
pass
except Exception as xxx_todo_changeme:
a().foo = xxx_todo_changeme
pass"""
self.check(b, a)
def test_bare_except(self):
b = """
try:
pass
except Exception, a:
pass
except:
pass"""
a = """
try:
pass
except Exception as a:
pass
except:
pass"""
self.check(b, a)
def test_bare_except_and_else_finally(self):
b = """
try:
pass
except Exception, a:
pass
except:
pass
else:
pass
finally:
pass"""
a = """
try:
pass
except Exception as a:
pass
except:
pass
else:
pass
finally:
pass"""
self.check(b, a)
def test_multi_fixed_excepts_before_bare_except(self):
b = """
try:
pass
except TypeError, b:
pass
except Exception, a:
pass
except:
pass"""
a = """
try:
pass
except TypeError as b:
pass
except Exception as a:
pass
except:
pass"""
self.check(b, a)
def test_one_line_suites(self):
b = """
try: raise TypeError
except TypeError, e:
pass
"""
a = """
try: raise TypeError
except TypeError as e:
pass
"""
self.check(b, a)
b = """
try:
raise TypeError
except TypeError, e: pass
"""
a = """
try:
raise TypeError
except TypeError as e: pass
"""
self.check(b, a)
b = """
try: raise TypeError
except TypeError, e: pass
"""
a = """
try: raise TypeError
except TypeError as e: pass
"""
self.check(b, a)
b = """
try: raise TypeError
except TypeError, e: pass
else: function()
finally: done()
"""
a = """
try: raise TypeError
except TypeError as e: pass
else: function()
finally: done()
"""
self.check(b, a)
# These should not be touched:
def test_unchanged_1(self):
s = """
try:
pass
except:
pass"""
self.unchanged(s)
def test_unchanged_2(self):
s = """
try:
pass
except Exception:
pass"""
self.unchanged(s)
def test_unchanged_3(self):
s = """
try:
pass
except (Exception, SystemExit):
pass"""
self.unchanged(s)
class Test_raise(FixerTestCase):
fixer = "raise"
def test_basic(self):
b = """raise Exception, 5"""
a = """raise Exception(5)"""
self.check(b, a)
def test_prefix_preservation(self):
b = """raise Exception,5"""
a = """raise Exception(5)"""
self.check(b, a)
b = """raise Exception, 5"""
a = """raise Exception(5)"""
self.check(b, a)
def test_with_comments(self):
b = """raise Exception, 5 # foo"""
a = """raise Exception(5) # foo"""
self.check(b, a)
b = """raise E, (5, 6) % (a, b) # foo"""
a = """raise E((5, 6) % (a, b)) # foo"""
self.check(b, a)
b = """def foo():
raise Exception, 5, 6 # foo"""
a = """def foo():
raise Exception(5).with_traceback(6) # foo"""
self.check(b, a)
def test_None_value(self):
b = """raise Exception(5), None, tb"""
a = """raise Exception(5).with_traceback(tb)"""
self.check(b, a)
def test_tuple_value(self):
b = """raise Exception, (5, 6, 7)"""
a = """raise Exception(5, 6, 7)"""
self.check(b, a)
def test_tuple_detection(self):
b = """raise E, (5, 6) % (a, b)"""
a = """raise E((5, 6) % (a, b))"""
self.check(b, a)
def test_tuple_exc_1(self):
b = """raise (((E1, E2), E3), E4), V"""
a = """raise E1(V)"""
self.check(b, a)
def test_tuple_exc_2(self):
b = """raise (E1, (E2, E3), E4), V"""
a = """raise E1(V)"""
self.check(b, a)
# These should produce a warning
def test_string_exc(self):
s = """raise 'foo'"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
def test_string_exc_val(self):
s = """raise "foo", 5"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
def test_string_exc_val_tb(self):
s = """raise "foo", 5, 6"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
# These should result in traceback-assignment
def test_tb_1(self):
b = """def foo():
raise Exception, 5, 6"""
a = """def foo():
raise Exception(5).with_traceback(6)"""
self.check(b, a)
def test_tb_2(self):
b = """def foo():
a = 5
raise Exception, 5, 6
b = 6"""
a = """def foo():
a = 5
raise Exception(5).with_traceback(6)
b = 6"""
self.check(b, a)
def test_tb_3(self):
b = """def foo():
raise Exception,5,6"""
a = """def foo():
raise Exception(5).with_traceback(6)"""
self.check(b, a)
def test_tb_4(self):
b = """def foo():
a = 5
raise Exception,5,6
b = 6"""
a = """def foo():
a = 5
raise Exception(5).with_traceback(6)
b = 6"""
self.check(b, a)
def test_tb_5(self):
b = """def foo():
raise Exception, (5, 6, 7), 6"""
a = """def foo():
raise Exception(5, 6, 7).with_traceback(6)"""
self.check(b, a)
def test_tb_6(self):
b = """def foo():
a = 5
raise Exception, (5, 6, 7), 6
b = 6"""
a = """def foo():
a = 5
raise Exception(5, 6, 7).with_traceback(6)
b = 6"""
self.check(b, a)
class Test_throw(FixerTestCase):
fixer = "throw"
def test_1(self):
b = """g.throw(Exception, 5)"""
a = """g.throw(Exception(5))"""
self.check(b, a)
def test_2(self):
b = """g.throw(Exception,5)"""
a = """g.throw(Exception(5))"""
self.check(b, a)
def test_3(self):
b = """g.throw(Exception, (5, 6, 7))"""
a = """g.throw(Exception(5, 6, 7))"""
self.check(b, a)
def test_4(self):
b = """5 + g.throw(Exception, 5)"""
a = """5 + g.throw(Exception(5))"""
self.check(b, a)
# These should produce warnings
def test_warn_1(self):
s = """g.throw("foo")"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
def test_warn_2(self):
s = """g.throw("foo", 5)"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
def test_warn_3(self):
s = """g.throw("foo", 5, 6)"""
self.warns_unchanged(s, "Python 3 does not support string exceptions")
# These should not be touched
def test_untouched_1(self):
s = """g.throw(Exception)"""
self.unchanged(s)
def test_untouched_2(self):
s = """g.throw(Exception(5, 6))"""
self.unchanged(s)
def test_untouched_3(self):
s = """5 + g.throw(Exception(5, 6))"""
self.unchanged(s)
# These should result in traceback-assignment
def test_tb_1(self):
b = """def foo():
g.throw(Exception, 5, 6)"""
a = """def foo():
g.throw(Exception(5).with_traceback(6))"""
self.check(b, a)
def test_tb_2(self):
b = """def foo():
a = 5
g.throw(Exception, 5, 6)
b = 6"""
a = """def foo():
a = 5
g.throw(Exception(5).with_traceback(6))
b = 6"""
self.check(b, a)
def test_tb_3(self):
b = """def foo():
g.throw(Exception,5,6)"""
a = """def foo():
g.throw(Exception(5).with_traceback(6))"""
self.check(b, a)
def test_tb_4(self):
b = """def foo():
a = 5
g.throw(Exception,5,6)
b = 6"""
a = """def foo():
a = 5
g.throw(Exception(5).with_traceback(6))
b = 6"""
self.check(b, a)
def test_tb_5(self):
b = """def foo():
g.throw(Exception, (5, 6, 7), 6)"""
a = """def foo():
g.throw(Exception(5, 6, 7).with_traceback(6))"""
self.check(b, a)
def test_tb_6(self):
b = """def foo():
a = 5
g.throw(Exception, (5, 6, 7), 6)
b = 6"""
a = """def foo():
a = 5
g.throw(Exception(5, 6, 7).with_traceback(6))
b = 6"""
self.check(b, a)
def test_tb_7(self):
b = """def foo():
a + g.throw(Exception, 5, 6)"""
a = """def foo():
a + g.throw(Exception(5).with_traceback(6))"""
self.check(b, a)
def test_tb_8(self):
b = """def foo():
a = 5
a + g.throw(Exception, 5, 6)
b = 6"""
a = """def foo():
a = 5
a + g.throw(Exception(5).with_traceback(6))
b = 6"""
self.check(b, a)
class Test_long(FixerTestCase):
fixer = "long"
def test_1(self):
b = """x = long(x)"""
a = """x = int(x)"""
self.check(b, a)
def test_2(self):
b = """y = isinstance(x, long)"""
a = """y = isinstance(x, int)"""
self.check(b, a)
def test_3(self):
b = """z = type(x) in (int, long)"""
a = """z = type(x) in (int, int)"""
self.check(b, a)
def test_unchanged(self):
s = """long = True"""
self.unchanged(s)
s = """s.long = True"""
self.unchanged(s)
s = """def long(): pass"""
self.unchanged(s)
s = """class long(): pass"""
self.unchanged(s)
s = """def f(long): pass"""
self.unchanged(s)
s = """def f(g, long): pass"""
self.unchanged(s)
s = """def f(x, long=True): pass"""
self.unchanged(s)
def test_prefix_preservation(self):
b = """x = long( x )"""
a = """x = int( x )"""
self.check(b, a)
class Test_execfile(FixerTestCase):
fixer = "execfile"
def test_conversion(self):
b = """execfile("fn")"""
a = """exec(compile(open("fn").read(), "fn", 'exec'))"""
self.check(b, a)
b = """execfile("fn", glob)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)"""
self.check(b, a)
b = """execfile("fn", glob, loc)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)"""
self.check(b, a)
b = """execfile("fn", globals=glob)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)"""
self.check(b, a)
b = """execfile("fn", locals=loc)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)"""
self.check(b, a)
b = """execfile("fn", globals=glob, locals=loc)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)"""
self.check(b, a)
def test_spacing(self):
b = """execfile( "fn" )"""
a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))"""
self.check(b, a)
b = """execfile("fn", globals = glob)"""
a = """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)"""
self.check(b, a)
class Test_isinstance(FixerTestCase):
fixer = "isinstance"
def test_remove_multiple_items(self):
b = """isinstance(x, (int, int, int))"""
a = """isinstance(x, int)"""
self.check(b, a)
b = """isinstance(x, (int, float, int, int, float))"""
a = """isinstance(x, (int, float))"""
self.check(b, a)
b = """isinstance(x, (int, float, int, int, float, str))"""
a = """isinstance(x, (int, float, str))"""
self.check(b, a)
b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))"""
a = """isinstance(foo() + bar(), (x(), y(), x(), int))"""
self.check(b, a)
def test_prefix_preservation(self):
b = """if isinstance( foo(), ( bar, bar, baz )) : pass"""
a = """if isinstance( foo(), ( bar, baz )) : pass"""
self.check(b, a)
def test_unchanged(self):
self.unchanged("isinstance(x, (str, int))")
class Test_dict(FixerTestCase):
fixer = "dict"
def test_prefix_preservation(self):
b = "if d. keys ( ) : pass"
a = "if list(d. keys ( )) : pass"
self.check(b, a)
b = "if d. items ( ) : pass"
a = "if list(d. items ( )) : pass"
self.check(b, a)
b = "if d. iterkeys ( ) : pass"
a = "if iter(d. keys ( )) : pass"
self.check(b, a)
b = "[i for i in d. iterkeys( ) ]"
a = "[i for i in d. keys( ) ]"
self.check(b, a)
b = "if d. viewkeys ( ) : pass"
a = "if d. keys ( ) : pass"
self.check(b, a)
b = "[i for i in d. viewkeys( ) ]"
a = "[i for i in d. keys( ) ]"
self.check(b, a)
def test_trailing_comment(self):
b = "d.keys() # foo"
a = "list(d.keys()) # foo"
self.check(b, a)
b = "d.items() # foo"
a = "list(d.items()) # foo"
self.check(b, a)
b = "d.iterkeys() # foo"
a = "iter(d.keys()) # foo"
self.check(b, a)
b = """[i for i in d.iterkeys() # foo
]"""
a = """[i for i in d.keys() # foo
]"""
self.check(b, a)
b = """[i for i in d.iterkeys() # foo
]"""
a = """[i for i in d.keys() # foo
]"""
self.check(b, a)
b = "d.viewitems() # foo"
a = "d.items() # foo"
self.check(b, a)
def test_unchanged(self):
for wrapper in fixer_util.consuming_calls:
s = "s = %s(d.keys())" % wrapper
self.unchanged(s)
s = "s = %s(d.values())" % wrapper
self.unchanged(s)
s = "s = %s(d.items())" % wrapper
self.unchanged(s)
def test_01(self):
b = "d.keys()"
a = "list(d.keys())"
self.check(b, a)
b = "a[0].foo().keys()"
a = "list(a[0].foo().keys())"
self.check(b, a)
def test_02(self):
b = "d.items()"
a = "list(d.items())"
self.check(b, a)
def test_03(self):
b = "d.values()"
a = "list(d.values())"
self.check(b, a)
def test_04(self):
b = "d.iterkeys()"
a = "iter(d.keys())"
self.check(b, a)
def test_05(self):
b = "d.iteritems()"
a = "iter(d.items())"
self.check(b, a)
def test_06(self):
b = "d.itervalues()"
a = "iter(d.values())"
self.check(b, a)
def test_07(self):
s = "list(d.keys())"
self.unchanged(s)
def test_08(self):
s = "sorted(d.keys())"
self.unchanged(s)
def test_09(self):
b = "iter(d.keys())"
a = "iter(list(d.keys()))"
self.check(b, a)
def test_10(self):
b = "foo(d.keys())"
a = "foo(list(d.keys()))"
self.check(b, a)
def test_11(self):
b = "for i in d.keys(): print i"
a = "for i in list(d.keys()): print i"
self.check(b, a)
def test_12(self):
b = "for i in d.iterkeys(): print i"
a = "for i in d.keys(): print i"
self.check(b, a)
def test_13(self):
b = "[i for i in d.keys()]"
a = "[i for i in list(d.keys())]"
self.check(b, a)
def test_14(self):
b = "[i for i in d.iterkeys()]"
a = "[i for i in d.keys()]"
self.check(b, a)
def test_15(self):
b = "(i for i in d.keys())"
a = "(i for i in list(d.keys()))"
self.check(b, a)
def test_16(self):
b = "(i for i in d.iterkeys())"
a = "(i for i in d.keys())"
self.check(b, a)
def test_17(self):
b = "iter(d.iterkeys())"
a = "iter(d.keys())"
self.check(b, a)
def test_18(self):
b = "list(d.iterkeys())"
a = "list(d.keys())"
self.check(b, a)
def test_19(self):
b = "sorted(d.iterkeys())"
a = "sorted(d.keys())"
self.check(b, a)
def test_20(self):
b = "foo(d.iterkeys())"
a = "foo(iter(d.keys()))"
self.check(b, a)
def test_21(self):
b = "print h.iterkeys().next()"
a = "print iter(h.keys()).next()"
self.check(b, a)
def test_22(self):
b = "print h.keys()[0]"
a = "print list(h.keys())[0]"
self.check(b, a)
def test_23(self):
b = "print list(h.iterkeys().next())"
a = "print list(iter(h.keys()).next())"
self.check(b, a)
def test_24(self):
b = "for x in h.keys()[0]: print x"
a = "for x in list(h.keys())[0]: print x"
self.check(b, a)
def test_25(self):
b = "d.viewkeys()"
a = "d.keys()"
self.check(b, a)
def test_26(self):
b = "d.viewitems()"
a = "d.items()"
self.check(b, a)
def test_27(self):
b = "d.viewvalues()"
a = "d.values()"
self.check(b, a)
def test_28(self):
b = "[i for i in d.viewkeys()]"
a = "[i for i in d.keys()]"
self.check(b, a)
def test_29(self):
b = "(i for i in d.viewkeys())"
a = "(i for i in d.keys())"
self.check(b, a)
def test_30(self):
b = "iter(d.viewkeys())"
a = "iter(d.keys())"
self.check(b, a)
def test_31(self):
b = "list(d.viewkeys())"
a = "list(d.keys())"
self.check(b, a)
def test_32(self):
b = "sorted(d.viewkeys())"
a = "sorted(d.keys())"
self.check(b, a)
class Test_xrange(FixerTestCase):
fixer = "xrange"
def test_prefix_preservation(self):
b = """x = xrange( 10 )"""
a = """x = range( 10 )"""
self.check(b, a)
b = """x = xrange( 1 , 10 )"""
a = """x = range( 1 , 10 )"""
self.check(b, a)
b = """x = xrange( 0 , 10 , 2 )"""
a = """x = range( 0 , 10 , 2 )"""
self.check(b, a)
def test_single_arg(self):
b = """x = xrange(10)"""
a = """x = range(10)"""
self.check(b, a)
def test_two_args(self):
b = """x = xrange(1, 10)"""
a = """x = range(1, 10)"""
self.check(b, a)
def test_three_args(self):
b = """x = xrange(0, 10, 2)"""
a = """x = range(0, 10, 2)"""
self.check(b, a)
def test_wrap_in_list(self):
b = """x = range(10, 3, 9)"""
a = """x = list(range(10, 3, 9))"""
self.check(b, a)
b = """x = foo(range(10, 3, 9))"""
a = """x = foo(list(range(10, 3, 9)))"""
self.check(b, a)
b = """x = range(10, 3, 9) + [4]"""
a = """x = list(range(10, 3, 9)) + [4]"""
self.check(b, a)
b = """x = range(10)[::-1]"""
a = """x = list(range(10))[::-1]"""
self.check(b, a)
b = """x = range(10) [3]"""
a = """x = list(range(10)) [3]"""
self.check(b, a)
def test_xrange_in_for(self):
b = """for i in xrange(10):\n j=i"""
a = """for i in range(10):\n j=i"""
self.check(b, a)
b = """[i for i in xrange(10)]"""
a = """[i for i in range(10)]"""
self.check(b, a)
def test_range_in_for(self):
self.unchanged("for i in range(10): pass")
self.unchanged("[i for i in range(10)]")
def test_in_contains_test(self):
self.unchanged("x in range(10, 3, 9)")
def test_in_consuming_context(self):
for call in fixer_util.consuming_calls:
self.unchanged("a = %s(range(10))" % call)
class Test_xrange_with_reduce(FixerTestCase):
def setUp(self):
super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"])
def test_double_transform(self):
b = """reduce(x, xrange(5))"""
a = """from functools import reduce
reduce(x, range(5))"""
self.check(b, a)
class Test_raw_input(FixerTestCase):
fixer = "raw_input"
def test_prefix_preservation(self):
b = """x = raw_input( )"""
a = """x = input( )"""
self.check(b, a)
b = """x = raw_input( '' )"""
a = """x = input( '' )"""
self.check(b, a)
def test_1(self):
b = """x = raw_input()"""
a = """x = input()"""
self.check(b, a)
def test_2(self):
b = """x = raw_input('')"""
a = """x = input('')"""
self.check(b, a)
def test_3(self):
b = """x = raw_input('prompt')"""
a = """x = input('prompt')"""
self.check(b, a)
def test_4(self):
b = """x = raw_input(foo(a) + 6)"""
a = """x = input(foo(a) + 6)"""
self.check(b, a)
def test_5(self):
b = """x = raw_input(invite).split()"""
a = """x = input(invite).split()"""
self.check(b, a)
def test_6(self):
b = """x = raw_input(invite) . split ()"""
a = """x = input(invite) . split ()"""
self.check(b, a)
def test_8(self):
b = "x = int(raw_input())"
a = "x = int(input())"
self.check(b, a)
class Test_funcattrs(FixerTestCase):
fixer = "funcattrs"
attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"]
def test(self):
for attr in self.attrs:
b = "a.func_%s" % attr
a = "a.__%s__" % attr
self.check(b, a)
b = "self.foo.func_%s.foo_bar" % attr
a = "self.foo.__%s__.foo_bar" % attr
self.check(b, a)
def test_unchanged(self):
for attr in self.attrs:
s = "foo(func_%s + 5)" % attr
self.unchanged(s)
s = "f(foo.__%s__)" % attr
self.unchanged(s)
s = "f(foo.__%s__.foo)" % attr
self.unchanged(s)
class Test_xreadlines(FixerTestCase):
fixer = "xreadlines"
def test_call(self):
b = "for x in f.xreadlines(): pass"
a = "for x in f: pass"
self.check(b, a)
b = "for x in foo().xreadlines(): pass"
a = "for x in foo(): pass"
self.check(b, a)
b = "for x in (5 + foo()).xreadlines(): pass"
a = "for x in (5 + foo()): pass"
self.check(b, a)
def test_attr_ref(self):
b = "foo(f.xreadlines + 5)"
a = "foo(f.__iter__ + 5)"
self.check(b, a)
b = "foo(f().xreadlines + 5)"
a = "foo(f().__iter__ + 5)"
self.check(b, a)
b = "foo((5 + f()).xreadlines + 5)"
a = "foo((5 + f()).__iter__ + 5)"
self.check(b, a)
def test_unchanged(self):
s = "for x in f.xreadlines(5): pass"
self.unchanged(s)
s = "for x in f.xreadlines(k=5): pass"
self.unchanged(s)
s = "for x in f.xreadlines(*k, **v): pass"
self.unchanged(s)
s = "foo(xreadlines)"
self.unchanged(s)
class ImportsFixerTests:
def test_import_module(self):
for old, new in self.modules.items():
b = "import %s" % old
a = "import %s" % new
self.check(b, a)
b = "import foo, %s, bar" % old
a = "import foo, %s, bar" % new
self.check(b, a)
def test_import_from(self):
for old, new in self.modules.items():
b = "from %s import foo" % old
a = "from %s import foo" % new
self.check(b, a)
b = "from %s import foo, bar" % old
a = "from %s import foo, bar" % new
self.check(b, a)
b = "from %s import (yes, no)" % old
a = "from %s import (yes, no)" % new
self.check(b, a)
def test_import_module_as(self):
for old, new in self.modules.items():
b = "import %s as foo_bar" % old
a = "import %s as foo_bar" % new
self.check(b, a)
b = "import %s as foo_bar" % old
a = "import %s as foo_bar" % new
self.check(b, a)
def test_import_from_as(self):
for old, new in self.modules.items():
b = "from %s import foo as bar" % old
a = "from %s import foo as bar" % new
self.check(b, a)
def test_star(self):
for old, new in self.modules.items():
b = "from %s import *" % old
a = "from %s import *" % new
self.check(b, a)
def test_import_module_usage(self):
for old, new in self.modules.items():
b = """
import %s
foo(%s.bar)
""" % (old, old)
a = """
import %s
foo(%s.bar)
""" % (new, new)
self.check(b, a)
b = """
from %s import x
%s = 23
""" % (old, old)
a = """
from %s import x
%s = 23
""" % (new, old)
self.check(b, a)
s = """
def f():
%s.method()
""" % (old,)
self.unchanged(s)
# test nested usage
b = """
import %s
%s.bar(%s.foo)
""" % (old, old, old)
a = """
import %s
%s.bar(%s.foo)
""" % (new, new, new)
self.check(b, a)
b = """
import %s
x.%s
""" % (old, old)
a = """
import %s
x.%s
""" % (new, old)
self.check(b, a)
class Test_imports(FixerTestCase, ImportsFixerTests):
fixer = "imports"
from ..fixes.fix_imports import MAPPING as modules
def test_multiple_imports(self):
b = """import urlparse, cStringIO"""
a = """import urllib.parse, io"""
self.check(b, a)
def test_multiple_imports_as(self):
b = """
import copy_reg as bar, HTMLParser as foo, urlparse
s = urlparse.spam(bar.foo())
"""
a = """
import copyreg as bar, html.parser as foo, urllib.parse
s = urllib.parse.spam(bar.foo())
"""
self.check(b, a)
class Test_imports2(FixerTestCase, ImportsFixerTests):
fixer = "imports2"
from ..fixes.fix_imports2 import MAPPING as modules
class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests):
def setUp(self):
super(Test_imports_fixer_order, self).setUp(['imports', 'imports2'])
from ..fixes.fix_imports2 import MAPPING as mapping2
self.modules = mapping2.copy()
from ..fixes.fix_imports import MAPPING as mapping1
for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'):
self.modules[key] = mapping1[key]
def test_after_local_imports_refactoring(self):
for fix in ("imports", "imports2"):
self.fixer = fix
self.assert_runs_after("import")
class Test_urllib(FixerTestCase):
fixer = "urllib"
from ..fixes.fix_urllib import MAPPING as modules
def test_import_module(self):
for old, changes in self.modules.items():
b = "import %s" % old
a = "import %s" % ", ".join(map(itemgetter(0), changes))
self.check(b, a)
def test_import_from(self):
for old, changes in self.modules.items():
all_members = []
for new, members in changes:
for member in members:
all_members.append(member)
b = "from %s import %s" % (old, member)
a = "from %s import %s" % (new, member)
self.check(b, a)
s = "from foo import %s" % member
self.unchanged(s)
b = "from %s import %s" % (old, ", ".join(members))
a = "from %s import %s" % (new, ", ".join(members))
self.check(b, a)
s = "from foo import %s" % ", ".join(members)
self.unchanged(s)
# test the breaking of a module into multiple replacements
b = "from %s import %s" % (old, ", ".join(all_members))
a = "\n".join(["from %s import %s" % (new, ", ".join(members))
for (new, members) in changes])
self.check(b, a)
def test_import_module_as(self):
for old in self.modules:
s = "import %s as foo" % old
self.warns_unchanged(s, "This module is now multiple modules")
def test_import_from_as(self):
for old, changes in self.modules.items():
for new, members in changes:
for member in members:
b = "from %s import %s as foo_bar" % (old, member)
a = "from %s import %s as foo_bar" % (new, member)
self.check(b, a)
b = "from %s import %s as blah, %s" % (old, member, member)
a = "from %s import %s as blah, %s" % (new, member, member)
self.check(b, a)
def test_star(self):
for old in self.modules:
s = "from %s import *" % old
self.warns_unchanged(s, "Cannot handle star imports")
def test_indented(self):
b = """
def foo():
from urllib import urlencode, urlopen
"""
a = """
def foo():
from urllib.parse import urlencode
from urllib.request import urlopen
"""
self.check(b, a)
b = """
def foo():
other()
from urllib import urlencode, urlopen
"""
a = """
def foo():
other()
from urllib.parse import urlencode
from urllib.request import urlopen
"""
self.check(b, a)
def test_import_module_usage(self):
for old, changes in self.modules.items():
for new, members in changes:
for member in members:
new_import = ", ".join([n for (n, mems)
in self.modules[old]])
b = """
import %s
foo(%s.%s)
""" % (old, old, member)
a = """
import %s
foo(%s.%s)
""" % (new_import, new, member)
self.check(b, a)
b = """
import %s
%s.%s(%s.%s)
""" % (old, old, member, old, member)
a = """
import %s
%s.%s(%s.%s)
""" % (new_import, new, member, new, member)
self.check(b, a)
class Test_input(FixerTestCase):
fixer = "input"
def test_prefix_preservation(self):
b = """x = input( )"""
a = """x = eval(input( ))"""
self.check(b, a)
b = """x = input( '' )"""
a = """x = eval(input( '' ))"""
self.check(b, a)
def test_trailing_comment(self):
b = """x = input() # foo"""
a = """x = eval(input()) # foo"""
self.check(b, a)
def test_idempotency(self):
s = """x = eval(input())"""
self.unchanged(s)
s = """x = eval(input(''))"""
self.unchanged(s)
s = """x = eval(input(foo(5) + 9))"""
self.unchanged(s)
def test_1(self):
b = """x = input()"""
a = """x = eval(input())"""
self.check(b, a)
def test_2(self):
b = """x = input('')"""
a = """x = eval(input(''))"""
self.check(b, a)
def test_3(self):
b = """x = input('prompt')"""
a = """x = eval(input('prompt'))"""
self.check(b, a)
def test_4(self):
b = """x = input(foo(5) + 9)"""
a = """x = eval(input(foo(5) + 9))"""
self.check(b, a)
class Test_tuple_params(FixerTestCase):
fixer = "tuple_params"
def test_unchanged_1(self):
s = """def foo(): pass"""
self.unchanged(s)
def test_unchanged_2(self):
s = """def foo(a, b, c): pass"""
self.unchanged(s)
def test_unchanged_3(self):
s = """def foo(a=3, b=4, c=5): pass"""
self.unchanged(s)
def test_1(self):
b = """
def foo(((a, b), c)):
x = 5"""
a = """
def foo(xxx_todo_changeme):
((a, b), c) = xxx_todo_changeme
x = 5"""
self.check(b, a)
def test_2(self):
b = """
def foo(((a, b), c), d):
x = 5"""
a = """
def foo(xxx_todo_changeme, d):
((a, b), c) = xxx_todo_changeme
x = 5"""
self.check(b, a)
def test_3(self):
b = """
def foo(((a, b), c), d) -> e:
x = 5"""
a = """
def foo(xxx_todo_changeme, d) -> e:
((a, b), c) = xxx_todo_changeme
x = 5"""
self.check(b, a)
def test_semicolon(self):
b = """
def foo(((a, b), c)): x = 5; y = 7"""
a = """
def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7"""
self.check(b, a)
def test_keywords(self):
b = """
def foo(((a, b), c), d, e=5) -> z:
x = 5"""
a = """
def foo(xxx_todo_changeme, d, e=5) -> z:
((a, b), c) = xxx_todo_changeme
x = 5"""
self.check(b, a)
def test_varargs(self):
b = """
def foo(((a, b), c), d, *vargs, **kwargs) -> z:
x = 5"""
a = """
def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z:
((a, b), c) = xxx_todo_changeme
x = 5"""
self.check(b, a)
def test_multi_1(self):
b = """
def foo(((a, b), c), (d, e, f)) -> z:
x = 5"""
a = """
def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
((a, b), c) = xxx_todo_changeme
(d, e, f) = xxx_todo_changeme1
x = 5"""
self.check(b, a)
def test_multi_2(self):
b = """
def foo(x, ((a, b), c), d, (e, f, g), y) -> z:
x = 5"""
a = """
def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z:
((a, b), c) = xxx_todo_changeme
(e, f, g) = xxx_todo_changeme1
x = 5"""
self.check(b, a)
def test_docstring(self):
b = """
def foo(((a, b), c), (d, e, f)) -> z:
"foo foo foo foo"
x = 5"""
a = """
def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z:
"foo foo foo foo"
((a, b), c) = xxx_todo_changeme
(d, e, f) = xxx_todo_changeme1
x = 5"""
self.check(b, a)
def test_lambda_no_change(self):
s = """lambda x: x + 5"""
self.unchanged(s)
def test_lambda_parens_single_arg(self):
b = """lambda (x): x + 5"""
a = """lambda x: x + 5"""
self.check(b, a)
b = """lambda(x): x + 5"""
a = """lambda x: x + 5"""
self.check(b, a)
b = """lambda ((((x)))): x + 5"""
a = """lambda x: x + 5"""
self.check(b, a)
b = """lambda((((x)))): x + 5"""
a = """lambda x: x + 5"""
self.check(b, a)
def test_lambda_simple(self):
b = """lambda (x, y): x + f(y)"""
a = """lambda x_y: x_y[0] + f(x_y[1])"""
self.check(b, a)
b = """lambda(x, y): x + f(y)"""
a = """lambda x_y: x_y[0] + f(x_y[1])"""
self.check(b, a)
b = """lambda (((x, y))): x + f(y)"""
a = """lambda x_y: x_y[0] + f(x_y[1])"""
self.check(b, a)
b = """lambda(((x, y))): x + f(y)"""
a = """lambda x_y: x_y[0] + f(x_y[1])"""
self.check(b, a)
def test_lambda_one_tuple(self):
b = """lambda (x,): x + f(x)"""
a = """lambda x1: x1[0] + f(x1[0])"""
self.check(b, a)
b = """lambda (((x,))): x + f(x)"""
a = """lambda x1: x1[0] + f(x1[0])"""
self.check(b, a)
def test_lambda_simple_multi_use(self):
b = """lambda (x, y): x + x + f(x) + x"""
a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]"""
self.check(b, a)
def test_lambda_simple_reverse(self):
b = """lambda (x, y): y + x"""
a = """lambda x_y: x_y[1] + x_y[0]"""
self.check(b, a)
def test_lambda_nested(self):
b = """lambda (x, (y, z)): x + y + z"""
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
self.check(b, a)
b = """lambda (((x, (y, z)))): x + y + z"""
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]"""
self.check(b, a)
def test_lambda_nested_multi_use(self):
b = """lambda (x, (y, z)): x + y + f(y)"""
a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])"""
self.check(b, a)
class Test_methodattrs(FixerTestCase):
fixer = "methodattrs"
attrs = ["func", "self", "class"]
def test(self):
for attr in self.attrs:
b = "a.im_%s" % attr
if attr == "class":
a = "a.__self__.__class__"
else:
a = "a.__%s__" % attr
self.check(b, a)
b = "self.foo.im_%s.foo_bar" % attr
if attr == "class":
a = "self.foo.__self__.__class__.foo_bar"
else:
a = "self.foo.__%s__.foo_bar" % attr
self.check(b, a)
def test_unchanged(self):
for attr in self.attrs:
s = "foo(im_%s + 5)" % attr
self.unchanged(s)
s = "f(foo.__%s__)" % attr
self.unchanged(s)
s = "f(foo.__%s__.foo)" % attr
self.unchanged(s)
class Test_next(FixerTestCase):
fixer = "next"
def test_1(self):
b = """it.next()"""
a = """next(it)"""
self.check(b, a)
def test_2(self):
b = """a.b.c.d.next()"""
a = """next(a.b.c.d)"""
self.check(b, a)
def test_3(self):
b = """(a + b).next()"""
a = """next((a + b))"""
self.check(b, a)
def test_4(self):
b = """a().next()"""
a = """next(a())"""
self.check(b, a)
def test_5(self):
b = """a().next() + b"""
a = """next(a()) + b"""
self.check(b, a)
def test_6(self):
b = """c( a().next() + b)"""
a = """c( next(a()) + b)"""
self.check(b, a)
def test_prefix_preservation_1(self):
b = """
for a in b:
foo(a)
a.next()
"""
a = """
for a in b:
foo(a)
next(a)
"""
self.check(b, a)
def test_prefix_preservation_2(self):
b = """
for a in b:
foo(a) # abc
# def
a.next()
"""
a = """
for a in b:
foo(a) # abc
# def
next(a)
"""
self.check(b, a)
def test_prefix_preservation_3(self):
b = """
next = 5
for a in b:
foo(a)
a.next()
"""
a = """
next = 5
for a in b:
foo(a)
a.__next__()
"""
self.check(b, a, ignore_warnings=True)
def test_prefix_preservation_4(self):
b = """
next = 5
for a in b:
foo(a) # abc
# def
a.next()
"""
a = """
next = 5
for a in b:
foo(a) # abc
# def
a.__next__()
"""
self.check(b, a, ignore_warnings=True)
def test_prefix_preservation_5(self):
b = """
next = 5
for a in b:
foo(foo(a), # abc
a.next())
"""
a = """
next = 5
for a in b:
foo(foo(a), # abc
a.__next__())
"""
self.check(b, a, ignore_warnings=True)
def test_prefix_preservation_6(self):
b = """
for a in b:
foo(foo(a), # abc
a.next())
"""
a = """
for a in b:
foo(foo(a), # abc
next(a))
"""
self.check(b, a)
def test_method_1(self):
b = """
class A:
def next(self):
pass
"""
a = """
class A:
def __next__(self):
pass
"""
self.check(b, a)
def test_method_2(self):
b = """
class A(object):
def next(self):
pass
"""
a = """
class A(object):
def __next__(self):
pass
"""
self.check(b, a)
def test_method_3(self):
b = """
class A:
def next(x):
pass
"""
a = """
class A:
def __next__(x):
pass
"""
self.check(b, a)
def test_method_4(self):
b = """
class A:
def __init__(self, foo):
self.foo = foo
def next(self):
pass
def __iter__(self):
return self
"""
a = """
class A:
def __init__(self, foo):
self.foo = foo
def __next__(self):
pass
def __iter__(self):
return self
"""
self.check(b, a)
def test_method_unchanged(self):
s = """
class A:
def next(self, a, b):
pass
"""
self.unchanged(s)
def test_shadowing_assign_simple(self):
s = """
next = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_assign_tuple_1(self):
s = """
(next, a) = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_assign_tuple_2(self):
s = """
(a, (b, (next, c)), a) = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_assign_list_1(self):
s = """
[next, a] = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_assign_list_2(self):
s = """
[a, [b, [next, c]], a] = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_builtin_assign(self):
s = """
def foo():
__builtin__.next = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_builtin_assign_in_tuple(self):
s = """
def foo():
(a, __builtin__.next) = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_builtin_assign_in_list(self):
s = """
def foo():
[a, __builtin__.next] = foo
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_assign_to_next(self):
s = """
def foo():
A.next = foo
class A:
def next(self, a, b):
pass
"""
self.unchanged(s)
def test_assign_to_next_in_tuple(self):
s = """
def foo():
(a, A.next) = foo
class A:
def next(self, a, b):
pass
"""
self.unchanged(s)
def test_assign_to_next_in_list(self):
s = """
def foo():
[a, A.next] = foo
class A:
def next(self, a, b):
pass
"""
self.unchanged(s)
def test_shadowing_import_1(self):
s = """
import foo.bar as next
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_2(self):
s = """
import bar, bar.foo as next
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_3(self):
s = """
import bar, bar.foo as next, baz
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_from_1(self):
s = """
from x import next
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_from_2(self):
s = """
from x.a import next
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_from_3(self):
s = """
from x import a, next, b
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_import_from_4(self):
s = """
from x.a import a, next, b
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_funcdef_1(self):
s = """
def next(a):
pass
class A:
def next(self, a, b):
pass
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_funcdef_2(self):
b = """
def next(a):
pass
class A:
def next(self):
pass
it.next()
"""
a = """
def next(a):
pass
class A:
def __next__(self):
pass
it.__next__()
"""
self.warns(b, a, "Calls to builtin next() possibly shadowed")
def test_shadowing_global_1(self):
s = """
def f():
global next
next = 5
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_global_2(self):
s = """
def f():
global a, next, b
next = 5
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_for_simple(self):
s = """
for next in it():
pass
b = 5
c = 6
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_for_tuple_1(self):
s = """
for next, b in it():
pass
b = 5
c = 6
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_shadowing_for_tuple_2(self):
s = """
for a, (next, c), b in it():
pass
b = 5
c = 6
"""
self.warns_unchanged(s, "Calls to builtin next() possibly shadowed")
def test_noncall_access_1(self):
b = """gnext = g.next"""
a = """gnext = g.__next__"""
self.check(b, a)
def test_noncall_access_2(self):
b = """f(g.next + 5)"""
a = """f(g.__next__ + 5)"""
self.check(b, a)
def test_noncall_access_3(self):
b = """f(g().next + 5)"""
a = """f(g().__next__ + 5)"""
self.check(b, a)
class Test_nonzero(FixerTestCase):
fixer = "nonzero"
def test_1(self):
b = """
class A:
def __nonzero__(self):
pass
"""
a = """
class A:
def __bool__(self):
pass
"""
self.check(b, a)
def test_2(self):
b = """
class A(object):
def __nonzero__(self):
pass
"""
a = """
class A(object):
def __bool__(self):
pass
"""
self.check(b, a)
def test_unchanged_1(self):
s = """
class A(object):
def __bool__(self):
pass
"""
self.unchanged(s)
def test_unchanged_2(self):
s = """
class A(object):
def __nonzero__(self, a):
pass
"""
self.unchanged(s)
def test_unchanged_func(self):
s = """
def __nonzero__(self):
pass
"""
self.unchanged(s)
class Test_numliterals(FixerTestCase):
fixer = "numliterals"
def test_octal_1(self):
b = """0755"""
a = """0o755"""
self.check(b, a)
def test_long_int_1(self):
b = """a = 12L"""
a = """a = 12"""
self.check(b, a)
def test_long_int_2(self):
b = """a = 12l"""
a = """a = 12"""
self.check(b, a)
def test_long_hex(self):
b = """b = 0x12l"""
a = """b = 0x12"""
self.check(b, a)
def test_comments_and_spacing(self):
b = """b = 0x12L"""
a = """b = 0x12"""
self.check(b, a)
b = """b = 0755 # spam"""
a = """b = 0o755 # spam"""
self.check(b, a)
def test_unchanged_int(self):
s = """5"""
self.unchanged(s)
def test_unchanged_float(self):
s = """5.0"""
self.unchanged(s)
def test_unchanged_octal(self):
s = """0o755"""
self.unchanged(s)
def test_unchanged_hex(self):
s = """0xABC"""
self.unchanged(s)
def test_unchanged_exp(self):
s = """5.0e10"""
self.unchanged(s)
def test_unchanged_complex_int(self):
s = """5 + 4j"""
self.unchanged(s)
def test_unchanged_complex_float(self):
s = """5.4 + 4.9j"""
self.unchanged(s)
def test_unchanged_complex_bare(self):
s = """4j"""
self.unchanged(s)
s = """4.4j"""
self.unchanged(s)
class Test_renames(FixerTestCase):
fixer = "renames"
modules = {"sys": ("maxint", "maxsize"),
}
def test_import_from(self):
for mod, (old, new) in self.modules.items():
b = "from %s import %s" % (mod, old)
a = "from %s import %s" % (mod, new)
self.check(b, a)
s = "from foo import %s" % old
self.unchanged(s)
def test_import_from_as(self):
for mod, (old, new) in self.modules.items():
b = "from %s import %s as foo_bar" % (mod, old)
a = "from %s import %s as foo_bar" % (mod, new)
self.check(b, a)
def test_import_module_usage(self):
for mod, (old, new) in self.modules.items():
b = """
import %s
foo(%s, %s.%s)
""" % (mod, mod, mod, old)
a = """
import %s
foo(%s, %s.%s)
""" % (mod, mod, mod, new)
self.check(b, a)
def XXX_test_from_import_usage(self):
# not implemented yet
for mod, (old, new) in self.modules.items():
b = """
from %s import %s
foo(%s, %s)
""" % (mod, old, mod, old)
a = """
from %s import %s
foo(%s, %s)
""" % (mod, new, mod, new)
self.check(b, a)
class Test_unicode(FixerTestCase):
fixer = "unicode"
def test_whitespace(self):
b = """unicode( x)"""
a = """str( x)"""
self.check(b, a)
b = """ unicode(x )"""
a = """ str(x )"""
self.check(b, a)
b = """ u'h'"""
a = """ 'h'"""
self.check(b, a)
def test_unicode_call(self):
b = """unicode(x, y, z)"""
a = """str(x, y, z)"""
self.check(b, a)
def test_unichr(self):
b = """unichr(u'h')"""
a = """chr('h')"""
self.check(b, a)
def test_unicode_literal_1(self):
b = '''u"x"'''
a = '''"x"'''
self.check(b, a)
def test_unicode_literal_2(self):
b = """ur'x'"""
a = """r'x'"""
self.check(b, a)
def test_unicode_literal_3(self):
b = """UR'''x''' """
a = """R'''x''' """
self.check(b, a)
def test_native_literal_escape_u(self):
b = """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """'\\\\\\\\u20ac\\\\U0001d121\\\\u20ac'"""
self.check(b, a)
b = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
def test_bytes_literal_escape_u(self):
b = """b'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """b'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
b = """br'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """br'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
def test_unicode_literal_escape_u(self):
b = """u'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
b = """ur'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
def test_native_unicode_literal_escape_u(self):
f = 'from __future__ import unicode_literals\n'
b = f + """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = f + """'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
b = f + """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
a = f + """r'\\\\\\u20ac\\U0001d121\\\\u20ac'"""
self.check(b, a)
class Test_callable(FixerTestCase):
fixer = "callable"
def test_prefix_preservation(self):
b = """callable( x)"""
a = """import collections\nisinstance( x, collections.Callable)"""
self.check(b, a)
b = """if callable(x): pass"""
a = """import collections
if isinstance(x, collections.Callable): pass"""
self.check(b, a)
def test_callable_call(self):
b = """callable(x)"""
a = """import collections\nisinstance(x, collections.Callable)"""
self.check(b, a)
def test_global_import(self):
b = """
def spam(foo):
callable(foo)"""[1:]
a = """
import collections
def spam(foo):
isinstance(foo, collections.Callable)"""[1:]
self.check(b, a)
b = """
import collections
def spam(foo):
callable(foo)"""[1:]
# same output if it was already imported
self.check(b, a)
b = """
from collections import *
def spam(foo):
callable(foo)"""[1:]
a = """
from collections import *
import collections
def spam(foo):
isinstance(foo, collections.Callable)"""[1:]
self.check(b, a)
b = """
do_stuff()
do_some_other_stuff()
assert callable(do_stuff)"""[1:]
a = """
import collections
do_stuff()
do_some_other_stuff()
assert isinstance(do_stuff, collections.Callable)"""[1:]
self.check(b, a)
b = """
if isinstance(do_stuff, Callable):
assert callable(do_stuff)
do_stuff(do_stuff)
if not callable(do_stuff):
exit(1)
else:
assert callable(do_stuff)
else:
assert not callable(do_stuff)"""[1:]
a = """
import collections
if isinstance(do_stuff, Callable):
assert isinstance(do_stuff, collections.Callable)
do_stuff(do_stuff)
if not isinstance(do_stuff, collections.Callable):
exit(1)
else:
assert isinstance(do_stuff, collections.Callable)
else:
assert not isinstance(do_stuff, collections.Callable)"""[1:]
self.check(b, a)
def test_callable_should_not_change(self):
a = """callable(*x)"""
self.unchanged(a)
a = """callable(x, y)"""
self.unchanged(a)
a = """callable(x, kw=y)"""
self.unchanged(a)
a = """callable()"""
self.unchanged(a)
class Test_filter(FixerTestCase):
fixer = "filter"
def test_prefix_preservation(self):
b = """x = filter( foo, 'abc' )"""
a = """x = list(filter( foo, 'abc' ))"""
self.check(b, a)
b = """x = filter( None , 'abc' )"""
a = """x = [_f for _f in 'abc' if _f]"""
self.check(b, a)
def test_filter_basic(self):
b = """x = filter(None, 'abc')"""
a = """x = [_f for _f in 'abc' if _f]"""
self.check(b, a)
b = """x = len(filter(f, 'abc'))"""
a = """x = len(list(filter(f, 'abc')))"""
self.check(b, a)
b = """x = filter(lambda x: x%2 == 0, range(10))"""
a = """x = [x for x in range(10) if x%2 == 0]"""
self.check(b, a)
# Note the parens around x
b = """x = filter(lambda (x): x%2 == 0, range(10))"""
a = """x = [x for x in range(10) if x%2 == 0]"""
self.check(b, a)
# XXX This (rare) case is not supported
## b = """x = filter(f, 'abc')[0]"""
## a = """x = list(filter(f, 'abc'))[0]"""
## self.check(b, a)
def test_filter_nochange(self):
a = """b.join(filter(f, 'abc'))"""
self.unchanged(a)
a = """(a + foo(5)).join(filter(f, 'abc'))"""
self.unchanged(a)
a = """iter(filter(f, 'abc'))"""
self.unchanged(a)
a = """list(filter(f, 'abc'))"""
self.unchanged(a)
a = """list(filter(f, 'abc'))[0]"""
self.unchanged(a)
a = """set(filter(f, 'abc'))"""
self.unchanged(a)
a = """set(filter(f, 'abc')).pop()"""
self.unchanged(a)
a = """tuple(filter(f, 'abc'))"""
self.unchanged(a)
a = """any(filter(f, 'abc'))"""
self.unchanged(a)
a = """all(filter(f, 'abc'))"""
self.unchanged(a)
a = """sum(filter(f, 'abc'))"""
self.unchanged(a)
a = """sorted(filter(f, 'abc'))"""
self.unchanged(a)
a = """sorted(filter(f, 'abc'), key=blah)"""
self.unchanged(a)
a = """sorted(filter(f, 'abc'), key=blah)[0]"""
self.unchanged(a)
a = """enumerate(filter(f, 'abc'))"""
self.unchanged(a)
a = """enumerate(filter(f, 'abc'), start=1)"""
self.unchanged(a)
a = """for i in filter(f, 'abc'): pass"""
self.unchanged(a)
a = """[x for x in filter(f, 'abc')]"""
self.unchanged(a)
a = """(x for x in filter(f, 'abc'))"""
self.unchanged(a)
def test_future_builtins(self):
a = "from future_builtins import spam, filter; filter(f, 'ham')"
self.unchanged(a)
b = """from future_builtins import spam; x = filter(f, 'abc')"""
a = """from future_builtins import spam; x = list(filter(f, 'abc'))"""
self.check(b, a)
a = "from future_builtins import *; filter(f, 'ham')"
self.unchanged(a)
class Test_map(FixerTestCase):
fixer = "map"
def check(self, b, a):
self.unchanged("from future_builtins import map; " + b, a)
super(Test_map, self).check(b, a)
def test_prefix_preservation(self):
b = """x = map( f, 'abc' )"""
a = """x = list(map( f, 'abc' ))"""
self.check(b, a)
def test_trailing_comment(self):
b = """x = map(f, 'abc') # foo"""
a = """x = list(map(f, 'abc')) # foo"""
self.check(b, a)
def test_None_with_multiple_arguments(self):
s = """x = map(None, a, b, c)"""
self.warns_unchanged(s, "cannot convert map(None, ...) with "
"multiple arguments")
def test_map_basic(self):
b = """x = map(f, 'abc')"""
a = """x = list(map(f, 'abc'))"""
self.check(b, a)
b = """x = len(map(f, 'abc', 'def'))"""
a = """x = len(list(map(f, 'abc', 'def')))"""
self.check(b, a)
b = """x = map(None, 'abc')"""
a = """x = list('abc')"""
self.check(b, a)
b = """x = map(lambda x: x+1, range(4))"""
a = """x = [x+1 for x in range(4)]"""
self.check(b, a)
# Note the parens around x
b = """x = map(lambda (x): x+1, range(4))"""
a = """x = [x+1 for x in range(4)]"""
self.check(b, a)
b = """
foo()
# foo
map(f, x)
"""
a = """
foo()
# foo
list(map(f, x))
"""
self.warns(b, a, "You should use a for loop here")
# XXX This (rare) case is not supported
## b = """x = map(f, 'abc')[0]"""
## a = """x = list(map(f, 'abc'))[0]"""
## self.check(b, a)
def test_map_nochange(self):
a = """b.join(map(f, 'abc'))"""
self.unchanged(a)
a = """(a + foo(5)).join(map(f, 'abc'))"""
self.unchanged(a)
a = """iter(map(f, 'abc'))"""
self.unchanged(a)
a = """list(map(f, 'abc'))"""
self.unchanged(a)
a = """list(map(f, 'abc'))[0]"""
self.unchanged(a)
a = """set(map(f, 'abc'))"""
self.unchanged(a)
a = """set(map(f, 'abc')).pop()"""
self.unchanged(a)
a = """tuple(map(f, 'abc'))"""
self.unchanged(a)
a = """any(map(f, 'abc'))"""
self.unchanged(a)
a = """all(map(f, 'abc'))"""
self.unchanged(a)
a = """sum(map(f, 'abc'))"""
self.unchanged(a)
a = """sorted(map(f, 'abc'))"""
self.unchanged(a)
a = """sorted(map(f, 'abc'), key=blah)"""
self.unchanged(a)
a = """sorted(map(f, 'abc'), key=blah)[0]"""
self.unchanged(a)
a = """enumerate(map(f, 'abc'))"""
self.unchanged(a)
a = """enumerate(map(f, 'abc'), start=1)"""
self.unchanged(a)
a = """for i in map(f, 'abc'): pass"""
self.unchanged(a)
a = """[x for x in map(f, 'abc')]"""
self.unchanged(a)
a = """(x for x in map(f, 'abc'))"""
self.unchanged(a)
def test_future_builtins(self):
a = "from future_builtins import spam, map, eggs; map(f, 'ham')"
self.unchanged(a)
b = """from future_builtins import spam, eggs; x = map(f, 'abc')"""
a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))"""
self.check(b, a)
a = "from future_builtins import *; map(f, 'ham')"
self.unchanged(a)
class Test_zip(FixerTestCase):
fixer = "zip"
def check(self, b, a):
self.unchanged("from future_builtins import zip; " + b, a)
super(Test_zip, self).check(b, a)
def test_zip_basic(self):
b = """x = zip(a, b, c)"""
a = """x = list(zip(a, b, c))"""
self.check(b, a)
b = """x = len(zip(a, b))"""
a = """x = len(list(zip(a, b)))"""
self.check(b, a)
def test_zip_nochange(self):
a = """b.join(zip(a, b))"""
self.unchanged(a)
a = """(a + foo(5)).join(zip(a, b))"""
self.unchanged(a)
a = """iter(zip(a, b))"""
self.unchanged(a)
a = """list(zip(a, b))"""
self.unchanged(a)
a = """list(zip(a, b))[0]"""
self.unchanged(a)
a = """set(zip(a, b))"""
self.unchanged(a)
a = """set(zip(a, b)).pop()"""
self.unchanged(a)
a = """tuple(zip(a, b))"""
self.unchanged(a)
a = """any(zip(a, b))"""
self.unchanged(a)
a = """all(zip(a, b))"""
self.unchanged(a)
a = """sum(zip(a, b))"""
self.unchanged(a)
a = """sorted(zip(a, b))"""
self.unchanged(a)
a = """sorted(zip(a, b), key=blah)"""
self.unchanged(a)
a = """sorted(zip(a, b), key=blah)[0]"""
self.unchanged(a)
a = """enumerate(zip(a, b))"""
self.unchanged(a)
a = """enumerate(zip(a, b), start=1)"""
self.unchanged(a)
a = """for i in zip(a, b): pass"""
self.unchanged(a)
a = """[x for x in zip(a, b)]"""
self.unchanged(a)
a = """(x for x in zip(a, b))"""
self.unchanged(a)
def test_future_builtins(self):
a = "from future_builtins import spam, zip, eggs; zip(a, b)"
self.unchanged(a)
b = """from future_builtins import spam, eggs; x = zip(a, b)"""
a = """from future_builtins import spam, eggs; x = list(zip(a, b))"""
self.check(b, a)
a = "from future_builtins import *; zip(a, b)"
self.unchanged(a)
class Test_standarderror(FixerTestCase):
fixer = "standarderror"
def test(self):
b = """x = StandardError()"""
a = """x = Exception()"""
self.check(b, a)
b = """x = StandardError(a, b, c)"""
a = """x = Exception(a, b, c)"""
self.check(b, a)
b = """f(2 + StandardError(a, b, c))"""
a = """f(2 + Exception(a, b, c))"""
self.check(b, a)
class Test_types(FixerTestCase):
fixer = "types"
def test_basic_types_convert(self):
b = """types.StringType"""
a = """bytes"""
self.check(b, a)
b = """types.DictType"""
a = """dict"""
self.check(b, a)
b = """types . IntType"""
a = """int"""
self.check(b, a)
b = """types.ListType"""
a = """list"""
self.check(b, a)
b = """types.LongType"""
a = """int"""
self.check(b, a)
b = """types.NoneType"""
a = """type(None)"""
self.check(b, a)
class Test_idioms(FixerTestCase):
fixer = "idioms"
def test_while(self):
b = """while 1: foo()"""
a = """while True: foo()"""
self.check(b, a)
b = """while 1: foo()"""
a = """while True: foo()"""
self.check(b, a)
b = """
while 1:
foo()
"""
a = """
while True:
foo()
"""
self.check(b, a)
def test_while_unchanged(self):
s = """while 11: foo()"""
self.unchanged(s)
s = """while 0: foo()"""
self.unchanged(s)
s = """while foo(): foo()"""
self.unchanged(s)
s = """while []: foo()"""
self.unchanged(s)
def test_eq_simple(self):
b = """type(x) == T"""
a = """isinstance(x, T)"""
self.check(b, a)
b = """if type(x) == T: pass"""
a = """if isinstance(x, T): pass"""
self.check(b, a)
def test_eq_reverse(self):
b = """T == type(x)"""
a = """isinstance(x, T)"""
self.check(b, a)
b = """if T == type(x): pass"""
a = """if isinstance(x, T): pass"""
self.check(b, a)
def test_eq_expression(self):
b = """type(x+y) == d.get('T')"""
a = """isinstance(x+y, d.get('T'))"""
self.check(b, a)
b = """type( x + y) == d.get('T')"""
a = """isinstance(x + y, d.get('T'))"""
self.check(b, a)
def test_is_simple(self):
b = """type(x) is T"""
a = """isinstance(x, T)"""
self.check(b, a)
b = """if type(x) is T: pass"""
a = """if isinstance(x, T): pass"""
self.check(b, a)
def test_is_reverse(self):
b = """T is type(x)"""
a = """isinstance(x, T)"""
self.check(b, a)
b = """if T is type(x): pass"""
a = """if isinstance(x, T): pass"""
self.check(b, a)
def test_is_expression(self):
b = """type(x+y) is d.get('T')"""
a = """isinstance(x+y, d.get('T'))"""
self.check(b, a)
b = """type( x + y) is d.get('T')"""
a = """isinstance(x + y, d.get('T'))"""
self.check(b, a)
def test_is_not_simple(self):
b = """type(x) is not T"""
a = """not isinstance(x, T)"""
self.check(b, a)
b = """if type(x) is not T: pass"""
a = """if not isinstance(x, T): pass"""
self.check(b, a)
def test_is_not_reverse(self):
b = """T is not type(x)"""
a = """not isinstance(x, T)"""
self.check(b, a)
b = """if T is not type(x): pass"""
a = """if not isinstance(x, T): pass"""
self.check(b, a)
def test_is_not_expression(self):
b = """type(x+y) is not d.get('T')"""
a = """not isinstance(x+y, d.get('T'))"""
self.check(b, a)
b = """type( x + y) is not d.get('T')"""
a = """not isinstance(x + y, d.get('T'))"""
self.check(b, a)
def test_ne_simple(self):
b = """type(x) != T"""
a = """not isinstance(x, T)"""
self.check(b, a)
b = """if type(x) != T: pass"""
a = """if not isinstance(x, T): pass"""
self.check(b, a)
def test_ne_reverse(self):
b = """T != type(x)"""
a = """not isinstance(x, T)"""
self.check(b, a)
b = """if T != type(x): pass"""
a = """if not isinstance(x, T): pass"""
self.check(b, a)
def test_ne_expression(self):
b = """type(x+y) != d.get('T')"""
a = """not isinstance(x+y, d.get('T'))"""
self.check(b, a)
b = """type( x + y) != d.get('T')"""
a = """not isinstance(x + y, d.get('T'))"""
self.check(b, a)
def test_type_unchanged(self):
a = """type(x).__name__"""
self.unchanged(a)
def test_sort_list_call(self):
b = """
v = list(t)
v.sort()
foo(v)
"""
a = """
v = sorted(t)
foo(v)
"""
self.check(b, a)
b = """
v = list(foo(b) + d)
v.sort()
foo(v)
"""
a = """
v = sorted(foo(b) + d)
foo(v)
"""
self.check(b, a)
b = """
while x:
v = list(t)
v.sort()
foo(v)
"""
a = """
while x:
v = sorted(t)
foo(v)
"""
self.check(b, a)
b = """
v = list(t)
# foo
v.sort()
foo(v)
"""
a = """
v = sorted(t)
# foo
foo(v)
"""
self.check(b, a)
b = r"""
v = list( t)
v.sort()
foo(v)
"""
a = r"""
v = sorted( t)
foo(v)
"""
self.check(b, a)
b = r"""
try:
m = list(s)
m.sort()
except: pass
"""
a = r"""
try:
m = sorted(s)
except: pass
"""
self.check(b, a)
b = r"""
try:
m = list(s)
# foo
m.sort()
except: pass
"""
a = r"""
try:
m = sorted(s)
# foo
except: pass
"""
self.check(b, a)
b = r"""
m = list(s)
# more comments
m.sort()"""
a = r"""
m = sorted(s)
# more comments"""
self.check(b, a)
def test_sort_simple_expr(self):
b = """
v = t
v.sort()
foo(v)
"""
a = """
v = sorted(t)
foo(v)
"""
self.check(b, a)
b = """
v = foo(b)
v.sort()
foo(v)
"""
a = """
v = sorted(foo(b))
foo(v)
"""
self.check(b, a)
b = """
v = b.keys()
v.sort()
foo(v)
"""
a = """
v = sorted(b.keys())
foo(v)
"""
self.check(b, a)
b = """
v = foo(b) + d
v.sort()
foo(v)
"""
a = """
v = sorted(foo(b) + d)
foo(v)
"""
self.check(b, a)
b = """
while x:
v = t
v.sort()
foo(v)
"""
a = """
while x:
v = sorted(t)
foo(v)
"""
self.check(b, a)
b = """
v = t
# foo
v.sort()
foo(v)
"""
a = """
v = sorted(t)
# foo
foo(v)
"""
self.check(b, a)
b = r"""
v = t
v.sort()
foo(v)
"""
a = r"""
v = sorted(t)
foo(v)
"""
self.check(b, a)
def test_sort_unchanged(self):
s = """
v = list(t)
w.sort()
foo(w)
"""
self.unchanged(s)
s = """
v = list(t)
v.sort(u)
foo(v)
"""
self.unchanged(s)
class Test_basestring(FixerTestCase):
fixer = "basestring"
def test_basestring(self):
b = """isinstance(x, basestring)"""
a = """isinstance(x, str)"""
self.check(b, a)
class Test_buffer(FixerTestCase):
fixer = "buffer"
def test_buffer(self):
b = """x = buffer(y)"""
a = """x = memoryview(y)"""
self.check(b, a)
def test_slicing(self):
b = """buffer(y)[4:5]"""
a = """memoryview(y)[4:5]"""
self.check(b, a)
class Test_future(FixerTestCase):
fixer = "future"
def test_future(self):
b = """from __future__ import braces"""
a = """"""
self.check(b, a)
b = """# comment\nfrom __future__ import braces"""
a = """# comment\n"""
self.check(b, a)
b = """from __future__ import braces\n# comment"""
a = """\n# comment"""
self.check(b, a)
def test_run_order(self):
self.assert_runs_after('print')
class Test_itertools(FixerTestCase):
fixer = "itertools"
def checkall(self, before, after):
# Because we need to check with and without the itertools prefix
# and on each of the three functions, these loops make it all
# much easier
for i in ('itertools.', ''):
for f in ('map', 'filter', 'zip'):
b = before %(i+'i'+f)
a = after %(f)
self.check(b, a)
def test_0(self):
# A simple example -- test_1 covers exactly the same thing,
# but it's not quite as clear.
b = "itertools.izip(a, b)"
a = "zip(a, b)"
self.check(b, a)
def test_1(self):
b = """%s(f, a)"""
a = """%s(f, a)"""
self.checkall(b, a)
def test_qualified(self):
b = """itertools.ifilterfalse(a, b)"""
a = """itertools.filterfalse(a, b)"""
self.check(b, a)
b = """itertools.izip_longest(a, b)"""
a = """itertools.zip_longest(a, b)"""
self.check(b, a)
def test_2(self):
b = """ifilterfalse(a, b)"""
a = """filterfalse(a, b)"""
self.check(b, a)
b = """izip_longest(a, b)"""
a = """zip_longest(a, b)"""
self.check(b, a)
def test_space_1(self):
b = """ %s(f, a)"""
a = """ %s(f, a)"""
self.checkall(b, a)
def test_space_2(self):
b = """ itertools.ifilterfalse(a, b)"""
a = """ itertools.filterfalse(a, b)"""
self.check(b, a)
b = """ itertools.izip_longest(a, b)"""
a = """ itertools.zip_longest(a, b)"""
self.check(b, a)
def test_run_order(self):
self.assert_runs_after('map', 'zip', 'filter')
class Test_itertools_imports(FixerTestCase):
fixer = 'itertools_imports'
def test_reduced(self):
b = "from itertools import imap, izip, foo"
a = "from itertools import foo"
self.check(b, a)
b = "from itertools import bar, imap, izip, foo"
a = "from itertools import bar, foo"
self.check(b, a)
b = "from itertools import chain, imap, izip"
a = "from itertools import chain"
self.check(b, a)
def test_comments(self):
b = "#foo\nfrom itertools import imap, izip"
a = "#foo\n"
self.check(b, a)
def test_none(self):
b = "from itertools import imap, izip"
a = ""
self.check(b, a)
b = "from itertools import izip"
a = ""
self.check(b, a)
def test_import_as(self):
b = "from itertools import izip, bar as bang, imap"
a = "from itertools import bar as bang"
self.check(b, a)
b = "from itertools import izip as _zip, imap, bar"
a = "from itertools import bar"
self.check(b, a)
b = "from itertools import imap as _map"
a = ""
self.check(b, a)
b = "from itertools import imap as _map, izip as _zip"
a = ""
self.check(b, a)
s = "from itertools import bar as bang"
self.unchanged(s)
def test_ifilter_and_zip_longest(self):
for name in "filterfalse", "zip_longest":
b = "from itertools import i%s" % (name,)
a = "from itertools import %s" % (name,)
self.check(b, a)
b = "from itertools import imap, i%s, foo" % (name,)
a = "from itertools import %s, foo" % (name,)
self.check(b, a)
b = "from itertools import bar, i%s, foo" % (name,)
a = "from itertools import bar, %s, foo" % (name,)
self.check(b, a)
def test_import_star(self):
s = "from itertools import *"
self.unchanged(s)
def test_unchanged(self):
s = "from itertools import foo"
self.unchanged(s)
class Test_import(FixerTestCase):
fixer = "import"
def setUp(self):
super(Test_import, self).setUp()
# Need to replace fix_import's exists method
# so we can check that it's doing the right thing
self.files_checked = []
self.present_files = set()
self.always_exists = True
def fake_exists(name):
self.files_checked.append(name)
return self.always_exists or (name in self.present_files)
from lib2to3.fixes import fix_import
fix_import.exists = fake_exists
def tearDown(self):
from lib2to3.fixes import fix_import
fix_import.exists = os.path.exists
def check_both(self, b, a):
self.always_exists = True
super(Test_import, self).check(b, a)
self.always_exists = False
super(Test_import, self).unchanged(b)
def test_files_checked(self):
def p(path):
# Takes a unix path and returns a path with correct separators
return os.path.pathsep.join(path.split("/"))
self.always_exists = False
self.present_files = set(['__init__.py'])
expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd')
names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py"))
for name in names_to_test:
self.files_checked = []
self.filename = name
self.unchanged("import jam")
if os.path.dirname(name):
name = os.path.dirname(name) + '/jam'
else:
name = 'jam'
expected_checks = set(name + ext for ext in expected_extensions)
expected_checks.add("__init__.py")
self.assertEqual(set(self.files_checked), expected_checks)
def test_not_in_package(self):
s = "import bar"
self.always_exists = False
self.present_files = set(["bar.py"])
self.unchanged(s)
def test_with_absolute_import_enabled(self):
s = "from __future__ import absolute_import\nimport bar"
self.always_exists = False
self.present_files = set(["__init__.py", "bar.py"])
self.unchanged(s)
def test_in_package(self):
b = "import bar"
a = "from . import bar"
self.always_exists = False
self.present_files = set(["__init__.py", "bar.py"])
self.check(b, a)
def test_import_from_package(self):
b = "import bar"
a = "from . import bar"
self.always_exists = False
self.present_files = set(["__init__.py", "bar" + os.path.sep])
self.check(b, a)
def test_already_relative_import(self):
s = "from . import bar"
self.unchanged(s)
def test_comments_and_indent(self):
b = "import bar # Foo"
a = "from . import bar # Foo"
self.check(b, a)
def test_from(self):
b = "from foo import bar, baz"
a = "from .foo import bar, baz"
self.check_both(b, a)
b = "from foo import bar"
a = "from .foo import bar"
self.check_both(b, a)
b = "from foo import (bar, baz)"
a = "from .foo import (bar, baz)"
self.check_both(b, a)
def test_dotted_from(self):
b = "from green.eggs import ham"
a = "from .green.eggs import ham"
self.check_both(b, a)
def test_from_as(self):
b = "from green.eggs import ham as spam"
a = "from .green.eggs import ham as spam"
self.check_both(b, a)
def test_import(self):
b = "import foo"
a = "from . import foo"
self.check_both(b, a)
b = "import foo, bar"
a = "from . import foo, bar"
self.check_both(b, a)
b = "import foo, bar, x"
a = "from . import foo, bar, x"
self.check_both(b, a)
b = "import x, y, z"
a = "from . import x, y, z"
self.check_both(b, a)
def test_import_as(self):
b = "import foo as x"
a = "from . import foo as x"
self.check_both(b, a)
b = "import a as b, b as c, c as d"
a = "from . import a as b, b as c, c as d"
self.check_both(b, a)
def test_local_and_absolute(self):
self.always_exists = False
self.present_files = set(["foo.py", "__init__.py"])
s = "import foo, bar"
self.warns_unchanged(s, "absolute and local imports together")
def test_dotted_import(self):
b = "import foo.bar"
a = "from . import foo.bar"
self.check_both(b, a)
def test_dotted_import_as(self):
b = "import foo.bar as bang"
a = "from . import foo.bar as bang"
self.check_both(b, a)
def test_prefix(self):
b = """
# prefix
import foo.bar
"""
a = """
# prefix
from . import foo.bar
"""
self.check_both(b, a)
class Test_set_literal(FixerTestCase):
fixer = "set_literal"
def test_basic(self):
b = """set([1, 2, 3])"""
a = """{1, 2, 3}"""
self.check(b, a)
b = """set((1, 2, 3))"""
a = """{1, 2, 3}"""
self.check(b, a)
b = """set((1,))"""
a = """{1}"""
self.check(b, a)
b = """set([1])"""
self.check(b, a)
b = """set((a, b))"""
a = """{a, b}"""
self.check(b, a)
b = """set([a, b])"""
self.check(b, a)
b = """set((a*234, f(args=23)))"""
a = """{a*234, f(args=23)}"""
self.check(b, a)
b = """set([a*23, f(23)])"""
a = """{a*23, f(23)}"""
self.check(b, a)
b = """set([a-234**23])"""
a = """{a-234**23}"""
self.check(b, a)
def test_listcomps(self):
b = """set([x for x in y])"""
a = """{x for x in y}"""
self.check(b, a)
b = """set([x for x in y if x == m])"""
a = """{x for x in y if x == m}"""
self.check(b, a)
b = """set([x for x in y for a in b])"""
a = """{x for x in y for a in b}"""
self.check(b, a)
b = """set([f(x) - 23 for x in y])"""
a = """{f(x) - 23 for x in y}"""
self.check(b, a)
def test_whitespace(self):
b = """set( [1, 2])"""
a = """{1, 2}"""
self.check(b, a)
b = """set([1 , 2])"""
a = """{1 , 2}"""
self.check(b, a)
b = """set([ 1 ])"""
a = """{ 1 }"""
self.check(b, a)
b = """set( [1] )"""
a = """{1}"""
self.check(b, a)
b = """set([ 1, 2 ])"""
a = """{ 1, 2 }"""
self.check(b, a)
b = """set([x for x in y ])"""
a = """{x for x in y }"""
self.check(b, a)
b = """set(
[1, 2]
)
"""
a = """{1, 2}\n"""
self.check(b, a)
def test_comments(self):
b = """set((1, 2)) # Hi"""
a = """{1, 2} # Hi"""
self.check(b, a)
# This isn't optimal behavior, but the fixer is optional.
b = """
# Foo
set( # Bar
(1, 2)
)
"""
a = """
# Foo
{1, 2}
"""
self.check(b, a)
def test_unchanged(self):
s = """set()"""
self.unchanged(s)
s = """set(a)"""
self.unchanged(s)
s = """set(a, b, c)"""
self.unchanged(s)
# Don't transform generators because they might have to be lazy.
s = """set(x for x in y)"""
self.unchanged(s)
s = """set(x for x in y if z)"""
self.unchanged(s)
s = """set(a*823-23**2 + f(23))"""
self.unchanged(s)
class Test_sys_exc(FixerTestCase):
fixer = "sys_exc"
def test_0(self):
b = "sys.exc_type"
a = "sys.exc_info()[0]"
self.check(b, a)
def test_1(self):
b = "sys.exc_value"
a = "sys.exc_info()[1]"
self.check(b, a)
def test_2(self):
b = "sys.exc_traceback"
a = "sys.exc_info()[2]"
self.check(b, a)
def test_3(self):
b = "sys.exc_type # Foo"
a = "sys.exc_info()[0] # Foo"
self.check(b, a)
def test_4(self):
b = "sys. exc_type"
a = "sys. exc_info()[0]"
self.check(b, a)
def test_5(self):
b = "sys .exc_type"
a = "sys .exc_info()[0]"
self.check(b, a)
class Test_paren(FixerTestCase):
fixer = "paren"
def test_0(self):
b = """[i for i in 1, 2 ]"""
a = """[i for i in (1, 2) ]"""
self.check(b, a)
def test_1(self):
b = """[i for i in 1, 2, ]"""
a = """[i for i in (1, 2,) ]"""
self.check(b, a)
def test_2(self):
b = """[i for i in 1, 2 ]"""
a = """[i for i in (1, 2) ]"""
self.check(b, a)
def test_3(self):
b = """[i for i in 1, 2 if i]"""
a = """[i for i in (1, 2) if i]"""
self.check(b, a)
def test_4(self):
b = """[i for i in 1, 2 ]"""
a = """[i for i in (1, 2) ]"""
self.check(b, a)
def test_5(self):
b = """(i for i in 1, 2)"""
a = """(i for i in (1, 2))"""
self.check(b, a)
def test_6(self):
b = """(i for i in 1 ,2 if i)"""
a = """(i for i in (1 ,2) if i)"""
self.check(b, a)
def test_unchanged_0(self):
s = """[i for i in (1, 2)]"""
self.unchanged(s)
def test_unchanged_1(self):
s = """[i for i in foo()]"""
self.unchanged(s)
def test_unchanged_2(self):
s = """[i for i in (1, 2) if nothing]"""
self.unchanged(s)
def test_unchanged_3(self):
s = """(i for i in (1, 2))"""
self.unchanged(s)
def test_unchanged_4(self):
s = """[i for i in m]"""
self.unchanged(s)
class Test_metaclass(FixerTestCase):
fixer = 'metaclass'
def test_unchanged(self):
self.unchanged("class X(): pass")
self.unchanged("class X(object): pass")
self.unchanged("class X(object1, object2): pass")
self.unchanged("class X(object1, object2, object3): pass")
self.unchanged("class X(metaclass=Meta): pass")
self.unchanged("class X(b, arg=23, metclass=Meta): pass")
self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass")
s = """
class X:
def __metaclass__(self): pass
"""
self.unchanged(s)
s = """
class X:
a[23] = 74
"""
self.unchanged(s)
def test_comments(self):
b = """
class X:
# hi
__metaclass__ = AppleMeta
"""
a = """
class X(metaclass=AppleMeta):
# hi
pass
"""
self.check(b, a)
b = """
class X:
__metaclass__ = Meta
# Bedtime!
"""
a = """
class X(metaclass=Meta):
pass
# Bedtime!
"""
self.check(b, a)
def test_meta(self):
# no-parent class, odd body
b = """
class X():
__metaclass__ = Q
pass
"""
a = """
class X(metaclass=Q):
pass
"""
self.check(b, a)
# one parent class, no body
b = """class X(object): __metaclass__ = Q"""
a = """class X(object, metaclass=Q): pass"""
self.check(b, a)
# one parent, simple body
b = """
class X(object):
__metaclass__ = Meta
bar = 7
"""
a = """
class X(object, metaclass=Meta):
bar = 7
"""
self.check(b, a)
b = """
class X:
__metaclass__ = Meta; x = 4; g = 23
"""
a = """
class X(metaclass=Meta):
x = 4; g = 23
"""
self.check(b, a)
# one parent, simple body, __metaclass__ last
b = """
class X(object):
bar = 7
__metaclass__ = Meta
"""
a = """
class X(object, metaclass=Meta):
bar = 7
"""
self.check(b, a)
# redefining __metaclass__
b = """
class X():
__metaclass__ = A
__metaclass__ = B
bar = 7
"""
a = """
class X(metaclass=B):
bar = 7
"""
self.check(b, a)
# multiple inheritance, simple body
b = """
class X(clsA, clsB):
__metaclass__ = Meta
bar = 7
"""
a = """
class X(clsA, clsB, metaclass=Meta):
bar = 7
"""
self.check(b, a)
# keywords in the class statement
b = """class m(a, arg=23): __metaclass__ = Meta"""
a = """class m(a, arg=23, metaclass=Meta): pass"""
self.check(b, a)
b = """
class X(expression(2 + 4)):
__metaclass__ = Meta
"""
a = """
class X(expression(2 + 4), metaclass=Meta):
pass
"""
self.check(b, a)
b = """
class X(expression(2 + 4), x**4):
__metaclass__ = Meta
"""
a = """
class X(expression(2 + 4), x**4, metaclass=Meta):
pass
"""
self.check(b, a)
b = """
class X:
__metaclass__ = Meta
save.py = 23
"""
a = """
class X(metaclass=Meta):
save.py = 23
"""
self.check(b, a)
class Test_getcwdu(FixerTestCase):
fixer = 'getcwdu'
def test_basic(self):
b = """os.getcwdu"""
a = """os.getcwd"""
self.check(b, a)
b = """os.getcwdu()"""
a = """os.getcwd()"""
self.check(b, a)
b = """meth = os.getcwdu"""
a = """meth = os.getcwd"""
self.check(b, a)
b = """os.getcwdu(args)"""
a = """os.getcwd(args)"""
self.check(b, a)
def test_comment(self):
b = """os.getcwdu() # Foo"""
a = """os.getcwd() # Foo"""
self.check(b, a)
def test_unchanged(self):
s = """os.getcwd()"""
self.unchanged(s)
s = """getcwdu()"""
self.unchanged(s)
s = """os.getcwdb()"""
self.unchanged(s)
def test_indentation(self):
b = """
if 1:
os.getcwdu()
"""
a = """
if 1:
os.getcwd()
"""
self.check(b, a)
def test_multilation(self):
b = """os .getcwdu()"""
a = """os .getcwd()"""
self.check(b, a)
b = """os. getcwdu"""
a = """os. getcwd"""
self.check(b, a)
b = """os.getcwdu ( )"""
a = """os.getcwd ( )"""
self.check(b, a)
class Test_operator(FixerTestCase):
fixer = "operator"
def test_operator_isCallable(self):
b = "operator.isCallable(x)"
a = "hasattr(x, '__call__')"
self.check(b, a)
def test_operator_sequenceIncludes(self):
b = "operator.sequenceIncludes(x, y)"
a = "operator.contains(x, y)"
self.check(b, a)
b = "operator .sequenceIncludes(x, y)"
a = "operator .contains(x, y)"
self.check(b, a)
b = "operator. sequenceIncludes(x, y)"
a = "operator. contains(x, y)"
self.check(b, a)
def test_operator_isSequenceType(self):
b = "operator.isSequenceType(x)"
a = "import collections\nisinstance(x, collections.Sequence)"
self.check(b, a)
def test_operator_isMappingType(self):
b = "operator.isMappingType(x)"
a = "import collections\nisinstance(x, collections.Mapping)"
self.check(b, a)
def test_operator_isNumberType(self):
b = "operator.isNumberType(x)"
a = "import numbers\nisinstance(x, numbers.Number)"
self.check(b, a)
def test_operator_repeat(self):
b = "operator.repeat(x, n)"
a = "operator.mul(x, n)"
self.check(b, a)
b = "operator .repeat(x, n)"
a = "operator .mul(x, n)"
self.check(b, a)
b = "operator. repeat(x, n)"
a = "operator. mul(x, n)"
self.check(b, a)
def test_operator_irepeat(self):
b = "operator.irepeat(x, n)"
a = "operator.imul(x, n)"
self.check(b, a)
b = "operator .irepeat(x, n)"
a = "operator .imul(x, n)"
self.check(b, a)
b = "operator. irepeat(x, n)"
a = "operator. imul(x, n)"
self.check(b, a)
def test_bare_isCallable(self):
s = "isCallable(x)"
t = "You should use 'hasattr(x, '__call__')' here."
self.warns_unchanged(s, t)
def test_bare_sequenceIncludes(self):
s = "sequenceIncludes(x, y)"
t = "You should use 'operator.contains(x, y)' here."
self.warns_unchanged(s, t)
def test_bare_operator_isSequenceType(self):
s = "isSequenceType(z)"
t = "You should use 'isinstance(z, collections.Sequence)' here."
self.warns_unchanged(s, t)
def test_bare_operator_isMappingType(self):
s = "isMappingType(x)"
t = "You should use 'isinstance(x, collections.Mapping)' here."
self.warns_unchanged(s, t)
def test_bare_operator_isNumberType(self):
s = "isNumberType(y)"
t = "You should use 'isinstance(y, numbers.Number)' here."
self.warns_unchanged(s, t)
def test_bare_operator_repeat(self):
s = "repeat(x, n)"
t = "You should use 'operator.mul(x, n)' here."
self.warns_unchanged(s, t)
def test_bare_operator_irepeat(self):
s = "irepeat(y, 187)"
t = "You should use 'operator.imul(y, 187)' here."
self.warns_unchanged(s, t)
class Test_exitfunc(FixerTestCase):
fixer = "exitfunc"
def test_simple(self):
b = """
import sys
sys.exitfunc = my_atexit
"""
a = """
import sys
import atexit
atexit.register(my_atexit)
"""
self.check(b, a)
def test_names_import(self):
b = """
import sys, crumbs
sys.exitfunc = my_func
"""
a = """
import sys, crumbs, atexit
atexit.register(my_func)
"""
self.check(b, a)
def test_complex_expression(self):
b = """
import sys
sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
"""
a = """
import sys
import atexit
atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
"""
self.check(b, a)
def test_comments(self):
b = """
import sys # Foo
sys.exitfunc = f # Blah
"""
a = """
import sys
import atexit # Foo
atexit.register(f) # Blah
"""
self.check(b, a)
b = """
import apples, sys, crumbs, larry # Pleasant comments
sys.exitfunc = func
"""
a = """
import apples, sys, crumbs, larry, atexit # Pleasant comments
atexit.register(func)
"""
self.check(b, a)
def test_in_a_function(self):
b = """
import sys
def f():
sys.exitfunc = func
"""
a = """
import sys
import atexit
def f():
atexit.register(func)
"""
self.check(b, a)
def test_no_sys_import(self):
b = """sys.exitfunc = f"""
a = """atexit.register(f)"""
msg = ("Can't find sys import; Please add an atexit import at the "
"top of your file.")
self.warns(b, a, msg)
def test_unchanged(self):
s = """f(sys.exitfunc)"""
self.unchanged(s)
class Test_asserts(FixerTestCase):
fixer = "asserts"
def test_deprecated_names(self):
tests = [
('self.assert_(True)', 'self.assertTrue(True)'),
('self.assertEquals(2, 2)', 'self.assertEqual(2, 2)'),
('self.assertNotEquals(2, 3)', 'self.assertNotEqual(2, 3)'),
('self.assertAlmostEquals(2, 3)', 'self.assertAlmostEqual(2, 3)'),
('self.assertNotAlmostEquals(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
('self.failUnlessEqual(2, 2)', 'self.assertEqual(2, 2)'),
('self.failIfEqual(2, 3)', 'self.assertNotEqual(2, 3)'),
('self.failUnlessAlmostEqual(2, 3)', 'self.assertAlmostEqual(2, 3)'),
('self.failIfAlmostEqual(2, 8)', 'self.assertNotAlmostEqual(2, 8)'),
('self.failUnless(True)', 'self.assertTrue(True)'),
('self.failUnlessRaises(foo)', 'self.assertRaises(foo)'),
('self.failIf(False)', 'self.assertFalse(False)'),
]
for b, a in tests:
self.check(b, a)
def test_variants(self):
b = 'eq = self.assertEquals'
a = 'eq = self.assertEqual'
self.check(b, a)
b = 'self.assertEquals(2, 3, msg="fail")'
a = 'self.assertEqual(2, 3, msg="fail")'
self.check(b, a)
b = 'self.assertEquals(2, 3, msg="fail") # foo'
a = 'self.assertEqual(2, 3, msg="fail") # foo'
self.check(b, a)
b = 'self.assertEquals (2, 3)'
a = 'self.assertEqual (2, 3)'
self.check(b, a)
b = ' self.assertEquals (2, 3)'
a = ' self.assertEqual (2, 3)'
self.check(b, a)
b = 'with self.failUnlessRaises(Explosion): explode()'
a = 'with self.assertRaises(Explosion): explode()'
self.check(b, a)
b = 'with self.failUnlessRaises(Explosion) as cm: explode()'
a = 'with self.assertRaises(Explosion) as cm: explode()'
self.check(b, a)
def test_unchanged(self):
self.unchanged('self.assertEqualsOnSaturday')
self.unchanged('self.assertEqualsOnSaturday(3, 5)')
| mit |
opendatadurban/scoda | scoda/public.py | 1 | 54121 | import itertools
import operator
from sqlalchemy_searchable import search
from scoda.app import app
from flask import request, url_for, redirect, flash, make_response, session, render_template, jsonify, Response, \
send_file
from flask_security import current_user
from itertools import zip_longest
from sqlalchemy.sql import select
from sqlalchemy import func, extract, desc
from .models import db
from .models import *
from .models.user import UserAnalysis
from .models.datasets import ExploreForm
from .models.maps import MapForm, NightFormETH, NightFormJHB
from pandas import read_sql_query
import gviz_api
import geojson, json
import pandas as pd
from .app import csrf
from werkzeug.datastructures import MultiDict
from urllib.parse import urlencode, urlparse, parse_qsl, urlsplit, parse_qs
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
@app.route('/help')
def help():
return render_template('help/help.html')
@app.route('/api/indicators-list/', defaults={'check': ''})
@app.route('/api/indicators-list/<check>', methods=['GET', 'POST'])
def api_indicators_list(check):
remove_list = ['Poverty rate', 'Gini Coefficient', 'Gross Value Add', 'Exports', 'Multiple deprivation index',
'Human Development Index']
if check == "codebook":
indicators_list = [[str(c.id), c.name] for c in CbIndicator.query.join(CbDataPoint,CbDataPoint.indicator_id == CbIndicator.id).all() if c.name not in remove_list]
else:
indicators_list = [[str(c.id), c.in_name] for c in Indicator.all() if c.in_name not in remove_list]
# print(indicators_list)
# payload = {"indicators_list": indicators_list}
return jsonify(indicators_list)
@app.route('/api/explore/', defaults={'check': ''})
@app.route('/api/explore/<check>', methods=['GET', 'POST'])
def api_explore(check):
form = ExploreForm()
status = 200
plot = 0
tour = 1
#ind = 76
#Note: Riaan Snyders: 10 June 2020 - Removed for now. Only functions on GET at the moment.
#if request.method == 'POST':
#if form.validate():
#data_json = request.get_json()
#ind = data_json["indicator_id"]
if request.args.get('indicator_id'):
ind = request.args.get('indicator_id')
else:
ind = 76
print(ind)
plot = 1
tour = 2
# codebook query
if check == "codebook":
query = db.session.query(CbRegion.name.label('re_name'), CbDataPoint.start_dt, CbIndicator.name.label('ds_name'), CbDataPoint.value). \
filter(CbDataPoint.indicator_id == ind).filter(CbDataPoint.indicator_id == CbIndicator.id). \
filter(CbDataPoint.region_id == CbRegion.id)
df = read_sql_query(query.statement, query.session.bind)
df = df.rename(columns={'name': 're_name', 'name.1': 'ds_name'})
df["year"] = df["start_dt"].apply(lambda x: int(x.strftime('%Y')))
df["start_dt"] = df["year"]
else:
query = db.session.query(Region.re_name, DataPoint.year, DataSet.ds_name, DataPoint.value). \
filter(DataPoint.indicator_id == ind).filter(DataPoint.dataset_id == DataSet.id). \
filter(DataPoint.region_id == Region.id)
df = read_sql_query(query.statement, query.session.bind)
df.to_csv('%s/data/%s' % (app.root_path, "data_test.csv"), index=False)
table = []
table_plot = []
years, cities, datasets = [list(df.year.unique()), list(df.re_name.unique()), list(df.ds_name.unique())]
cities = [c for c in cities]
options_list = [{'optid': i, 'optname': d} for i, d in enumerate(datasets, start=1)]
years_list = [{'optid': i, 'optname': 'Year: %s' % d} for i, d in enumerate(sorted(years), start=1)]
plot_type = 1
print(len(years))
if (len(datasets) > 1) or (len(years) == 1):
plot_type = 2
colours = ['#f44336', '#03a9f4', '#4caf50', '#ffc107', '#03a9f4', '#ff5722', '#9c27b0', '#8bc34a',
'#ffeb3b', '#9e9e9e', '#3f51b5', '#e91e63']
series = {i: {'color': colours[i]} for i in range(len(datasets))}
view = list(range(2, len(datasets) + 2))
view.insert(0, 0)
minVal = min(map(float, list(df.value.unique())))
maxVal = max(map(float, list(df.value.unique()))) * 1.1
head = ['City', 'Year']
for i in datasets:
head.append(str(i))
table.append(head)
table_plot.append(head)
# df.re_name = df.re_name.str.encode('utf-8')
if plot_type == 1:
df_i = df.iloc[:, [0, 1, 3]]
schema = [('City', 'string'), ('Year', 'string'), ('%s' % datasets[0], 'number')]
data_table = gviz_api.DataTable(schema)
data_table.LoadData(df_i.values)
table_plot = data_table.ToJSon(columns_order=('City', '%s' % datasets[0], 'Year'))
for c in cities:
for y in years:
row = [str(c), str(y)]
for d in datasets:
datapoint = df.loc[(df["re_name"] == c) & (df["year"] == y) & (df["ds_name"] == d), "value"]
if len(datapoint) == 0:
row.append(None)
else:
row.append(
float(df.loc[(df["re_name"] == c) & (df["year"] == y) & (
df["ds_name"] == d), "value"]))
table.append(row)
else:
for c in cities:
for y in years:
row = [str(c), str(y)]
for d in datasets:
datapoint = df.loc[(df["re_name"] == c) & (df["year"] == y) & (df["ds_name"] == d), "value"]
if len(datapoint) == 0:
row.append(None)
else:
row.append(
float(df.loc[(df["re_name"] == c) & (df["year"] == y) & (
df["ds_name"] == d), "value"]))
table.append(row)
yrs = ['Year'] + [str(y) for y in years[::-1]]
payload = {"plot":plot, "table":table, "table_plot":table_plot,"colours":colours,"year":str(max(years)), "series":series,
"view":view, "plot_type":plot_type,"min":minVal,"max":maxVal, "cities":cities, "options_list":options_list,
"years_list":years_list,"tour":tour, "years":yrs}
return jsonify(payload)
# else:
# form_errors = form.errors
# return {"form_errors":form_errors}
@app.route('/explore', methods=['GET', 'POST'])
def explore():
analyses = []
if current_user.is_authenticated:
query = db.session.query(UserAnalysis.id, UserAnalysis.ds_name, UserAnalysis.description) \
.filter(UserAnalysis.user_id == current_user.id).order_by(UserAnalysis.id.desc())
analyses = []
for i in grouper(query, 4):
analyses.append(i)
session['explore'] = []
form = ExploreForm()
status = 200
plot = 0
tour = 1
if request.method == 'POST':
if form.validate():
plot = 1
tour = 2
ind = form.indicator_id.data
query = db.session.query(Region.re_name, DataPoint.year, DataSet.ds_name, DataPoint.value). \
filter(DataPoint.indicator_id == ind).filter(DataPoint.dataset_id == DataSet.id). \
filter(DataPoint.region_id == Region.id)
print(query.all())
indicator = Indicator.query.get(ind)
df = read_sql_query(query.statement, query.session.bind)
# df.to_csv('%s/data/%s' % (app.root_path, "data_test.csv"), index=False)
table = []
years, cities, datasets = [list(df.year.unique()), list(df.re_name.unique()), list(df.ds_name.unique())]
cities = [c for c in cities]
options_list = [{'optid': i, 'optname': d} for i, d in enumerate(datasets, start=1)]
years_list = [{'optid': i, 'optname': 'Year: %s' % d} for i, d in enumerate(sorted(years), start=1)]
plot_type = 1
if (len(datasets) > 1) or (len(years) == 1):
plot_type = 2
colours = ['#f44336', '#03a9f4', '#4caf50', '#ffc107', '#03a9f4', '#ff5722', '#9c27b0', '#8bc34a',
'#ffeb3b', '#9e9e9e', '#3f51b5', '#e91e63']
series = {i: {'color': colours[i]} for i in range(len(datasets))}
view = list(range(2, len(datasets) + 2))
view.insert(0, 0)
minVal = min(map(float, list(df.value.unique())))
maxVal = max(map(float, list(df.value.unique()))) * 1.1
head = ['City', 'Year']
for i in datasets:
head.append(str(i))
table.append(head)
print(df)
# df.re_name = df.re_name.str.encode('utf-8')
if plot_type == 1:
df = df.iloc[:, [0, 1, 3]]
schema = [('City', 'string'), ('Year', 'string'), ('%s' % datasets[0], 'number')]
data_table = gviz_api.DataTable(schema)
data_table.LoadData(df.values)
table = data_table.ToJSon(columns_order=('City', '%s' % datasets[0], 'Year'))
else:
for c in cities:
for y in years:
row = [str(c), str(y)]
for d in datasets:
datapoint = df.loc[(df["re_name"] == c) & (df["year"] == y) & (df["ds_name"] == d), "value"]
if len(datapoint) == 0:
row.append(None)
else:
row.append(
float(df.loc[(df["re_name"] == c) & (df["year"] == y) & (
df["ds_name"] == d), "value"]))
table.append(row)
yrs = ['Year'] + [str(y) for y in years[::-1]]
return render_template('explore/explore.html', form=form, plot=plot, table=table, colours=colours,
year=str(max(years)), series=series, view=view, plot_type=plot_type, min=minVal,
max=maxVal, cities=cities, options_list=options_list, years_list=years_list,
tour=tour, indicator=indicator, analyses=analyses, years=yrs)
else:
if request.is_xhr:
status = 412
else:
flash('Please correct the problems below and try again.', 'warning')
else:
return render_template('explore/explore.html', form=form, tour=tour)
if not request.is_xhr:
resp = make_response(
render_template('explore/explore.html', form=form, plot=plot, tour=tour, analyses=analyses))
else:
resp = ''
return (resp, status,
# ensure the browser refreshes the page when Back is pressed
{'Cache-Control': 'no-cache, no-store, must-revalidate'})
@app.route('/demographics/<region_id>/<city_ward_code>/download', methods=['GET'])
def demographics_download(region_id, city_ward_code):
region = Region.query.get(region_id).re_name
if city_ward_code == 'None':
query = db.session.query(Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == region_id).all()
df = pd.DataFrame()
df['Year'] = range(1996, 2031)
for g in query:
df['%s - Ward %s' % (region, g[1])] = list(g[0])
else:
query = db.session.query(Ward.data, Ward.city_ward_code) \
.filter(Ward.city_ward_code == city_ward_code) \
.filter(Ward.region_id == region_id).all()
df = pd.DataFrame()
df['Year'] = range(1996, 2031)
for g in query:
df['%s - Ward %s' % (region, g[1])] = list(g[0])
return Response(df.to_csv(index=False), mimetype="text/csv",
headers={"Content-disposition": "attachment; filename=demographics.csv"})
@app.route('/demographics', methods=['GET', 'POST'])
def demographics():
analyses = []
if current_user.is_authenticated:
query = db.session.query(UserAnalysis.id, UserAnalysis.ds_name, UserAnalysis.description) \
.filter(UserAnalysis.user_id == current_user.id).order_by(UserAnalysis.id.desc())
analyses = []
for i in grouper(query, 4):
analyses.append(i)
session['demo'] = []
if 'maps' not in session.keys():
session['maps'] = {0: {}, 1: {}}
form1 = MapForm(prefix='form1', region_id='1', year=1)
print(form1.city_ward_code.choices)
status = 200
tour = 1
geometries1 = {}
forms = [form1]
if request.method == 'POST':
if all(f.validate() for f in forms):
for f, F in enumerate(forms):
for field in F:
if str(field.data) == 'None':
field.data = session['maps'][str(f)][field.name[6:]]
else:
session['maps'][str(f)][field.name[6:]] = field.data
tour = 0
# query = db.session.query(Area.geom.ST_AsGeoJSON(), Area.data)
year1 = int(form1.year.data)
year_ind1 = range(1996, 2031)
if form1.city_ward_code.data == '':
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == form1.region_id.data)
geometries1 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
if year1 == 0:
flow = 0
else:
flow = round(g[1][year1] - g[1][year1 - 1])
geometries1['features'].append({"type": "Feature", "properties": {"density": round(g[1][year1]),
"flow": flow,
"name": 'Ward %s' % g[2],
"year": year_ind1[year1]},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == form1.region_id.data).all()
region = db.session.query(Region.re_name).filter(Region.id == form1.region_id.data).first()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', '%s' % str(region[0])]]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m1 = 1.05 * max(df.sum(axis=0).tolist())
else:
query = db.session.query(Area.geom.ST_AsGeoJSON(), Area.data, Area.city_ward_code) \
.filter(Area.city_ward_code == form1.city_ward_code.data) \
.filter(Area.region_id == form1.region_id.data)
geometries1 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
if year1 == 0:
flow = 0
else:
flow = round(g[1][year1] - g[1][year1 - 1])
geometries1['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][year1]),
"flow": flow,
"name": 'Area %s' % g[2],
"year": year_ind1[year1]},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.city_ward_code == form1.city_ward_code.data). \
filter(Ward.region_id == form1.region_id.data).first()
region = db.session.query(Region.re_name).filter(Region.id == form1.region_id.data).first()
region2 = db.session.query(Ward.city_ward_code).filter(Ward.city_ward_code == form1.city_ward_code.data) \
.first()
results = []
for r in query:
row = [val for val in list(r)]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', '%s - Ward %s' % (str(region[0]), str(region2[0]))]]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m1 = 1.05 * max(df.sum(axis=0).tolist())
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == form1.region_id.data).order_by(
Ward.city_ward_code).distinct()
form1.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in enumerate(query.all()
, start=1)]
form1.city_ward_code.choices.insert(0, ('', 'View All'))
return render_template('demographics/demographics.html', form1=form1, geometries1=geometries1,
table1=table1, tour=tour, max1=m1, region1=form1.region_id.data,
ward1=form1.city_ward_code.data, analyses=analyses)
else:
if request.is_xhr:
status = 412
else:
flash('Please correct the problems below and try again.', 'warning')
else:
session['maps'][0] = {'city_ward_code': '', 'region_id': 1, 'year': 1}
session['maps'][1] = {'city_ward_code': '', 'region_id': 4, 'year': 1}
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 1)
geometries1 = {"type": "FeatureCollection",
"features": []}
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries1['features'].append({"type": "Feature", "properties": {"density": round(g[1][1]),
"flow": round(g[1][1] - g[1][0]),
"name": 'Ward %s' % g[2],
"year": 1997},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 1).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', 'Johannesburg']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m = 1.05 * max(df.sum(axis=0).tolist())
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 4)
for g in query:
d = json.loads(g[0])
geometries2['features'].append({"type": "Feature", "properties": {"density": round(g[1][1]),
"flow": round(g[1][1] - g[1][0]),
"name": 'Ward %s' % g[2],
"year": 1997},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 4).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table2 = [['Year', 'EThekwini']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table2.append([str(y), val])
m2 = 1.05 * max(df.sum(axis=0).tolist())
return render_template('demographics/demographics.html', form1=form1, geometries1=geometries1,
tour=tour, table1=table1, max1=m, region1=1, ward1=None, ward2=None, analyses=analyses
)
if not request.is_xhr:
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 1)
geometries1 = {"type": "FeatureCollection",
"features": []}
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries1['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
geometries2['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 1).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', 'Johannesburg']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m = 1.05 * max(df.sum(axis=0).tolist())
resp = make_response(render_template('demographics/demographics.html', form1=form1,
geometries1=geometries1, table1=table1,
tour=tour, max1=m, region1=1,
ward1=None, analyses=analyses))
else:
resp = ''
return (resp, status,
# ensure the browser refreshes the page when Back is pressed
{'Cache-Control': 'no-cache, no-store, must-revalidate'})
@app.route('/api/demographics', methods=['GET', 'POST'])
@csrf.exempt
def api_demographics():
analyses = []
session['demo'] = []
if 'maps' not in session.keys():
session['maps'] = {0: {}, 1: {}}
form1 = MapForm(prefix='form1', region_id='1', year=1)
geometries1 = {}
if request.method == 'POST':
data = request.get_json()
print(data)
#data = request.data.decode('utf-8')
#object = parse_qs(urlsplit('?' + data).query)
#object = {key: str(value[0]) for key, value in object.items()}
#if 'csrf_token' in object: del object['csrf_token']
#form1 = MapForm(MultiDict(object))
form1 = data
print(form1['year'])
#if form1.validate():
if form1:
tour = 0
# query = db.session.query(Area.geom.ST_AsGeoJSON(), Area.data)
#year1 = int(form1.year)
year1 = int(form1['year'])
year_ind1 = range(1996, 2031)
#if form1.city_ward_code.data == '':
if form1['city_ward_code'] == '':
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == form1['region_id'])
geometries1 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
if year1 == 0:
flow = 0
else:
flow = round(g[1][year1] - g[1][year1 - 1])
geometries1['features'].append({"type": "Feature", "properties": {"density": round(g[1][year1]),
"flow": flow,
"name": 'Ward %s' % g[2],
"year": year_ind1[year1]},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == form1['region_id']).all()
region = db.session.query(Region.re_name).filter(Region.id == form1['region_id']).first()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', '%s' % str(region[0])]]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m1 = 1.05 * max(df.sum(axis=0).tolist())
else:
query = db.session.query(Area.geom.ST_AsGeoJSON(), Area.data, Area.city_ward_code) \
.filter(Area.city_ward_code == int(form1['city_ward_code'])) \
.filter(Area.region_id == int(form1['region_id']))
geometries1 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
if year1 == 0:
flow = 0
else:
flow = round(g[1][year1] - g[1][year1 - 1])
geometries1['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][year1]),
"flow": flow,
"name": 'Area %s' % g[2],
"year": year_ind1[year1]},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.city_ward_code == int(form1['city_ward_code'])). \
filter(Ward.region_id == int(form1['region_id'])).first()
region = db.session.query(Region.re_name).filter(Region.id == int(form1['region_id'])).first()
region2 = db.session.query(Ward.city_ward_code).filter(Ward.city_ward_code == int(form1['city_ward_code'])) \
.first()
results = []
for r in query:
row = [val for val in list(r)]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', '%s - Ward %s' % (str(region[0]), str(region2[0]))]]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m1 = 1.05 * max(df.sum(axis=0).tolist())
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == int(form1['region_id'])).order_by(
Ward.city_ward_code).distinct()
#form1.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in enumerate(query.all()
#, start=1)]
#form1.city_ward_code.choices.insert(0, ('', 'View All'))
resp = jsonify({'success': True, 'geometries1': geometries1,'table1':table1,
'tour':tour, 'max1':m1, 'region1':form1['region_id'],'ward1':form1['city_ward_code']})
resp.status_code = 200
return resp
else:
message = 'Please correct the problems below and try again.'
resp = jsonify(message=message)
resp.status_code = 500
return resp
else:
session['maps'][0] = {'city_ward_code': '', 'region_id': 1, 'year': 1}
session['maps'][1] = {'city_ward_code': '', 'region_id': 4, 'year': 1}
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 1)
geometries1 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries1['features'].append({"type": "Feature", "properties": {"density": round(g[1][1]),
"flow": round(g[1][1] - g[1][0]),
"name": 'Ward %s' % g[2],
"year": 1997},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 1).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', 'Johannesburg']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m = 1.05 * max(df.sum(axis=0).tolist())
resp = jsonify({'success': True, 'table1': table1,
'max1': m, 'region1': 1, 'ward1': None,'ward2':None, 'geometries1': geometries1,
'form_year':form1.year.choices,'form_ward':form1.city_ward_code.choices,'form_city':form1.region_id.choices})
resp.status_code = 200
return resp
@app.route('/nightlights_jhb', methods=['GET', 'POST'])
def demographics_night_jhb():
analyses = []
if current_user.is_authenticated:
query = db.session.query(UserAnalysis.id, UserAnalysis.ds_name, UserAnalysis.description) \
.filter(UserAnalysis.user_id == current_user.id).order_by(UserAnalysis.id.desc())
analyses = []
for i in grouper(query, 4):
analyses.append(i)
session['night'] = []
form = NightFormJHB()
status = 200
tour = 1
if request.method == 'POST':
if form.validate():
tour = 0
if form.city_ward_code.data == '':
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference). \
filter(Grid.region_id == 1)
geometries = {"type": "FeatureCollection",
"features": []}
bias_ind = [x / 10.0 for x in range(5, 21, 1)].index(float(form.grid_bias.data))
for g in query:
d = json.loads(g[0])
geometries['features'].append({"type": "Feature", "properties": {"density": round(g[1][bias_ind] - g[3]),
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == 1).order_by(
Ward.city_ward_code).distinct()
form.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in
enumerate(query.all()
, start=1)]
form.city_ward_code.choices.insert(0, ('', 'View All'))
return render_template('demographics/demographics_night.html', form=form, geometries=geometries,
bias_val=form.grid_bias.data)
else:
w = db.session.query(Ward.id).filter(Ward.city_ward_code == form.city_ward_code.data)\
.filter(Ward.region_id == 1).first()
w = Ward.query.get(w[0])
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference) \
.filter(Grid.geom.intersects(w.geom))
geometries = {"type": "FeatureCollection",
"features": []}
bias_ind = [x / 10.0 for x in range(5, 21, 1)].index(float(form.grid_bias.data))
for g in query:
d = json.loads(g[0])
geometries['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][bias_ind] - g[3]),
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code)\
.filter(Ward.city_ward_code == form.city_ward_code.data).filter(Ward.region_id == 1)
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries2['features'].append(
{"type": "Feature", "properties": {"density": 0,
"name": 'Ward %s' % form.city_ward_code.data,
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == 1).order_by(
Ward.city_ward_code).distinct()
form.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in enumerate(query.all()
, start=1)]
form.city_ward_code.choices.insert(0, ('', 'View All'))
return render_template('demographics/demographics_night.html', form=form, geometries=geometries,
bias_val=form.grid_bias.data, geometries2=geometries2, ward=form.city_ward_code.data)
else:
if request.is_xhr:
status = 412
else:
flash('Please correct the problems below and try again.', 'warning')
else:
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference). \
filter(Grid.region_id == 1)
geometries = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries['features'].append({"type": "Feature", "properties": {"density": g[1][0] - g[3],
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
return render_template('demographics/demographics_night.html', form=form, bias_val=0.5, geometries=geometries,
analyses=analyses)
if not request.is_xhr:
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 1)
geometries1 = {"type": "FeatureCollection",
"features": []}
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries1['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
geometries2['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 1).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', 'Johannesburg']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m = 1.05 * max(df.sum(axis=0).tolist())
resp = make_response(render_template('demographics/demographics.html', form1=form1, form2=form2,
geometries1=geometries1, geometries2=geometries2, table1=table1,
table2=table1, tour=tour, max1=m, max2=m, region1=1, region2=1,
ward1=None, ward2=None, analyses=analyses))
else:
resp = ''
return (resp, status,
# ensure the browser refreshes the page when Back is pressed
{'Cache-Control': 'no-cache, no-store, must-revalidate'})
@app.route('/nightlights_eth', methods=['GET', 'POST'])
def demographics_night_eth():
analyses = []
if current_user.is_authenticated:
query = db.session.query(UserAnalysis.id, UserAnalysis.ds_name, UserAnalysis.description) \
.filter(UserAnalysis.user_id == current_user.id).order_by(UserAnalysis.id.desc())
analyses = []
for i in grouper(query, 4):
analyses.append(i)
session['night'] = []
form = NightFormETH()
status = 200
tour = 1
if request.method == 'POST':
if form.validate():
tour = 0
if form.city_ward_code.data == '':
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference). \
filter(Grid.region_id == 4)
geometries = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries['features'].append({"type": "Feature", "properties": {"density": round(g[1][0]-g[3]),
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == 4).order_by(
Ward.city_ward_code).distinct()
form.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in
enumerate(query.all()
, start=1)]
form.city_ward_code.choices.insert(0, ('', 'View All'))
return render_template('demographics/demographics_night_ETH.html', form=form, geometries=geometries)
else:
w = db.session.query(Ward.id).filter(Ward.city_ward_code == form.city_ward_code.data)\
.filter(Ward.region_id == 4).first()
w = Ward.query.get(w[0])
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference) \
.filter(Grid.geom.intersects(w.geom)).filter(Grid.region_id == 4)
geometries = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]-g[3]),
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code)\
.filter(Ward.city_ward_code == form.city_ward_code.data).filter(Ward.region_id == 4)
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries2['features'].append(
{"type": "Feature", "properties": {"density": 0,
"name": 'Ward %s' % form.city_ward_code.data,
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.city_ward_code).filter(Ward.region_id == 4).order_by(
Ward.city_ward_code).distinct()
form.city_ward_code.choices = [[str(i), 'Ward %s' % row.city_ward_code] for i, row in enumerate(query.all()
, start=1)]
form.city_ward_code.choices.insert(0, ('', 'View All'))
return render_template('demographics/demographics_night_ETH.html', form=form, geometries=geometries,
geometries2=geometries2, ward=form.city_ward_code.data)
else:
if request.is_xhr:
status = 412
else:
flash('Please correct the problems below and try again.', 'warning')
else:
query = db.session.query(Grid.geom.ST_AsGeoJSON(), Grid.data, Grid.city_grid_id, Grid.reference). \
filter(Grid.region_id == 4)
geometries = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries['features'].append({"type": "Feature", "properties": {"density": round(g[1][0]-g[3]),
"name": 'Grid %s' % g[2],
"year": 2016},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
return render_template('demographics/demographics_night_ETH.html', form=form, geometries=geometries,
analyses=analyses)
if not request.is_xhr:
query = db.session.query(Ward.geom.ST_AsGeoJSON(), Ward.data, Ward.city_ward_code). \
filter(Ward.region_id == 1)
geometries1 = {"type": "FeatureCollection",
"features": []}
geometries2 = {"type": "FeatureCollection",
"features": []}
for g in query:
d = json.loads(g[0])
geometries1['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
geometries2['features'].append(
{"type": "Feature", "properties": {"density": round(g[1][0]), "flow": 0, "name": g[2],
"year": 1996},
"geometry": {"type": "Polygon", "coordinates": d['coordinates']}})
query = db.session.query(Ward.data).filter(Ward.region_id == 1).all()
results = []
for r in query:
row = [val for val in list(r)[0]]
results.append(row)
df = pd.DataFrame(results).fillna(value=0)
table1 = [['Year', 'Johannesburg']]
for y, val in zip(range(1996, 2031), df.sum(axis=0).tolist()):
table1.append([str(y), val])
m = 1.05 * max(df.sum(axis=0).tolist())
resp = make_response(render_template('demographics/demographics.html', form1=form1, form2=form2,
geometries1=geometries1, geometries2=geometries2, table1=table1,
table2=table1, tour=tour, max1=m, max2=m, region1=1, region2=1,
ward1=None, ward2=None, analyses=analyses))
else:
resp = ''
return (resp, status,
# ensure the browser refreshes the page when Back is pressed
{'Cache-Control': 'no-cache, no-store, must-revalidate'})
@app.route('/return-land/')
def land_gen():
return send_file('data/Ethekwini_Region_Data.xlsx', as_attachment=True)
@app.route('/_parse_data', methods=['GET'])
def parse_data():
kwargs = {}
for i in ['dataset_id', 'indicator_id', 'region_id', 'type_id', 'theme_id', 'year']:
param = request.args.get(i)
if (i == 'year'):
if (str(param) != 'Empty') and (param is not None) and (str(param) != ''):
kwargs[i] = int(param)
else:
pass
elif (param is not None) and (str(param) != ''):
kwargs[i] = param
session['explore'] = [i for i in kwargs]
datasets = db.session.query(DataPoint.dataset_id).filter_by(**kwargs).distinct()
indicators = db.session.query(DataPoint.indicator_id).filter_by(**kwargs).distinct()
regions = db.session.query(DataPoint.region_id).filter_by(**kwargs).distinct()
types = db.session.query(DataPoint.type_id).filter_by(**kwargs).distinct()
themes = db.session.query(DataPoint.theme_id).filter_by(**kwargs).distinct()
years = db.session.query(DataPoint.year).filter_by(**kwargs).distinct()
response = {}
remove_list = ['Poverty rate', 'Gini Coefficient', 'Gross Value Add', 'Exports', 'Multiple deprivation index',
'Human Development Index']
dataset_list = [(i[0], str(DataSet.query.filter_by(id=i).first().ds_name)) for i in datasets if
str(DataSet.query.filter_by(id=i).first().ds_name) not in remove_list]
if 'dataset_id' not in session['explore']:
dataset_list.insert(0, ('', 'Empty'))
else:
dataset_list.insert(1, ('', 'Empty'))
response['dataset'] = dataset_list
indicator_list = [[i[0], str(Indicator.query.filter_by(id=i).first().in_name)] for i in indicators if
str(Indicator.query.filter_by(id=i).first().in_name) not in remove_list]
if 'indicator_id' not in session['explore']:
indicator_list.insert(0, ('', 'Empty'))
response['ind_ready'] = 0
else:
indicator_list.insert(1, ('', 'Empty'))
response['ind_ready'] = 1
response['indicator'] = indicator_list
region_list = [(i[0], str(Region.query.filter_by(id=i).first().re_name)) for i in regions]
if 'region_id' not in session['explore']:
region_list.insert(0, ('', 'Empty'))
else:
region_list.insert(1, ('', 'Empty'))
response['region'] = region_list
type_list = [(i[0], str(Type.query.filter_by(id=i).first().ty_name)) for i in types]
if 'type_id' not in session['explore']:
type_list.insert(0, ('', 'Empty'))
else:
type_list.insert(1, ('', 'Empty'))
response['type'] = type_list
theme_list = [(i[0], str(Theme.query.filter_by(id=i).first().th_name)) for i in themes]
if 'theme_id' not in session['explore']:
theme_list.insert(0, ('', 'Empty'))
else:
theme_list.insert(1, ('', 'Empty'))
response['theme'] = theme_list
year_list = [(str(i), str(y[0])) for i, y in enumerate(sorted(years))]
if 'year' not in session['explore']:
year_list.insert(0, ('', 'Empty'))
else:
year_list.insert(1, ('', 'Empty'))
response['year'] = year_list
return jsonify(response)
@app.route('/_parse_demo', methods=['GET'])
def parse_demo():
kwargs = {}
for i in ['region_id', 'ward_id']:
param = request.args.get(i)
if (param is not None) and (str(param) != ''):
kwargs[i] = param
session['demo'] = [i for i in kwargs]
wards = db.session.query(Ward.city_ward_code).filter_by(**kwargs).distinct().order_by(Ward.city_ward_code)
response = {}
ward_list = [(str(i[0]), 'Ward %s' % Ward.query.filter_by(id=i).first().city_ward_code) for i in wards]
if 'ward_id' not in session['demo']:
ward_list.insert(0, ('', 'View All'))
else:
ward_list.insert(1, ('', 'View All'))
response['wards'] = ward_list
return jsonify(response)
@app.route('/api/codebook', methods=['GET', 'POST'])
@app.route('/api/codebook/<int:page>', methods=['GET', 'POST'])
@csrf.exempt
def api_codebook(page=1):
query = db.session.query(CbIndicator). \
outerjoin(CbTheme, CbTheme.id == CbIndicator.theme_id). \
outerjoin(CbSource, CbSource.id == CbIndicator.source_id). \
outerjoin(CbUnit, CbUnit.id == CbIndicator.unit_id)
if request.method == 'POST':
data = request.get_json()
if data['c88']:
query = query.filter(CbIndicator.c88_theme.in_(data['c88']))
if data['socr']:
query = query.filter(CbIndicator.socr_theme.in_(data['socr']))
if data['sdg']:
query = query.filter(CbIndicator.sdg_theme.in_(data['sdg']))
if data['search']:
query = search(query, data['search'], sort=True)
else:
query = query.limit(150).offset((page - 1) * 20)
row_count = query.count()
query = query.all()
# query.sort(key=lambda x: x.code)
result_list = [row_count]
for day, dicts_for_group_code in itertools.groupby(query, key=lambda x:x.group_code):
dicts_for_group_code = list(dicts_for_group_code)
day_dict = {
"id": str(dicts_for_group_code[0].id),
"varCode": dicts_for_group_code[0].code,
"groupCode": dicts_for_group_code[0].group_code,
"indicator": dicts_for_group_code[0].name,
"c88": dicts_for_group_code[0].c88_theme,
"socr": dicts_for_group_code[0].socr_theme,
"sdg": dicts_for_group_code[0].sdg_theme,
"definition": dicts_for_group_code[0].definition,
"source": dicts_for_group_code[0].source.name if dicts_for_group_code[0].source else None,
"reportingResponsibility": dicts_for_group_code[0].reporting_responsibility,
"notesOnCalculation": dicts_for_group_code[0].notes_on_calculation,
"variableType": dicts_for_group_code[0].unit.name,
"frequencyOfCollection": dicts_for_group_code[0].frequency_of_collection,
"automatibility": dicts_for_group_code[0].automatable,
"granulity": dicts_for_group_code[0].granularity,
"gathering_method": dicts_for_group_code[0].gathering_method,
"expandability": dicts_for_group_code[0].expandable,
"period": dicts_for_group_code[0].period,
"unit_of_measurement": dicts_for_group_code[0].unit.name,
"source_link": dicts_for_group_code[0].url_link,
"data_check":True if dicts_for_group_code[0].indicator_data else False
}
children = []
dicts_for_group_code.pop(0)
for d in dicts_for_group_code:
child = {
"id": str(d.id),
"varCode": d.code,
"groupCode": d.group_code,
"indicator": d.name,
"c88": d.c88_theme,
"socr": d.socr_theme,
"sdg": d.sdg_theme,
"definition": d.definition,
"source": d.source.name if d.source else None,
"reportingResponsibility": d.reporting_responsibility,
"notesOnCalculation": d.notes_on_calculation,
"variableType": d.unit.name,
"frequencyOfCollection": d.frequency_of_collection,
"automatibility": d.automatable,
"granulity": d.granularity,
"gathering_method": d.gathering_method,
"expandability": d.expandable,
"period": d.period,
"unit_of_measurement": d.unit.name,
"source_link": d.url_link,
"data_check": bool(d.indicator_data),
}
children.append(child)
day_dict.update({"children": children})
result_list.append(day_dict)
return jsonify(result_list)
| apache-2.0 |
DickJC123/mxnet | python/mxnet/ndarray/sparse.py | 9 | 63306 | # 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.
# coding: utf-8
# pylint: disable=wildcard-import, unused-wildcard-import, too-many-lines
"""Sparse NDArray API of MXNet."""
try:
from __builtin__ import slice as py_slice
from __builtin__ import sum as py_sum
except ImportError:
from builtins import slice as py_slice
from builtins import sum as py_sum
import ctypes
import warnings
import operator
from array import array as native_array
__all__ = ["_ndarray_cls", "csr_matrix", "row_sparse_array",
"BaseSparseNDArray", "CSRNDArray", "RowSparseNDArray",
"add", "subtract", "multiply", "divide"]
import numpy as np
from ..base import NotSupportedForSparseNDArray
from ..base import _LIB, numeric_types
from ..base import c_array_buf, mx_real_t, integer_types
from ..base import NDArrayHandle, check_call
from ..context import Context, current_context
from . import _internal
from . import op
try:
from .gen_sparse import retain as gs_retain # pylint: disable=redefined-builtin
except ImportError:
gs_retain = None
from ._internal import _set_ndarray_class
from .ndarray import NDArray, _storage_type, _DTYPE_NP_TO_MX, _DTYPE_MX_TO_NP
from .ndarray import _STORAGE_TYPE_STR_TO_ID, _STORAGE_TYPE_ROW_SPARSE, _STORAGE_TYPE_CSR, _int64_enabled
from .ndarray import _STORAGE_TYPE_UNDEFINED, _STORAGE_TYPE_DEFAULT
from .ndarray import zeros as _zeros_ndarray
from .ndarray import array as _array
from .ndarray import _ufunc_helper
try:
import scipy.sparse as spsp
except ImportError:
spsp = None
_STORAGE_AUX_TYPES = {
'row_sparse': [np.int64],
'csr': [np.int64, np.int64]
}
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None):
"""Return a new handle with specified storage type, shape, dtype and context.
Empty handle is only used to hold results
Returns
-------
handle
A new empty ndarray handle
"""
hdl = NDArrayHandle()
for aux_t in aux_types:
if np.dtype(aux_t) != np.dtype("int64"):
raise NotImplementedError("only int64 is supported for aux types")
aux_type_ids = [int(_DTYPE_NP_TO_MX[np.dtype(aux_t).type]) for aux_t in aux_types]
aux_shapes = [(0,) for aux_t in aux_types] if aux_shapes is None else aux_shapes
aux_shape_lens = [len(aux_shape) for aux_shape in aux_shapes]
aux_shapes = py_sum(aux_shapes, ())
num_aux = ctypes.c_uint(len(aux_types))
if _int64_enabled():
check_call(_LIB.MXNDArrayCreateSparseEx64(
ctypes.c_int(int(_STORAGE_TYPE_STR_TO_ID[stype])),
c_array_buf(ctypes.c_int64, native_array('q', shape)),
ctypes.c_int(len(shape)),
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
ctypes.c_int(int(delay_alloc)),
ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
num_aux,
c_array_buf(ctypes.c_int, native_array('i', aux_type_ids)),
c_array_buf(ctypes.c_int, native_array('i', aux_shape_lens)),
c_array_buf(ctypes.c_int64, native_array('q', aux_shapes)),
ctypes.byref(hdl)))
else:
check_call(_LIB.MXNDArrayCreateSparseEx(
ctypes.c_int(int(_STORAGE_TYPE_STR_TO_ID[stype])),
c_array_buf(ctypes.c_uint, native_array('I', shape)),
ctypes.c_uint(len(shape)),
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
ctypes.c_int(int(delay_alloc)),
ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
num_aux,
c_array_buf(ctypes.c_int, native_array('i', aux_type_ids)),
c_array_buf(ctypes.c_uint, native_array('I', aux_shape_lens)),
c_array_buf(ctypes.c_uint, native_array('I', aux_shapes)),
ctypes.byref(hdl)))
return hdl
class BaseSparseNDArray(NDArray):
"""The base class of an NDArray stored in a sparse storage format.
See CSRNDArray and RowSparseNDArray for more details.
"""
def __repr__(self):
"""Returns a string representation of the sparse array."""
shape_info = 'x'.join(['%d' % x for x in self.shape])
# The data content is not displayed since the array usually has big shape
return '\n<%s %s @%s>' % (self.__class__.__name__,
shape_info, self.context)
def __add__(self, other):
return add(self, other)
def __sub__(self, other):
return subtract(self, other)
def __mul__(self, other):
return multiply(self, other)
def __div__(self, other):
return divide(self, other)
def __iadd__(self, other):
raise NotImplementedError()
def __isub__(self, other):
raise NotImplementedError()
def __imul__(self, other):
raise NotImplementedError()
def __idiv__(self, other):
raise NotImplementedError()
def __itruediv__(self, other):
raise NotImplementedError()
def _sync_copyfrom(self, source_array):
raise NotImplementedError()
def _at(self, idx):
raise NotSupportedForSparseNDArray(self._at, '[idx]', idx)
def _slice(self, start, stop):
raise NotSupportedForSparseNDArray(self._slice, None, start, stop)
def reshape(self, *shape, **kwargs):
raise NotSupportedForSparseNDArray(self.reshape, None, shape)
@property
def size(self):
# the `size` for a sparse ndarray is ambiguous, hence disabled.
raise NotImplementedError()
def _aux_type(self, i):
"""Data-type of the array's ith aux data.
Returns
-------
numpy.dtype
This BaseSparseNDArray's aux data type.
"""
aux_type = ctypes.c_int()
check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type)))
return _DTYPE_MX_TO_NP[aux_type.value]
@property
def _num_aux(self):
"""The number of aux data used to help store the sparse ndarray.
"""
return len(_STORAGE_AUX_TYPES[self.stype])
@property
def _aux_types(self):
"""The data types of the aux data for the BaseSparseNDArray.
"""
aux_types = []
num_aux = self._num_aux
for i in range(num_aux):
aux_types.append(self._aux_type(i))
return aux_types
def asnumpy(self):
"""Return a dense ``numpy.ndarray`` object with value copied from this array
"""
return self.tostype('default').asnumpy()
def astype(self, dtype, copy=True):
"""Return a copy of the array after casting to a specified type.
Parameters
----------
dtype : numpy.dtype or str
The type of the returned array.
copy : bool
Default `True`. By default, astype always returns a newly
allocated ndarray on the same context. If this is set to
`False`, and the dtype requested is the same as the ndarray's
dtype, the ndarray is returned instead of a copy.
Examples
--------
>>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32')
>>> y = x.astype('int32')
>>> y.dtype
<type 'numpy.int32'>
"""
if not copy and np.dtype(dtype) == self.dtype:
return self
# Use copyto for casting, as op.cast(self, dtype=dtype) doesn't support sparse stype
res = zeros(shape=self.shape, ctx=self.context,
dtype=dtype, stype=self.stype)
self.copyto(res)
return res
def copyto(self, other):
"""Copies the value of this array to another array.
Parameters
----------
other : NDArray or CSRNDArray or RowSparseNDArray or Context
The destination array or context.
Returns
-------
NDArray or CSRNDArray or RowSparseNDArray
The copied array.
"""
# pylint: disable= no-member, protected-access
if isinstance(other, NDArray):
if other.handle is self.handle:
warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)
return False
return _internal._copyto(self, out=other)
elif isinstance(other, Context):
hret = _ndarray_cls(_new_alloc_handle(self.stype, self.shape, other,
True, self.dtype, self._aux_types))
return _internal._copyto(self, out=hret)
else:
raise TypeError('copyto does not support type ' + str(type(other)))
# pylint: enable= no-member, protected-access
def check_format(self, full_check=True):
"""Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True).
"""
check_call(_LIB.MXNDArraySyncCheckFormat(self.handle, ctypes.c_bool(full_check)))
def _data(self):
"""A deep copy NDArray of the data array associated with the BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl)))
return NDArray(hdl)
def _aux_data(self, i):
""" Get a deep copy NDArray of the i-th aux data array associated with the
BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetAuxNDArray(self.handle, i, ctypes.byref(hdl)))
return NDArray(hdl)
# pylint: disable=abstract-method
class CSRNDArray(BaseSparseNDArray):
"""A sparse representation of 2D NDArray in the Compressed Sparse Row format.
A CSRNDArray represents an NDArray as three separate arrays: `data`,
`indptr` and `indices`. It uses the CSR representation where the column indices for
row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their corresponding values are stored
in ``data[indptr[i]:indptr[i+1]]``.
The column indices for a given row are expected to be sorted in ascending order.
Duplicate column entries for the same row are not allowed.
Example
-------
>>> a = mx.nd.array([[0, 1, 0], [2, 0, 0], [0, 0, 0], [0, 0, 3]])
>>> a = a.tostype('csr')
>>> a.data.asnumpy()
array([ 1., 2., 3.], dtype=float32)
>>> a.indices.asnumpy()
array([1, 0, 2])
>>> a.indptr.asnumpy()
array([0, 1, 2, 2, 3])
See Also
--------
csr_matrix: Several ways to construct a CSRNDArray
"""
def __reduce__(self):
return CSRNDArray, (None,), super(CSRNDArray, self).__getstate__()
def __iadd__(self, other):
(self + other).copyto(self)
return self
def __isub__(self, other):
(self - other).copyto(self)
return self
def __imul__(self, other):
(self * other).copyto(self)
return self
def __idiv__(self, other):
(self / other).copyto(self)
return self
def __itruediv__(self, other):
(self / other).copyto(self)
return self
def __getitem__(self, key):
"""x.__getitem__(i) <=> x[i]
Returns a newly created NDArray based on the indexing key.
Parameters
----------
key : int or mxnet.ndarray.NDArray.slice
Indexing key.
Examples
--------
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> a = mx.nd.sparse.csr_matrix((data, indices, indptr), shape=(3, 3))
>>> a.asnumpy()
array([[ 1., 0., 2.],
[ 0., 0., 3.],
[ 4., 5., 6.]], dtype=float32)
>>> a[1:2].asnumpy()
array([[ 0., 0., 3.]], dtype=float32)
>>> a[1].asnumpy()
array([[ 0., 0., 3.]], dtype=float32)
>>> a[-1].asnumpy()
array([[ 4., 5., 6.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if isinstance(key, int):
if key == -1:
begin = self.shape[0] - 1
else:
begin = key
return op.slice(self, begin=begin, end=begin+1)
if isinstance(key, py_slice):
if key.step is not None:
raise ValueError('CSRNDArray only supports continuous slicing on axis 0')
if key.start is not None or key.stop is not None:
begin = key.start if key.start else 0
end = key.stop if key.stop else self.shape[0]
return op.slice(self, begin=begin, end=end)
else:
return self
if isinstance(key, tuple):
raise ValueError('Multi-dimension indexing is not supported')
raise ValueError('Undefined behaviour for {}'.format(key))
# pylint: enable= no-member, protected-access
def __setitem__(self, key, value):
"""x.__setitem__(i, y) <=> x[i]=y
Set self[key] to value. Only slice key [:] is supported.
Parameters
----------
key : mxnet.ndarray.NDArray.slice
The indexing key.
value : NDArray or CSRNDArray or numpy.ndarray
The value to set.
Examples
--------
>>> src = mx.nd.sparse.zeros('csr', (3,3))
>>> src.asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
>>> # assign CSRNDArray with same storage type
>>> x = mx.nd.ones((3,3)).tostype('csr')
>>> x[:] = src
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> # assign NDArray to CSRNDArray
>>> x[:] = mx.nd.ones((3,3)) * 2
>>> x.asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
"""
if not self.writable:
raise ValueError('Failed to assign to a readonly CSRNDArray')
if isinstance(key, py_slice):
if key.step is not None or key.start is not None or key.stop is not None:
raise ValueError('Assignment with slice for CSRNDArray is not ' \
'implemented yet.')
if isinstance(value, NDArray):
# avoid copying to itself
if value.handle is not self.handle:
value.copyto(self)
elif isinstance(value, numeric_types):
raise ValueError("Assigning numeric types to CSRNDArray is " \
"not implemented yet.")
elif isinstance(value, (np.ndarray, np.generic)):
# TODO(haibin/anisub) check scipy.sparse and use _sync_copy_from to
# avoid the temporary copy
warnings.warn('Assigning non-NDArray object to CSRNDArray is not efficient',
RuntimeWarning)
tmp = _array(value)
tmp.copyto(self)
else:
raise TypeError('type %s not supported' % str(type(value)))
else:
assert(isinstance(key, (int, tuple)))
raise Exception('CSRNDArray only supports [:] for assignment')
@property
def indices(self):
"""A deep copy NDArray of the indices array of the CSRNDArray.
This generates a deep copy of the column indices of the current `csr` matrix.
Returns
-------
NDArray
This CSRNDArray's indices array.
"""
return self._aux_data(1)
@property
def indptr(self):
"""A deep copy NDArray of the indptr array of the CSRNDArray.
This generates a deep copy of the `indptr` of the current `csr` matrix.
Returns
-------
NDArray
This CSRNDArray's indptr array.
"""
return self._aux_data(0)
@property
def data(self):
"""A deep copy NDArray of the data array of the CSRNDArray.
This generates a deep copy of the `data` of the current `csr` matrix.
Returns
-------
NDArray
This CSRNDArray's data array.
"""
return self._data()
@indices.setter
def indices(self, indices):
raise NotImplementedError()
@indptr.setter
def indptr(self, indptr):
raise NotImplementedError()
@data.setter
def data(self, data):
raise NotImplementedError()
def tostype(self, stype):
"""Return a copy of the array with chosen storage type.
Returns
-------
NDArray or CSRNDArray
A copy of the array with the chosen storage stype
"""
# pylint: disable= no-member, protected-access
if stype == 'row_sparse':
raise ValueError("cast_storage from csr to row_sparse is not supported")
return op.cast_storage(self, stype=stype)
# pylint: enable= no-member, protected-access
def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``CSRNDArray`` object, then ``other.shape`` and
``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a context, a new ``CSRNDArray`` will be first created on
the target context, and the value of ``self`` is copied.
Parameters
----------
other : NDArray or CSRNDArray or Context
The destination array or context.
Returns
-------
NDArray or CSRNDArray
The copied array. If ``other`` is an ``NDArray`` or ``CSRNDArray``, then the return
value and ``other`` will point to the same ``NDArray`` or ``CSRNDArray``.
"""
if isinstance(other, Context):
return super(CSRNDArray, self).copyto(other)
elif isinstance(other, NDArray):
stype = other.stype
if stype in ('default', 'csr'):
return super(CSRNDArray, self).copyto(other)
else:
raise TypeError('copyto does not support destination NDArray stype ' + str(stype))
else:
raise TypeError('copyto does not support type ' + str(type(other)))
def asscipy(self):
"""Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array
Examples
--------
>>> x = mx.nd.sparse.zeros('csr', (2,3))
>>> y = x.asscipy()
>>> type(y)
<type 'scipy.sparse.csr.csr_matrix'>
>>> y
<2x3 sparse matrix of type '<type 'numpy.float32'>'
with 0 stored elements in Compressed Sparse Row format>
"""
data = self.data.asnumpy()
indices = self.indices.asnumpy()
indptr = self.indptr.asnumpy()
if not spsp:
raise ImportError("scipy could not be imported. "
"Please make sure that the scipy is installed.")
return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)
# pylint: disable=abstract-method
class RowSparseNDArray(BaseSparseNDArray):
"""A sparse representation of a set of NDArray row slices at given indices.
A RowSparseNDArray represents a multidimensional NDArray using two separate arrays: `data` and
`indices`. The number of dimensions has to be at least 2.
- data: an NDArray of any dtype with shape [D0, D1, ..., Dn].
- indices: a 1-D int64 NDArray with shape [D0] with values sorted in ascending order.
The `indices` stores the indices of the row slices with non-zeros,
while the values are stored in `data`. The corresponding NDArray ``dense``
represented by RowSparseNDArray ``rsp`` has
``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]``
>>> dense.asnumpy()
array([[ 1., 2., 3.],
[ 0., 0., 0.],
[ 4., 0., 5.],
[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
>>> rsp = dense.tostype('row_sparse')
>>> rsp.indices.asnumpy()
array([0, 2], dtype=int64)
>>> rsp.data.asnumpy()
array([[ 1., 2., 3.],
[ 4., 0., 5.]], dtype=float32)
A RowSparseNDArray is typically used to represent non-zero row slices of a large NDArray
of shape [LARGE0, D1, .. , Dn] where LARGE0 >> D0 and most row slices are zeros.
RowSparseNDArray is used principally in the definition of gradients for operations
that have sparse gradients (e.g. sparse dot and sparse embedding).
See Also
--------
row_sparse_array: Several ways to construct a RowSparseNDArray
"""
def __reduce__(self):
return RowSparseNDArray, (None,), super(RowSparseNDArray, self).__getstate__()
def __iadd__(self, other):
(self + other).copyto(self)
return self
def __isub__(self, other):
(self - other).copyto(self)
return self
def __imul__(self, other):
(self * other).copyto(self)
return self
def __idiv__(self, other):
(self / other).copyto(self)
return self
def __itruediv__(self, other):
(self / other).copyto(self)
return self
def __getitem__(self, key):
"""x.__getitem__(i) <=> x[i]
Returns a sliced view of this array.
Parameters
----------
key : mxnet.ndarray.NDArray.slice
Indexing key.
Examples
--------
>>> x = mx.nd.sparse.zeros('row_sparse', (2, 3))
>>> x[:].asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
"""
if isinstance(key, int):
raise Exception("__getitem__ with int key is not implemented for RowSparseNDArray yet")
if isinstance(key, py_slice):
if key.step is not None or key.start is not None or key.stop is not None:
raise Exception('RowSparseNDArray only supports [:] for __getitem__')
return self
if isinstance(key, tuple):
raise ValueError('Multi-dimension indexing is not supported')
raise ValueError('Undefined behaviour for {}'.format(key))
def __setitem__(self, key, value):
"""x.__setitem__(i, y) <=> x[i]=y
Set self[key] to value. Only slice key [:] is supported.
Parameters
----------
key : mxnet.ndarray.NDArray.slice
The indexing key.
value : NDArray or numpy.ndarray
The value to set.
Examples
--------
>>> src = mx.nd.row_sparse([[1, 0, 2], [4, 5, 6]], [0, 2], (3,3))
>>> src.asnumpy()
array([[ 1., 0., 2.],
[ 0., 0., 0.],
[ 4., 5., 6.]], dtype=float32)
>>> # assign RowSparseNDArray with same storage type
>>> x = mx.nd.sparse.zeros('row_sparse', (3,3))
>>> x[:] = src
>>> x.asnumpy()
array([[ 1., 0., 2.],
[ 0., 0., 0.],
[ 4., 5., 6.]], dtype=float32)
>>> # assign NDArray to RowSparseNDArray
>>> x[:] = mx.nd.ones((3,3))
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if not self.writable:
raise ValueError('Failed to assign to a readonly RowSparseNDArray')
if isinstance(key, py_slice):
if key.step is not None or key.start is not None or key.stop is not None:
raise ValueError('Assignment with slice for RowSparseNDArray ' \
'is not implmented yet.')
if isinstance(value, NDArray):
# avoid copying to itself
if value.handle is not self.handle:
value.copyto(self)
elif isinstance(value, numeric_types):
_internal._set_value(float(value), out=self)
elif isinstance(value, (np.ndarray, np.generic)):
warnings.warn('Assigning non-NDArray object to RowSparseNDArray is not efficient',
RuntimeWarning)
tmp = _array(value)
tmp.copyto(self)
else:
raise TypeError('type %s not supported' % str(type(value)))
else:
assert(isinstance(key, (int, tuple)))
raise TypeError('RowSparseNDArray only supports [:] for assignment')
# pylint: enable= no-member, protected-access
@property
def indices(self):
"""A deep copy NDArray of the indices array of the RowSparseNDArray.
This generates a deep copy of the row indices of the current `row_sparse` matrix.
Returns
-------
NDArray
This RowSparseNDArray's indices array.
"""
return self._aux_data(0)
@property
def data(self):
"""A deep copy NDArray of the data array of the RowSparseNDArray.
This generates a deep copy of the `data` of the current `row_sparse` matrix.
Returns
-------
NDArray
This RowSparseNDArray's data array.
"""
return self._data()
@indices.setter
def indices(self, indices):
raise NotImplementedError()
@data.setter
def data(self, data):
raise NotImplementedError()
def tostype(self, stype):
"""Return a copy of the array with chosen storage type.
Returns
-------
NDArray or RowSparseNDArray
A copy of the array with the chosen storage stype
"""
# pylint: disable= no-member, protected-access
if stype == 'csr':
raise ValueError("cast_storage from row_sparse to csr is not supported")
return op.cast_storage(self, stype=stype)
# pylint: enable= no-member, protected-access
def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a context, a new ``RowSparseNDArray`` will be first created on
the target context, and the value of ``self`` is copied.
Parameters
----------
other : NDArray or RowSparseNDArray or Context
The destination array or context.
Returns
-------
NDArray or RowSparseNDArray
The copied array. If ``other`` is an ``NDArray`` or ``RowSparseNDArray``, then the
return value and ``other`` will point to the same ``NDArray`` or ``RowSparseNDArray``.
"""
if isinstance(other, Context):
return super(RowSparseNDArray, self).copyto(other)
elif isinstance(other, NDArray):
stype = other.stype
if stype in ('default', 'row_sparse'):
return super(RowSparseNDArray, self).copyto(other)
else:
raise TypeError('copyto does not support destination NDArray stype ' + str(stype))
else:
raise TypeError('copyto does not support type ' + str(type(other)))
def retain(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`retain`.
The arguments are the same as for :py:func:`retain`, with
this array as data.
"""
if not gs_retain:
raise ImportError("gen_sparse could not be imported")
return gs_retain(*args, **kwargs)
def _prepare_src_array(source_array, dtype):
"""Prepare `source_array` so that it can be used to construct NDArray.
`source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \
nor an `np.ndarray`.
"""
if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray):
try:
source_array = np.array(source_array, dtype=dtype)
except:
raise TypeError('values must be array like object')
return source_array
def _prepare_default_dtype(src_array, dtype):
"""Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray
or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise."""
if dtype is None:
if isinstance(src_array, (NDArray, np.ndarray)):
dtype = src_array.dtype
elif spsp and isinstance(src_array, spsp.csr.csr_matrix):
dtype = src_array.dtype
else:
dtype = mx_real_t
return dtype
def _check_shape(s1, s2):
"""check s1 == s2 if both are not None"""
if s1 and s2 and s1 != s2:
raise ValueError("Shape mismatch detected. " + str(s1) + " v.s. " + str(s2))
def csr_matrix(arg1, shape=None, ctx=None, dtype=None):
"""Creates a `CSRNDArray`, an 2D array with compressed sparse row (CSR) format.
The CSRNDArray can be instantiated in several ways:
- csr_matrix(D):
to construct a CSRNDArray with a dense 2D array ``D``
- **D** (*array_like*) - An object exposing the array interface, an object whose \
`__array__` method returns an array, or any (nested) sequence.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is ``D.dtype`` if ``D`` is an NDArray or numpy.ndarray, \
float32 otherwise.
- csr_matrix(S)
to construct a CSRNDArray with a sparse 2D array ``S``
- **S** (*CSRNDArray or scipy.sparse.csr.csr_matrix*) - A sparse matrix.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is ``S.dtype``.
- csr_matrix((M, N))
to construct an empty CSRNDArray with shape ``(M, N)``
- **M** (*int*) - Number of rows in the matrix
- **N** (*int*) - Number of columns in the matrix
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is float32.
- csr_matrix((data, indices, indptr))
to construct a CSRNDArray based on the definition of compressed sparse row format \
using three separate arrays, \
where the column indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]`` \
and their corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``. \
The column indices for a given row are expected to be **sorted in ascending order.** \
Duplicate column entries for the same row are not allowed.
- **data** (*array_like*) - An object exposing the array interface, which \
holds all the non-zero entries of the matrix in row-major order.
- **indices** (*array_like*) - An object exposing the array interface, which \
stores the column index for each non-zero element in ``data``.
- **indptr** (*array_like*) - An object exposing the array interface, which \
stores the offset into ``data`` of the first non-zero element number of each \
row of the matrix.
- **shape** (*tuple of int, optional*) - The shape of the array. The default \
shape is inferred from the indices and indptr arrays.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is ``data.dtype`` if ``data`` is an NDArray or numpy.ndarray, \
float32 otherwise.
- csr_matrix((data, (row, col)))
to construct a CSRNDArray based on the COOrdinate format \
using three seperate arrays, \
where ``row[i]`` is the row index of the element, \
``col[i]`` is the column index of the element \
and ``data[i]`` is the data corresponding to the element. All the missing \
elements in the input are taken to be zeroes.
- **data** (*array_like*) - An object exposing the array interface, which \
holds all the non-zero entries of the matrix in COO format.
- **row** (*array_like*) - An object exposing the array interface, which \
stores the row index for each non zero element in ``data``.
- **col** (*array_like*) - An object exposing the array interface, which \
stores the col index for each non zero element in ``data``.
- **shape** (*tuple of int, optional*) - The shape of the array. The default \
shape is inferred from the ``row`` and ``col`` arrays.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is float32.
Parameters
----------
arg1: tuple of int, tuple of array_like, array_like, CSRNDArray, scipy.sparse.csr_matrix, \
scipy.sparse.coo_matrix, tuple of int or tuple of array_like
The argument to help instantiate the csr matrix. See above for further details.
shape : tuple of int, optional
The shape of the csr matrix.
ctx: Context, optional
Device context (default is the current default context).
dtype: str or numpy.dtype, optional
The data type of the output array.
Returns
-------
CSRNDArray
A `CSRNDArray` with the `csr` storage representation.
Example
-------
>>> a = mx.nd.sparse.csr_matrix(([1, 2, 3], [1, 0, 2], [0, 1, 2, 2, 3]), shape=(4, 3))
>>> a.asnumpy()
array([[ 0., 1., 0.],
[ 2., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 3.]], dtype=float32)
See Also
--------
CSRNDArray : MXNet NDArray in compressed sparse row format.
"""
# construct a csr matrix from (M, N) or (data, indices, indptr)
if isinstance(arg1, tuple):
arg_len = len(arg1)
if arg_len == 2:
# construct a sparse csr matrix from
# scipy coo matrix if input format is coo
if isinstance(arg1[1], tuple) and len(arg1[1]) == 2:
data, (row, col) = arg1
if isinstance(data, NDArray):
data = data.asnumpy()
if isinstance(row, NDArray):
row = row.asnumpy()
if isinstance(col, NDArray):
col = col.asnumpy()
if not spsp:
raise ImportError("scipy could not be imported. "
"Please make sure that the scipy is installed.")
coo = spsp.coo_matrix((data, (row, col)), shape=shape)
_check_shape(coo.shape, shape)
csr = coo.tocsr()
return array(csr, ctx=ctx, dtype=dtype)
else:
# empty matrix with shape
_check_shape(arg1, shape)
return empty('csr', arg1, ctx=ctx, dtype=dtype)
elif arg_len == 3:
# data, indices, indptr
return _csr_matrix_from_definition(arg1[0], arg1[1], arg1[2], shape=shape,
ctx=ctx, dtype=dtype)
else:
raise ValueError("Unexpected length of input tuple: " + str(arg_len))
else:
# construct a csr matrix from a sparse / dense one
if isinstance(arg1, CSRNDArray) or (spsp and isinstance(arg1, spsp.csr.csr_matrix)):
# construct a csr matrix from scipy or CSRNDArray
_check_shape(arg1.shape, shape)
return array(arg1, ctx=ctx, dtype=dtype)
elif isinstance(arg1, RowSparseNDArray):
raise ValueError("Unexpected input type: RowSparseNDArray")
else:
# construct a csr matrix from a dense one
# prepare default ctx and dtype since mx.nd.array doesn't use default values
# based on source_array
dtype = _prepare_default_dtype(arg1, dtype)
# create dns array with provided dtype. ctx is not passed since copy across
# ctx requires dtype to be the same
dns = _array(arg1, dtype=dtype)
if ctx is not None and dns.context != ctx:
dns = dns.as_in_context(ctx)
_check_shape(dns.shape, shape)
return dns.tostype('csr')
def _csr_matrix_from_definition(data, indices, indptr, shape=None, ctx=None,
dtype=None, indices_type=None, indptr_type=None):
"""Create a `CSRNDArray` based on data, indices and indptr"""
# pylint: disable= no-member, protected-access
storage_type = 'csr'
# context
ctx = current_context() if ctx is None else ctx
# types
dtype = _prepare_default_dtype(data, dtype)
indptr_type = _STORAGE_AUX_TYPES[storage_type][0] if indptr_type is None else indptr_type
indices_type = _STORAGE_AUX_TYPES[storage_type][1] if indices_type is None else indices_type
# prepare src array and types
data = _prepare_src_array(data, dtype)
indptr = _prepare_src_array(indptr, indptr_type)
indices = _prepare_src_array(indices, indices_type)
# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays
# if they are not for now. In the future, we should provide a c-api
# to accept np.ndarray types to copy from to result.data and aux_data
if not isinstance(data, NDArray):
data = _array(data, ctx, dtype)
if not isinstance(indptr, NDArray):
indptr = _array(indptr, ctx, indptr_type)
if not isinstance(indices, NDArray):
indices = _array(indices, ctx, indices_type)
if shape is None:
if indices.shape[0] == 0:
raise ValueError('invalid shape')
shape = (len(indptr) - 1, op.max(indices).asscalar() + 1)
# verify shapes
aux_shapes = [indptr.shape, indices.shape]
if data.ndim != 1 or indptr.ndim != 1 or indices.ndim != 1 or \
indptr.shape[0] == 0 or len(shape) != 2:
raise ValueError('invalid shape')
result = CSRNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype,
[indptr_type, indices_type], aux_shapes))
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1)))
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indptr.handle, ctypes.c_int(0)))
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(1)))
return result
# pylint: enable= no-member, protected-access
def row_sparse_array(arg1, shape=None, ctx=None, dtype=None):
"""Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \
tensor slices at given indices.
The RowSparseNDArray can be instantiated in several ways:
- row_sparse_array(D):
to construct a RowSparseNDArray with a dense ndarray ``D``
- **D** (*array_like*) - An object exposing the array interface, an object whose \
`__array__` method returns an array, or any (nested) sequence.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is ``D.dtype`` if ``D`` is an NDArray or numpy.ndarray, \
float32 otherwise.
- row_sparse_array(S)
to construct a RowSparseNDArray with a sparse ndarray ``S``
- **S** (*RowSparseNDArray*) - A sparse ndarray.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is ``S.dtype``.
- row_sparse_array((D0, D1 .. Dn))
to construct an empty RowSparseNDArray with shape ``(D0, D1, ... Dn)``
- **D0, D1 .. Dn** (*int*) - The shape of the ndarray
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is float32.
- row_sparse_array((data, indices))
to construct a RowSparseNDArray based on the definition of row sparse format \
using two separate arrays, \
where the `indices` stores the indices of the row slices with non-zeros,
while the values are stored in `data`. The corresponding NDArray ``dense``
represented by RowSparseNDArray ``rsp`` has \
``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]``
The row indices for are expected to be **sorted in ascending order.** \
- **data** (*array_like*) - An object exposing the array interface, which \
holds all the non-zero row slices of the array.
- **indices** (*array_like*) - An object exposing the array interface, which \
stores the row index for each row slice with non-zero elements.
- **shape** (*tuple of int, optional*) - The shape of the array. The default \
shape is inferred from the indices and indptr arrays.
- **ctx** (*Context, optional*) - Device context \
(default is the current default context).
- **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \
The default dtype is float32.
Parameters
----------
arg1 : NDArray, numpy.ndarray, RowSparseNDArray, tuple of int or tuple of array_like
The argument to help instantiate the row sparse ndarray. See above for further details.
shape : tuple of int, optional
The shape of the row sparse ndarray. (Default value = None)
ctx : Context, optional
Device context (default is the current default context).
dtype : str or numpy.dtype, optional
The data type of the output array. (Default value = None)
Returns
-------
RowSparseNDArray
An `RowSparseNDArray` with the `row_sparse` storage representation.
Examples
--------
>>> a = mx.nd.sparse.row_sparse_array(([[1, 2], [3, 4]], [1, 4]), shape=(6, 2))
>>> a.asnumpy()
array([[ 0., 0.],
[ 1., 2.],
[ 0., 0.],
[ 0., 0.],
[ 3., 4.],
[ 0., 0.]], dtype=float32)
See Also
--------
RowSparseNDArray : MXNet NDArray in row sparse format.
"""
# construct a row sparse array from (D0, D1 ..) or (data, indices)
if isinstance(arg1, tuple):
arg_len = len(arg1)
if arg_len < 2:
raise ValueError("Unexpected length of input tuple: " + str(arg_len))
if arg_len > 2:
# empty ndarray with shape
_check_shape(arg1, shape)
return empty('row_sparse', arg1, ctx=ctx, dtype=dtype)
else:
# len(arg1) = 2, is either shape or (data, indices)
if isinstance(arg1[0], integer_types) and isinstance(arg1[1], integer_types):
# empty ndarray with shape
_check_shape(arg1, shape)
return empty('row_sparse', arg1, ctx=ctx, dtype=dtype)
else:
# data, indices, indptr
return _row_sparse_ndarray_from_definition(arg1[0], arg1[1], shape=shape,
ctx=ctx, dtype=dtype)
else:
# construct a row sparse ndarray from a dense / sparse array
if isinstance(arg1, RowSparseNDArray):
# construct a row sparse ndarray from RowSparseNDArray
_check_shape(arg1.shape, shape)
return array(arg1, ctx=ctx, dtype=dtype)
elif isinstance(arg1, CSRNDArray):
raise ValueError("Unexpected input type: CSRNDArray")
else:
# construct a csr matrix from a dense one
# prepare default dtype since mx.nd.array doesn't use default values
# based on source_array
dtype = _prepare_default_dtype(arg1, dtype)
# create dns array with provided dtype. ctx is not passed since copy across
# ctx requires dtype to be the same
dns = _array(arg1, dtype=dtype)
if ctx is not None and dns.context != ctx:
dns = dns.as_in_context(ctx)
_check_shape(dns.shape, shape)
return dns.tostype('row_sparse')
def _row_sparse_ndarray_from_definition(data, indices, shape=None, ctx=None,
dtype=None, indices_type=None):
"""Create a `RowSparseNDArray` based on data and indices"""
storage_type = 'row_sparse'
# context
ctx = current_context() if ctx is None else ctx
# types
dtype = _prepare_default_dtype(data, dtype)
indices_type = _STORAGE_AUX_TYPES[storage_type][0] if indices_type is None else indices_type
# prepare src array and types
data = _prepare_src_array(data, dtype)
indices = _prepare_src_array(indices, indices_type)
# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays
# if they are not for now. In the future, we should provide a c-api
# to accept np.ndarray types to copy from to result.data and aux_data
if not isinstance(data, NDArray):
data = _array(data, ctx, dtype)
if not isinstance(indices, NDArray):
indices = _array(indices, ctx, indices_type)
if shape is None:
num_indices = indices.shape[0]
if num_indices == 0:
raise ValueError('invalid shape')
dim0 = indices[num_indices - 1].asscalar() + 1
shape = (dim0, ) + data.shape[1:]
# verify shapes
if data.ndim != len(shape) or indices.ndim != 1 or np.prod(shape[1:]) == 0:
raise ValueError("invalid shape")
result = RowSparseNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype,
[indices_type], [indices.shape]))
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1)))
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(0)))
return result
def _ndarray_cls(handle, writable=True, stype=_STORAGE_TYPE_UNDEFINED):
if stype == _STORAGE_TYPE_UNDEFINED:
stype = _storage_type(handle)
if stype == _STORAGE_TYPE_DEFAULT:
return NDArray(handle, writable=writable)
elif stype == _STORAGE_TYPE_CSR:
return CSRNDArray(handle, writable=writable)
elif stype == _STORAGE_TYPE_ROW_SPARSE:
return RowSparseNDArray(handle, writable=writable)
else:
raise Exception("unknown storage type: %s"%stype)
_set_ndarray_class(_ndarray_cls)
def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)`` when shapes of lhs and rhs do not
match. If lhs.shape == rhs.shape, this is equivalent to
``mx.nd.elemwise_add(lhs, rhs)``
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.abs
Parameters
----------
lhs : scalar or mxnet.ndarray.sparse.array
First array to be added.
rhs : scalar or mxnet.ndarray.sparse.array
Second array to be added.
If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
The element-wise sum of the input arrays.
Examples
--------
>>> a = mx.nd.ones((2,3)).tostype('csr')
>>> b = mx.nd.ones((2,3)).tostype('csr')
>>> a.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> b.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (a+b).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
>>> c = mx.nd.ones((2,3)).tostype('row_sparse')
>>> d = mx.nd.ones((2,3)).tostype('row_sparse')
>>> c.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> d.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (c+d).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_add,
operator.add,
_internal._plus_scalar,
None)
return _ufunc_helper(
lhs,
rhs,
op.broadcast_add,
operator.add,
_internal._plus_scalar,
None)
# pylint: enable= no-member, protected-access
def subtract(lhs, rhs):
"""Returns element-wise difference of the input arrays with broadcasting.
Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and
``mx.nd.broadcast_minus(lhs, rhs)`` when shapes of lhs and rhs do not
match. If lhs.shape == rhs.shape, this is equivalent to
``mx.nd.elemwise_sub(lhs, rhs)``
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.sparse.array
First array to be subtracted.
rhs : scalar or mxnet.ndarray.sparse.array
Second array to be subtracted.
If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.__spec__
Returns
-------
NDArray
The element-wise difference of the input arrays.
Examples
--------
>>> a = mx.nd.ones((2,3)).tostype('csr')
>>> b = mx.nd.ones((2,3)).tostype('csr')
>>> a.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> b.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (a-b).asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
>>> c = mx.nd.ones((2,3)).tostype('row_sparse')
>>> d = mx.nd.ones((2,3)).tostype('row_sparse')
>>> c.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> d.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> (c-d).asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_sub,
operator.sub,
_internal._minus_scalar,
None)
return _ufunc_helper(
lhs,
rhs,
op.broadcast_sub,
operator.sub,
_internal._minus_scalar,
None)
# pylint: enable= no-member, protected-access
def multiply(lhs, rhs):
"""Returns element-wise product of the input arrays with broadcasting.
Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_mul(lhs, rhs)``
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.sparse.array
First array to be multiplied.
rhs : scalar or mxnet.ndarray.sparse.array
Second array to be multiplied.
If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
The element-wise multiplication of the input arrays.
Examples
--------
>>> x = mx.nd.ones((2,3)).tostype('csr')
>>> y = mx.nd.arange(2).reshape((2,1))
>>> z = mx.nd.arange(3)
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> y.asnumpy()
array([[ 0.],
[ 1.]], dtype=float32)
>>> z.asnumpy()
array([ 0., 1., 2.], dtype=float32)
>>> (x*2).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
>>> (x*y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> mx.nd.sparse.multiply(x, y).asnumpy()
array([[ 0., 0., 0.],
[ 1., 1., 1.]], dtype=float32)
>>> (x*z).asnumpy()
array([[ 0., 1., 2.],
[ 0., 1., 2.]], dtype=float32)
>>> mx.nd.sparse.multiply(x, z).asnumpy()
array([[ 0., 1., 2.],
[ 0., 1., 2.]], dtype=float32)
>>> z = z.reshape((1, 3))
>>> z.asnumpy()
array([[ 0., 1., 2.]], dtype=float32)
>>> (x*z).asnumpy()
array([[ 0., 1., 2.],
[ 0., 1., 2.]], dtype=float32)
>>> mx.nd.sparse.multiply(x, z).asnumpy()
array([[ 0., 1., 2.],
[ 0., 1., 2.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_mul,
operator.mul,
_internal._mul_scalar,
None)
return _ufunc_helper(
lhs,
rhs,
op.broadcast_mul,
operator.mul,
_internal._mul_scalar,
None)
# pylint: enable= no-member, protected-access
def divide(lhs, rhs):
"""Returns element-wise division of the input arrays with broadcasting.
Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_div(lhs, rhs)``
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
----------
lhs : scalar or mxnet.ndarray.sparse.array
First array in division.
rhs : scalar or mxnet.ndarray.sparse.array
Second array in division.
The arrays to be divided. If ``lhs.shape != rhs.shape``, they must be
broadcastable to a common shape.
Returns
-------
NDArray
The element-wise division of the input arrays.
Examples
--------
>>> x = (mx.nd.ones((2,3))*6).tostype('csr')
>>> y = mx.nd.arange(2).reshape((2,1)) + 1
>>> z = mx.nd.arange(3) + 1
>>> x.asnumpy()
array([[ 6., 6., 6.],
[ 6., 6., 6.]], dtype=float32)
>>> y.asnumpy()
array([[ 1.],
[ 2.]], dtype=float32)
>>> z.asnumpy()
array([ 1., 2., 3.], dtype=float32)
>>> x/2
<NDArray 2x3 @cpu(0)>
>>> (x/3).asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
>>> (x/y).asnumpy()
array([[ 6., 6., 6.],
[ 3., 3., 3.]], dtype=float32)
>>> mx.nd.sparse.divide(x,y).asnumpy()
array([[ 6., 6., 6.],
[ 3., 3., 3.]], dtype=float32)
>>> (x/z).asnumpy()
array([[ 6., 3., 2.],
[ 6., 3., 2.]], dtype=float32)
>>> mx.nd.sprase.divide(x,z).asnumpy()
array([[ 6., 3., 2.],
[ 6., 3., 2.]], dtype=float32)
>>> z = z.reshape((1,3))
>>> z.asnumpy()
array([[ 1., 2., 3.]], dtype=float32)
>>> (x/z).asnumpy()
array([[ 6., 3., 2.],
[ 6., 3., 2.]], dtype=float32)
>>> mx.nd.sparse.divide(x,z).asnumpy()
array([[ 6., 3., 2.],
[ 6., 3., 2.]], dtype=float32)
"""
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_div,
operator.truediv,
_internal._div_scalar,
None)
return _ufunc_helper(
lhs,
rhs,
op.broadcast_div,
operator.truediv,
_internal._div_scalar,
None)
# pylint: enable= no-member, protected-access
def zeros(stype, shape, ctx=None, dtype=None, **kwargs):
"""Return a new array of given shape and type, filled with zeros.
Parameters
----------
stype: string
The storage type of the empty array, such as 'row_sparse', 'csr', etc
shape : int or tuple of int
The shape of the empty array
ctx : Context, optional
An optional device context (default is the current default context)
dtype : str or numpy.dtype, optional
An optional value type (default is `float32`)
Returns
-------
RowSparseNDArray or CSRNDArray
A created array
Examples
--------
>>> mx.nd.sparse.zeros('csr', (1,2))
<CSRNDArray 1x2 @cpu(0)>
>>> mx.nd.sparse.zeros('row_sparse', (1,2), ctx=mx.cpu(), dtype='float16').asnumpy()
array([[ 0., 0.]], dtype=float16)
"""
# pylint: disable= no-member, protected-access
if stype == 'default':
return _zeros_ndarray(shape, ctx=ctx, dtype=dtype, **kwargs)
if ctx is None:
ctx = current_context()
dtype = mx_real_t if dtype is None else dtype
if stype in ('row_sparse', 'csr'):
aux_types = _STORAGE_AUX_TYPES[stype]
else:
raise ValueError("unknown storage type: " + stype)
out = _ndarray_cls(_new_alloc_handle(stype, shape, ctx, True, dtype, aux_types))
return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, out=out, **kwargs)
# pylint: enable= no-member, protected-access
def empty(stype, shape, ctx=None, dtype=None):
"""Returns a new array of given shape and type, without initializing entries.
Parameters
----------
stype: string
The storage type of the empty array, such as 'row_sparse', 'csr', etc
shape : int or tuple of int
The shape of the empty array.
ctx : Context, optional
An optional device context (default is the current default context).
dtype : str or numpy.dtype, optional
An optional value type (default is `float32`).
Returns
-------
CSRNDArray or RowSparseNDArray
A created array.
"""
if isinstance(shape, int):
shape = (shape, )
if ctx is None:
ctx = current_context()
if dtype is None:
dtype = mx_real_t
assert(stype is not None)
if stype in ('csr', 'row_sparse'):
return zeros(stype, shape, ctx=ctx, dtype=dtype)
else:
raise Exception("unknown stype : " + str(stype))
def array(source_array, ctx=None, dtype=None):
"""Creates a sparse array from any object exposing the array interface.
Parameters
----------
source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix
The source sparse array
ctx : Context, optional
The default context is ``source_array.context`` if ``source_array`` is an NDArray. \
The current default context otherwise.
dtype : str or numpy.dtype, optional
The data type of the output array. The default dtype is ``source_array.dtype``
if `source_array` is an `NDArray`, `numpy.ndarray` or `scipy.sparse.csr.csr_matrix`, \
`float32` otherwise.
Returns
-------
RowSparseNDArray or CSRNDArray
An array with the same contents as the `source_array`.
Examples
--------
>>> import scipy.sparse as spsp
>>> csr = spsp.csr_matrix((2, 100))
>>> mx.nd.sparse.array(csr)
<CSRNDArray 2x100 @cpu(0)>
>>> mx.nd.sparse.array(mx.nd.sparse.zeros('csr', (3, 2)))
<CSRNDArray 3x2 @cpu(0)>
>>> mx.nd.sparse.array(mx.nd.sparse.zeros('row_sparse', (3, 2)))
<RowSparseNDArray 3x2 @cpu(0)>
"""
ctx = current_context() if ctx is None else ctx
if isinstance(source_array, NDArray):
assert(source_array.stype != 'default'), \
"Please use `tostype` to create RowSparseNDArray or CSRNDArray from an NDArray"
# prepare dtype and ctx based on source_array, if not provided
dtype = _prepare_default_dtype(source_array, dtype)
# if both dtype and ctx are different from source_array, we cannot copy directly
if source_array.dtype != dtype and source_array.context != ctx:
arr = empty(source_array.stype, source_array.shape, dtype=dtype)
arr[:] = source_array
arr = arr.as_in_context(ctx)
else:
arr = empty(source_array.stype, source_array.shape, dtype=dtype, ctx=ctx)
arr[:] = source_array
return arr
elif spsp and isinstance(source_array, spsp.csr.csr_matrix):
# TODO(haibin) implement `_sync_copy_from` with scipy csr object to reduce a copy
# preprocess scipy csr to canonical form
csr = source_array.sorted_indices()
csr.sum_duplicates()
dtype = _prepare_default_dtype(source_array, dtype)
return csr_matrix((csr.data, csr.indices, csr.indptr), shape=csr.shape, \
dtype=dtype, ctx=ctx)
elif isinstance(source_array, (np.ndarray, np.generic)):
raise ValueError("Please use mx.nd.array to create an NDArray with source_array of type ",
type(source_array))
else:
raise ValueError("Unexpected source_array type: ", type(source_array))
| apache-2.0 |
yangalex/Otomata-python | Oto.py | 1 | 12557 | import pygame
# initialize sounds
pygame.mixer.init(buffer=200) # This can be increased for better sound quality, but causes latency (incorrect tempo)
pygame.mixer.set_num_channels(100)
# Set variables used to represent the arrows in each cell
LEFT = ((10, 37.5), (65, 10), (65, 65))
RIGHT = ((10, 10), (10, 65), (65, 37.5))
UP = ((10, 65), (65, 65), (37.5, 10))
DOWN = ((10, 10), (65, 10), (37.5, 65))
# Class Oto
# Creates an Oto object (a cell in the grid)
# It is able to: move itself, play music, check if it collides with anything and change its state (direction)
class Oto(pygame.sprite.Sprite):
# Initialize instruments and sounds
instrument = ""
sounds = []
C1 = pygame.mixer.Sound("Sounds/{}C1.wav".format(instrument))
sounds.append(C1)
D = pygame.mixer.Sound("Sounds/{}D.wav".format(instrument))
sounds.append(D)
E = pygame.mixer.Sound("Sounds/{}E.wav".format(instrument))
sounds.append(E)
F = pygame.mixer.Sound("Sounds/{}F.wav".format(instrument))
sounds.append(F)
G = pygame.mixer.Sound("Sounds/{}G.wav".format(instrument))
sounds.append(G)
A = pygame.mixer.Sound("Sounds/{}A.wav".format(instrument))
sounds.append(A)
B = pygame.mixer.Sound("Sounds/{}B.wav".format(instrument))
sounds.append(B)
C2 = pygame.mixer.Sound("Sounds/{}C2.wav".format(instrument))
sounds.append(C2)
D2 = pygame.mixer.Sound("Sounds/{}D2.wav".format(instrument))
sounds.append(D2)
# Set volumes
for sound in sounds:
sound.set_volume(1) # value from 0.0-1.0; increase for higher volume
# Constructor
# input: pygame.Surface, int, int, int, int
def __init__(self, screen, width, height, boardW, boardH):
pygame.sprite.Sprite.__init__(self) # call parent constructor
self.image = pygame.Surface((width, height))
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), DOWN, 0)
self.rect = self.image.get_rect()
self.screen = screen
self.orientation = "v"
self.width = width
self.height = height
self.boardW = boardW
self.boardH = boardH
self.vy = width
self.vx = height
self.color = 255, 255, 255
self.oscillating = False
# Input: none
# Output: none
# Side-effect: changes the orientation of the object (vertical or horizontal)
def changeOrientation(self):
if self.orientation == "v":
self.orientation = "h"
elif self.orientation == "h":
self.orientation = "v"
# Called each time the group sprite is updated
def update(self):
if self.orientation == "v":
# If the cell hits either the top or bottom wall
if (self.rect.y+self.height == self.boardH and self.vy > 0) or (self.rect.y == 0 and self.vy < 0):
# Change direction
self.vy *= -1
# Play sounds depending on coordinates
if self.rect.x == 0:
Oto.C1.play()
elif self.rect.x == self.width:
Oto.D.play()
elif self.rect.x == self.width*2:
Oto.E.play()
elif self.rect.x == self.width*3:
Oto.F.play()
elif self.rect.x == self.width*4:
Oto.G.play()
elif self.rect.x == self.width*5:
Oto.A.play()
elif self.rect.x == self.width*6:
Oto.B.play()
elif self.rect.x == self.width*7:
Oto.C2.play()
elif self.rect.x == self.width*8:
Oto.D2.play()
# Redraw the arrow depending on which wall it hits
if self.rect.y+self.height == self.boardH:
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), UP, 0)
elif self.rect.y == 0:
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), DOWN, 0)
# This is a special case that happens when two arrows at the edge meet and start going around in circles (oscillating)
# This ensures that they still continue playing when they hit the wall
if self.oscillating and (self.rect.x+self.width == self.boardW or self.rect.x == 0):
if self.rect.y == 0:
Oto.D2.play()
elif self.rect.y == self.height:
Oto.C2.play()
elif self.rect.y == self.height*2:
Oto.B.play()
elif self.rect.y == self.height*3:
Oto.A.play()
elif self.rect.y == self.height*4:
Oto.G.play()
elif self.rect.y == self.height*5:
Oto.F.play()
elif self.rect.y == self.height*6:
Oto.E.play()
elif self.rect.y == self.height*7:
Oto.D.play()
elif self.rect.y == self.height*8:
Oto.C1.play()
# Move object
self.rect.y += self.vy
elif self.orientation == "h":
# If the cell hits the right or left wall
if (self.rect.x+self.width == self.boardW and self.vx > 0) or (self.rect.x == 0 and self.vx < 0):
self.vx *= -1
if self.rect.y == 0:
Oto.D2.play()
elif self.rect.y == self.height:
Oto.C2.play()
elif self.rect.y == self.height*2:
Oto.B.play()
elif self.rect.y == self.height*3:
Oto.A.play()
elif self.rect.y == self.height*4:
Oto.G.play()
elif self.rect.y == self.height*5:
Oto.F.play()
elif self.rect.y == self.height*6:
Oto.E.play()
elif self.rect.y == self.height*7:
Oto.D.play()
elif self.rect.y == self.height*8:
Oto.C1.play()
# Redraw the arrow depending on which wall it hits
if self.rect.x+self.width == self.boardW:
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), LEFT, 0)
elif self.rect.x == 0:
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), RIGHT, 0)
# This is a special case that happens when two arrows at the edge meet and start going around in circles (oscillating)
# This ensures that they still continue playing when they hit the wall
if self.oscillating and (self.rect.y+self.height == self.boardH or self.rect.y == 0):
if self.rect.x == 0:
Oto.C1.play()
elif self.rect.x == self.width:
Oto.D.play()
elif self.rect.x == self.width*2:
Oto.E.play()
elif self.rect.x == self.width*3:
Oto.F.play()
elif self.rect.x == self.width*4:
Oto.G.play()
elif self.rect.x == self.width*5:
Oto.A.play()
elif self.rect.x == self.width*6:
Oto.B.play()
elif self.rect.x == self.width*7:
Oto.C2.play()
elif self.rect.x == self.width*8:
Oto.D2.play()
# Move object
self.rect.x += self.vx
# Check Collisions
def checkCollision(self, spritesList):
for sprite in spritesList:
# Make sure that object is not comparing against itself
if self != sprite:
# Change orientation depending on which direction it was going initially
if pygame.sprite.collide_rect(self, sprite):
if self.orientation == "v" and self.vy > 0:
self.changeOrientation()
self.vx = -self.width
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), LEFT, 0)
elif self.orientation == "v" and self.vy < 0:
self.changeOrientation()
self.vx = self.width
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), RIGHT, 0)
elif self.orientation == "h" and self.vx > 0:
self.changeOrientation()
self.vy = self.height
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), DOWN, 0)
elif self.orientation == "h" and self.vx < 0:
self.changeOrientation()
self.vy = -self.height
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), UP, 0)
# Check to see if sprite is in oscillating mode (The arrows are exactly the same in every attribute)
if (self.orientation == sprite.orientation and self.vx == sprite.vx and self.rect.x == sprite.rect.x
and self.rect.y == sprite.rect.y) or (self.orientation == sprite.orientation and self.vy == sprite.vy
and self.rect.x == sprite.rect.x and self.rect.y == sprite.rect.y):
self.oscillating = True
else:
self.oscillating = False
# Change the state of the arrow to left, right, up or down (User right click)
def changeState(self):
if self.orientation == "v":
self.orientation = "h"
if self.vy > 0:
self.vx = -self.width
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), LEFT, 0)
elif self.vy < 0:
self.vx = self.width
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), RIGHT, 0)
elif self.orientation == "h":
self.orientation = "v"
if self.vx > 0:
self.vy = self.height
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), DOWN, 0)
elif self.vx < 0:
self.vy = -self.height
self.image.fill((0, 0, 0))
pygame.draw.polygon(self.image, (255, 255, 255), UP, 0)
# input: string
# output: none
# side-effect: changes the instrument being played
# Has to be a class method in other to affect all other instances of the Oto objects
@classmethod
def changeInstrument(cls, newInstrument):
Oto.instrument = newInstrument
# Reload sounds
sounds = []
Oto.C1 = pygame.mixer.Sound("Sounds/{}C1.wav".format(Oto.instrument))
sounds.append(Oto.C1)
Oto.D = pygame.mixer.Sound("Sounds/{}D.wav".format(Oto.instrument))
sounds.append(Oto.D)
Oto.E = pygame.mixer.Sound("Sounds/{}E.wav".format(Oto.instrument))
sounds.append(Oto.E)
Oto.F = pygame.mixer.Sound("Sounds/{}F.wav".format(Oto.instrument))
sounds.append(Oto.F)
Oto.G = pygame.mixer.Sound("Sounds/{}G.wav".format(Oto.instrument))
sounds.append(Oto.G)
Oto.A = pygame.mixer.Sound("Sounds/{}A.wav".format(Oto.instrument))
sounds.append(Oto.A)
Oto.B = pygame.mixer.Sound("Sounds/{}B.wav".format(Oto.instrument))
sounds.append(Oto.B)
Oto.C2 = pygame.mixer.Sound("Sounds/{}C2.wav".format(Oto.instrument))
sounds.append(Oto.C2)
Oto.D2 = pygame.mixer.Sound("Sounds/{}D2.wav".format(Oto.instrument))
sounds.append(Oto.D2)
# Set volumes
for sound in sounds:
sound.set_volume(1)
# input: none
# output: x coordinates of object
# side-effect: none
# Not really used, but here just in case
def getX(self):
return self.rect.x
# input: none
# output: y coordinates of object
# side-effect: none
# Not really used, but here just in case
def getY(self):
return self.rect.y
| mit |
stevenewey/django | tests/template_tests/filter_tests/test_upper.py | 388 | 1245 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template.defaultfilters import upper
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class UpperTests(SimpleTestCase):
"""
The "upper" filter messes up entities (which are case-sensitive),
so it's not safe for non-escaping purposes.
"""
@setup({'upper01': '{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}'})
def test_upper01(self):
output = self.engine.render_to_string('upper01', {'a': 'a & b', 'b': mark_safe('a & b')})
self.assertEqual(output, 'A & B A & B')
@setup({'upper02': '{{ a|upper }} {{ b|upper }}'})
def test_upper02(self):
output = self.engine.render_to_string('upper02', {'a': 'a & b', 'b': mark_safe('a & b')})
self.assertEqual(output, 'A & B A &AMP; B')
class FunctionTests(SimpleTestCase):
def test_upper(self):
self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT')
def test_unicode(self):
# lowercase e umlaut
self.assertEqual(upper('\xeb'), '\xcb')
def test_non_string_input(self):
self.assertEqual(upper(123), '123')
| bsd-3-clause |
rcosnita/fantastico-todo | todo/__init__.py | 3 | 1065 | '''Copyright 2013 Cosnita Radu Viorel
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.'''
| mit |
tulip-control/tulip-control | tulip/spec/gr1_fragment.py | 1 | 12733 | # Copyright (c) 2014, 2015 by California Institute of Technology
# 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.
#
# 3. Neither the name of the California Institute of Technology 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 CALTECH
# OR THE 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.
#
"""Test if given formula belongs to an LTL fragment that
is convertible to deterministic Buchi Automata
(readily expressible in GR(1) ).
reference
=========
1. Andreas Morgenstern and Klaus Schneider,
A LTL Fragment for GR(1)-Synthesis,
in Proceedings First International Workshop on
Interactions, Games and Protocols (iWIGP),
Electronic Proceedings in Theoretical Computer Science (EPTCS),
50, pp. 33--45, 2011,
http://doi.org/10.4204/EPTCS.50.3
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
import networkx as nx
from tulip import transys as trs
from tulip.spec import lexyacc, GRSpec
from tulip.spec import transformation as tx
from tulip.spec import parser
from tulip.spec import ast as sast
def check(formula):
"""Parse formula string and create abstract syntax tree (AST).
"""
ast = lexyacc.parse(formula)
dfa = trs.automata.FiniteWordAutomaton(atomic_proposition_based=False,
deterministic=True)
dfa.alphabet |= {'!', 'W', 'U', 'G', 'F',
'U_left', 'U_right',
'W_left', 'W_right'}
dfa.states.add_from({'gf', 'fg', 'g', 'f'})
dfa.states.initial.add('gf')
dfa.transitions.add('gf', 'fg', letter='!')
dfa.transitions.add('fg', 'gf', letter='!')
dfa.transitions.add('g', 'f', letter='!')
dfa.transitions.add('f', 'g', letter='!')
dfa.transitions.add('gf', 'gf', letter='W')
dfa.transitions.add('gf', 'gf', letter='U_left')
dfa.transitions.add('gf', 'gf', letter='G')
dfa.transitions.add('fg', 'fg', letter='U')
dfa.transitions.add('fg', 'fg', letter='F')
dfa.transitions.add('fg', 'fg', letter='W_right')
dfa.transitions.add('gf', 'f', letter='U_right')
dfa.transitions.add('gf', 'f', letter='F')
dfa.transitions.add('fg', 'g', letter='W_left')
dfa.transitions.add('fg', 'g', letter='G')
dfa.transitions.add('g', 'g', letter='W')
dfa.transitions.add('g', 'g', letter='G')
dfa.transitions.add('f', 'f', letter='U')
dfa.transitions.add('f', 'f', letter='F')
# plot tree automaton
# dfa.save('dfa.pdf')
# plot parse tree
sast.dump_dot(ast, 'ast.dot')
# sync product of AST with DFA,
# to check acceptance
Q = [(ast, 'gf')]
while Q:
s, q = Q.pop()
logger.info('visiting: ' + str(s) + ', ' + str(q))
if isinstance(s, sast.Unary):
op = s.operator
if op in {'!', 'G', 'F'}:
t = dfa.transitions.find(q, letter=op)
if not t:
raise Exception('not in fragment')
qi, qj, w = t[0]
Q.append((s.operand, qj))
else:
# ignore
Q.append((s.operand, q))
elif isinstance(s, sast.Binary):
op = s.operator
if op in {'W', 'U'}:
t = dfa.transitions.find(q, letter=op)
if t:
qi, qj, w = t[0]
Q.append((s.op_l, qj))
Q.append((s.op_r, qj))
else:
t = dfa.transitions.find(q, letter=op + '_left')
if not t:
raise Exception('not in fragment')
qi, qj, w = t[0]
Q.append((s.op_l, qj))
t = dfa.transitions.find(q, letter=op + '_right')
if not t:
raise Exception('not in fragment')
qi, qj, w = t[0]
Q.append((s.op_r, qj))
else:
# ignore
Q.append((s.op_l, q))
Q.append((s.op_r, q))
elif isinstance(s, sast.Var):
print('reached var')
return ast
def str_to_grspec(f):
"""Return `GRSpec` from LTL formula `f` as `str`.
Formula `f` must be in the form:
A -> G
where each of A, G is a conjunction of terms: `B`, `[]C`, `[]<>B`.
For more details on `B, C`, see [split_gr1].
@type f: `str`
@rtype: [GRSpec]
"""
t = parser.parse(f)
assert t.operator == '->'
env, sys = t.operands
d = {'assume': split_gr1(env),
'assert': split_gr1(sys)}
return GRSpec(env_init=d['assume']['init'],
env_safety=d['assume']['G'],
env_prog=d['assume']['GF'],
sys_init=d['assert']['init'],
sys_safety=d['assert']['G'],
sys_prog=d['assert']['GF'])
def split_gr1(f):
"""Return `dict` of GR(1) subformulae.
The formula `f` is assumed to be a conjunction of expressions
of the form:
`B`, `[]C` or `[]<>B`
where:
- `C` can contain "next"
- `B` cannot contain "next"
@param f: temporal logic formula
@type f: `str` or AST
@return: conjunctions of formulae A, B as `str`, grouped by keys:
`'init', 'G', 'GF'`
@rtype: `dict` of `str`: `list` of `str`
"""
# TODO: preprocess by applying syntactic identities: [][] = [] etc
try:
f + 's'
t = parser.parse(f)
except TypeError:
t = f
g = tx.Tree.from_recursive_ast(t)
# collect boundary of conjunction operators
Q = [g.root]
b = list() # use lists to preserve as much given syntactic order
while Q:
u = Q.pop()
# terminal ?
if not g.succ.get(u):
b.append(u)
continue
# operator
if u.operator == '&':
# use `u.operands` instead of `g.successors`
# to preserve original order
Q.extend(u.operands)
else:
b.append(u)
d = {'init': list(), 'G': list(), 'GF': list()}
for u in b:
# terminal ?
if not g.succ.get(u):
d['init'].append(u)
continue
# some operator
if u.operator != 'G':
d['init'].append(u)
continue
# G
(v,) = u.operands
# terminal in G ?
if not g.succ.get(v):
d['G'].append(v)
continue
# some operator in G
if v.operator == 'F':
(w,) = v.operands
d['GF'].append(w)
else:
# not a GF
d['G'].append(v)
# assert only admissible temporal operators
ops = {'G', 'F', 'U', 'V', 'R'}
operators = {'G': ops}
ops = set(ops)
ops.add('X')
operators.update(init=ops, GF=ops)
for part, f in d.items():
ops = operators[part]
for u in f:
op = has_operator(u, g, ops)
if op is None:
continue
raise AssertionError((
'found inadmissible operator "{op}" '
'in "{f}" formula').format(
op=op, f=u))
# conjoin (except for progress)
init = ' & '.join(u.flatten() for u in reversed(d['init']))
d['init'] = [init]
safe = ' & '.join(u.flatten() for u in reversed(d['G']))
d['G'] = [safe]
# flatten individual progress formulae
d['GF'] = [u.flatten() for u in d['GF']]
return d
def has_operator(u, g, operators):
try:
if u.operator in operators:
return u.operator
except AttributeError:
pass
for v in nx.descendants(g, u):
# terminal
if not g.succ.get(v):
continue
# operator
# is it temporal except for 'X' ?
if v.operator in operators:
return v.operator
return None
def stability_to_gr1(p, aux='aux'):
"""Convert C{<>[] p} to GR(1).
Warning: This conversion is sound, but not complete.
See p.2, U{[E10]
<https://tulip-control.sourceforge.io/doc/bibliography.html#e10>}
GR(1) form::
!(aux) &&
[](aux -> X aux) &&
[]<>(aux) &&
[](aux -> p)
@type p: str
@param aux: name to use for auxiliary variable
@type aux: str
@rtype: L{GRSpec}
"""
logging.warning(
'Conversion of stability (<>[]p) to GR(1)' +
'is sound, but NOT complete.'
)
a = aux
a0 = a
p = _paren(p)
a = _paren(a)
v = tx.check_var_name_conflict(p, a0)
sys_vars = v | {a0}
sys_init = {'!' + a}
sys_safe = {a + ' -> ' + p,
a + ' -> X ' + a}
sys_prog = {a}
return GRSpec(sys_vars=sys_vars, sys_init=sys_init,
sys_safety=sys_safe, sys_prog=sys_prog)
def response_to_gr1(p, q, aux='aux'):
"""Convert C{[](p -> <> q)} to GR(1).
GR(1) form::
[]<>(aux) &&
[]( (p && !q) -> X ! aux) &&
[]( (! aux && !q) -> X ! aux)
@type p: str
@type q: str
@param aux: name to use for auxiliary variable
@type aux: str
@rtype: L{GRSpec}
"""
a = aux
a0 = a
p = _paren(p)
q = _paren(q)
a = _paren(a)
s = p + ' -> <> ' + q
v = tx.check_var_name_conflict(s, a0)
sys_vars = v | {a0}
# sys_init = {a}
sys_safe = {
'(' + p + ' && !' + q + ') -> X !' + a,
'(!' + a + ' && !' + q + ') -> X !' + a
}
sys_prog = {a}
return GRSpec(sys_vars=sys_vars, # sys_init=sys_init,
sys_safety=sys_safe, sys_prog=sys_prog)
def eventually_to_gr1(p, aux='aux'):
"""Convert C{<> p} to GR(1).
GR(1) form::
!(aux) &&
[](aux -> X aux) &&
[]<>(aux) &&
[]( (!p && !aux) -> X!(aux) )
@type p: str
@param aux: name to use for auxiliary variable
@type aux: str
@rtype: L{GRSpec}
"""
a = aux
a0 = a
p = _paren(p)
a = _paren(a)
v = tx.check_var_name_conflict(p, a0)
sys_vars = v | {a0}
sys_init = {'!(' + a + ')'}
sys_safe = {
'(!' + p + ' && !' + a + ') -> X !' + a,
a + ' -> X ' + a
}
sys_prog = {a}
return GRSpec(sys_vars=sys_vars, sys_init=sys_init,
sys_safety=sys_safe, sys_prog=sys_prog)
def until_to_gr1(p, q, aux='aux'):
"""Convert C{p U q} to GR(1).
GR(1) form::
(!q -> !aux) &&
[](q -> aux)
[](aux -> X aux) &&
[]<>(aux) &&
[]( (!aux && X(!q) ) -> X!(aux) ) &&
[](!aux -> p)
@type p: str
@param aux: name to use for auxiliary variable
@type aux: str
@rtype: L{GRSpec}
"""
a = aux
a0 = a
p = _paren(p)
q = _paren(q)
a = _paren(a)
s = p + ' && ' + q
v = tx.check_var_name_conflict(s, a0)
sys_vars = v | {a0}
sys_init = {'!' + q + ' -> !' + a}
sys_safe = {
q + ' -> ' + a,
'( (X !' + q + ') && !' + a + ') -> X !' + a,
a + ' -> X ' + a,
'(!' + a + ') -> ' + p
}
sys_prog = {a}
return GRSpec(sys_vars=sys_vars, sys_init=sys_init,
sys_safety=sys_safe, sys_prog=sys_prog)
def _paren(x):
return '({x})'.format(x=x)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
s = '(a U b) && []a && <>a && <>a && []<>(<>z)'
parsed_formula = check(s)
print('Parsing result: ' + str(parsed_formula))
| bsd-3-clause |
prheenan/appm_project_2 | util.py | 1 | 2469 | from collections import Counter
import numpy as np
def getKmers(string,kV):
return [ string[i:i+kV] for i in range(0,len(string)-kV+1)]
def getCounters(seqs,kmer,goodIdx):
working = seqs[goodIdx]
# transform the dna into their kmers. Use a counter structure,
# which is much faster. it stored the unique elements and counts
# see: https://docs.python.org/2/library/collections.html#collections.Counter
return [ Counter(getKmers(x,kmer)) for x in working]
def getMinKFromCounters(counters,kmer,goodIdx,returnKmers=None,
printProgress=True):
# assuming 'counters' is a counter object with each {kmer : count} as a dict
kmerDat = [ tmpSet.most_common() for tmpSet in counters ]
kmerSet = map(lambda x: [item[0] for item in x],kmerDat)
kmerCounts = map(lambda x: [item[1] for item in x],kmerDat)
# maximum count (ie: the maximum number of times *any* kmer happens
# this needs to be 1 to find the appropriate value...
maxCount = map(max,kmerCounts)
# get the index where the max was one (ie: at most 1 of the kmers)
bestIdx = [ goodIdx[i] for i,c in enumerate(maxCount) if c<=1]
# update the bookkeeping stuff; of the originals (goodIdx.size), how many
# did we find the right kmer for len(bestIdx)
kNotFoundNum = goodIdx.size - len(bestIdx)
if (printProgress):
# assume we are just interested in the first kmer set, for debugging..
print("GetMinK: {:d} seqs left, average max of {:.1f} {:d}-mers".
format(kNotFoundNum,np.mean(maxCount),kmer))
kmer += 1
if (returnKmers is None):
return kmer,kNotFoundNum,bestIdx
else:
# also return the data the the 'returnKmers' most common ones.
return kmer,kNotFoundNum,bestIdx,kmerDat[0][:returnKmers]
def getMinKIdxAndCount(seqs,kmer,goodIdx,returnKmers=None,printProgress=True):
# returnKmers: if not none, returns this many (including -1, all)
# of the kmers found
# get the set of each of the kmers, using the unique set of the counters
# see: https://docs.python.org/2/library/collections.html#collections.Counter
counters = getCounters(seqs,kmer,goodIdx)
# For each counter, get all its elements (most common defaults to n)
# and record the count (second element, first index)
# see: https://docs.python.org/2/library/collections.html#collections.Counter
return getMinKFromCounters(counters,kmer,goodIdx,returnKmers,printProgress)
| gpl-2.0 |
Ale-/civics | apps/models/migrations/0034_auto_20180110_1120.py | 1 | 1405 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2018-01-10 11:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('models', '0033_auto_20170927_1158'),
]
operations = [
migrations.AlterField(
model_name='event',
name='agent',
field=models.CharField(choices=[('IM', 'Iniciativas municipales / Gobierno'), ('UO', 'Universidades / ONG / Fundaciones'), ('OI', 'Organismos internacionales'), ('ES', 'Empresa social / Startup'), ('IC', 'Iniciativa ciudadana'), ('JA', 'Juntas / Asociaciones de vecinos'), ('CC', 'Iniciativas ciudadanas extinguidas')], default='IM', help_text='El tipo de agente involucrado en la actividad', max_length=2, verbose_name='tipo de agente'),
),
migrations.AlterField(
model_name='initiative',
name='agent',
field=models.CharField(choices=[('IM', 'Iniciativas municipales / Gobierno'), ('UO', 'Universidades / ONG / Fundaciones'), ('OI', 'Organismos internacionales'), ('ES', 'Empresa social / Startup'), ('IC', 'Iniciativa ciudadana'), ('JA', 'Juntas / Asociaciones de vecinos'), ('CC', 'Iniciativas ciudadanas extinguidas')], default='IM', help_text='El tipo de agente involucrado en la iniciativa', max_length=2, verbose_name='tipo de agente'),
),
]
| gpl-3.0 |
gohin/django | tests/raw_query/tests.py | 119 | 12345 | from __future__ import unicode_literals
from datetime import date
from django.db.models.query_utils import InvalidQuery
from django.test import TestCase, skipUnlessDBFeature
from .models import Author, Book, BookFkAsPk, Coffee, FriendlyAuthor, Reviewer
class RawQueryTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(first_name='Joe', last_name='Smith', dob=date(1950, 9, 20))
cls.a2 = Author.objects.create(first_name='Jill', last_name='Doe', dob=date(1920, 4, 2))
cls.a3 = Author.objects.create(first_name='Bob', last_name='Smith', dob=date(1986, 1, 25))
cls.a4 = Author.objects.create(first_name='Bill', last_name='Jones', dob=date(1932, 5, 10))
cls.b1 = Book.objects.create(title='The awesome book', author=cls.a1, paperback=False, opening_line='It was a bright cold day in April and the clocks were striking thirteen.')
cls.b2 = Book.objects.create(title='The horrible book', author=cls.a1, paperback=True, opening_line='On an evening in the latter part of May a middle-aged man was walking homeward from Shaston to the village of Marlott, in the adjoining Vale of Blakemore, or Blackmoor.')
cls.b3 = Book.objects.create(title='Another awesome book', author=cls.a1, paperback=False, opening_line='A squat grey building of only thirty-four stories.')
cls.b4 = Book.objects.create(title='Some other book', author=cls.a3, paperback=True, opening_line='It was the day my grandmother exploded.')
cls.c1 = Coffee.objects.create(brand='dunkin doughnuts')
cls.c2 = Coffee.objects.create(brand='starbucks')
cls.r1 = Reviewer.objects.create()
cls.r2 = Reviewer.objects.create()
cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4)
def assertSuccessfulRawQuery(self, model, query, expected_results,
expected_annotations=(), params=[], translations=None):
"""
Execute the passed query against the passed model and check the output
"""
results = list(model.objects.raw(query, params=params, translations=translations))
self.assertProcessed(model, results, expected_results, expected_annotations)
self.assertAnnotations(results, expected_annotations)
def assertProcessed(self, model, results, orig, expected_annotations=()):
"""
Compare the results of a raw query against expected results
"""
self.assertEqual(len(results), len(orig))
for index, item in enumerate(results):
orig_item = orig[index]
for annotation in expected_annotations:
setattr(orig_item, *annotation)
for field in model._meta.fields:
# Check that all values on the model are equal
self.assertEqual(
getattr(item, field.attname),
getattr(orig_item, field.attname)
)
# This includes checking that they are the same type
self.assertEqual(
type(getattr(item, field.attname)),
type(getattr(orig_item, field.attname))
)
def assertNoAnnotations(self, results):
"""
Check that the results of a raw query contain no annotations
"""
self.assertAnnotations(results, ())
def assertAnnotations(self, results, expected_annotations):
"""
Check that the passed raw query results contain the expected
annotations
"""
if expected_annotations:
for index, result in enumerate(results):
annotation, value = expected_annotations[index]
self.assertTrue(hasattr(result, annotation))
self.assertEqual(getattr(result, annotation), value)
def test_simple_raw_query(self):
"""
Basic test of raw query with a simple database query
"""
query = "SELECT * FROM raw_query_author"
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_raw_query_lazy(self):
"""
Raw queries are lazy: they aren't actually executed until they're
iterated over.
"""
q = Author.objects.raw('SELECT * FROM raw_query_author')
self.assertIsNone(q.query.cursor)
list(q)
self.assertIsNotNone(q.query.cursor)
def test_FK_raw_query(self):
"""
Test of a simple raw query against a model containing a foreign key
"""
query = "SELECT * FROM raw_query_book"
books = Book.objects.all()
self.assertSuccessfulRawQuery(Book, query, books)
def test_db_column_handler(self):
"""
Test of a simple raw query against a model containing a field with
db_column defined.
"""
query = "SELECT * FROM raw_query_coffee"
coffees = Coffee.objects.all()
self.assertSuccessfulRawQuery(Coffee, query, coffees)
def test_order_handler(self):
"""
Test of raw raw query's tolerance for columns being returned in any
order
"""
selects = (
('dob, last_name, first_name, id'),
('last_name, dob, first_name, id'),
('first_name, last_name, dob, id'),
)
for select in selects:
query = "SELECT %s FROM raw_query_author" % select
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_translations(self):
"""
Test of raw query's optional ability to translate unexpected result
column names to specific model fields
"""
query = "SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author"
translations = {'first': 'first_name', 'last': 'last_name'}
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
def test_params(self):
"""
Test passing optional query parameters
"""
query = "SELECT * FROM raw_query_author WHERE first_name = %s"
author = Author.objects.all()[2]
params = [author.first_name]
qset = Author.objects.raw(query, params=params)
results = list(qset)
self.assertProcessed(Author, results, [author])
self.assertNoAnnotations(results)
self.assertEqual(len(results), 1)
self.assertIsInstance(repr(qset), str)
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_pyformat_params(self):
"""
Test passing optional query parameters
"""
query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s"
author = Author.objects.all()[2]
params = {'first': author.first_name}
qset = Author.objects.raw(query, params=params)
results = list(qset)
self.assertProcessed(Author, results, [author])
self.assertNoAnnotations(results)
self.assertEqual(len(results), 1)
self.assertIsInstance(repr(qset), str)
def test_query_representation(self):
"""
Test representation of raw query with parameters
"""
query = "SELECT * FROM raw_query_author WHERE last_name = %(last)s"
qset = Author.objects.raw(query, {'last': 'foo'})
self.assertEqual(repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>")
self.assertEqual(repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>")
query = "SELECT * FROM raw_query_author WHERE last_name = %s"
qset = Author.objects.raw(query, {'foo'})
self.assertEqual(repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>")
self.assertEqual(repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>")
def test_many_to_many(self):
"""
Test of a simple raw query against a model containing a m2m field
"""
query = "SELECT * FROM raw_query_reviewer"
reviewers = Reviewer.objects.all()
self.assertSuccessfulRawQuery(Reviewer, query, reviewers)
def test_extra_conversions(self):
"""
Test to insure that extra translations are ignored.
"""
query = "SELECT * FROM raw_query_author"
translations = {'something': 'else'}
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
def test_missing_fields(self):
query = "SELECT id, first_name, dob FROM raw_query_author"
for author in Author.objects.raw(query):
self.assertNotEqual(author.first_name, None)
# last_name isn't given, but it will be retrieved on demand
self.assertNotEqual(author.last_name, None)
def test_missing_fields_without_PK(self):
query = "SELECT first_name, dob FROM raw_query_author"
try:
list(Author.objects.raw(query))
self.fail('Query without primary key should fail')
except InvalidQuery:
pass
def test_annotations(self):
query = "SELECT a.*, count(b.id) as book_count FROM raw_query_author a LEFT JOIN raw_query_book b ON a.id = b.author_id GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id"
expected_annotations = (
('book_count', 3),
('book_count', 0),
('book_count', 1),
('book_count', 0),
)
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations)
def test_white_space_query(self):
query = " SELECT * FROM raw_query_author"
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_multiple_iterations(self):
query = "SELECT * FROM raw_query_author"
normal_authors = Author.objects.all()
raw_authors = Author.objects.raw(query)
# First Iteration
first_iterations = 0
for index, raw_author in enumerate(raw_authors):
self.assertEqual(normal_authors[index], raw_author)
first_iterations += 1
# Second Iteration
second_iterations = 0
for index, raw_author in enumerate(raw_authors):
self.assertEqual(normal_authors[index], raw_author)
second_iterations += 1
self.assertEqual(first_iterations, second_iterations)
def test_get_item(self):
# Indexing on RawQuerySets
query = "SELECT * FROM raw_query_author ORDER BY id ASC"
third_author = Author.objects.raw(query)[2]
self.assertEqual(third_author.first_name, 'Bob')
first_two = Author.objects.raw(query)[0:2]
self.assertEqual(len(first_two), 2)
self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test'])
def test_inheritance(self):
# date is the end of the Cuban Missile Crisis, I have no idea when
# Wesley was born
f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun",
dob=date(1962, 10, 28))
query = "SELECT * FROM raw_query_friendlyauthor"
self.assertEqual(
[o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]
)
def test_query_count(self):
self.assertNumQueries(1, list, Author.objects.raw("SELECT * FROM raw_query_author"))
def test_subquery_in_raw_sql(self):
try:
list(Book.objects.raw('SELECT id FROM (SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq'))
except InvalidQuery:
self.fail("Using a subquery in a RawQuerySet raised InvalidQuery")
def test_db_column_name_is_used_in_raw_query(self):
"""
Regression test that ensures the `column` attribute on the field is
used to generate the list of fields included in the query, as opposed
to the `attname`. This is important when the primary key is a
ForeignKey field because `attname` and `column` are not necessarily the
same.
"""
b = BookFkAsPk.objects.create(book=self.b1)
self.assertEqual(list(BookFkAsPk.objects.raw('SELECT not_the_default FROM raw_query_bookfkaspk')), [b])
| bsd-3-clause |
pseudo-cluster/pseudo-cluster | scripts/pseudo_cluster/statistics_analyzer.py | 1 | 3861 | # -*- coding: utf-8 -*-
import imp
import sys
import gettext
import tasks_list
import metrics
import statistics_plotter
def metric_module_import(metric_name):
"""
импортирует модуль, который
обеспечивает работу с метрикой.
"""
try:
#module=importlib("metrics.metric_"+metric_name)
module=imp.load_source(
metric_name,
"%s/metric_%s.py" % (metrics.__path__[0], metric_name)
)
except IOError, e:
print e
sys.exit(3)
return module
class Statistics_analyzer(object):
"""
Класс для анализа статистики и её отображения
в виде текстовых файлов.
Поддерживает расчёт по некоторому набору метрик.
"""
def __init__(self):
"""
Конструктор
"""
#
#список задач
#на котором будет
#вычисляться метрика
#
self.tasks_list = None
#
# Коэффициент сжатия времени
#
self.time_compression = 1
#
# Объект расчётчика метрики.
# импортируется из
# соответствующего модуля.
#
self.metric_counter=None
#
# вычисленные значения
#
self.counted_values = None
def get_metrics_list(self):
"""
Получает список доступных в
текущий момент метрик
"""
metrics_list=dict()
for module_name in metrics.__all__:
metric_name=module_name.partition('_')[2]
module=metric_module_import(metric_name)
metrics_list[metric_name]=module.metric_short_description
return metrics_list
def get_metric_description(self,metric_name):
"""
Получает описание метрики по её имени
"""
if "metric_%s" % metric_name not in metrics.__all__:
print _("Metric with name '%s' is not found") % metric_name
sys.exit(3)
module=metric_module_import(metric_name)
return module.metric_description
def register_metric_counter(self, metric_name, parameters):
"""
Регистрирует вычислитель метрики, по имени и параметрам.
"""
module=metric_module_import(metric_name)
self.metric_counter=module.Metric_counter(self.tasks_list,parameters)
def count_metric(self):
"""
Вычисляет значение метрики
"""
self.counted_values=self.metric_counter.count_values(self.time_compression)
def print_values(self,file_name):
"""
Печатает вычисленные значения в файл
"""
f=open(file_name,"w")
s=self.metric_counter.get_header_string()
f.write(s+'\n')
for key in self.counted_values.keys():
s=self.metric_counter.format_row(key,self.counted_values[key])
f.write(s+'\n')
f.close()
def plot_values(self,metric_name,file_name):
"""
Отрисовывает график, если это необходимо.
"""
plotter=statistics_plotter.Plotter(_("Print values by metric '%s'") % metric_name,
self.counted_values,
self.metric_counter.get_header_string().split('\t'),
self.metric_counter.get_draw_type()
)
plotter.draw(file_name)
| lgpl-2.1 |
catiedev/mbed-os | TESTS/netsocket/host_tests/udp_echo.py | 48 | 3957 | """
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 sys
import socket
from sys import stdout
from threading import Thread
from SocketServer import BaseRequestHandler, UDPServer
from mbed_host_tests import BaseHostTest, event_callback
class UDPEchoClientHandler(BaseRequestHandler):
def handle(self):
""" UDP packet handler. Echoes data back to sender's address.
"""
data, sock = self.request
sock.sendto(data, self.client_address)
class UDPEchoClientTest(BaseHostTest):
def __init__(self):
"""
Initialise test parameters.
:return:
"""
BaseHostTest.__init__(self)
self.SERVER_IP = None # Will be determined after knowing the target IP
self.SERVER_PORT = 0 # Let TCPServer choose an arbitrary port
self.server = None
self.server_thread = None
self.target_ip = None
@staticmethod
def find_interface_to_target_addr(target_ip):
"""
Finds IP address of the interface through which it is connected to the target.
:return:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((target_ip, 0)) # Target IP, any port
except socket.error:
s.connect((target_ip, 8000)) # Target IP, 'random' port
ip = s.getsockname()[0]
s.close()
return ip
def setup_udp_server(self):
"""
sets up a UDP server for target to connect and send test data.
:return:
"""
# !NOTE: There should mechanism to assert in the host test
if self.SERVER_IP is None:
self.log("setup_udp_server() called before determining server IP!")
self.notify_complete(False)
# Returning none will suppress host test from printing success code
self.server = UDPServer((self.SERVER_IP, self.SERVER_PORT), UDPEchoClientHandler)
ip, port = self.server.server_address
self.SERVER_PORT = port
self.server.allow_reuse_address = True
self.log("HOST: Listening for UDP packets: " + self.SERVER_IP + ":" + str(self.SERVER_PORT))
self.server_thread = Thread(target=UDPEchoClientTest.server_thread_func, args=(self,))
self.server_thread.start()
@staticmethod
def server_thread_func(this):
"""
Thread function to run TCP server forever.
:param this:
:return:
"""
this.server.serve_forever()
@event_callback("target_ip")
def _callback_target_ip(self, key, value, timestamp):
"""
Callback to handle reception of target's IP address.
:param key:
:param value:
:param timestamp:
:return:
"""
self.target_ip = value
self.SERVER_IP = self.find_interface_to_target_addr(self.target_ip)
self.setup_udp_server()
@event_callback("host_ip")
def _callback_host_ip(self, key, value, timestamp):
"""
Callback for request for host IP Addr
"""
self.send_kv("host_ip", self.SERVER_IP)
@event_callback("host_port")
def _callback_host_port(self, key, value, timestamp):
"""
Callback for request for host port
"""
self.send_kv("host_port", self.SERVER_PORT)
def teardown(self):
if self.server:
self.server.shutdown()
self.server_thread.join()
| apache-2.0 |
CapOM/ChromiumGStreamerBackend | tools/telemetry/telemetry/util/perf_tests_results_helper.py | 26 | 5370 | # Copyright 2013 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 re
import sys
import json
import math
from telemetry.util import perf_result_data_type
# Mapping from result type to test output
RESULT_TYPES = {perf_result_data_type.UNIMPORTANT: 'RESULT ',
perf_result_data_type.DEFAULT: '*RESULT ',
perf_result_data_type.INFORMATIONAL: '',
perf_result_data_type.UNIMPORTANT_HISTOGRAM: 'HISTOGRAM ',
perf_result_data_type.HISTOGRAM: '*HISTOGRAM '}
def _EscapePerfResult(s):
"""Escapes |s| for use in a perf result."""
return re.sub(r'[\:|=/#&,]', '_', s)
def FlattenList(values):
"""Returns a simple list without sub-lists."""
ret = []
for entry in values:
if isinstance(entry, list):
ret.extend(FlattenList(entry))
else:
ret.append(entry)
return ret
def GeomMeanAndStdDevFromHistogram(histogram_json):
histogram = json.loads(histogram_json)
# Handle empty histograms gracefully.
if not 'buckets' in histogram:
return 0.0, 0.0
count = 0
sum_of_logs = 0
for bucket in histogram['buckets']:
if 'high' in bucket:
bucket['mean'] = (bucket['low'] + bucket['high']) / 2.0
else:
bucket['mean'] = bucket['low']
if bucket['mean'] > 0:
sum_of_logs += math.log(bucket['mean']) * bucket['count']
count += bucket['count']
if count == 0:
return 0.0, 0.0
sum_of_squares = 0
geom_mean = math.exp(sum_of_logs / count)
for bucket in histogram['buckets']:
if bucket['mean'] > 0:
sum_of_squares += (bucket['mean'] - geom_mean) ** 2 * bucket['count']
return geom_mean, math.sqrt(sum_of_squares / count)
def _ValueToString(v):
# Special case for floats so we don't print using scientific notation.
if isinstance(v, float):
return '%f' % v
else:
return str(v)
def _MeanAndStdDevFromList(values):
avg = None
sd = None
if len(values) > 1:
try:
value = '[%s]' % ','.join([_ValueToString(v) for v in values])
avg = sum([float(v) for v in values]) / len(values)
sqdiffs = [(float(v) - avg) ** 2 for v in values]
variance = sum(sqdiffs) / (len(values) - 1)
sd = math.sqrt(variance)
except ValueError:
value = ', '.join(values)
else:
value = values[0]
return value, avg, sd
def PrintPages(page_list):
"""Prints list of pages to stdout in the format required by perf tests."""
print 'Pages: [%s]' % ','.join([_EscapePerfResult(p) for p in page_list])
def PrintPerfResult(measurement, trace, values, units,
result_type=perf_result_data_type.DEFAULT,
print_to_stdout=True):
"""Prints numerical data to stdout in the format required by perf tests.
The string args may be empty but they must not contain any colons (:) or
equals signs (=).
This is parsed by the buildbot using:
http://src.chromium.org/viewvc/chrome/trunk/tools/build/scripts/slave/process_log_utils.py
Args:
measurement: A description of the quantity being measured, e.g. "vm_peak".
On the dashboard, this maps to a particular graph. Mandatory.
trace: A description of the particular data point, e.g. "reference".
On the dashboard, this maps to a particular "line" in the graph.
Mandatory.
values: A list of numeric measured values. An N-dimensional list will be
flattened and treated as a simple list.
units: A description of the units of measure, e.g. "bytes".
result_type: Accepts values of perf_result_data_type.ALL_TYPES.
print_to_stdout: If True, prints the output in stdout instead of returning
the output to caller.
Returns:
String of the formated perf result.
"""
assert perf_result_data_type.IsValidType(result_type), \
'result type: %s is invalid' % result_type
trace_name = _EscapePerfResult(trace)
if (result_type == perf_result_data_type.UNIMPORTANT or
result_type == perf_result_data_type.DEFAULT or
result_type == perf_result_data_type.INFORMATIONAL):
assert isinstance(values, list)
assert '/' not in measurement
flattened_values = FlattenList(values)
assert len(flattened_values)
value, avg, sd = _MeanAndStdDevFromList(flattened_values)
output = '%s%s: %s%s%s %s' % (
RESULT_TYPES[result_type],
_EscapePerfResult(measurement),
trace_name,
# Do not show equal sign if the trace is empty. Usually it happens when
# measurement is enough clear to describe the result.
'= ' if trace_name else '',
value,
units)
else:
assert perf_result_data_type.IsHistogram(result_type)
assert isinstance(values, list)
# The histograms can only be printed individually, there's no computation
# across different histograms.
assert len(values) == 1
value = values[0]
output = '%s%s: %s= %s %s' % (
RESULT_TYPES[result_type],
_EscapePerfResult(measurement),
trace_name,
value,
units)
avg, sd = GeomMeanAndStdDevFromHistogram(value)
if avg:
output += '\nAvg %s: %f%s' % (measurement, avg, units)
if sd:
output += '\nSd %s: %f%s' % (measurement, sd, units)
if print_to_stdout:
print output
sys.stdout.flush()
return output
| bsd-3-clause |
lzweopard/carve | external/gtest-1.5.0/test/gtest_xml_output_unittest.py | 306 | 9711 | #!/usr/bin/env python
#
# Copyright 2006, 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.
"""Unit test for the gtest_xml_output module"""
__author__ = 'eefacm@gmail.com (Sean Mcafee)'
import errno
import os
import sys
from xml.dom import minidom, Node
import gtest_test_utils
import gtest_xml_test_utils
GTEST_OUTPUT_FLAG = "--gtest_output"
GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml"
GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_"
SUPPORTS_STACK_TRACES = False
if SUPPORTS_STACK_TRACES:
STACK_TRACE_TEMPLATE = "\nStack trace:\n*"
else:
STACK_TRACE_TEMPLATE = ""
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="15" failures="4" disabled="2" errors="0" time="*" name="AllTests">
<testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/>
</testsuite>
<testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="Fails" status="run" time="*" classname="FailedTest">
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*">
<testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" time="*" classname="MixedResultTest">
<failure message="Value of: 2
Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 2
Expected: 1%(stack)s]]></failure>
<failure message="Value of: 3
Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Value of: 3
Expected: 2%(stack)s]]></failure>
</testcase>
<testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/>
</testsuite>
<testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest">
<failure message="Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*">
<testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest">
<failure message="Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
</testsuite>
<testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*">
<testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/>
</testsuite>
<testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*">
<testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/>
<testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/>
<testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/>
<testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/>
</testsuite>
<testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*">
<testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/>
<testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/>
<testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/>
</testsuite>
</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE}
EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="0" failures="0" disabled="0" errors="0" time="*" name="AllTests">
</testsuites>"""
class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
"""
Unit test for Google Test's XML output functionality.
"""
def testNonEmptyXmlOutput(self):
"""
Runs a test program that generates a non-empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
def testEmptyXmlOutput(self):
"""
Runs a test program that generates an empty XML output, and
tests that the XML output is expected.
"""
self._TestXmlOutput("gtest_no_test_unittest",
EXPECTED_EMPTY_XML, 0)
def testDefaultOutputFile(self):
"""
Confirms that Google Test produces an XML output file with the expected
default name if no name is explicitly specified.
"""
output_file = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_DEFAULT_OUTPUT_FILE)
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
"gtest_no_test_unittest")
try:
os.remove(output_file)
except OSError, e:
if e.errno != errno.ENOENT:
raise
p = gtest_test_utils.Subprocess(
[gtest_prog_path, "%s=xml" % GTEST_OUTPUT_FLAG],
working_dir=gtest_test_utils.GetTempDir())
self.assert_(p.exited)
self.assertEquals(0, p.exit_code)
self.assert_(os.path.isfile(output_file))
def testSuppressedXmlOutput(self):
"""
Tests that no XML file is generated if the default XML listener is
shut down before RUN_ALL_TESTS is invoked.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
GTEST_PROGRAM_NAME + "out.xml")
if os.path.isfile(xml_path):
os.remove(xml_path)
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
command = [gtest_prog_path,
"%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path),
"--shut_down_xml"]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
self.assert_(False,
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(1, p.exit_code,
"'%s' exited with code %s, which doesn't match "
"the expected exit code %s."
% (command, p.exit_code, 1))
self.assert_(not os.path.isfile(xml_path))
def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code):
"""
Asserts that the XML document generated by running the program
gtest_prog_name matches expected_xml, a string containing another
XML document. Furthermore, the program's exit code must be
expected_exit_code.
"""
xml_path = os.path.join(gtest_test_utils.GetTempDir(),
gtest_prog_name + "out.xml")
gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
command = [gtest_prog_path, "%s=xml:%s" % (GTEST_OUTPUT_FLAG, xml_path)]
p = gtest_test_utils.Subprocess(command)
if p.terminated_by_signal:
self.assert_(False,
"%s was killed by signal %d" % (gtest_prog_name, p.signal))
else:
self.assert_(p.exited)
self.assertEquals(expected_exit_code, p.exit_code,
"'%s' exited with code %s, which doesn't match "
"the expected exit code %s."
% (command, p.exit_code, expected_exit_code))
expected = minidom.parseString(expected_xml)
actual = minidom.parse(xml_path)
self.NormalizeXml(actual.documentElement)
self.AssertEquivalentNodes(expected.documentElement,
actual.documentElement)
expected.unlink()
actual .unlink()
if __name__ == '__main__':
os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
gtest_test_utils.Main()
| gpl-3.0 |
phlizik/xbmctorrent | resources/site-packages/xbmctorrent/tvdb.py | 5 | 7208 | BASE_URL = "http://www.thetvdb.com"
HEADERS = {
"Referer": BASE_URL,
}
API_URL = "%s/api" % BASE_URL
API_KEY = "1D62F2F90030C444"
LANG = "en"
def dom2dict(node):
ret = {}
for child in node:
if len(child):
ret.setdefault(child.tag.lower(), []).append(dom2dict(child))
else:
ret[child.tag.lower()] = child.text
return ret
def split_keys(meta, *keys):
for key in keys:
if meta.get(key):
meta[key] = filter(None, meta[key].split("|"))
return meta
def image_url(fragment):
return "%s/banners/%s" % (BASE_URL, fragment)
def banner(show_id):
from urlparse import urljoin
return urljoin(BASE_URL, "banners/graphical/%s" % show_id)
def season_url(show_id, season):
return "%s/banners/seasons/%s-%d-2.jpg" % (BASE_URL, show_id, season)
def update_image_urls(meta):
if isinstance(meta, dict):
for k, v in meta.items():
if isinstance(v, list):
map(update_image_urls, v)
elif isinstance(v, dict):
update_image_urls(v)
elif k in ["banner", "fanart", "poster", "filename", "bannerpath", "vignettepath", "thumbnailpath"] and isinstance(v, basestring):
meta[k] = image_url(v)
return meta
def show_url(show_id):
return "%s/%s/series/%s/%s.xml" % (API_URL, API_KEY, show_id, LANG)
def show_base_url(show_id):
return "%s/%s/series/%s" % (API_URL, API_KEY, show_id)
def show_banners_url(show_id):
return "%s/banners.xml" % (API_URL, API_KEY, show_id)
def get(show_id):
from xbmctorrent.caching import shelf
with shelf("com.thetvdb.show.%s" % show_id) as show:
if not show:
import xml.etree.ElementTree as ET
from xbmctorrent.utils import url_get
dom = ET.fromstring(url_get(show_url(show_id), headers=HEADERS, with_immunicity=False))
if not len(dom):
return
meta = dom2dict(dom[0])
meta = split_keys(meta, "actors", "genre", "writer")
update_image_urls(meta)
show.update(meta)
return dict(show)
def search(name, complete=False):
from xbmctorrent.caching import shelf
import hashlib
search_hash = hashlib.sha1(name).hexdigest()
with shelf("com.thetvdb.search.%s" % search_hash) as show:
if not show:
import re
import xml.etree.ElementTree as ET
from xbmctorrent.utils import url_get
dom = ET.fromstring(url_get("%s/api/GetSeries.php" % BASE_URL, params={
"seriesname": name,
}, headers=HEADERS, with_immunicity=False))
if not len(dom):
return
meta = dom2dict(dom[0])
if not complete:
return update_image_urls(meta)
show.update(get(meta["id"]))
return show
def get_banners(show_id):
import xml.etree.ElementTree as ET
from xbmctorrent.utils import url_get
r = url_get("%s/banners.xml" % show_base_url(show_id), headers=HEADERS, with_immunicity=False)
dom = ET.fromstring(r)
if not len(dom):
return
return update_image_urls(dom2dict(dom))["banner"]
def get_all_meta(show_id):
import xml.etree.ElementTree as ET
from concurrent import futures
from xbmctorrent.utils import url_get, joining
def _get_all_meta():
r = url_get("%s/all/%s.xml" % (show_base_url(show_id), LANG), headers=HEADERS, with_immunicity=False)
dom = ET.fromstring(r)
if not len(dom):
return
return update_image_urls(dom2dict(dom))
with futures.ThreadPoolExecutor(max_workers=2) as pool:
meta = pool.submit(_get_all_meta)
banners = pool.submit(get_banners, show_id)
meta = meta.result()
meta["series"][0]["episodes"] = meta["episode"]
meta = meta["series"][0]
meta["banners"] = banners.result() or []
return meta
def get_list_item(meta):
m = lambda x: meta.get(x) or ""
m_list = lambda x: meta.get(x) and ", ".join(meta[x]) or ""
return {
"label": meta["seriesname"],
"icon": m("poster"),
"thumbnail": m("poster"),
"info": {
"count": meta["id"],
"title": meta["seriesname"],
"genre": m_list("genre"),
"plot": m("overview"),
"plot_outline": m("overview"),
"tagline": m("overview"),
"rating": m("rating"),
"code": m("imdb_id"),
"mpaa": m("contentrating"),
"cast": m("actors") or [],
"castandrole": m("actors") or [],
"tvshowtitle": meta["seriesname"],
"studio": m("network"),
"status": m("status"),
"premiered": m("firstaired"),
"duration": m("runtime"),
"picturepath": m("poster"),
"year": meta.get("firstaired") and meta["firstaired"].split("-")[0] or "",
"votes": "%s votes" % meta["ratingcount"],
},
"properties": {
"fanart_image": m("fanart"),
},
}
def get_season_list_item(meta, season):
m = lambda x: meta.get(x) or ""
m_list = lambda x: meta.get(x) and ", ".join(meta[x]) or ""
season_id = filter(lambda ep: int(ep["seasonnumber"]) == season, meta["episodes"])[0]["seasonid"]
item = {
"label": "Season %d" % season,
"info": {
"count": season_id,
"tvshowtitle": meta["seriesname"],
"season": season,
},
"properties": {
"fanart_image": m("fanart"),
},
}
season_banners = [banner for banner in meta["banners"] if banner["bannertype"] == "season" and int(banner["season"]) == season]
if season_banners:
item["icon"] = item["thumbnail"] = season_banners[0]["bannerpath"]
return item
def build_episode_list_items(show_meta, season):
episodes = [episode for episode in show_meta["episodes"] if int(episode["seasonnumber"]) == season]
episodes = sorted(episodes, key=lambda ep: int(ep["episodenumber"]))
for episode in episodes:
m = lambda x: episode.get(x) or ""
yield {
"label": m("episodename"),
"icon": m("filename"),
"thumbnail": m("filename"),
"info": {
"count": m("id"),
"season": season,
"episode": m("episodenumber"),
"title": m("episodename"),
"originaltitle": m("episodename"),
"plot": m("overview"),
"plot_outline": m("overview"),
"tagline": m("overview"),
"rating": float(m("rating") or 0),
"code": m("imdb_id"),
"premiered": m("firstaired"),
"cast": episode.get("gueststars") and filter(None, episode["gueststars"].split("|")) or [],
"tvshowtitle": show_meta.get("seriesname") or "",
"writer": episode.get("writer") and ", ".join(filter(None, episode["writer"].split("|"))) or "",
},
"properties": {
"fanart_image": show_meta.get("fanart") or "",
},
}
| gpl-3.0 |
wolverineav/neutron | neutron/tests/functional/agent/linux/test_process_monitor.py | 21 | 3784 | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_config import cfg
from six import moves
from neutron.agent.linux import external_process
from neutron.agent.linux import utils
from neutron.tests import base
from neutron.tests.functional.agent.linux import simple_daemon
UUID_FORMAT = "test-uuid-%d"
SERVICE_NAME = "service"
class BaseTestProcessMonitor(base.BaseTestCase):
def setUp(self):
super(BaseTestProcessMonitor, self).setUp()
cfg.CONF.set_override('check_child_processes_interval', 1, 'AGENT')
self._child_processes = []
self._process_monitor = None
self.create_child_processes_manager('respawn')
self.addCleanup(self.cleanup_spawned_children)
def create_child_processes_manager(self, action):
cfg.CONF.set_override('check_child_processes_action', action, 'AGENT')
self._process_monitor = self.build_process_monitor()
def build_process_monitor(self):
return external_process.ProcessMonitor(
config=cfg.CONF,
resource_type='test')
def _make_cmdline_callback(self, uuid):
def _cmdline_callback(pidfile):
cmdline = ["python", simple_daemon.__file__,
"--uuid=%s" % uuid,
"--pid_file=%s" % pidfile]
return cmdline
return _cmdline_callback
def spawn_n_children(self, n, service=None):
self._child_processes = []
for child_number in moves.range(n):
uuid = self._child_uuid(child_number)
_callback = self._make_cmdline_callback(uuid)
pm = external_process.ProcessManager(
conf=cfg.CONF,
uuid=uuid,
default_cmd_callback=_callback,
service=service)
pm.enable()
self._process_monitor.register(uuid, SERVICE_NAME, pm)
self._child_processes.append(pm)
@staticmethod
def _child_uuid(child_number):
return UUID_FORMAT % child_number
def _kill_last_child(self):
self._child_processes[-1].disable()
def wait_for_all_children_respawned(self):
def all_children_active():
return all(pm.active for pm in self._child_processes)
for pm in self._child_processes:
directory = os.path.dirname(pm.get_pid_file_name())
self.assertEqual(0o755, os.stat(directory).st_mode & 0o777)
# we need to allow extra_time for the check process to happen
# and properly execute action over the gone processes under
# high load conditions
max_wait_time = (
cfg.CONF.AGENT.check_child_processes_interval + 5)
utils.wait_until_true(
all_children_active,
timeout=max_wait_time,
sleep=0.01,
exception=RuntimeError('Not all children respawned.'))
def cleanup_spawned_children(self):
self._process_monitor.stop()
for pm in self._child_processes:
pm.disable()
class TestProcessMonitor(BaseTestProcessMonitor):
def test_respawn_handler(self):
self.spawn_n_children(2)
self._kill_last_child()
self.wait_for_all_children_respawned()
| apache-2.0 |
EmuxEvans/Wox | PythonHome/Lib/site-packages/pip/_vendor/requests/packages/chardet/jisfreq.py | 3131 | 47315 | ######################## 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 #########################
# Sampling from about 20M text materials include literature and computer technology
#
# Japanese frequency table, applied to both S-JIS and EUC-JP
# They are sorted in order.
# 128 --> 0.77094
# 256 --> 0.85710
# 512 --> 0.92635
# 1024 --> 0.97130
# 2048 --> 0.99431
#
# Ideal Distribution Ratio = 0.92635 / (1-0.92635) = 12.58
# Random Distribution Ration = 512 / (2965+62+83+86-512) = 0.191
#
# Typical Distribution Ratio, 25% of IDR
JIS_TYPICAL_DISTRIBUTION_RATIO = 3.0
# Char to FreqOrder table ,
JIS_TABLE_SIZE = 4368
JISCharToFreqOrder = (
40, 1, 6, 182, 152, 180, 295,2127, 285, 381,3295,4304,3068,4606,3165,3510, # 16
3511,1822,2785,4607,1193,2226,5070,4608, 171,2996,1247, 18, 179,5071, 856,1661, # 32
1262,5072, 619, 127,3431,3512,3230,1899,1700, 232, 228,1294,1298, 284, 283,2041, # 48
2042,1061,1062, 48, 49, 44, 45, 433, 434,1040,1041, 996, 787,2997,1255,4305, # 64
2108,4609,1684,1648,5073,5074,5075,5076,5077,5078,3687,5079,4610,5080,3927,3928, # 80
5081,3296,3432, 290,2285,1471,2187,5082,2580,2825,1303,2140,1739,1445,2691,3375, # 96
1691,3297,4306,4307,4611, 452,3376,1182,2713,3688,3069,4308,5083,5084,5085,5086, # 112
5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102, # 128
5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,4097,5113,5114,5115,5116,5117, # 144
5118,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133, # 160
5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149, # 176
5150,5151,5152,4612,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164, # 192
5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,1472, 598, 618, 820,1205, # 208
1309,1412,1858,1307,1692,5176,5177,5178,5179,5180,5181,5182,1142,1452,1234,1172, # 224
1875,2043,2149,1793,1382,2973, 925,2404,1067,1241, 960,1377,2935,1491, 919,1217, # 240
1865,2030,1406,1499,2749,4098,5183,5184,5185,5186,5187,5188,2561,4099,3117,1804, # 256
2049,3689,4309,3513,1663,5189,3166,3118,3298,1587,1561,3433,5190,3119,1625,2998, # 272
3299,4613,1766,3690,2786,4614,5191,5192,5193,5194,2161, 26,3377, 2,3929, 20, # 288
3691, 47,4100, 50, 17, 16, 35, 268, 27, 243, 42, 155, 24, 154, 29, 184, # 304
4, 91, 14, 92, 53, 396, 33, 289, 9, 37, 64, 620, 21, 39, 321, 5, # 320
12, 11, 52, 13, 3, 208, 138, 0, 7, 60, 526, 141, 151,1069, 181, 275, # 336
1591, 83, 132,1475, 126, 331, 829, 15, 69, 160, 59, 22, 157, 55,1079, 312, # 352
109, 38, 23, 25, 10, 19, 79,5195, 61, 382,1124, 8, 30,5196,5197,5198, # 368
5199,5200,5201,5202,5203,5204,5205,5206, 89, 62, 74, 34,2416, 112, 139, 196, # 384
271, 149, 84, 607, 131, 765, 46, 88, 153, 683, 76, 874, 101, 258, 57, 80, # 400
32, 364, 121,1508, 169,1547, 68, 235, 145,2999, 41, 360,3027, 70, 63, 31, # 416
43, 259, 262,1383, 99, 533, 194, 66, 93, 846, 217, 192, 56, 106, 58, 565, # 432
280, 272, 311, 256, 146, 82, 308, 71, 100, 128, 214, 655, 110, 261, 104,1140, # 448
54, 51, 36, 87, 67,3070, 185,2618,2936,2020, 28,1066,2390,2059,5207,5208, # 464
5209,5210,5211,5212,5213,5214,5215,5216,4615,5217,5218,5219,5220,5221,5222,5223, # 480
5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,3514,5237,5238, # 496
5239,5240,5241,5242,5243,5244,2297,2031,4616,4310,3692,5245,3071,5246,3598,5247, # 512
4617,3231,3515,5248,4101,4311,4618,3808,4312,4102,5249,4103,4104,3599,5250,5251, # 528
5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267, # 544
5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283, # 560
5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299, # 576
5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315, # 592
5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331, # 608
5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347, # 624
5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363, # 640
5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379, # 656
5380,5381, 363, 642,2787,2878,2788,2789,2316,3232,2317,3434,2011, 165,1942,3930, # 672
3931,3932,3933,5382,4619,5383,4620,5384,5385,5386,5387,5388,5389,5390,5391,5392, # 688
5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408, # 704
5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424, # 720
5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440, # 736
5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456, # 752
5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472, # 768
5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488, # 784
5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504, # 800
5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520, # 816
5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536, # 832
5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552, # 848
5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568, # 864
5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584, # 880
5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600, # 896
5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616, # 912
5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632, # 928
5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648, # 944
5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664, # 960
5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680, # 976
5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696, # 992
5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712, # 1008
5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728, # 1024
5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5741,5742,5743,5744, # 1040
5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5760, # 1056
5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776, # 1072
5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5787,5788,5789,5790,5791,5792, # 1088
5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808, # 1104
5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824, # 1120
5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840, # 1136
5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856, # 1152
5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872, # 1168
5873,5874,5875,5876,5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888, # 1184
5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904, # 1200
5905,5906,5907,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, # 1216
5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936, # 1232
5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952, # 1248
5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968, # 1264
5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984, # 1280
5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000, # 1296
6001,6002,6003,6004,6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016, # 1312
6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032, # 1328
6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048, # 1344
6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064, # 1360
6065,6066,6067,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080, # 1376
6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096, # 1392
6097,6098,6099,6100,6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112, # 1408
6113,6114,2044,2060,4621, 997,1235, 473,1186,4622, 920,3378,6115,6116, 379,1108, # 1424
4313,2657,2735,3934,6117,3809, 636,3233, 573,1026,3693,3435,2974,3300,2298,4105, # 1440
854,2937,2463, 393,2581,2417, 539, 752,1280,2750,2480, 140,1161, 440, 708,1569, # 1456
665,2497,1746,1291,1523,3000, 164,1603, 847,1331, 537,1997, 486, 508,1693,2418, # 1472
1970,2227, 878,1220, 299,1030, 969, 652,2751, 624,1137,3301,2619, 65,3302,2045, # 1488
1761,1859,3120,1930,3694,3516, 663,1767, 852, 835,3695, 269, 767,2826,2339,1305, # 1504
896,1150, 770,1616,6118, 506,1502,2075,1012,2519, 775,2520,2975,2340,2938,4314, # 1520
3028,2086,1224,1943,2286,6119,3072,4315,2240,1273,1987,3935,1557, 175, 597, 985, # 1536
3517,2419,2521,1416,3029, 585, 938,1931,1007,1052,1932,1685,6120,3379,4316,4623, # 1552
804, 599,3121,1333,2128,2539,1159,1554,2032,3810, 687,2033,2904, 952, 675,1467, # 1568
3436,6121,2241,1096,1786,2440,1543,1924, 980,1813,2228, 781,2692,1879, 728,1918, # 1584
3696,4624, 548,1950,4625,1809,1088,1356,3303,2522,1944, 502, 972, 373, 513,2827, # 1600
586,2377,2391,1003,1976,1631,6122,2464,1084, 648,1776,4626,2141, 324, 962,2012, # 1616
2177,2076,1384, 742,2178,1448,1173,1810, 222, 102, 301, 445, 125,2420, 662,2498, # 1632
277, 200,1476,1165,1068, 224,2562,1378,1446, 450,1880, 659, 791, 582,4627,2939, # 1648
3936,1516,1274, 555,2099,3697,1020,1389,1526,3380,1762,1723,1787,2229, 412,2114, # 1664
1900,2392,3518, 512,2597, 427,1925,2341,3122,1653,1686,2465,2499, 697, 330, 273, # 1680
380,2162, 951, 832, 780, 991,1301,3073, 965,2270,3519, 668,2523,2636,1286, 535, # 1696
1407, 518, 671, 957,2658,2378, 267, 611,2197,3030,6123, 248,2299, 967,1799,2356, # 1712
850,1418,3437,1876,1256,1480,2828,1718,6124,6125,1755,1664,2405,6126,4628,2879, # 1728
2829, 499,2179, 676,4629, 557,2329,2214,2090, 325,3234, 464, 811,3001, 992,2342, # 1744
2481,1232,1469, 303,2242, 466,1070,2163, 603,1777,2091,4630,2752,4631,2714, 322, # 1760
2659,1964,1768, 481,2188,1463,2330,2857,3600,2092,3031,2421,4632,2318,2070,1849, # 1776
2598,4633,1302,2254,1668,1701,2422,3811,2905,3032,3123,2046,4106,1763,1694,4634, # 1792
1604, 943,1724,1454, 917, 868,2215,1169,2940, 552,1145,1800,1228,1823,1955, 316, # 1808
1080,2510, 361,1807,2830,4107,2660,3381,1346,1423,1134,4108,6127, 541,1263,1229, # 1824
1148,2540, 545, 465,1833,2880,3438,1901,3074,2482, 816,3937, 713,1788,2500, 122, # 1840
1575, 195,1451,2501,1111,6128, 859, 374,1225,2243,2483,4317, 390,1033,3439,3075, # 1856
2524,1687, 266, 793,1440,2599, 946, 779, 802, 507, 897,1081, 528,2189,1292, 711, # 1872
1866,1725,1167,1640, 753, 398,2661,1053, 246, 348,4318, 137,1024,3440,1600,2077, # 1888
2129, 825,4319, 698, 238, 521, 187,2300,1157,2423,1641,1605,1464,1610,1097,2541, # 1904
1260,1436, 759,2255,1814,2150, 705,3235, 409,2563,3304, 561,3033,2005,2564, 726, # 1920
1956,2343,3698,4109, 949,3812,3813,3520,1669, 653,1379,2525, 881,2198, 632,2256, # 1936
1027, 778,1074, 733,1957, 514,1481,2466, 554,2180, 702,3938,1606,1017,1398,6129, # 1952
1380,3521, 921, 993,1313, 594, 449,1489,1617,1166, 768,1426,1360, 495,1794,3601, # 1968
1177,3602,1170,4320,2344, 476, 425,3167,4635,3168,1424, 401,2662,1171,3382,1998, # 1984
1089,4110, 477,3169, 474,6130,1909, 596,2831,1842, 494, 693,1051,1028,1207,3076, # 2000
606,2115, 727,2790,1473,1115, 743,3522, 630, 805,1532,4321,2021, 366,1057, 838, # 2016
684,1114,2142,4322,2050,1492,1892,1808,2271,3814,2424,1971,1447,1373,3305,1090, # 2032
1536,3939,3523,3306,1455,2199, 336, 369,2331,1035, 584,2393, 902, 718,2600,6131, # 2048
2753, 463,2151,1149,1611,2467, 715,1308,3124,1268, 343,1413,3236,1517,1347,2663, # 2064
2093,3940,2022,1131,1553,2100,2941,1427,3441,2942,1323,2484,6132,1980, 872,2368, # 2080
2441,2943, 320,2369,2116,1082, 679,1933,3941,2791,3815, 625,1143,2023, 422,2200, # 2096
3816,6133, 730,1695, 356,2257,1626,2301,2858,2637,1627,1778, 937, 883,2906,2693, # 2112
3002,1769,1086, 400,1063,1325,3307,2792,4111,3077, 456,2345,1046, 747,6134,1524, # 2128
884,1094,3383,1474,2164,1059, 974,1688,2181,2258,1047, 345,1665,1187, 358, 875, # 2144
3170, 305, 660,3524,2190,1334,1135,3171,1540,1649,2542,1527, 927, 968,2793, 885, # 2160
1972,1850, 482, 500,2638,1218,1109,1085,2543,1654,2034, 876, 78,2287,1482,1277, # 2176
861,1675,1083,1779, 724,2754, 454, 397,1132,1612,2332, 893, 672,1237, 257,2259, # 2192
2370, 135,3384, 337,2244, 547, 352, 340, 709,2485,1400, 788,1138,2511, 540, 772, # 2208
1682,2260,2272,2544,2013,1843,1902,4636,1999,1562,2288,4637,2201,1403,1533, 407, # 2224
576,3308,1254,2071, 978,3385, 170, 136,1201,3125,2664,3172,2394, 213, 912, 873, # 2240
3603,1713,2202, 699,3604,3699, 813,3442, 493, 531,1054, 468,2907,1483, 304, 281, # 2256
4112,1726,1252,2094, 339,2319,2130,2639, 756,1563,2944, 748, 571,2976,1588,2425, # 2272
2715,1851,1460,2426,1528,1392,1973,3237, 288,3309, 685,3386, 296, 892,2716,2216, # 2288
1570,2245, 722,1747,2217, 905,3238,1103,6135,1893,1441,1965, 251,1805,2371,3700, # 2304
2601,1919,1078, 75,2182,1509,1592,1270,2640,4638,2152,6136,3310,3817, 524, 706, # 2320
1075, 292,3818,1756,2602, 317, 98,3173,3605,3525,1844,2218,3819,2502, 814, 567, # 2336
385,2908,1534,6137, 534,1642,3239, 797,6138,1670,1529, 953,4323, 188,1071, 538, # 2352
178, 729,3240,2109,1226,1374,2000,2357,2977, 731,2468,1116,2014,2051,6139,1261, # 2368
1593, 803,2859,2736,3443, 556, 682, 823,1541,6140,1369,2289,1706,2794, 845, 462, # 2384
2603,2665,1361, 387, 162,2358,1740, 739,1770,1720,1304,1401,3241,1049, 627,1571, # 2400
2427,3526,1877,3942,1852,1500, 431,1910,1503, 677, 297,2795, 286,1433,1038,1198, # 2416
2290,1133,1596,4113,4639,2469,1510,1484,3943,6141,2442, 108, 712,4640,2372, 866, # 2432
3701,2755,3242,1348, 834,1945,1408,3527,2395,3243,1811, 824, 994,1179,2110,1548, # 2448
1453, 790,3003, 690,4324,4325,2832,2909,3820,1860,3821, 225,1748, 310, 346,1780, # 2464
2470, 821,1993,2717,2796, 828, 877,3528,2860,2471,1702,2165,2910,2486,1789, 453, # 2480
359,2291,1676, 73,1164,1461,1127,3311, 421, 604, 314,1037, 589, 116,2487, 737, # 2496
837,1180, 111, 244, 735,6142,2261,1861,1362, 986, 523, 418, 581,2666,3822, 103, # 2512
855, 503,1414,1867,2488,1091, 657,1597, 979, 605,1316,4641,1021,2443,2078,2001, # 2528
1209, 96, 587,2166,1032, 260,1072,2153, 173, 94, 226,3244, 819,2006,4642,4114, # 2544
2203, 231,1744, 782, 97,2667, 786,3387, 887, 391, 442,2219,4326,1425,6143,2694, # 2560
633,1544,1202, 483,2015, 592,2052,1958,2472,1655, 419, 129,4327,3444,3312,1714, # 2576
1257,3078,4328,1518,1098, 865,1310,1019,1885,1512,1734, 469,2444, 148, 773, 436, # 2592
1815,1868,1128,1055,4329,1245,2756,3445,2154,1934,1039,4643, 579,1238, 932,2320, # 2608
353, 205, 801, 115,2428, 944,2321,1881, 399,2565,1211, 678, 766,3944, 335,2101, # 2624
1459,1781,1402,3945,2737,2131,1010, 844, 981,1326,1013, 550,1816,1545,2620,1335, # 2640
1008, 371,2881, 936,1419,1613,3529,1456,1395,2273,1834,2604,1317,2738,2503, 416, # 2656
1643,4330, 806,1126, 229, 591,3946,1314,1981,1576,1837,1666, 347,1790, 977,3313, # 2672
764,2861,1853, 688,2429,1920,1462, 77, 595, 415,2002,3034, 798,1192,4115,6144, # 2688
2978,4331,3035,2695,2582,2072,2566, 430,2430,1727, 842,1396,3947,3702, 613, 377, # 2704
278, 236,1417,3388,3314,3174, 757,1869, 107,3530,6145,1194, 623,2262, 207,1253, # 2720
2167,3446,3948, 492,1117,1935, 536,1838,2757,1246,4332, 696,2095,2406,1393,1572, # 2736
3175,1782, 583, 190, 253,1390,2230, 830,3126,3389, 934,3245,1703,1749,2979,1870, # 2752
2545,1656,2204, 869,2346,4116,3176,1817, 496,1764,4644, 942,1504, 404,1903,1122, # 2768
1580,3606,2945,1022, 515, 372,1735, 955,2431,3036,6146,2797,1110,2302,2798, 617, # 2784
6147, 441, 762,1771,3447,3607,3608,1904, 840,3037, 86, 939,1385, 572,1370,2445, # 2800
1336, 114,3703, 898, 294, 203,3315, 703,1583,2274, 429, 961,4333,1854,1951,3390, # 2816
2373,3704,4334,1318,1381, 966,1911,2322,1006,1155, 309, 989, 458,2718,1795,1372, # 2832
1203, 252,1689,1363,3177, 517,1936, 168,1490, 562, 193,3823,1042,4117,1835, 551, # 2848
470,4645, 395, 489,3448,1871,1465,2583,2641, 417,1493, 279,1295, 511,1236,1119, # 2864
72,1231,1982,1812,3004, 871,1564, 984,3449,1667,2696,2096,4646,2347,2833,1673, # 2880
3609, 695,3246,2668, 807,1183,4647, 890, 388,2333,1801,1457,2911,1765,1477,1031, # 2896
3316,3317,1278,3391,2799,2292,2526, 163,3450,4335,2669,1404,1802,6148,2323,2407, # 2912
1584,1728,1494,1824,1269, 298, 909,3318,1034,1632, 375, 776,1683,2061, 291, 210, # 2928
1123, 809,1249,1002,2642,3038, 206,1011,2132, 144, 975, 882,1565, 342, 667, 754, # 2944
1442,2143,1299,2303,2062, 447, 626,2205,1221,2739,2912,1144,1214,2206,2584, 760, # 2960
1715, 614, 950,1281,2670,2621, 810, 577,1287,2546,4648, 242,2168, 250,2643, 691, # 2976
123,2644, 647, 313,1029, 689,1357,2946,1650, 216, 771,1339,1306, 808,2063, 549, # 2992
913,1371,2913,2914,6149,1466,1092,1174,1196,1311,2605,2396,1783,1796,3079, 406, # 3008
2671,2117,3949,4649, 487,1825,2220,6150,2915, 448,2348,1073,6151,2397,1707, 130, # 3024
900,1598, 329, 176,1959,2527,1620,6152,2275,4336,3319,1983,2191,3705,3610,2155, # 3040
3706,1912,1513,1614,6153,1988, 646, 392,2304,1589,3320,3039,1826,1239,1352,1340, # 3056
2916, 505,2567,1709,1437,2408,2547, 906,6154,2672, 384,1458,1594,1100,1329, 710, # 3072
423,3531,2064,2231,2622,1989,2673,1087,1882, 333, 841,3005,1296,2882,2379, 580, # 3088
1937,1827,1293,2585, 601, 574, 249,1772,4118,2079,1120, 645, 901,1176,1690, 795, # 3104
2207, 478,1434, 516,1190,1530, 761,2080, 930,1264, 355, 435,1552, 644,1791, 987, # 3120
220,1364,1163,1121,1538, 306,2169,1327,1222, 546,2645, 218, 241, 610,1704,3321, # 3136
1984,1839,1966,2528, 451,6155,2586,3707,2568, 907,3178, 254,2947, 186,1845,4650, # 3152
745, 432,1757, 428,1633, 888,2246,2221,2489,3611,2118,1258,1265, 956,3127,1784, # 3168
4337,2490, 319, 510, 119, 457,3612, 274,2035,2007,4651,1409,3128, 970,2758, 590, # 3184
2800, 661,2247,4652,2008,3950,1420,1549,3080,3322,3951,1651,1375,2111, 485,2491, # 3200
1429,1156,6156,2548,2183,1495, 831,1840,2529,2446, 501,1657, 307,1894,3247,1341, # 3216
666, 899,2156,1539,2549,1559, 886, 349,2208,3081,2305,1736,3824,2170,2759,1014, # 3232
1913,1386, 542,1397,2948, 490, 368, 716, 362, 159, 282,2569,1129,1658,1288,1750, # 3248
2674, 276, 649,2016, 751,1496, 658,1818,1284,1862,2209,2087,2512,3451, 622,2834, # 3264
376, 117,1060,2053,1208,1721,1101,1443, 247,1250,3179,1792,3952,2760,2398,3953, # 3280
6157,2144,3708, 446,2432,1151,2570,3452,2447,2761,2835,1210,2448,3082, 424,2222, # 3296
1251,2449,2119,2836, 504,1581,4338, 602, 817, 857,3825,2349,2306, 357,3826,1470, # 3312
1883,2883, 255, 958, 929,2917,3248, 302,4653,1050,1271,1751,2307,1952,1430,2697, # 3328
2719,2359, 354,3180, 777, 158,2036,4339,1659,4340,4654,2308,2949,2248,1146,2232, # 3344
3532,2720,1696,2623,3827,6158,3129,1550,2698,1485,1297,1428, 637, 931,2721,2145, # 3360
914,2550,2587, 81,2450, 612, 827,2646,1242,4655,1118,2884, 472,1855,3181,3533, # 3376
3534, 569,1353,2699,1244,1758,2588,4119,2009,2762,2171,3709,1312,1531,6159,1152, # 3392
1938, 134,1830, 471,3710,2276,1112,1535,3323,3453,3535, 982,1337,2950, 488, 826, # 3408
674,1058,1628,4120,2017, 522,2399, 211, 568,1367,3454, 350, 293,1872,1139,3249, # 3424
1399,1946,3006,1300,2360,3324, 588, 736,6160,2606, 744, 669,3536,3828,6161,1358, # 3440
199, 723, 848, 933, 851,1939,1505,1514,1338,1618,1831,4656,1634,3613, 443,2740, # 3456
3829, 717,1947, 491,1914,6162,2551,1542,4121,1025,6163,1099,1223, 198,3040,2722, # 3472
370, 410,1905,2589, 998,1248,3182,2380, 519,1449,4122,1710, 947, 928,1153,4341, # 3488
2277, 344,2624,1511, 615, 105, 161,1212,1076,1960,3130,2054,1926,1175,1906,2473, # 3504
414,1873,2801,6164,2309, 315,1319,3325, 318,2018,2146,2157, 963, 631, 223,4342, # 3520
4343,2675, 479,3711,1197,2625,3712,2676,2361,6165,4344,4123,6166,2451,3183,1886, # 3536
2184,1674,1330,1711,1635,1506, 799, 219,3250,3083,3954,1677,3713,3326,2081,3614, # 3552
1652,2073,4657,1147,3041,1752, 643,1961, 147,1974,3955,6167,1716,2037, 918,3007, # 3568
1994, 120,1537, 118, 609,3184,4345, 740,3455,1219, 332,1615,3830,6168,1621,2980, # 3584
1582, 783, 212, 553,2350,3714,1349,2433,2082,4124, 889,6169,2310,1275,1410, 973, # 3600
166,1320,3456,1797,1215,3185,2885,1846,2590,2763,4658, 629, 822,3008, 763, 940, # 3616
1990,2862, 439,2409,1566,1240,1622, 926,1282,1907,2764, 654,2210,1607, 327,1130, # 3632
3956,1678,1623,6170,2434,2192, 686, 608,3831,3715, 903,3957,3042,6171,2741,1522, # 3648
1915,1105,1555,2552,1359, 323,3251,4346,3457, 738,1354,2553,2311,2334,1828,2003, # 3664
3832,1753,2351,1227,6172,1887,4125,1478,6173,2410,1874,1712,1847, 520,1204,2607, # 3680
264,4659, 836,2677,2102, 600,4660,3833,2278,3084,6174,4347,3615,1342, 640, 532, # 3696
543,2608,1888,2400,2591,1009,4348,1497, 341,1737,3616,2723,1394, 529,3252,1321, # 3712
983,4661,1515,2120, 971,2592, 924, 287,1662,3186,4349,2700,4350,1519, 908,1948, # 3728
2452, 156, 796,1629,1486,2223,2055, 694,4126,1259,1036,3392,1213,2249,2742,1889, # 3744
1230,3958,1015, 910, 408, 559,3617,4662, 746, 725, 935,4663,3959,3009,1289, 563, # 3760
867,4664,3960,1567,2981,2038,2626, 988,2263,2381,4351, 143,2374, 704,1895,6175, # 3776
1188,3716,2088, 673,3085,2362,4352, 484,1608,1921,2765,2918, 215, 904,3618,3537, # 3792
894, 509, 976,3043,2701,3961,4353,2837,2982, 498,6176,6177,1102,3538,1332,3393, # 3808
1487,1636,1637, 233, 245,3962, 383, 650, 995,3044, 460,1520,1206,2352, 749,3327, # 3824
530, 700, 389,1438,1560,1773,3963,2264, 719,2951,2724,3834, 870,1832,1644,1000, # 3840
839,2474,3717, 197,1630,3394, 365,2886,3964,1285,2133, 734, 922, 818,1106, 732, # 3856
480,2083,1774,3458, 923,2279,1350, 221,3086, 85,2233,2234,3835,1585,3010,2147, # 3872
1387,1705,2382,1619,2475, 133, 239,2802,1991,1016,2084,2383, 411,2838,1113, 651, # 3888
1985,1160,3328, 990,1863,3087,1048,1276,2647, 265,2627,1599,3253,2056, 150, 638, # 3904
2019, 656, 853, 326,1479, 680,1439,4354,1001,1759, 413,3459,3395,2492,1431, 459, # 3920
4355,1125,3329,2265,1953,1450,2065,2863, 849, 351,2678,3131,3254,3255,1104,1577, # 3936
227,1351,1645,2453,2193,1421,2887, 812,2121, 634, 95,2435, 201,2312,4665,1646, # 3952
1671,2743,1601,2554,2702,2648,2280,1315,1366,2089,3132,1573,3718,3965,1729,1189, # 3968
328,2679,1077,1940,1136, 558,1283, 964,1195, 621,2074,1199,1743,3460,3619,1896, # 3984
1916,1890,3836,2952,1154,2112,1064, 862, 378,3011,2066,2113,2803,1568,2839,6178, # 4000
3088,2919,1941,1660,2004,1992,2194, 142, 707,1590,1708,1624,1922,1023,1836,1233, # 4016
1004,2313, 789, 741,3620,6179,1609,2411,1200,4127,3719,3720,4666,2057,3721, 593, # 4032
2840, 367,2920,1878,6180,3461,1521, 628,1168, 692,2211,2649, 300, 720,2067,2571, # 4048
2953,3396, 959,2504,3966,3539,3462,1977, 701,6181, 954,1043, 800, 681, 183,3722, # 4064
1803,1730,3540,4128,2103, 815,2314, 174, 467, 230,2454,1093,2134, 755,3541,3397, # 4080
1141,1162,6182,1738,2039, 270,3256,2513,1005,1647,2185,3837, 858,1679,1897,1719, # 4096
2954,2324,1806, 402, 670, 167,4129,1498,2158,2104, 750,6183, 915, 189,1680,1551, # 4112
455,4356,1501,2455, 405,1095,2955, 338,1586,1266,1819, 570, 641,1324, 237,1556, # 4128
2650,1388,3723,6184,1368,2384,1343,1978,3089,2436, 879,3724, 792,1191, 758,3012, # 4144
1411,2135,1322,4357, 240,4667,1848,3725,1574,6185, 420,3045,1546,1391, 714,4358, # 4160
1967, 941,1864, 863, 664, 426, 560,1731,2680,1785,2864,1949,2363, 403,3330,1415, # 4176
1279,2136,1697,2335, 204, 721,2097,3838, 90,6186,2085,2505, 191,3967, 124,2148, # 4192
1376,1798,1178,1107,1898,1405, 860,4359,1243,1272,2375,2983,1558,2456,1638, 113, # 4208
3621, 578,1923,2609, 880, 386,4130, 784,2186,2266,1422,2956,2172,1722, 497, 263, # 4224
2514,1267,2412,2610, 177,2703,3542, 774,1927,1344, 616,1432,1595,1018, 172,4360, # 4240
2325, 911,4361, 438,1468,3622, 794,3968,2024,2173,1681,1829,2957, 945, 895,3090, # 4256
575,2212,2476, 475,2401,2681, 785,2744,1745,2293,2555,1975,3133,2865, 394,4668, # 4272
3839, 635,4131, 639, 202,1507,2195,2766,1345,1435,2572,3726,1908,1184,1181,2457, # 4288
3727,3134,4362, 843,2611, 437, 916,4669, 234, 769,1884,3046,3047,3623, 833,6187, # 4304
1639,2250,2402,1355,1185,2010,2047, 999, 525,1732,1290,1488,2612, 948,1578,3728, # 4320
2413,2477,1216,2725,2159, 334,3840,1328,3624,2921,1525,4132, 564,1056, 891,4363, # 4336
1444,1698,2385,2251,3729,1365,2281,2235,1717,6188, 864,3841,2515, 444, 527,2767, # 4352
2922,3625, 544, 461,6189, 566, 209,2437,3398,2098,1065,2068,3331,3626,3257,2137, # 4368 #last 512
#Everything below is of no interest for detection purpose
2138,2122,3730,2888,1995,1820,1044,6190,6191,6192,6193,6194,6195,6196,6197,6198, # 4384
6199,6200,6201,6202,6203,6204,6205,4670,6206,6207,6208,6209,6210,6211,6212,6213, # 4400
6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,6224,6225,6226,6227,6228,6229, # 4416
6230,6231,6232,6233,6234,6235,6236,6237,3187,6238,6239,3969,6240,6241,6242,6243, # 4432
6244,4671,6245,6246,4672,6247,6248,4133,6249,6250,4364,6251,2923,2556,2613,4673, # 4448
4365,3970,6252,6253,6254,6255,4674,6256,6257,6258,2768,2353,4366,4675,4676,3188, # 4464
4367,3463,6259,4134,4677,4678,6260,2267,6261,3842,3332,4368,3543,6262,6263,6264, # 4480
3013,1954,1928,4135,4679,6265,6266,2478,3091,6267,4680,4369,6268,6269,1699,6270, # 4496
3544,4136,4681,6271,4137,6272,4370,2804,6273,6274,2593,3971,3972,4682,6275,2236, # 4512
4683,6276,6277,4684,6278,6279,4138,3973,4685,6280,6281,3258,6282,6283,6284,6285, # 4528
3974,4686,2841,3975,6286,6287,3545,6288,6289,4139,4687,4140,6290,4141,6291,4142, # 4544
6292,6293,3333,6294,6295,6296,4371,6297,3399,6298,6299,4372,3976,6300,6301,6302, # 4560
4373,6303,6304,3843,3731,6305,4688,4374,6306,6307,3259,2294,6308,3732,2530,4143, # 4576
6309,4689,6310,6311,6312,3048,6313,6314,4690,3733,2237,6315,6316,2282,3334,6317, # 4592
6318,3844,6319,6320,4691,6321,3400,4692,6322,4693,6323,3049,6324,4375,6325,3977, # 4608
6326,6327,6328,3546,6329,4694,3335,6330,4695,4696,6331,6332,6333,6334,4376,3978, # 4624
6335,4697,3979,4144,6336,3980,4698,6337,6338,6339,6340,6341,4699,4700,4701,6342, # 4640
6343,4702,6344,6345,4703,6346,6347,4704,6348,4705,4706,3135,6349,4707,6350,4708, # 4656
6351,4377,6352,4709,3734,4145,6353,2506,4710,3189,6354,3050,4711,3981,6355,3547, # 4672
3014,4146,4378,3735,2651,3845,3260,3136,2224,1986,6356,3401,6357,4712,2594,3627, # 4688
3137,2573,3736,3982,4713,3628,4714,4715,2682,3629,4716,6358,3630,4379,3631,6359, # 4704
6360,6361,3983,6362,6363,6364,6365,4147,3846,4717,6366,6367,3737,2842,6368,4718, # 4720
2628,6369,3261,6370,2386,6371,6372,3738,3984,4719,3464,4720,3402,6373,2924,3336, # 4736
4148,2866,6374,2805,3262,4380,2704,2069,2531,3138,2806,2984,6375,2769,6376,4721, # 4752
4722,3403,6377,6378,3548,6379,6380,2705,3092,1979,4149,2629,3337,2889,6381,3338, # 4768
4150,2557,3339,4381,6382,3190,3263,3739,6383,4151,4723,4152,2558,2574,3404,3191, # 4784
6384,6385,4153,6386,4724,4382,6387,6388,4383,6389,6390,4154,6391,4725,3985,6392, # 4800
3847,4155,6393,6394,6395,6396,6397,3465,6398,4384,6399,6400,6401,6402,6403,6404, # 4816
4156,6405,6406,6407,6408,2123,6409,6410,2326,3192,4726,6411,6412,6413,6414,4385, # 4832
4157,6415,6416,4158,6417,3093,3848,6418,3986,6419,6420,3849,6421,6422,6423,4159, # 4848
6424,6425,4160,6426,3740,6427,6428,6429,6430,3987,6431,4727,6432,2238,6433,6434, # 4864
4386,3988,6435,6436,3632,6437,6438,2843,6439,6440,6441,6442,3633,6443,2958,6444, # 4880
6445,3466,6446,2364,4387,3850,6447,4388,2959,3340,6448,3851,6449,4728,6450,6451, # 4896
3264,4729,6452,3193,6453,4389,4390,2706,3341,4730,6454,3139,6455,3194,6456,3051, # 4912
2124,3852,1602,4391,4161,3853,1158,3854,4162,3989,4392,3990,4731,4732,4393,2040, # 4928
4163,4394,3265,6457,2807,3467,3855,6458,6459,6460,3991,3468,4733,4734,6461,3140, # 4944
2960,6462,4735,6463,6464,6465,6466,4736,4737,4738,4739,6467,6468,4164,2403,3856, # 4960
6469,6470,2770,2844,6471,4740,6472,6473,6474,6475,6476,6477,6478,3195,6479,4741, # 4976
4395,6480,2867,6481,4742,2808,6482,2493,4165,6483,6484,6485,6486,2295,4743,6487, # 4992
6488,6489,3634,6490,6491,6492,6493,6494,6495,6496,2985,4744,6497,6498,4745,6499, # 5008
6500,2925,3141,4166,6501,6502,4746,6503,6504,4747,6505,6506,6507,2890,6508,6509, # 5024
6510,6511,6512,6513,6514,6515,6516,6517,6518,6519,3469,4167,6520,6521,6522,4748, # 5040
4396,3741,4397,4749,4398,3342,2125,4750,6523,4751,4752,4753,3052,6524,2961,4168, # 5056
6525,4754,6526,4755,4399,2926,4169,6527,3857,6528,4400,4170,6529,4171,6530,6531, # 5072
2595,6532,6533,6534,6535,3635,6536,6537,6538,6539,6540,6541,6542,4756,6543,6544, # 5088
6545,6546,6547,6548,4401,6549,6550,6551,6552,4402,3405,4757,4403,6553,6554,6555, # 5104
4172,3742,6556,6557,6558,3992,3636,6559,6560,3053,2726,6561,3549,4173,3054,4404, # 5120
6562,6563,3993,4405,3266,3550,2809,4406,6564,6565,6566,4758,4759,6567,3743,6568, # 5136
4760,3744,4761,3470,6569,6570,6571,4407,6572,3745,4174,6573,4175,2810,4176,3196, # 5152
4762,6574,4177,6575,6576,2494,2891,3551,6577,6578,3471,6579,4408,6580,3015,3197, # 5168
6581,3343,2532,3994,3858,6582,3094,3406,4409,6583,2892,4178,4763,4410,3016,4411, # 5184
6584,3995,3142,3017,2683,6585,4179,6586,6587,4764,4412,6588,6589,4413,6590,2986, # 5200
6591,2962,3552,6592,2963,3472,6593,6594,4180,4765,6595,6596,2225,3267,4414,6597, # 5216
3407,3637,4766,6598,6599,3198,6600,4415,6601,3859,3199,6602,3473,4767,2811,4416, # 5232
1856,3268,3200,2575,3996,3997,3201,4417,6603,3095,2927,6604,3143,6605,2268,6606, # 5248
3998,3860,3096,2771,6607,6608,3638,2495,4768,6609,3861,6610,3269,2745,4769,4181, # 5264
3553,6611,2845,3270,6612,6613,6614,3862,6615,6616,4770,4771,6617,3474,3999,4418, # 5280
4419,6618,3639,3344,6619,4772,4182,6620,2126,6621,6622,6623,4420,4773,6624,3018, # 5296
6625,4774,3554,6626,4183,2025,3746,6627,4184,2707,6628,4421,4422,3097,1775,4185, # 5312
3555,6629,6630,2868,6631,6632,4423,6633,6634,4424,2414,2533,2928,6635,4186,2387, # 5328
6636,4775,6637,4187,6638,1891,4425,3202,3203,6639,6640,4776,6641,3345,6642,6643, # 5344
3640,6644,3475,3346,3641,4000,6645,3144,6646,3098,2812,4188,3642,3204,6647,3863, # 5360
3476,6648,3864,6649,4426,4001,6650,6651,6652,2576,6653,4189,4777,6654,6655,6656, # 5376
2846,6657,3477,3205,4002,6658,4003,6659,3347,2252,6660,6661,6662,4778,6663,6664, # 5392
6665,6666,6667,6668,6669,4779,4780,2048,6670,3478,3099,6671,3556,3747,4004,6672, # 5408
6673,6674,3145,4005,3748,6675,6676,6677,6678,6679,3408,6680,6681,6682,6683,3206, # 5424
3207,6684,6685,4781,4427,6686,4782,4783,4784,6687,6688,6689,4190,6690,6691,3479, # 5440
6692,2746,6693,4428,6694,6695,6696,6697,6698,6699,4785,6700,6701,3208,2727,6702, # 5456
3146,6703,6704,3409,2196,6705,4429,6706,6707,6708,2534,1996,6709,6710,6711,2747, # 5472
6712,6713,6714,4786,3643,6715,4430,4431,6716,3557,6717,4432,4433,6718,6719,6720, # 5488
6721,3749,6722,4006,4787,6723,6724,3644,4788,4434,6725,6726,4789,2772,6727,6728, # 5504
6729,6730,6731,2708,3865,2813,4435,6732,6733,4790,4791,3480,6734,6735,6736,6737, # 5520
4436,3348,6738,3410,4007,6739,6740,4008,6741,6742,4792,3411,4191,6743,6744,6745, # 5536
6746,6747,3866,6748,3750,6749,6750,6751,6752,6753,6754,6755,3867,6756,4009,6757, # 5552
4793,4794,6758,2814,2987,6759,6760,6761,4437,6762,6763,6764,6765,3645,6766,6767, # 5568
3481,4192,6768,3751,6769,6770,2174,6771,3868,3752,6772,6773,6774,4193,4795,4438, # 5584
3558,4796,4439,6775,4797,6776,6777,4798,6778,4799,3559,4800,6779,6780,6781,3482, # 5600
6782,2893,6783,6784,4194,4801,4010,6785,6786,4440,6787,4011,6788,6789,6790,6791, # 5616
6792,6793,4802,6794,6795,6796,4012,6797,6798,6799,6800,3349,4803,3483,6801,4804, # 5632
4195,6802,4013,6803,6804,4196,6805,4014,4015,6806,2847,3271,2848,6807,3484,6808, # 5648
6809,6810,4441,6811,4442,4197,4443,3272,4805,6812,3412,4016,1579,6813,6814,4017, # 5664
6815,3869,6816,2964,6817,4806,6818,6819,4018,3646,6820,6821,4807,4019,4020,6822, # 5680
6823,3560,6824,6825,4021,4444,6826,4198,6827,6828,4445,6829,6830,4199,4808,6831, # 5696
6832,6833,3870,3019,2458,6834,3753,3413,3350,6835,4809,3871,4810,3561,4446,6836, # 5712
6837,4447,4811,4812,6838,2459,4448,6839,4449,6840,6841,4022,3872,6842,4813,4814, # 5728
6843,6844,4815,4200,4201,4202,6845,4023,6846,6847,4450,3562,3873,6848,6849,4816, # 5744
4817,6850,4451,4818,2139,6851,3563,6852,6853,3351,6854,6855,3352,4024,2709,3414, # 5760
4203,4452,6856,4204,6857,6858,3874,3875,6859,6860,4819,6861,6862,6863,6864,4453, # 5776
3647,6865,6866,4820,6867,6868,6869,6870,4454,6871,2869,6872,6873,4821,6874,3754, # 5792
6875,4822,4205,6876,6877,6878,3648,4206,4455,6879,4823,6880,4824,3876,6881,3055, # 5808
4207,6882,3415,6883,6884,6885,4208,4209,6886,4210,3353,6887,3354,3564,3209,3485, # 5824
2652,6888,2728,6889,3210,3755,6890,4025,4456,6891,4825,6892,6893,6894,6895,4211, # 5840
6896,6897,6898,4826,6899,6900,4212,6901,4827,6902,2773,3565,6903,4828,6904,6905, # 5856
6906,6907,3649,3650,6908,2849,3566,6909,3567,3100,6910,6911,6912,6913,6914,6915, # 5872
4026,6916,3355,4829,3056,4457,3756,6917,3651,6918,4213,3652,2870,6919,4458,6920, # 5888
2438,6921,6922,3757,2774,4830,6923,3356,4831,4832,6924,4833,4459,3653,2507,6925, # 5904
4834,2535,6926,6927,3273,4027,3147,6928,3568,6929,6930,6931,4460,6932,3877,4461, # 5920
2729,3654,6933,6934,6935,6936,2175,4835,2630,4214,4028,4462,4836,4215,6937,3148, # 5936
4216,4463,4837,4838,4217,6938,6939,2850,4839,6940,4464,6941,6942,6943,4840,6944, # 5952
4218,3274,4465,6945,6946,2710,6947,4841,4466,6948,6949,2894,6950,6951,4842,6952, # 5968
4219,3057,2871,6953,6954,6955,6956,4467,6957,2711,6958,6959,6960,3275,3101,4843, # 5984
6961,3357,3569,6962,4844,6963,6964,4468,4845,3570,6965,3102,4846,3758,6966,4847, # 6000
3878,4848,4849,4029,6967,2929,3879,4850,4851,6968,6969,1733,6970,4220,6971,6972, # 6016
6973,6974,6975,6976,4852,6977,6978,6979,6980,6981,6982,3759,6983,6984,6985,3486, # 6032
3487,6986,3488,3416,6987,6988,6989,6990,6991,6992,6993,6994,6995,6996,6997,4853, # 6048
6998,6999,4030,7000,7001,3211,7002,7003,4221,7004,7005,3571,4031,7006,3572,7007, # 6064
2614,4854,2577,7008,7009,2965,3655,3656,4855,2775,3489,3880,4222,4856,3881,4032, # 6080
3882,3657,2730,3490,4857,7010,3149,7011,4469,4858,2496,3491,4859,2283,7012,7013, # 6096
7014,2365,4860,4470,7015,7016,3760,7017,7018,4223,1917,7019,7020,7021,4471,7022, # 6112
2776,4472,7023,7024,7025,7026,4033,7027,3573,4224,4861,4034,4862,7028,7029,1929, # 6128
3883,4035,7030,4473,3058,7031,2536,3761,3884,7032,4036,7033,2966,2895,1968,4474, # 6144
3276,4225,3417,3492,4226,2105,7034,7035,1754,2596,3762,4227,4863,4475,3763,4864, # 6160
3764,2615,2777,3103,3765,3658,3418,4865,2296,3766,2815,7036,7037,7038,3574,2872, # 6176
3277,4476,7039,4037,4477,7040,7041,4038,7042,7043,7044,7045,7046,7047,2537,7048, # 6192
7049,7050,7051,7052,7053,7054,4478,7055,7056,3767,3659,4228,3575,7057,7058,4229, # 6208
7059,7060,7061,3660,7062,3212,7063,3885,4039,2460,7064,7065,7066,7067,7068,7069, # 6224
7070,7071,7072,7073,7074,4866,3768,4867,7075,7076,7077,7078,4868,3358,3278,2653, # 6240
7079,7080,4479,3886,7081,7082,4869,7083,7084,7085,7086,7087,7088,2538,7089,7090, # 6256
7091,4040,3150,3769,4870,4041,2896,3359,4230,2930,7092,3279,7093,2967,4480,3213, # 6272
4481,3661,7094,7095,7096,7097,7098,7099,7100,7101,7102,2461,3770,7103,7104,4231, # 6288
3151,7105,7106,7107,4042,3662,7108,7109,4871,3663,4872,4043,3059,7110,7111,7112, # 6304
3493,2988,7113,4873,7114,7115,7116,3771,4874,7117,7118,4232,4875,7119,3576,2336, # 6320
4876,7120,4233,3419,4044,4877,4878,4482,4483,4879,4484,4234,7121,3772,4880,1045, # 6336
3280,3664,4881,4882,7122,7123,7124,7125,4883,7126,2778,7127,4485,4486,7128,4884, # 6352
3214,3887,7129,7130,3215,7131,4885,4045,7132,7133,4046,7134,7135,7136,7137,7138, # 6368
7139,7140,7141,7142,7143,4235,7144,4886,7145,7146,7147,4887,7148,7149,7150,4487, # 6384
4047,4488,7151,7152,4888,4048,2989,3888,7153,3665,7154,4049,7155,7156,7157,7158, # 6400
7159,7160,2931,4889,4890,4489,7161,2631,3889,4236,2779,7162,7163,4891,7164,3060, # 6416
7165,1672,4892,7166,4893,4237,3281,4894,7167,7168,3666,7169,3494,7170,7171,4050, # 6432
7172,7173,3104,3360,3420,4490,4051,2684,4052,7174,4053,7175,7176,7177,2253,4054, # 6448
7178,7179,4895,7180,3152,3890,3153,4491,3216,7181,7182,7183,2968,4238,4492,4055, # 6464
7184,2990,7185,2479,7186,7187,4493,7188,7189,7190,7191,7192,4896,7193,4897,2969, # 6480
4494,4898,7194,3495,7195,7196,4899,4495,7197,3105,2731,7198,4900,7199,7200,7201, # 6496
4056,7202,3361,7203,7204,4496,4901,4902,7205,4497,7206,7207,2315,4903,7208,4904, # 6512
7209,4905,2851,7210,7211,3577,7212,3578,4906,7213,4057,3667,4907,7214,4058,2354, # 6528
3891,2376,3217,3773,7215,7216,7217,7218,7219,4498,7220,4908,3282,2685,7221,3496, # 6544
4909,2632,3154,4910,7222,2337,7223,4911,7224,7225,7226,4912,4913,3283,4239,4499, # 6560
7227,2816,7228,7229,7230,7231,7232,7233,7234,4914,4500,4501,7235,7236,7237,2686, # 6576
7238,4915,7239,2897,4502,7240,4503,7241,2516,7242,4504,3362,3218,7243,7244,7245, # 6592
4916,7246,7247,4505,3363,7248,7249,7250,7251,3774,4506,7252,7253,4917,7254,7255, # 6608
3284,2991,4918,4919,3219,3892,4920,3106,3497,4921,7256,7257,7258,4922,7259,4923, # 6624
3364,4507,4508,4059,7260,4240,3498,7261,7262,4924,7263,2992,3893,4060,3220,7264, # 6640
7265,7266,7267,7268,7269,4509,3775,7270,2817,7271,4061,4925,4510,3776,7272,4241, # 6656
4511,3285,7273,7274,3499,7275,7276,7277,4062,4512,4926,7278,3107,3894,7279,7280, # 6672
4927,7281,4513,7282,7283,3668,7284,7285,4242,4514,4243,7286,2058,4515,4928,4929, # 6688
4516,7287,3286,4244,7288,4517,7289,7290,7291,3669,7292,7293,4930,4931,4932,2355, # 6704
4933,7294,2633,4518,7295,4245,7296,7297,4519,7298,7299,4520,4521,4934,7300,4246, # 6720
4522,7301,7302,7303,3579,7304,4247,4935,7305,4936,7306,7307,7308,7309,3777,7310, # 6736
4523,7311,7312,7313,4248,3580,7314,4524,3778,4249,7315,3581,7316,3287,7317,3221, # 6752
7318,4937,7319,7320,7321,7322,7323,7324,4938,4939,7325,4525,7326,7327,7328,4063, # 6768
7329,7330,4940,7331,7332,4941,7333,4526,7334,3500,2780,1741,4942,2026,1742,7335, # 6784
7336,3582,4527,2388,7337,7338,7339,4528,7340,4250,4943,7341,7342,7343,4944,7344, # 6800
7345,7346,3020,7347,4945,7348,7349,7350,7351,3895,7352,3896,4064,3897,7353,7354, # 6816
7355,4251,7356,7357,3898,7358,3779,7359,3780,3288,7360,7361,4529,7362,4946,4530, # 6832
2027,7363,3899,4531,4947,3222,3583,7364,4948,7365,7366,7367,7368,4949,3501,4950, # 6848
3781,4951,4532,7369,2517,4952,4252,4953,3155,7370,4954,4955,4253,2518,4533,7371, # 6864
7372,2712,4254,7373,7374,7375,3670,4956,3671,7376,2389,3502,4065,7377,2338,7378, # 6880
7379,7380,7381,3061,7382,4957,7383,7384,7385,7386,4958,4534,7387,7388,2993,7389, # 6896
3062,7390,4959,7391,7392,7393,4960,3108,4961,7394,4535,7395,4962,3421,4536,7396, # 6912
4963,7397,4964,1857,7398,4965,7399,7400,2176,3584,4966,7401,7402,3422,4537,3900, # 6928
3585,7403,3782,7404,2852,7405,7406,7407,4538,3783,2654,3423,4967,4539,7408,3784, # 6944
3586,2853,4540,4541,7409,3901,7410,3902,7411,7412,3785,3109,2327,3903,7413,7414, # 6960
2970,4066,2932,7415,7416,7417,3904,3672,3424,7418,4542,4543,4544,7419,4968,7420, # 6976
7421,4255,7422,7423,7424,7425,7426,4067,7427,3673,3365,4545,7428,3110,2559,3674, # 6992
7429,7430,3156,7431,7432,3503,7433,3425,4546,7434,3063,2873,7435,3223,4969,4547, # 7008
4548,2898,4256,4068,7436,4069,3587,3786,2933,3787,4257,4970,4971,3788,7437,4972, # 7024
3064,7438,4549,7439,7440,7441,7442,7443,4973,3905,7444,2874,7445,7446,7447,7448, # 7040
3021,7449,4550,3906,3588,4974,7450,7451,3789,3675,7452,2578,7453,4070,7454,7455, # 7056
7456,4258,3676,7457,4975,7458,4976,4259,3790,3504,2634,4977,3677,4551,4260,7459, # 7072
7460,7461,7462,3907,4261,4978,7463,7464,7465,7466,4979,4980,7467,7468,2213,4262, # 7088
7469,7470,7471,3678,4981,7472,2439,7473,4263,3224,3289,7474,3908,2415,4982,7475, # 7104
4264,7476,4983,2655,7477,7478,2732,4552,2854,2875,7479,7480,4265,7481,4553,4984, # 7120
7482,7483,4266,7484,3679,3366,3680,2818,2781,2782,3367,3589,4554,3065,7485,4071, # 7136
2899,7486,7487,3157,2462,4072,4555,4073,4985,4986,3111,4267,2687,3368,4556,4074, # 7152
3791,4268,7488,3909,2783,7489,2656,1962,3158,4557,4987,1963,3159,3160,7490,3112, # 7168
4988,4989,3022,4990,4991,3792,2855,7491,7492,2971,4558,7493,7494,4992,7495,7496, # 7184
7497,7498,4993,7499,3426,4559,4994,7500,3681,4560,4269,4270,3910,7501,4075,4995, # 7200
4271,7502,7503,4076,7504,4996,7505,3225,4997,4272,4077,2819,3023,7506,7507,2733, # 7216
4561,7508,4562,7509,3369,3793,7510,3590,2508,7511,7512,4273,3113,2994,2616,7513, # 7232
7514,7515,7516,7517,7518,2820,3911,4078,2748,7519,7520,4563,4998,7521,7522,7523, # 7248
7524,4999,4274,7525,4564,3682,2239,4079,4565,7526,7527,7528,7529,5000,7530,7531, # 7264
5001,4275,3794,7532,7533,7534,3066,5002,4566,3161,7535,7536,4080,7537,3162,7538, # 7280
7539,4567,7540,7541,7542,7543,7544,7545,5003,7546,4568,7547,7548,7549,7550,7551, # 7296
7552,7553,7554,7555,7556,5004,7557,7558,7559,5005,7560,3795,7561,4569,7562,7563, # 7312
7564,2821,3796,4276,4277,4081,7565,2876,7566,5006,7567,7568,2900,7569,3797,3912, # 7328
7570,7571,7572,4278,7573,7574,7575,5007,7576,7577,5008,7578,7579,4279,2934,7580, # 7344
7581,5009,7582,4570,7583,4280,7584,7585,7586,4571,4572,3913,7587,4573,3505,7588, # 7360
5010,7589,7590,7591,7592,3798,4574,7593,7594,5011,7595,4281,7596,7597,7598,4282, # 7376
5012,7599,7600,5013,3163,7601,5014,7602,3914,7603,7604,2734,4575,4576,4577,7605, # 7392
7606,7607,7608,7609,3506,5015,4578,7610,4082,7611,2822,2901,2579,3683,3024,4579, # 7408
3507,7612,4580,7613,3226,3799,5016,7614,7615,7616,7617,7618,7619,7620,2995,3290, # 7424
7621,4083,7622,5017,7623,7624,7625,7626,7627,4581,3915,7628,3291,7629,5018,7630, # 7440
7631,7632,7633,4084,7634,7635,3427,3800,7636,7637,4582,7638,5019,4583,5020,7639, # 7456
3916,7640,3801,5021,4584,4283,7641,7642,3428,3591,2269,7643,2617,7644,4585,3592, # 7472
7645,4586,2902,7646,7647,3227,5022,7648,4587,7649,4284,7650,7651,7652,4588,2284, # 7488
7653,5023,7654,7655,7656,4589,5024,3802,7657,7658,5025,3508,4590,7659,7660,7661, # 7504
1969,5026,7662,7663,3684,1821,2688,7664,2028,2509,4285,7665,2823,1841,7666,2689, # 7520
3114,7667,3917,4085,2160,5027,5028,2972,7668,5029,7669,7670,7671,3593,4086,7672, # 7536
4591,4087,5030,3803,7673,7674,7675,7676,7677,7678,7679,4286,2366,4592,4593,3067, # 7552
2328,7680,7681,4594,3594,3918,2029,4287,7682,5031,3919,3370,4288,4595,2856,7683, # 7568
3509,7684,7685,5032,5033,7686,7687,3804,2784,7688,7689,7690,7691,3371,7692,7693, # 7584
2877,5034,7694,7695,3920,4289,4088,7696,7697,7698,5035,7699,5036,4290,5037,5038, # 7600
5039,7700,7701,7702,5040,5041,3228,7703,1760,7704,5042,3229,4596,2106,4089,7705, # 7616
4597,2824,5043,2107,3372,7706,4291,4090,5044,7707,4091,7708,5045,3025,3805,4598, # 7632
4292,4293,4294,3373,7709,4599,7710,5046,7711,7712,5047,5048,3806,7713,7714,7715, # 7648
5049,7716,7717,7718,7719,4600,5050,7720,7721,7722,5051,7723,4295,3429,7724,7725, # 7664
7726,7727,3921,7728,3292,5052,4092,7729,7730,7731,7732,7733,7734,7735,5053,5054, # 7680
7736,7737,7738,7739,3922,3685,7740,7741,7742,7743,2635,5055,7744,5056,4601,7745, # 7696
7746,2560,7747,7748,7749,7750,3923,7751,7752,7753,7754,7755,4296,2903,7756,7757, # 7712
7758,7759,7760,3924,7761,5057,4297,7762,7763,5058,4298,7764,4093,7765,7766,5059, # 7728
3925,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,3595,7777,4299,5060,4094, # 7744
7778,3293,5061,7779,7780,4300,7781,7782,4602,7783,3596,7784,7785,3430,2367,7786, # 7760
3164,5062,5063,4301,7787,7788,4095,5064,5065,7789,3374,3115,7790,7791,7792,7793, # 7776
7794,7795,7796,3597,4603,7797,7798,3686,3116,3807,5066,7799,7800,5067,7801,7802, # 7792
4604,4302,5068,4303,4096,7803,7804,3294,7805,7806,5069,4605,2690,7807,3026,7808, # 7808
7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824, # 7824
7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7840
7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,7856, # 7856
7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,7872, # 7872
7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,7888, # 7888
7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,7904, # 7904
7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920, # 7920
7921,7922,7923,7924,3926,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, # 7936
7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, # 7952
7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, # 7968
7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, # 7984
7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, # 8000
8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, # 8016
8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, # 8032
8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, # 8048
8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, # 8064
8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, # 8080
8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, # 8096
8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, # 8112
8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, # 8128
8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, # 8144
8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, # 8160
8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, # 8176
8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, # 8192
8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, # 8208
8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, # 8224
8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, # 8240
8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, # 8256
8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271) # 8272
# flake8: noqa
| mit |
analogdevicesinc/gnuradio | gr-blocks/python/blocks/qa_udp_source_sink.py | 40 | 3667 | #!/usr/bin/env python
#
# Copyright 2008,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr, gr_unittest, blocks
import os
from threading import Timer
class test_udp_sink_source(gr_unittest.TestCase):
def setUp(self):
os.environ['GR_CONF_CONTROLPORT_ON'] = 'False'
self.tb_snd = gr.top_block()
self.tb_rcv = gr.top_block()
def tearDown(self):
self.tb_rcv = None
self.tb_snd = None
def test_001(self):
# Tests calling disconnect/reconnect.
port = 65510
n_data = 16
src_data = [x for x in range(n_data)]
expected_result = tuple(src_data)
src = blocks.vector_source_s(src_data, False)
udp_snd = blocks.udp_sink(gr.sizeof_short, 'localhost', port)
self.tb_snd.connect(src, udp_snd)
self.tb_snd.run()
udp_snd.disconnect()
udp_snd.connect('localhost', port+1)
src.rewind()
self.tb_snd.run()
def test_002(self):
port = 65520
n_data = 100
src_data = [float(x) for x in range(n_data)]
expected_result = tuple(src_data)
src = blocks.vector_source_f(src_data, False)
udp_snd = blocks.udp_sink(gr.sizeof_float, 'localhost', port)
self.tb_snd.connect(src, udp_snd)
udp_rcv = blocks.udp_source(gr.sizeof_float, 'localhost', port)
dst = blocks.vector_sink_f()
self.tb_rcv.connect(udp_rcv, dst)
self.tb_rcv.start()
self.tb_snd.run()
udp_snd.disconnect()
self.timeout = False
q = Timer(2.0,self.stop_rcv)
q.start()
self.tb_rcv.wait()
q.cancel()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
self.assert_(not self.timeout)
def test_003(self):
port = 65530
udp_rcv = blocks.udp_source(gr.sizeof_float, '0.0.0.0', 0, eof=False)
rcv_port = udp_rcv.get_port()
udp_snd = blocks.udp_sink(gr.sizeof_float, '127.0.0.1', port)
udp_snd.connect('127.0.0.1', rcv_port)
n_data = 16
src_data = [float(x) for x in range(n_data)]
expected_result = tuple(src_data)
src = blocks.vector_source_f(src_data)
dst = blocks.vector_sink_f()
self.tb_snd.connect(src, udp_snd)
self.tb_rcv.connect(udp_rcv, dst)
self.tb_rcv.start()
self.tb_snd.run()
udp_snd.disconnect()
self.timeout = False
q = Timer(2.0,self.stop_rcv)
q.start()
self.tb_rcv.wait()
q.cancel()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
self.assert_(self.timeout) # source ignores EOF?
def stop_rcv(self):
self.timeout = True
self.tb_rcv.stop()
#print "tb_rcv stopped by Timer"
if __name__ == '__main__':
gr_unittest.run(test_udp_sink_source, "test_udp_sink_source.xml")
| gpl-3.0 |
kschultz1986/robots_for_all | src/navigation/amcl/test/basic_localization.py | 7 | 3176 | #!/usr/bin/env python
import sys
import time
from math import fmod, pi
import unittest
import rospy
import rostest
from tf.msg import tfMessage
from tf.transformations import euler_from_quaternion
from std_srvs.srv import Empty
class TestBasicLocalization(unittest.TestCase):
def setUp(self):
self.tf = None
self.target_x = None
self.target_y = None
self.target_a = None
def tf_cb(self, msg):
for t in msg.transforms:
if t.header.frame_id == 'map':
self.tf = t.transform
(a_curr, a_diff) = self.compute_angle_diff()
print 'Curr:\t %16.6f %16.6f %16.6f' % (self.tf.translation.x, self.tf.translation.y, a_curr)
print 'Target:\t %16.6f %16.6f %16.6f' % (self.target_x, self.target_y, self.target_a)
print 'Diff:\t %16.6f %16.6f %16.6f' % (
abs(self.tf.translation.x - self.target_x), abs(self.tf.translation.y - self.target_y), a_diff)
def compute_angle_diff(self):
rot = self.tf.rotation
a = euler_from_quaternion([rot.x, rot.y, rot.z, rot.w])[2]
d_a = self.target_a
return (a, abs(fmod(a - d_a + 5*pi, 2*pi) - pi))
def test_basic_localization(self):
global_localization = int(sys.argv[1])
self.target_x = float(sys.argv[2])
self.target_y = float(sys.argv[3])
self.target_a = float(sys.argv[4])
tolerance_d = float(sys.argv[5])
tolerance_a = float(sys.argv[6])
target_time = float(sys.argv[7])
if global_localization == 1:
#print 'Waiting for service global_localization'
rospy.wait_for_service('global_localization')
global_localization = rospy.ServiceProxy('global_localization', Empty)
global_localization()
rospy.init_node('test', anonymous=True)
while(rospy.rostime.get_time() == 0.0):
#print 'Waiting for initial time publication'
time.sleep(0.1)
start_time = rospy.rostime.get_time()
# TODO: This should be replace by a pytf listener
rospy.Subscriber('/tf', tfMessage, self.tf_cb)
while (rospy.rostime.get_time() - start_time) < target_time:
#print 'Waiting for end time %.6f (current: %.6f)'%(target_time,(rospy.rostime.get_time() - start_time))
time.sleep(0.1)
(a_curr, a_diff) = self.compute_angle_diff()
print 'Curr:\t %16.6f %16.6f %16.6f' % (self.tf.translation.x, self.tf.translation.y, a_curr)
print 'Target:\t %16.6f %16.6f %16.6f' % (self.target_x, self.target_y, self.target_a)
print 'Diff:\t %16.6f %16.6f %16.6f' % (
abs(self.tf.translation.x - self.target_x), abs(self.tf.translation.y - self.target_y), a_diff)
self.assertNotEquals(self.tf, None)
self.assertTrue(abs(self.tf.translation.x - self.target_x) <= tolerance_d)
self.assertTrue(abs(self.tf.translation.y - self.target_y) <= tolerance_d)
self.assertTrue(a_diff <= tolerance_a)
if __name__ == '__main__':
rostest.run('amcl', 'amcl_localization',
TestBasicLocalization, sys.argv)
| gpl-3.0 |
poldracklab/mriqc | mriqc/bin/labeler.py | 1 | 2466 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
# @Author: dbirman
# @Date: 2017-06-14 16:51:24
import sys
import csv
import random
import webbrowser
import os
import numpy as np
# other functions
def num_rows(data):
for j in range(1, 4):
if len(data[j]) == 0:
return j
return 4
def main():
"""read the input file"""
print("Reading file sinfo.csv")
csvfile = open("sinfo.csv", "rb")
csvreader = csv.reader(csvfile)
file = list(csvreader)
# display statistics
finished = [0.0, 0.0, 0.0]
hold = np.zeros((3, len(file) - 1))
hold[:] = np.nan
total = 601
for i in range(1, len(file)):
for j in range(1, 4):
if len(file[i][j]) > 0:
finished[j - 1] = finished[j - 1] + 1
hold[j - 1, i - 1] = int(file[i][j])
finished = np.divide(np.round(np.divide(finished, total) * 1000), 10)
print(f"Completed: {' '.join(['%g%%' % f for f in finished])}")
print(f"Total: {np.round(np.divide(np.sum(finished), 3))}%")
input("Waiting: [enter]")
# file[1:] are all the rows
order = range(1, len(file))
random.shuffle(order)
# pick a random row
for row in order:
# check how many entires it has
curEnt = num_rows(file[row])
if curEnt <= 1:
# if less than 1, run the row
print("Check participant #" + file[row][0])
fname = os.getcwd() + "/abide/" + file[row][0]
if os.path.isfile(fname):
webbrowser.open("file://" + fname)
quality = input("Quality? [-1/0/1/e/c] ")
if quality == "e":
break
if quality == "c":
print("Current comment: " + file[row][4])
comment = input("Comment: ")
if len(comment) > 0:
file[row][4] = comment
quality = input("Quality? [-1/0/1/e] ")
if quality == "e":
break
file[row][curEnt] = quality
else:
print("File does not exist")
print("Writing file sinfo.csv")
outfile = open("sinfo.csv", "wb")
csvwriter = csv.writer(outfile)
csvwriter.writerows(file)
print("Ending")
if __name__ == "__main__":
main()
sys.exit(0)
| bsd-3-clause |
goodwinnk/intellij-community | python/lib/Lib/encodings/cp1026.py | 593 | 13369 | """ Python Character Mapping Codec cp1026 generated from 'MAPPINGS/VENDORS/MICSFT/EBCDIC/CP1026.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp1026',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x9c' # 0x04 -> CONTROL
u'\t' # 0x05 -> HORIZONTAL TABULATION
u'\x86' # 0x06 -> CONTROL
u'\x7f' # 0x07 -> DELETE
u'\x97' # 0x08 -> CONTROL
u'\x8d' # 0x09 -> CONTROL
u'\x8e' # 0x0A -> CONTROL
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x9d' # 0x14 -> CONTROL
u'\x85' # 0x15 -> CONTROL
u'\x08' # 0x16 -> BACKSPACE
u'\x87' # 0x17 -> CONTROL
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x92' # 0x1A -> CONTROL
u'\x8f' # 0x1B -> CONTROL
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u'\x80' # 0x20 -> CONTROL
u'\x81' # 0x21 -> CONTROL
u'\x82' # 0x22 -> CONTROL
u'\x83' # 0x23 -> CONTROL
u'\x84' # 0x24 -> CONTROL
u'\n' # 0x25 -> LINE FEED
u'\x17' # 0x26 -> END OF TRANSMISSION BLOCK
u'\x1b' # 0x27 -> ESCAPE
u'\x88' # 0x28 -> CONTROL
u'\x89' # 0x29 -> CONTROL
u'\x8a' # 0x2A -> CONTROL
u'\x8b' # 0x2B -> CONTROL
u'\x8c' # 0x2C -> CONTROL
u'\x05' # 0x2D -> ENQUIRY
u'\x06' # 0x2E -> ACKNOWLEDGE
u'\x07' # 0x2F -> BELL
u'\x90' # 0x30 -> CONTROL
u'\x91' # 0x31 -> CONTROL
u'\x16' # 0x32 -> SYNCHRONOUS IDLE
u'\x93' # 0x33 -> CONTROL
u'\x94' # 0x34 -> CONTROL
u'\x95' # 0x35 -> CONTROL
u'\x96' # 0x36 -> CONTROL
u'\x04' # 0x37 -> END OF TRANSMISSION
u'\x98' # 0x38 -> CONTROL
u'\x99' # 0x39 -> CONTROL
u'\x9a' # 0x3A -> CONTROL
u'\x9b' # 0x3B -> CONTROL
u'\x14' # 0x3C -> DEVICE CONTROL FOUR
u'\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE
u'\x9e' # 0x3E -> CONTROL
u'\x1a' # 0x3F -> SUBSTITUTE
u' ' # 0x40 -> SPACE
u'\xa0' # 0x41 -> NO-BREAK SPACE
u'\xe2' # 0x42 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x43 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x44 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe1' # 0x45 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe3' # 0x46 -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x47 -> LATIN SMALL LETTER A WITH RING ABOVE
u'{' # 0x48 -> LEFT CURLY BRACKET
u'\xf1' # 0x49 -> LATIN SMALL LETTER N WITH TILDE
u'\xc7' # 0x4A -> LATIN CAPITAL LETTER C WITH CEDILLA
u'.' # 0x4B -> FULL STOP
u'<' # 0x4C -> LESS-THAN SIGN
u'(' # 0x4D -> LEFT PARENTHESIS
u'+' # 0x4E -> PLUS SIGN
u'!' # 0x4F -> EXCLAMATION MARK
u'&' # 0x50 -> AMPERSAND
u'\xe9' # 0x51 -> LATIN SMALL LETTER E WITH ACUTE
u'\xea' # 0x52 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x53 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x54 -> LATIN SMALL LETTER E WITH GRAVE
u'\xed' # 0x55 -> LATIN SMALL LETTER I WITH ACUTE
u'\xee' # 0x56 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x57 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xec' # 0x58 -> LATIN SMALL LETTER I WITH GRAVE
u'\xdf' # 0x59 -> LATIN SMALL LETTER SHARP S (GERMAN)
u'\u011e' # 0x5A -> LATIN CAPITAL LETTER G WITH BREVE
u'\u0130' # 0x5B -> LATIN CAPITAL LETTER I WITH DOT ABOVE
u'*' # 0x5C -> ASTERISK
u')' # 0x5D -> RIGHT PARENTHESIS
u';' # 0x5E -> SEMICOLON
u'^' # 0x5F -> CIRCUMFLEX ACCENT
u'-' # 0x60 -> HYPHEN-MINUS
u'/' # 0x61 -> SOLIDUS
u'\xc2' # 0x62 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xc4' # 0x63 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc0' # 0x64 -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc1' # 0x65 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xc3' # 0x66 -> LATIN CAPITAL LETTER A WITH TILDE
u'\xc5' # 0x67 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'[' # 0x68 -> LEFT SQUARE BRACKET
u'\xd1' # 0x69 -> LATIN CAPITAL LETTER N WITH TILDE
u'\u015f' # 0x6A -> LATIN SMALL LETTER S WITH CEDILLA
u',' # 0x6B -> COMMA
u'%' # 0x6C -> PERCENT SIGN
u'_' # 0x6D -> LOW LINE
u'>' # 0x6E -> GREATER-THAN SIGN
u'?' # 0x6F -> QUESTION MARK
u'\xf8' # 0x70 -> LATIN SMALL LETTER O WITH STROKE
u'\xc9' # 0x71 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xca' # 0x72 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xcb' # 0x73 -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xc8' # 0x74 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0x75 -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0x76 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0x77 -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0x78 -> LATIN CAPITAL LETTER I WITH GRAVE
u'\u0131' # 0x79 -> LATIN SMALL LETTER DOTLESS I
u':' # 0x7A -> COLON
u'\xd6' # 0x7B -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\u015e' # 0x7C -> LATIN CAPITAL LETTER S WITH CEDILLA
u"'" # 0x7D -> APOSTROPHE
u'=' # 0x7E -> EQUALS SIGN
u'\xdc' # 0x7F -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xd8' # 0x80 -> LATIN CAPITAL LETTER O WITH STROKE
u'a' # 0x81 -> LATIN SMALL LETTER A
u'b' # 0x82 -> LATIN SMALL LETTER B
u'c' # 0x83 -> LATIN SMALL LETTER C
u'd' # 0x84 -> LATIN SMALL LETTER D
u'e' # 0x85 -> LATIN SMALL LETTER E
u'f' # 0x86 -> LATIN SMALL LETTER F
u'g' # 0x87 -> LATIN SMALL LETTER G
u'h' # 0x88 -> LATIN SMALL LETTER H
u'i' # 0x89 -> LATIN SMALL LETTER I
u'\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'}' # 0x8C -> RIGHT CURLY BRACKET
u'`' # 0x8D -> GRAVE ACCENT
u'\xa6' # 0x8E -> BROKEN BAR
u'\xb1' # 0x8F -> PLUS-MINUS SIGN
u'\xb0' # 0x90 -> DEGREE SIGN
u'j' # 0x91 -> LATIN SMALL LETTER J
u'k' # 0x92 -> LATIN SMALL LETTER K
u'l' # 0x93 -> LATIN SMALL LETTER L
u'm' # 0x94 -> LATIN SMALL LETTER M
u'n' # 0x95 -> LATIN SMALL LETTER N
u'o' # 0x96 -> LATIN SMALL LETTER O
u'p' # 0x97 -> LATIN SMALL LETTER P
u'q' # 0x98 -> LATIN SMALL LETTER Q
u'r' # 0x99 -> LATIN SMALL LETTER R
u'\xaa' # 0x9A -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x9B -> MASCULINE ORDINAL INDICATOR
u'\xe6' # 0x9C -> LATIN SMALL LIGATURE AE
u'\xb8' # 0x9D -> CEDILLA
u'\xc6' # 0x9E -> LATIN CAPITAL LIGATURE AE
u'\xa4' # 0x9F -> CURRENCY SIGN
u'\xb5' # 0xA0 -> MICRO SIGN
u'\xf6' # 0xA1 -> LATIN SMALL LETTER O WITH DIAERESIS
u's' # 0xA2 -> LATIN SMALL LETTER S
u't' # 0xA3 -> LATIN SMALL LETTER T
u'u' # 0xA4 -> LATIN SMALL LETTER U
u'v' # 0xA5 -> LATIN SMALL LETTER V
u'w' # 0xA6 -> LATIN SMALL LETTER W
u'x' # 0xA7 -> LATIN SMALL LETTER X
u'y' # 0xA8 -> LATIN SMALL LETTER Y
u'z' # 0xA9 -> LATIN SMALL LETTER Z
u'\xa1' # 0xAA -> INVERTED EXCLAMATION MARK
u'\xbf' # 0xAB -> INVERTED QUESTION MARK
u']' # 0xAC -> RIGHT SQUARE BRACKET
u'$' # 0xAD -> DOLLAR SIGN
u'@' # 0xAE -> COMMERCIAL AT
u'\xae' # 0xAF -> REGISTERED SIGN
u'\xa2' # 0xB0 -> CENT SIGN
u'\xa3' # 0xB1 -> POUND SIGN
u'\xa5' # 0xB2 -> YEN SIGN
u'\xb7' # 0xB3 -> MIDDLE DOT
u'\xa9' # 0xB4 -> COPYRIGHT SIGN
u'\xa7' # 0xB5 -> SECTION SIGN
u'\xb6' # 0xB6 -> PILCROW SIGN
u'\xbc' # 0xB7 -> VULGAR FRACTION ONE QUARTER
u'\xbd' # 0xB8 -> VULGAR FRACTION ONE HALF
u'\xbe' # 0xB9 -> VULGAR FRACTION THREE QUARTERS
u'\xac' # 0xBA -> NOT SIGN
u'|' # 0xBB -> VERTICAL LINE
u'\xaf' # 0xBC -> MACRON
u'\xa8' # 0xBD -> DIAERESIS
u'\xb4' # 0xBE -> ACUTE ACCENT
u'\xd7' # 0xBF -> MULTIPLICATION SIGN
u'\xe7' # 0xC0 -> LATIN SMALL LETTER C WITH CEDILLA
u'A' # 0xC1 -> LATIN CAPITAL LETTER A
u'B' # 0xC2 -> LATIN CAPITAL LETTER B
u'C' # 0xC3 -> LATIN CAPITAL LETTER C
u'D' # 0xC4 -> LATIN CAPITAL LETTER D
u'E' # 0xC5 -> LATIN CAPITAL LETTER E
u'F' # 0xC6 -> LATIN CAPITAL LETTER F
u'G' # 0xC7 -> LATIN CAPITAL LETTER G
u'H' # 0xC8 -> LATIN CAPITAL LETTER H
u'I' # 0xC9 -> LATIN CAPITAL LETTER I
u'\xad' # 0xCA -> SOFT HYPHEN
u'\xf4' # 0xCB -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'~' # 0xCC -> TILDE
u'\xf2' # 0xCD -> LATIN SMALL LETTER O WITH GRAVE
u'\xf3' # 0xCE -> LATIN SMALL LETTER O WITH ACUTE
u'\xf5' # 0xCF -> LATIN SMALL LETTER O WITH TILDE
u'\u011f' # 0xD0 -> LATIN SMALL LETTER G WITH BREVE
u'J' # 0xD1 -> LATIN CAPITAL LETTER J
u'K' # 0xD2 -> LATIN CAPITAL LETTER K
u'L' # 0xD3 -> LATIN CAPITAL LETTER L
u'M' # 0xD4 -> LATIN CAPITAL LETTER M
u'N' # 0xD5 -> LATIN CAPITAL LETTER N
u'O' # 0xD6 -> LATIN CAPITAL LETTER O
u'P' # 0xD7 -> LATIN CAPITAL LETTER P
u'Q' # 0xD8 -> LATIN CAPITAL LETTER Q
u'R' # 0xD9 -> LATIN CAPITAL LETTER R
u'\xb9' # 0xDA -> SUPERSCRIPT ONE
u'\xfb' # 0xDB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\\' # 0xDC -> REVERSE SOLIDUS
u'\xf9' # 0xDD -> LATIN SMALL LETTER U WITH GRAVE
u'\xfa' # 0xDE -> LATIN SMALL LETTER U WITH ACUTE
u'\xff' # 0xDF -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\xfc' # 0xE0 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xf7' # 0xE1 -> DIVISION SIGN
u'S' # 0xE2 -> LATIN CAPITAL LETTER S
u'T' # 0xE3 -> LATIN CAPITAL LETTER T
u'U' # 0xE4 -> LATIN CAPITAL LETTER U
u'V' # 0xE5 -> LATIN CAPITAL LETTER V
u'W' # 0xE6 -> LATIN CAPITAL LETTER W
u'X' # 0xE7 -> LATIN CAPITAL LETTER X
u'Y' # 0xE8 -> LATIN CAPITAL LETTER Y
u'Z' # 0xE9 -> LATIN CAPITAL LETTER Z
u'\xb2' # 0xEA -> SUPERSCRIPT TWO
u'\xd4' # 0xEB -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'#' # 0xEC -> NUMBER SIGN
u'\xd2' # 0xED -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd5' # 0xEF -> LATIN CAPITAL LETTER O WITH TILDE
u'0' # 0xF0 -> DIGIT ZERO
u'1' # 0xF1 -> DIGIT ONE
u'2' # 0xF2 -> DIGIT TWO
u'3' # 0xF3 -> DIGIT THREE
u'4' # 0xF4 -> DIGIT FOUR
u'5' # 0xF5 -> DIGIT FIVE
u'6' # 0xF6 -> DIGIT SIX
u'7' # 0xF7 -> DIGIT SEVEN
u'8' # 0xF8 -> DIGIT EIGHT
u'9' # 0xF9 -> DIGIT NINE
u'\xb3' # 0xFA -> SUPERSCRIPT THREE
u'\xdb' # 0xFB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'"' # 0xFC -> QUOTATION MARK
u'\xd9' # 0xFD -> LATIN CAPITAL LETTER U WITH GRAVE
u'\xda' # 0xFE -> LATIN CAPITAL LETTER U WITH ACUTE
u'\x9f' # 0xFF -> CONTROL
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| apache-2.0 |
hynnet/hiwifi-openwrt-HC5661-HC5761 | staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/SocketServer.py | 30 | 23321 | """Generic socket server classes.
This module tries to capture the various aspects of defining a server:
For socket-based servers:
- address family:
- AF_INET{,6}: IP (Internet Protocol) sockets (default)
- AF_UNIX: Unix domain sockets
- others, e.g. AF_DECNET are conceivable (see <socket.h>
- socket type:
- SOCK_STREAM (reliable stream, e.g. TCP)
- SOCK_DGRAM (datagrams, e.g. UDP)
For request-based servers (including socket-based):
- client address verification before further looking at the request
(This is actually a hook for any processing that needs to look
at the request before anything else, e.g. logging)
- how to handle multiple requests:
- synchronous (one request is handled at a time)
- forking (each request is handled by a new process)
- threading (each request is handled by a new thread)
The classes in this module favor the server type that is simplest to
write: a synchronous TCP/IP server. This is bad class design, but
save some typing. (There's also the issue that a deep class hierarchy
slows down method lookups.)
There are five classes in an inheritance diagram, four of which represent
synchronous servers of four types:
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
Note that UnixDatagramServer derives from UDPServer, not from
UnixStreamServer -- the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both
unix server classes.
Forking and threading versions of each type of server can be created
using the ForkingMixIn and ThreadingMixIn mix-in classes. For
instance, a threading UDP server class is created as follows:
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
The Mix-in class must come first, since it overrides a method defined
in UDPServer! Setting the various member variables also changes
the behavior of the underlying server mechanism.
To implement a service, you must derive a class from
BaseRequestHandler and redefine its handle() method. You can then run
various versions of the service by combining one of the server classes
with your request handler class.
The request handler class must be different for datagram or stream
services. This can be hidden by using the request handler
subclasses StreamRequestHandler or DatagramRequestHandler.
Of course, you still have to use your head!
For instance, it makes no sense to use a forking server if the service
contains state in memory that can be modified by requests (since the
modifications in the child process would never reach the initial state
kept in the parent process and passed to each child). In this case,
you can use a threading server, but you will probably have to use
locks to avoid two requests that come in nearly simultaneous to apply
conflicting changes to the server state.
On the other hand, if you are building e.g. an HTTP server, where all
data is stored externally (e.g. in the file system), a synchronous
class will essentially render the service "deaf" while one request is
being handled -- which may be for a very long time if a client is slow
to read all the data it has requested. Here a threading or forking
server is appropriate.
In some cases, it may be appropriate to process part of a request
synchronously, but to finish processing in a forked child depending on
the request data. This can be implemented by using a synchronous
server and doing an explicit fork in the request handler class
handle() method.
Another approach to handling multiple simultaneous requests in an
environment that supports neither threads nor fork (or where these are
too expensive or inappropriate for the service) is to maintain an
explicit table of partially finished requests and to use select() to
decide which request to work on next (or whether to handle a new
incoming request). This is particularly important for stream services
where each client can potentially be connected for a long time (if
threads or subprocesses cannot be used).
Future work:
- Standard classes for Sun RPC (which uses either UDP or TCP)
- Standard mix-in classes to implement various authentication
and encryption schemes
- Standard framework for select-based multiplexing
XXX Open problems:
- What to do with out-of-band data?
BaseServer:
- split generic "request" functionality out into BaseServer class.
Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
example: read entries from a SQL database (requires overriding
get_request() to return a table entry from the database).
entry is processed by a RequestHandlerClass.
"""
# Author of the BaseServer patch: Luke Kenneth Casson Leighton
# XXX Warning!
# There is a test suite for this module, but it cannot be run by the
# standard regression test.
# To run it manually, run Lib/test/test_socketserver.py.
__version__ = "0.4"
import socket
import select
import sys
import os
try:
import threading
except ImportError:
import dummy_threading as threading
__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
"ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
"StreamRequestHandler","DatagramRequestHandler",
"ThreadingMixIn", "ForkingMixIn"]
if hasattr(socket, "AF_UNIX"):
__all__.extend(["UnixStreamServer","UnixDatagramServer",
"ThreadingUnixStreamServer",
"ThreadingUnixDatagramServer"])
class BaseServer:
"""Base class for server classes.
Methods for the caller:
- __init__(server_address, RequestHandlerClass)
- serve_forever(poll_interval=0.5)
- shutdown()
- handle_request() # if you do not use serve_forever()
- fileno() -> int # for select()
Methods that may be overridden:
- server_bind()
- server_activate()
- get_request() -> request, client_address
- handle_timeout()
- verify_request(request, client_address)
- server_close()
- process_request(request, client_address)
- shutdown_request(request)
- close_request(request)
- handle_error()
Methods for derived classes:
- finish_request(request, client_address)
Class variables that may be overridden by derived classes or
instances:
- timeout
- address_family
- socket_type
- allow_reuse_address
Instance variables:
- RequestHandlerClass
- socket
"""
timeout = None
def __init__(self, server_address, RequestHandlerClass):
"""Constructor. May be extended, do not override."""
self.server_address = server_address
self.RequestHandlerClass = RequestHandlerClass
self.__is_shut_down = threading.Event()
self.__shutdown_request = False
def server_activate(self):
"""Called by constructor to activate the server.
May be overridden.
"""
pass
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__is_shut_down.clear()
try:
while not self.__shutdown_request:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if self in r:
self._handle_request_noblock()
finally:
self.__shutdown_request = False
self.__is_shut_down.set()
def shutdown(self):
"""Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while
serve_forever() is running in another thread, or it will
deadlock.
"""
self.__shutdown_request = True
self.__is_shut_down.wait()
# The distinction between handling, getting, processing and
# finishing a request is fairly arbitrary. Remember:
#
# - handle_request() is the top-level call. It calls
# select, get_request(), verify_request() and process_request()
# - get_request() is different for stream or datagram sockets
# - process_request() is the place that may fork a new process
# or create a new thread to finish the request
# - finish_request() instantiates the request handler class;
# this constructor will handle the request all by itself
def handle_request(self):
"""Handle one request, possibly blocking.
Respects self.timeout.
"""
# Support people who used socket.settimeout() to escape
# handle_request before self.timeout was available.
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(timeout, self.timeout)
fd_sets = select.select([self], [], [], timeout)
if not fd_sets[0]:
self.handle_timeout()
return
self._handle_request_noblock()
def _handle_request_noblock(self):
"""Handle one request, without blocking.
I assume that select.select has returned that the socket is
readable before this function was called, so there should be
no risk of blocking in get_request().
"""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
self.shutdown_request(request)
def handle_timeout(self):
"""Called if no new request arrives within self.timeout.
Overridden by ForkingMixIn.
"""
pass
def verify_request(self, request, client_address):
"""Verify the request. May be overridden.
Return True if we should proceed with this request.
"""
return True
def process_request(self, request, client_address):
"""Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
"""
self.finish_request(request, client_address)
self.shutdown_request(request)
def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
pass
def finish_request(self, request, client_address):
"""Finish one request by instantiating RequestHandlerClass."""
self.RequestHandlerClass(request, client_address, self)
def shutdown_request(self, request):
"""Called to shutdown and close an individual request."""
self.close_request(request)
def close_request(self, request):
"""Called to clean up an individual request."""
pass
def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
"""
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40
class TCPServer(BaseServer):
"""Base class for various socket-based server classes.
Defaults to synchronous IP stream (i.e., TCP).
Methods for the caller:
- __init__(server_address, RequestHandlerClass, bind_and_activate=True)
- serve_forever(poll_interval=0.5)
- shutdown()
- handle_request() # if you don't use serve_forever()
- fileno() -> int # for select()
Methods that may be overridden:
- server_bind()
- server_activate()
- get_request() -> request, client_address
- handle_timeout()
- verify_request(request, client_address)
- process_request(request, client_address)
- shutdown_request(request)
- close_request(request)
- handle_error()
Methods for derived classes:
- finish_request(request, client_address)
Class variables that may be overridden by derived classes or
instances:
- timeout
- address_family
- socket_type
- request_queue_size (only for stream sockets)
- allow_reuse_address
Instance variables:
- server_address
- RequestHandlerClass
- socket
"""
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM
request_queue_size = 5
allow_reuse_address = False
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
"""Constructor. May be extended, do not override."""
BaseServer.__init__(self, server_address, RequestHandlerClass)
self.socket = socket.socket(self.address_family,
self.socket_type)
if bind_and_activate:
self.server_bind()
self.server_activate()
def server_bind(self):
"""Called by constructor to bind the socket.
May be overridden.
"""
if self.allow_reuse_address:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
self.server_address = self.socket.getsockname()
def server_activate(self):
"""Called by constructor to activate the server.
May be overridden.
"""
self.socket.listen(self.request_queue_size)
def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
self.socket.close()
def fileno(self):
"""Return socket file number.
Interface required by select().
"""
return self.socket.fileno()
def get_request(self):
"""Get the request and client address from the socket.
May be overridden.
"""
return self.socket.accept()
def shutdown_request(self, request):
"""Called to shutdown and close an individual request."""
try:
#explicitly shutdown. socket.close() merely releases
#the socket and waits for GC to perform the actual close.
request.shutdown(socket.SHUT_WR)
except socket.error:
pass #some platforms may raise ENOTCONN here
self.close_request(request)
def close_request(self, request):
"""Called to clean up an individual request."""
request.close()
class UDPServer(TCPServer):
"""UDP server class."""
allow_reuse_address = False
socket_type = socket.SOCK_DGRAM
max_packet_size = 8192
def get_request(self):
data, client_addr = self.socket.recvfrom(self.max_packet_size)
return (data, self.socket), client_addr
def server_activate(self):
# No need to call listen() for UDP.
pass
def shutdown_request(self, request):
# No need to shutdown anything.
self.close_request(request)
def close_request(self, request):
# No need to close anything.
pass
class ForkingMixIn:
"""Mix-in class to handle each request in a new process."""
timeout = 300
active_children = None
max_children = 40
def collect_children(self):
"""Internal routine to wait for children that have exited."""
if self.active_children is None: return
while len(self.active_children) >= self.max_children:
# XXX: This will wait for any child process, not just ones
# spawned by this library. This could confuse other
# libraries that expect to be able to wait for their own
# children.
try:
pid, status = os.waitpid(0, 0)
except os.error:
pid = None
if pid not in self.active_children: continue
self.active_children.remove(pid)
# XXX: This loop runs more system calls than it ought
# to. There should be a way to put the active_children into a
# process group and then use os.waitpid(-pgid) to wait for any
# of that set, but I couldn't find a way to allocate pgids
# that couldn't collide.
for child in self.active_children:
try:
pid, status = os.waitpid(child, os.WNOHANG)
except os.error:
pid = None
if not pid: continue
try:
self.active_children.remove(pid)
except ValueError, e:
raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
self.active_children))
def handle_timeout(self):
"""Wait for zombies after self.timeout seconds of inactivity.
May be extended, do not override.
"""
self.collect_children()
def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork()
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request) #close handle in parent process
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
self.shutdown_request(request)
finally:
os._exit(1)
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
# Decides how threads will act upon termination of the
# main process
daemon_threads = False
def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request)
def process_request(self, request, client_address):
"""Start a new thread to process the request."""
t = threading.Thread(target = self.process_request_thread,
args = (request, client_address))
t.daemon = self.daemon_threads
t.start()
class ForkingUDPServer(ForkingMixIn, UDPServer): pass
class ForkingTCPServer(ForkingMixIn, TCPServer): pass
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
if hasattr(socket, 'AF_UNIX'):
class UnixStreamServer(TCPServer):
address_family = socket.AF_UNIX
class UnixDatagramServer(UDPServer):
address_family = socket.AF_UNIX
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
class BaseRequestHandler:
"""Base class for request handler classes.
This class is instantiated for each request to be handled. The
constructor sets the instance variables request, client_address
and server, and then calls the handle() method. To implement a
specific service, all you need to do is to derive a class which
defines a handle() method.
The handle() method can find the request as self.request, the
client address as self.client_address, and the server (in case it
needs access to per-server information) as self.server. Since a
separate instance is created for each request, the handle() method
can define arbitrary other instance variariables.
"""
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
self.setup()
try:
self.handle()
finally:
self.finish()
def setup(self):
pass
def handle(self):
pass
def finish(self):
pass
# The following two classes make it possible to use the same service
# class for stream or datagram servers.
# Each class sets up these instance variables:
# - rfile: a file object from which receives the request is read
# - wfile: a file object to which the reply is written
# When the handle() method returns, wfile is flushed properly
class StreamRequestHandler(BaseRequestHandler):
"""Define self.rfile and self.wfile for stream sockets."""
# Default buffer sizes for rfile, wfile.
# We default rfile to buffered because otherwise it could be
# really slow for large data (a getc() call per byte); we make
# wfile unbuffered because (a) often after a write() we want to
# read and we need to flush the line; (b) big writes to unbuffered
# files are typically optimized by stdio even when big reads
# aren't.
rbufsize = -1
wbufsize = 0
# A timeout to apply to the request socket, if not None.
timeout = None
# Disable nagle algorithm for this socket, if True.
# Use only when wbufsize != 0, to avoid small packets.
disable_nagle_algorithm = False
def setup(self):
self.connection = self.request
if self.timeout is not None:
self.connection.settimeout(self.timeout)
if self.disable_nagle_algorithm:
self.connection.setsockopt(socket.IPPROTO_TCP,
socket.TCP_NODELAY, True)
self.rfile = self.connection.makefile('rb', self.rbufsize)
self.wfile = self.connection.makefile('wb', self.wbufsize)
def finish(self):
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
self.rfile.close()
class DatagramRequestHandler(BaseRequestHandler):
# XXX Regrettably, I cannot get this working on Linux;
# s.recvfrom() doesn't return a meaningful client address.
"""Define self.rfile and self.wfile for datagram sockets."""
def setup(self):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
self.packet, self.socket = self.request
self.rfile = StringIO(self.packet)
self.wfile = StringIO()
def finish(self):
self.socket.sendto(self.wfile.getvalue(), self.client_address)
| gpl-2.0 |
tim-smart/kernel_lge_mako | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py | 12980 | 5411 | # SchedGui.py - Python extension for perf script, basic GUI code for
# traces drawing and overview.
#
# Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com>
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
try:
import wx
except ImportError:
raise ImportError, "You need to install the wxpython lib for this script"
class RootFrame(wx.Frame):
Y_OFFSET = 100
RECT_HEIGHT = 100
RECT_SPACE = 50
EVENT_MARKING_WIDTH = 5
def __init__(self, sched_tracer, title, parent = None, id = -1):
wx.Frame.__init__(self, parent, id, title)
(self.screen_width, self.screen_height) = wx.GetDisplaySize()
self.screen_width -= 10
self.screen_height -= 10
self.zoom = 0.5
self.scroll_scale = 20
self.sched_tracer = sched_tracer
self.sched_tracer.set_root_win(self)
(self.ts_start, self.ts_end) = sched_tracer.interval()
self.update_width_virtual()
self.nr_rects = sched_tracer.nr_rectangles() + 1
self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
# whole window panel
self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height))
# scrollable container
self.scroll = wx.ScrolledWindow(self.panel)
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale)
self.scroll.EnableScrolling(True, True)
self.scroll.SetFocus()
# scrollable drawing area
self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2))
self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Fit()
self.Fit()
self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING)
self.txt = None
self.Show(True)
def us_to_px(self, val):
return val / (10 ** 3) * self.zoom
def px_to_us(self, val):
return (val / self.zoom) * (10 ** 3)
def scroll_start(self):
(x, y) = self.scroll.GetViewStart()
return (x * self.scroll_scale, y * self.scroll_scale)
def scroll_start_us(self):
(x, y) = self.scroll_start()
return self.px_to_us(x)
def paint_rectangle_zone(self, nr, color, top_color, start, end):
offset_px = self.us_to_px(start - self.ts_start)
width_px = self.us_to_px(end - self.ts_start)
offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
width_py = RootFrame.RECT_HEIGHT
dc = self.dc
if top_color is not None:
(r, g, b) = top_color
top_color = wx.Colour(r, g, b)
brush = wx.Brush(top_color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH)
width_py -= RootFrame.EVENT_MARKING_WIDTH
offset_py += RootFrame.EVENT_MARKING_WIDTH
(r ,g, b) = color
color = wx.Colour(r, g, b)
brush = wx.Brush(color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, width_py)
def update_rectangles(self, dc, start, end):
start += self.ts_start
end += self.ts_start
self.sched_tracer.fill_zone(start, end)
def on_paint(self, event):
dc = wx.PaintDC(self.scroll_panel)
self.dc = dc
width = min(self.width_virtual, self.screen_width)
(x, y) = self.scroll_start()
start = self.px_to_us(x)
end = self.px_to_us(x + width)
self.update_rectangles(dc, start, end)
def rect_from_ypixel(self, y):
y -= RootFrame.Y_OFFSET
rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT:
return -1
return rect
def update_summary(self, txt):
if self.txt:
self.txt.Destroy()
self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50))
def on_mouse_down(self, event):
(x, y) = event.GetPositionTuple()
rect = self.rect_from_ypixel(y)
if rect == -1:
return
t = self.px_to_us(x) + self.ts_start
self.sched_tracer.mouse_down(rect, t)
def update_width_virtual(self):
self.width_virtual = self.us_to_px(self.ts_end - self.ts_start)
def __zoom(self, x):
self.update_width_virtual()
(xpos, ypos) = self.scroll.GetViewStart()
xpos = self.us_to_px(x) / self.scroll_scale
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos)
self.Refresh()
def zoom_in(self):
x = self.scroll_start_us()
self.zoom *= 2
self.__zoom(x)
def zoom_out(self):
x = self.scroll_start_us()
self.zoom /= 2
self.__zoom(x)
def on_key_press(self, event):
key = event.GetRawKeyCode()
if key == ord("+"):
self.zoom_in()
return
if key == ord("-"):
self.zoom_out()
return
key = event.GetKeyCode()
(x, y) = self.scroll.GetViewStart()
if key == wx.WXK_RIGHT:
self.scroll.Scroll(x + 1, y)
elif key == wx.WXK_LEFT:
self.scroll.Scroll(x - 1, y)
elif key == wx.WXK_DOWN:
self.scroll.Scroll(x, y + 1)
elif key == wx.WXK_UP:
self.scroll.Scroll(x, y - 1)
| gpl-2.0 |
AnhellO/DAS_Sistemas | Ago-Dic-2018/Max/Proyecto Final/Proyect/SqlCrudApi.py | 1 | 1826 | import sqlite3
from ApiClientes import *
from AbstractClassBuilders import *
import sys
#Autor y programador - "Maximiliano García De Santiago"
class SqlCRUDCliente(AbstractProyectClient):
def __init__(self):
self.conexion = sqlite3.connect('ProyectTaco.db')
self.cursor = self.conexion.cursor()
def CrearCliente(self, Cliente):
cliente = (Cliente.Id, Cliente.Nombre, Cliente.Genero, Cliente.Email, Cliente.Edad)
self.cursor.execute("INSERT INTO Clientes (Id, Nombre, Genero, Email, Edad) VALUES (?,?,?,?,?)", cliente)
self.conexion.commit()
Cliente.Id = self.cursor.lastrowid
print('cliente guardado')
return Cliente
def MostrarListaClientes(self):
self.cursor.execute("SELECT * from Clientes")
for Clientes in self.cursor.fetchall():
clt = Cliente(Clientes[1], Clientes[2], Clientes[3], Clientes[4], Clientes[0])
print(clt)
def ConsultarCliente(self, Id):
self.cursor.execute("SELECT * from Clientes where Id = ?", [Id])
for Clientes in self.cursor.fetchall():
clt = Cliente(Clientes[0], Clientes[1], Clientes[2], Clientes[3], Clientes[4])
return print(clt)
def BorrarCliente(self, Id):
self.cursor.execute("DELETE from Clientes WHERE Id=?", [Id])
self.conexion.commit()
print('Cliente borrado')
return True
if __name__ == "__main__":
UrlCliente = ApiCliente()
crud2 = SqlCRUDCliente()
# Id = 6
# Borrar = crud.BorrarCliente(5)
# MostrarLista = crud.MostrarListaClientes()
# ConsultarCliente = crud.ConsultarCliente(Id)
# while Id <= 20:
# cliente1 = UrlCliente.DatosCliente('https://randomuser.me/api/', Id)
# newcliente = crud.CrearCliente(cliente1)
# sleep(1)
# Id += 1
| mit |
PriceChild/ansible | lib/ansible/modules/network/f5/bigip_routedomain.py | 15 | 16691 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2016 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/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: bigip_routedomain
short_description: Manage route domains on a BIG-IP
description:
- Manage route domains on a BIG-IP
version_added: "2.2"
options:
bwc_policy:
description:
- The bandwidth controller for the route domain.
connection_limit:
description:
- The maximum number of concurrent connections allowed for the
route domain. Setting this to C(0) turns off connection limits.
description:
description:
- Specifies descriptive text that identifies the route domain.
flow_eviction_policy:
description:
- The eviction policy to use with this route domain. Apply an eviction
policy to provide customized responses to flow overflows and slow
flows on the route domain.
id:
description:
- The unique identifying integer representing the route domain.
required: true
parent:
description:
Specifies the route domain the system searches when it cannot
find a route in the configured domain.
required: false
routing_protocol:
description:
- Dynamic routing protocols for the system to use in the route domain.
choices:
- BFD
- BGP
- IS-IS
- OSPFv2
- OSPFv3
- PIM
- RIP
- RIPng
service_policy:
description:
- Service policy to associate with the route domain.
state:
description:
- Whether the route domain should exist or not.
required: false
default: present
choices:
- present
- absent
strict:
description:
- Specifies whether the system enforces cross-routing restrictions
or not.
choices:
- enabled
- disabled
vlans:
description:
- VLANs for the system to use in the route domain
notes:
- Requires the f5-sdk Python package on the host. This is as easy as
pip install f5-sdk.
extends_documentation_fragment: f5
requirements:
- f5-sdk
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = '''
- name: Create a route domain
bigip_routedomain:
id: "1234"
password: "secret"
server: "lb.mydomain.com"
state: "present"
user: "admin"
delegate_to: localhost
- name: Set VLANs on the route domain
bigip_routedomain:
id: "1234"
password: "secret"
server: "lb.mydomain.com"
state: "present"
user: "admin"
vlans:
- net1
- foo
delegate_to: localhost
'''
RETURN = '''
id:
description: The ID of the route domain that was changed
returned: changed
type: int
sample: 2
description:
description: The description of the route domain
returned: changed
type: string
sample: "route domain foo"
strict:
description: The new strict isolation setting
returned: changed
type: string
sample: "enabled"
parent:
description: The new parent route domain
returned: changed
type: int
sample: 0
vlans:
description: List of new VLANs the route domain is applied to
returned: changed
type: list
sample: ['/Common/http-tunnel', '/Common/socks-tunnel']
routing_protocol:
description: List of routing protocols applied to the route domain
returned: changed
type: list
sample: ['bfd', 'bgp']
bwc_policy:
description: The new bandwidth controller
returned: changed
type: string
sample: /Common/foo
connection_limit:
description: The new connection limit for the route domain
returned: changed
type: integer
sample: 100
flow_eviction_policy:
description: The new eviction policy to use with this route domain
returned: changed
type: string
sample: /Common/default-eviction-policy
service_policy:
description: The new service policy to use with this route domain
returned: changed
type: string
sample: /Common-my-service-policy
'''
try:
from f5.bigip import ManagementRoot
from icontrol.session import iControlUnexpectedHTTPError
HAS_F5SDK = True
except ImportError:
HAS_F5SDK = False
PROTOCOLS = [
'BFD', 'BGP', 'IS-IS', 'OSPFv2', 'OSPFv3', 'PIM', 'RIP', 'RIPng'
]
STRICTS = ['enabled', 'disabled']
class BigIpRouteDomain(object):
def __init__(self, *args, **kwargs):
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
# The params that change in the module
self.cparams = dict()
kwargs['name'] = str(kwargs['id'])
# Stores the params that are sent to the module
self.params = kwargs
self.api = ManagementRoot(kwargs['server'],
kwargs['user'],
kwargs['password'],
port=kwargs['server_port'])
def absent(self):
if not self.exists():
return False
if self.params['check_mode']:
return True
rd = self.api.tm.net.route_domains.route_domain.load(
name=self.params['name']
)
rd.delete()
if self.exists():
raise F5ModuleError("Failed to delete the route domain")
else:
return True
def present(self):
if self.exists():
return self.update()
else:
if self.params['check_mode']:
return True
return self.create()
def read(self):
"""Read information and transform it
The values that are returned by BIG-IP in the f5-sdk can have encoding
attached to them as well as be completely missing in some cases.
Therefore, this method will transform the data from the BIG-IP into a
format that is more easily consumable by the rest of the class and the
parameters that are supported by the module.
"""
p = dict()
r = self.api.tm.net.route_domains.route_domain.load(
name=self.params['name']
)
p['id'] = int(r.id)
p['name'] = str(r.name)
if hasattr(r, 'connectionLimit'):
p['connection_limit'] = int(r.connectionLimit)
if hasattr(r, 'description'):
p['description'] = str(r.description)
if hasattr(r, 'strict'):
p['strict'] = str(r.strict)
if hasattr(r, 'parent'):
p['parent'] = r.parent
if hasattr(r, 'vlans'):
p['vlans'] = list(set([str(x) for x in r.vlans]))
if hasattr(r, 'routingProtocol'):
p['routing_protocol'] = list(set([str(x) for x in r.routingProtocol]))
if hasattr(r, 'flowEvictionPolicy'):
p['flow_eviction_policy'] = str(r.flowEvictionPolicy)
if hasattr(r, 'bwcPolicy'):
p['bwc_policy'] = str(r.bwcPolicy)
if hasattr(r, 'servicePolicy'):
p['service_policy'] = str(r.servicePolicy)
return p
def domains(self):
result = []
domains = self.api.tm.net.route_domains.get_collection()
for domain in domains:
# Just checking for the addition of the partition here for
# different versions of BIG-IP
if '/' + self.params['partition'] + '/' in domain.name:
result.append(domain.name)
else:
full_name = '/%s/%s' % (self.params['partition'], domain.name)
result.append(full_name)
return result
def create(self):
params = dict()
params['id'] = self.params['id']
params['name'] = self.params['name']
partition = self.params['partition']
description = self.params['description']
strict = self.params['strict']
parent = self.params['parent']
bwc_policy = self.params['bwc_policy']
vlans = self.params['vlans']
routing_protocol = self.params['routing_protocol']
connection_limit = self.params['connection_limit']
flow_eviction_policy = self.params['flow_eviction_policy']
service_policy = self.params['service_policy']
if description is not None:
params['description'] = description
if strict is not None:
params['strict'] = strict
if parent is not None:
parent = '/%s/%s' % (partition, parent)
if parent in self.domains():
params['parent'] = parent
else:
raise F5ModuleError(
"The parent route domain was not found"
)
if bwc_policy is not None:
policy = '/%s/%s' % (partition, bwc_policy)
params['bwcPolicy'] = policy
if vlans is not None:
params['vlans'] = []
for vlan in vlans:
vname = '/%s/%s' % (partition, vlan)
params['vlans'].append(vname)
if routing_protocol is not None:
params['routingProtocol'] = []
for protocol in routing_protocol:
if protocol in PROTOCOLS:
params['routingProtocol'].append(protocol)
else:
raise F5ModuleError(
"routing_protocol must be one of: %s" % (PROTOCOLS)
)
if connection_limit is not None:
params['connectionLimit'] = connection_limit
if flow_eviction_policy is not None:
policy = '/%s/%s' % (partition, flow_eviction_policy)
params['flowEvictionPolicy'] = policy
if service_policy is not None:
policy = '/%s/%s' % (partition, service_policy)
params['servicePolicy'] = policy
self.api.tm.net.route_domains.route_domain.create(**params)
exists = self.api.tm.net.route_domains.route_domain.exists(
name=self.params['name']
)
if exists:
return True
else:
raise F5ModuleError(
"An error occurred while creating the route domain"
)
def update(self):
changed = False
params = dict()
current = self.read()
check_mode = self.params['check_mode']
partition = self.params['partition']
description = self.params['description']
strict = self.params['strict']
parent = self.params['parent']
bwc_policy = self.params['bwc_policy']
vlans = self.params['vlans']
routing_protocol = self.params['routing_protocol']
connection_limit = self.params['connection_limit']
flow_eviction_policy = self.params['flow_eviction_policy']
service_policy = self.params['service_policy']
if description is not None:
if 'description' in current:
if description != current['description']:
params['description'] = description
else:
params['description'] = description
if strict is not None:
if strict != current['strict']:
params['strict'] = strict
if parent is not None:
parent = '/%s/%s' % (partition, parent)
if 'parent' in current:
if parent != current['parent']:
params['parent'] = parent
else:
params['parent'] = parent
if bwc_policy is not None:
policy = '/%s/%s' % (partition, bwc_policy)
if 'bwc_policy' in current:
if policy != current['bwc_policy']:
params['bwcPolicy'] = policy
else:
params['bwcPolicy'] = policy
if vlans is not None:
tmp = set()
for vlan in vlans:
vname = '/%s/%s' % (partition, vlan)
tmp.add(vname)
tmp = list(tmp)
if 'vlans' in current:
if tmp != current['vlans']:
params['vlans'] = tmp
else:
params['vlans'] = tmp
if routing_protocol is not None:
tmp = set()
for protocol in routing_protocol:
if protocol in PROTOCOLS:
tmp.add(protocol)
else:
raise F5ModuleError(
"routing_protocol must be one of: %s" % (PROTOCOLS)
)
tmp = list(tmp)
if 'routing_protocol' in current:
if tmp != current['routing_protocol']:
params['routingProtocol'] = tmp
else:
params['routingProtocol'] = tmp
if connection_limit is not None:
if connection_limit != current['connection_limit']:
params['connectionLimit'] = connection_limit
if flow_eviction_policy is not None:
policy = '/%s/%s' % (partition, flow_eviction_policy)
if 'flow_eviction_policy' in current:
if policy != current['flow_eviction_policy']:
params['flowEvictionPolicy'] = policy
else:
params['flowEvictionPolicy'] = policy
if service_policy is not None:
policy = '/%s/%s' % (partition, service_policy)
if 'service_policy' in current:
if policy != current['service_policy']:
params['servicePolicy'] = policy
else:
params['servicePolicy'] = policy
if params:
changed = True
self.cparams = camel_dict_to_snake_dict(params)
if check_mode:
return changed
else:
return changed
try:
rd = self.api.tm.net.route_domains.route_domain.load(
name=self.params['name']
)
rd.update(**params)
rd.refresh()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(e)
return True
def exists(self):
return self.api.tm.net.route_domains.route_domain.exists(
name=self.params['name']
)
def flush(self):
result = dict()
state = self.params['state']
if self.params['check_mode']:
if value == current:
changed = False
else:
changed = True
else:
if state == "present":
changed = self.present()
current = self.read()
result.update(current)
elif state == "absent":
changed = self.absent()
result.update(dict(changed=changed))
return result
def main():
argument_spec = f5_argument_spec()
meta_args = dict(
id=dict(required=True, type='int'),
description=dict(required=False, default=None),
strict=dict(required=False, default=None, choices=STRICTS),
parent=dict(required=False, type='int', default=None),
vlans=dict(required=False, default=None, type='list'),
routing_protocol=dict(required=False, default=None, type='list'),
bwc_policy=dict(required=False, type='str', default=None),
connection_limit=dict(required=False, type='int', default=None),
flow_eviction_policy=dict(required=False, type='str', default=None),
service_policy=dict(required=False, type='str', default=None)
)
argument_spec.update(meta_args)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
try:
obj = BigIpRouteDomain(check_mode=module.check_mode, **module.params)
result = obj.flush()
module.exit_json(**result)
except F5ModuleError as e:
module.fail_json(msg=str(e))
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import camel_dict_to_snake_dict
from ansible.module_utils.f5_utils import *
if __name__ == '__main__':
main()
| gpl-3.0 |
sivaprakashniet/push_pull | p2p/lib/python2.7/site-packages/compressor/js.py | 1 | 2297 | from compressor.conf import settings
from compressor.base import Compressor, SOURCE_HUNK, SOURCE_FILE
class JsCompressor(Compressor):
def __init__(self, content=None, output_prefix="js", context=None):
filters = list(settings.COMPRESS_JS_FILTERS)
super(JsCompressor, self).__init__(content, output_prefix, context, filters)
def split_contents(self):
if self.split_content:
return self.split_content
self.extra_nodes = []
for elem in self.parser.js_elems():
attribs = self.parser.elem_attribs(elem)
if 'src' in attribs:
basename = self.get_basename(attribs['src'])
filename = self.get_filename(basename)
content = (SOURCE_FILE, filename, basename, elem)
else:
content = (SOURCE_HUNK, self.parser.elem_content(elem), None, elem)
self.split_content.append(content)
if 'async' in attribs:
extra = ' async'
elif 'defer' in attribs:
extra = ' defer'
else:
extra = ''
# Append to the previous node if it had the same attribute
append_to_previous = (self.extra_nodes and
self.extra_nodes[-1][0] == extra)
if append_to_previous and settings.COMPRESS_ENABLED:
self.extra_nodes[-1][1].split_content.append(content)
else:
node = self.__class__(content=self.parser.elem_str(elem),
context=self.context)
node.split_content.append(content)
self.extra_nodes.append((extra, node))
return self.split_content
def output(self, *args, **kwargs):
if (settings.COMPRESS_ENABLED or settings.COMPRESS_PRECOMPILERS or
kwargs.get('forced', False)):
self.split_contents()
if hasattr(self, 'extra_nodes'):
ret = []
for extra, subnode in self.extra_nodes:
subnode.extra_context.update({'extra': extra})
ret.append(subnode.output(*args, **kwargs))
return '\n'.join(ret)
return super(JsCompressor, self).output(*args, **kwargs)
| bsd-3-clause |
adieu/django-nonrel | tests/regressiontests/file_uploads/uploadhandler.py | 9 | 2147 | """
Upload handlers to test the upload API.
"""
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.files.uploadhandler import (FileUploadHandler, StopUpload,
StopFutureHandlers)
from StringIO import StringIO
class QuotaUploadHandler(FileUploadHandler):
"""
This test upload handler terminates the connection if more than a quota
(5MB) is uploaded.
"""
QUOTA = 5 * 2**20 # 5 MB
def __init__(self, request=None):
super(QuotaUploadHandler, self).__init__(request)
self.total_upload = 0
def receive_data_chunk(self, raw_data, start):
self.total_upload += len(raw_data)
if self.total_upload >= self.QUOTA:
raise StopUpload(connection_reset=True)
return raw_data
def file_complete(self, file_size):
return None
class CustomUploadError(Exception):
pass
class ErroringUploadHandler(FileUploadHandler):
"""A handler that raises an exception."""
def receive_data_chunk(self, raw_data, start):
raise CustomUploadError("Oops!")
class ContentTypeExtraUploadHandler(FileUploadHandler):
"""
File upload handler that handles content_type_extra
"""
def new_file(self, *args, **kwargs):
super(ContentTypeExtraUploadHandler, self).new_file(*args, **kwargs)
self.blobkey = self.content_type_extra.get('blob-key', '')
self.file = StringIO()
self.file.write(self.blobkey)
self.active = self.blobkey is not None
if self.active:
raise StopFutureHandlers()
def receive_data_chunk(self, raw_data, start):
"""
Add the data to the StringIO file.
"""
if not self.active:
return raw_data
def file_complete(self, file_size):
if not self.active:
return
self.file.seek(0)
return InMemoryUploadedFile(
file = self.file,
field_name = self.field_name,
name = self.file_name,
content_type = self.content_type,
size = file_size,
charset = self.charset
)
| bsd-3-clause |
falbassini/Samples | python/v2.0/get_userprofiles.py | 3 | 1582 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to get a list of all user profiles."""
import sys
from apiclient import sample_tools
from oauth2client import client
def main(argv):
# Authenticate and construct service.
service, _ = sample_tools.init(
argv, 'dfareporting', 'v2.0', __doc__, __file__, parents=[],
scope=['https://www.googleapis.com/auth/dfareporting',
'https://www.googleapis.com/auth/dfatrafficking'])
try:
# Construct the request.
request = service.userProfiles().list()
# Execute request and print response.
response = request.execute()
for profile in response['items']:
print ('Found user profile with ID %s and user name "%s".'
% (profile['profileId'], profile['userName']))
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| apache-2.0 |
xunmengfeng/engine | sky/engine/bindings/scripts/compiler.py | 12 | 6345 | #!/usr/bin/python
# Copyright (C) 2014 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.
"""Compile an .idl file to Dart bindings (.h and .cpp files).
Design doc: ??????
"""
from optparse import OptionParser
import os
import sys
from dart_compiler import IdlCompiler
from code_generator_dart import CodeGeneratorDart
def parse_options():
parser = OptionParser()
parser.add_option('--output-directory')
parser.add_option('--interfaces-info-file')
parser.add_option('--write-file-only-if-changed', type='int', default='1')
parser.add_option('--generate-dart-blink',
action='append',
type='string',
dest='blink_global_entries',
nargs=2,
help="Pickle file directory and idl file list (dart:blink)")
parser.add_option('--generate-globals',
action='append',
type='string',
dest='global_entries',
nargs=2,
help="Pickle file directory and idl file list (global class table)")
# ensure output comes last, so command line easy to parse via regexes
parser.disable_interspersed_args()
options, args = parser.parse_args()
if options.output_directory is None:
parser.error('Must specify output directory using --output-directory.')
options.write_file_only_if_changed = bool(options.write_file_only_if_changed)
if bool(options.global_entries) or bool(options.blink_global_entries):
return options, None
if len(args) != 1:
parser.error('Must specify exactly 1 input file as argument, but %d given.' % len(args))
filename = os.path.realpath(args[0])
return options, filename
def idl_filename_to_interface_name(idl_filename):
basename = os.path.basename(idl_filename)
interface_name, _ = os.path.splitext(basename)
return interface_name
class IdlCompilerDart(IdlCompiler):
def __init__(self, *args, **kwargs):
IdlCompiler.__init__(self, *args, **kwargs)
interfaces_info = self.interfaces_info
self.output_directory = self.output_directory
self.code_generator = CodeGeneratorDart(interfaces_info, self.output_directory)
def compile_file(self, idl_filename):
interface_name = idl_filename_to_interface_name(idl_filename)
header_filename = os.path.join(self.output_directory,
'Dart%s.h' % interface_name)
cpp_filename = os.path.join(self.output_directory,
'Dart%s.cpp' % interface_name)
dart_filename = os.path.join(self.output_directory,
'%s.dart' % interface_name)
output_paths = (header_filename, cpp_filename, dart_filename)
self.compile_and_write(idl_filename, output_paths)
def generate_global(self, global_entries):
expanded_global_entries = []
for (directory, file_list_file) in global_entries:
with open(file_list_file) as input_file:
idl_file_list = sorted([line.rstrip('\n')
for line in input_file])
expanded_global_entries.append((directory, idl_file_list))
global_header_filename = os.path.join(self.output_directory, 'DartGlobal.h')
global_cpp_filename = os.path.join(self.output_directory, 'DartGlobal.cpp')
self.generate_global_and_write(expanded_global_entries,
(global_header_filename, global_cpp_filename))
def generate_dart_blink(self, global_entries):
global_dart_blink_filename = os.path.join(self.output_directory,
'dart_sky.dart')
expanded_global_entries = []
for (directory, file_list_file) in global_entries:
with open(file_list_file) as input_file:
idl_file_list = sorted([line.rstrip('\n')
for line in input_file])
expanded_global_entries.append((directory, idl_file_list))
self.generate_dart_blink_and_write(expanded_global_entries,
global_dart_blink_filename)
def main():
options, filename = parse_options()
idl_compiler = IdlCompilerDart(options.output_directory,
interfaces_info_filename=options.interfaces_info_file,
only_if_changed=options.write_file_only_if_changed)
if bool(options.global_entries):
idl_compiler.generate_global(options.global_entries)
elif bool(options.blink_global_entries):
idl_compiler.generate_dart_blink(options.blink_global_entries)
else:
idl_compiler.compile_file(filename)
if __name__ == '__main__':
sys.exit(main())
| bsd-3-clause |
SanketDG/networkx | networkx/generators/classic.py | 1 | 20233 | # Copyright (C) 2004-2016 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
"""
Generators for some classic graphs.
The typical graph generator is called as follows:
>>> G=nx.complete_graph(100)
returning the complete graph on n nodes labeled 0,..,99
as a simple graph. Except for empty_graph, all the generators
in this module return a Graph class (i.e. a simple, undirected graph).
"""
from __future__ import division
import itertools
import networkx as nx
from networkx.algorithms.bipartite.generators import complete_bipartite_graph
from networkx.utils import accumulate
from networkx.utils import flatten
from networkx.utils import is_list_of_ints
__author__ ="""Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)"""
__all__ = [ 'balanced_tree',
'barbell_graph',
'complete_graph',
'complete_multipartite_graph',
'circular_ladder_graph',
'circulant_graph',
'cycle_graph',
'dorogovtsev_goltsev_mendes_graph',
'empty_graph',
'full_rary_tree',
'grid_graph',
'grid_2d_graph',
'hypercube_graph',
'ladder_graph',
'lollipop_graph',
'null_graph',
'path_graph',
'star_graph',
'trivial_graph',
'wheel_graph']
#-------------------------------------------------------------------
# Some Classic Graphs
#-------------------------------------------------------------------
def _tree_edges(n,r):
# helper function for trees
# yields edges in rooted tree at 0 with n nodes and branching ratio r
nodes=iter(range(n))
parents=[next(nodes)] # stack of max length r
while parents:
source=parents.pop(0)
for i in range(r):
try:
target=next(nodes)
parents.append(target)
yield source,target
except StopIteration:
break
def full_rary_tree(r, n, create_using=None):
"""Creates a full r-ary tree of n vertices.
Sometimes called a k-ary, n-ary, or m-ary tree. "... all non-leaf
vertices have exactly r children and all levels are full except
for some rightmost position of the bottom level (if a leaf at the
bottom level is missing, then so are all of the leaves to its
right." [1]_
Parameters
----------
r : int
branching factor of the tree
n : int
Number of nodes in the tree
create_using : NetworkX graph type, optional
Use specified type to construct graph (default = networkx.Graph)
Returns
-------
G : networkx Graph
An r-ary tree with n nodes
References
----------
.. [1] An introduction to data structures and algorithms,
James Andrew Storer, Birkhauser Boston 2001, (page 225).
"""
G=nx.empty_graph(n,create_using)
G.add_edges_from(_tree_edges(n,r))
return G
def balanced_tree(r, h, create_using=None):
"""Return the perfectly balanced ``r``-ary tree of height ``h``.
Parameters
----------
r : int
Branching factor of the tree; each node will have ``r``
children.
h : int
Height of the tree.
create_using : NetworkX graph
Use the specified graph as the base for the generated tree; see
the documentation of :func:`~networkx.empty_graph` for more
information.
Returns
-------
G : NetworkX graph
A balanced ``r``-ary tree of height ``h``.
Notes
-----
This is the rooted tree where all leaves are at distance ``h`` from
the root. The root has degree ``r`` and all other internal nodes
have degree ``r + 1``.
Node labels are integers, starting from zero.
A balanced tree is also known as a *complete ``r``-ary tree*.
"""
# The number of nodes in the balanced tree is `1 + r + ... + r^h`,
# which is computed by using the closed-form formula for a geometric
# sum with ratio `r`. In the special case that `r` is 1, the number
# of nodes is simply `h + 1` (since the tree is actually a path
# graph).
if r == 1:
n = h + 1
else:
# This must be an integer if both `r` and `h` are integers. If
# they are not, we force integer division anyway.
n = (1 - r ** (h + 1)) // (1 - r)
return full_rary_tree(r, n, create_using=create_using)
def barbell_graph(m1,m2,create_using=None):
"""Return the Barbell Graph: two complete graphs connected by a path.
For m1 > 1 and m2 >= 0.
Two identical complete graphs K_{m1} form the left and right bells,
and are connected by a path P_{m2}.
The 2*m1+m2 nodes are numbered
0,...,m1-1 for the left barbell,
m1,...,m1+m2-1 for the path,
and m1+m2,...,2*m1+m2-1 for the right barbell.
The 3 subgraphs are joined via the edges (m1-1,m1) and (m1+m2-1,m1+m2).
If m2=0, this is merely two complete graphs joined together.
This graph is an extremal example in David Aldous
and Jim Fill's etext on Random Walks on Graphs.
"""
if create_using is not None and create_using.is_directed():
raise nx.NetworkXError("Directed Graph not supported")
if m1<2:
raise nx.NetworkXError(\
"Invalid graph description, m1 should be >=2")
if m2<0:
raise nx.NetworkXError(\
"Invalid graph description, m2 should be >=0")
# left barbell
G=complete_graph(m1,create_using)
G.name="barbell_graph(%d,%d)"%(m1,m2)
# connecting path
G.add_nodes_from([v for v in range(m1,m1+m2-1)])
if m2>1:
G.add_edges_from([(v,v+1) for v in range(m1,m1+m2-1)])
# right barbell
G.add_edges_from( (u,v) for u in range(m1+m2,2*m1+m2) for v in range(u+1,2*m1+m2))
# connect it up
G.add_edge(m1-1,m1)
if m2>0:
G.add_edge(m1+m2-1,m1+m2)
return G
def complete_graph(n,create_using=None):
""" Return the complete graph K_n with n nodes.
Node labels are the integers 0 to n-1.
"""
G=empty_graph(n,create_using)
G.name="complete_graph(%d)"%(n)
if n>1:
if G.is_directed():
edges=itertools.permutations(range(n),2)
else:
edges=itertools.combinations(range(n),2)
G.add_edges_from(edges)
return G
def circular_ladder_graph(n,create_using=None):
"""Return the circular ladder graph CL_n of length n.
CL_n consists of two concentric n-cycles in which
each of the n pairs of concentric nodes are joined by an edge.
Node labels are the integers 0 to n-1
"""
G=ladder_graph(n,create_using)
G.name="circular_ladder_graph(%d)"%n
G.add_edge(0,n-1)
G.add_edge(n,2*n-1)
return G
def circulant_graph(n, offsets, create_using=None):
"""Generates the circulant graph Ci_n(x_1, x_2, ..., x_m) with n vertices.
Returns
-------
The graph Ci_n(x_1, ..., x_m) consisting of n vertices 0, ..., n-1 such
that the vertex with label i is connected to the vertices labelled (i + x)
and (i - x), for all x in x_1 up to x_m, with the indices taken modulo n.
Parameters
----------
n : integer
The number of vertices the generated graph is to contain.
offsets : list of integers
A list of vertex offsets, x_1 up to x_m, as described above.
create_using : NetworkX graph type, optional
Use specified type to construct graph (default = networkx.Graph)
Examples
--------
Many well-known graph families are subfamilies of the circulant graphs; for
example, to generate the cycle graph on n points, we connect every vertex to
every other at offset plus or minus one. For n = 10,
>>> import networkx
>>> G = networkx.generators.classic.circulant_graph(10, [1])
>>> edges = [
... (0, 9), (0, 1), (1, 2), (2, 3), (3, 4),
... (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
...
>>> sorted(edges) == sorted(G.edges())
True
Similarly, we can generate the complete graph on 5 points with the set of
offsets [1, 2]:
>>> G = networkx.generators.classic.circulant_graph(5, [1, 2])
>>> edges = [
... (0, 1), (0, 2), (0, 3), (0, 4), (1, 2),
... (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
...
>>> sorted(edges) == sorted(G.edges())
True
"""
G = empty_graph(n, create_using)
template = 'circulant_graph(%d, [%s])'
G.name = template % (n, ', '.join(str(j) for j in offsets))
for i in range(n):
for j in offsets:
G.add_edge(i, (i - j) % n)
G.add_edge(i, (i + j) % n)
return G
def cycle_graph(n,create_using=None):
"""Return the cycle graph C_n over n nodes.
C_n is the n-path with two end-nodes connected.
Node labels are the integers 0 to n-1
If create_using is a DiGraph, the direction is in increasing order.
"""
G=path_graph(n,create_using)
G.name="cycle_graph(%d)"%n
if n>1: G.add_edge(n-1,0)
return G
def dorogovtsev_goltsev_mendes_graph(n,create_using=None):
"""Return the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
n is the generation.
See: arXiv:/cond-mat/0112143 by Dorogovtsev, Goltsev and Mendes.
"""
if create_using is not None:
if create_using.is_directed():
raise nx.NetworkXError("Directed Graph not supported")
if create_using.is_multigraph():
raise nx.NetworkXError("Multigraph not supported")
G=empty_graph(0,create_using)
G.name="Dorogovtsev-Goltsev-Mendes Graph"
G.add_edge(0,1)
if n==0:
return G
new_node = 2 # next node to be added
for i in range(1,n+1): #iterate over number of generations.
last_generation_edges = list(G.edges())
number_of_edges_in_last_generation = len(last_generation_edges)
for j in range(0,number_of_edges_in_last_generation):
G.add_edge(new_node,last_generation_edges[j][0])
G.add_edge(new_node,last_generation_edges[j][1])
new_node += 1
return G
def empty_graph(n=0,create_using=None):
"""Return the empty graph with n nodes and zero edges.
Node labels are the integers 0 to n-1
For example:
>>> G=nx.empty_graph(10)
>>> G.number_of_nodes()
10
>>> G.number_of_edges()
0
The variable create_using should point to a "graph"-like object that
will be cleaned (nodes and edges will be removed) and refitted as
an empty "graph" with n nodes with integer labels. This capability
is useful for specifying the class-nature of the resulting empty
"graph" (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
The variable create_using has two main uses:
Firstly, the variable create_using can be used to create an
empty digraph, network,etc. For example,
>>> n=10
>>> G=nx.empty_graph(n,create_using=nx.DiGraph())
will create an empty digraph on n nodes.
Secondly, one can pass an existing graph (digraph, pseudograph,
etc.) via create_using. For example, if G is an existing graph
(resp. digraph, pseudograph, etc.), then empty_graph(n,create_using=G)
will empty G (i.e. delete all nodes and edges using G.clear() in
base) and then add n nodes and zero edges, and return the modified
graph (resp. digraph, pseudograph, etc.).
See also create_empty_copy(G).
"""
if create_using is None:
# default empty graph is a simple graph
G=nx.Graph()
else:
G=create_using
G.clear()
G.add_nodes_from(range(n))
G.name="empty_graph(%d)"%n
return G
def grid_2d_graph(m,n,periodic=False,create_using=None):
""" Return the 2d grid graph of mxn nodes,
each connected to its nearest neighbors.
Optional argument periodic=True will connect
boundary nodes via periodic boundary conditions.
"""
G=empty_graph(0,create_using)
G.name="grid_2d_graph"
rows=range(m)
columns=range(n)
G.add_nodes_from( (i,j) for i in rows for j in columns )
G.add_edges_from( ((i,j),(i-1,j)) for i in rows for j in columns if i>0 )
G.add_edges_from( ((i,j),(i,j-1)) for i in rows for j in columns if j>0 )
if G.is_directed():
G.add_edges_from( ((i,j),(i+1,j)) for i in rows for j in columns if i<m-1 )
G.add_edges_from( ((i,j),(i,j+1)) for i in rows for j in columns if j<n-1 )
if periodic:
if n>2:
G.add_edges_from( ((i,0),(i,n-1)) for i in rows )
if G.is_directed():
G.add_edges_from( ((i,n-1),(i,0)) for i in rows )
if m>2:
G.add_edges_from( ((0,j),(m-1,j)) for j in columns )
if G.is_directed():
G.add_edges_from( ((m-1,j),(0,j)) for j in columns )
G.name="periodic_grid_2d_graph(%d,%d)"%(m,n)
return G
def grid_graph(dim,periodic=False):
""" Return the n-dimensional grid graph.
The dimension is the length of the list 'dim' and the
size in each dimension is the value of the list element.
E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph.
If periodic=True then join grid edges with periodic boundary conditions.
"""
dlabel="%s"%dim
if dim==[]:
G=empty_graph(0)
G.name="grid_graph(%s)"%dim
return G
if not is_list_of_ints(dim):
raise nx.NetworkXError("dim is not a list of integers")
if min(dim)<=0:
raise nx.NetworkXError(\
"dim is not a list of strictly positive integers")
if periodic:
func=cycle_graph
else:
func=path_graph
dim=list(dim)
current_dim=dim.pop()
G=func(current_dim)
while len(dim)>0:
current_dim=dim.pop()
# order matters: copy before it is cleared during the creation of Gnew
Gold=G.copy()
Gnew=func(current_dim)
# explicit: create_using=None
# This is so that we get a new graph of Gnew's class.
G=nx.cartesian_product(Gnew,Gold)
# graph G is done but has labels of the form (1,(2,(3,1)))
# so relabel
H=nx.relabel_nodes(G, flatten)
H.name="grid_graph(%s)"%dlabel
return H
def hypercube_graph(n):
"""Return the n-dimensional hypercube.
Node labels are the integers 0 to 2**n - 1.
"""
dim=n*[2]
G=grid_graph(dim)
G.name="hypercube_graph_(%d)"%n
return G
def ladder_graph(n,create_using=None):
"""Return the Ladder graph of length n.
This is two rows of n nodes, with
each pair connected by a single edge.
Node labels are the integers 0 to 2*n - 1.
"""
if create_using is not None and create_using.is_directed():
raise nx.NetworkXError("Directed Graph not supported")
G=empty_graph(2*n,create_using)
G.name="ladder_graph_(%d)"%n
G.add_edges_from([(v,v+1) for v in range(n-1)])
G.add_edges_from([(v,v+1) for v in range(n,2*n-1)])
G.add_edges_from([(v,v+n) for v in range(n)])
return G
def lollipop_graph(m,n,create_using=None):
"""Return the Lollipop Graph; `K_m` connected to `P_n`.
This is the Barbell Graph without the right barbell.
For m>1 and n>=0, the complete graph K_m is connected to the
path P_n. The resulting m+n nodes are labelled 0,...,m-1 for the
complete graph and m,...,m+n-1 for the path. The 2 subgraphs
are joined via the edge (m-1,m). If n=0, this is merely a complete
graph.
Node labels are the integers 0 to number_of_nodes - 1.
(This graph is an extremal example in David Aldous and Jim
Fill's etext on Random Walks on Graphs.)
"""
if create_using is not None and create_using.is_directed():
raise nx.NetworkXError("Directed Graph not supported")
if m<2:
raise nx.NetworkXError(\
"Invalid graph description, m should be >=2")
if n<0:
raise nx.NetworkXError(\
"Invalid graph description, n should be >=0")
# the ball
G=complete_graph(m,create_using)
# the stick
G.add_nodes_from([v for v in range(m,m+n)])
if n>1:
G.add_edges_from([(v,v+1) for v in range(m,m+n-1)])
# connect ball to stick
if m>0: G.add_edge(m-1,m)
G.name="lollipop_graph(%d,%d)"%(m,n)
return G
def null_graph(create_using=None):
"""Return the Null graph with no nodes or edges.
See empty_graph for the use of create_using.
"""
G=empty_graph(0,create_using)
G.name="null_graph()"
return G
def path_graph(n,create_using=None):
"""Return the Path graph P_n of n nodes linearly connected by n-1 edges.
Node labels are the integers 0 to n - 1.
If create_using is a DiGraph then the edges are directed in
increasing order.
"""
G=empty_graph(n,create_using)
G.name="path_graph(%d)"%n
G.add_edges_from([(v,v+1) for v in range(n-1)])
return G
def star_graph(n,create_using=None):
""" Return the Star graph with n+1 nodes: one center node, connected to n outer nodes.
Node labels are the integers 0 to n.
"""
G=complete_bipartite_graph(1,n,create_using)
G.name="star_graph(%d)"%n
return G
def trivial_graph(create_using=None):
""" Return the Trivial graph with one node (with integer label 0) and no edges.
"""
G=empty_graph(1,create_using)
G.name="trivial_graph()"
return G
def wheel_graph(n,create_using=None):
""" Return the wheel graph: a single hub node connected to each node of the (n-1)-node cycle graph.
Node labels are the integers 0 to n - 1.
"""
if n == 0:
return nx.empty_graph(n, create_using=create_using)
G=star_graph(n-1,create_using)
G.name="wheel_graph(%d)"%n
G.add_edges_from([(v,v+1) for v in range(1,n-1)])
if n>2:
G.add_edge(1,n-1)
return G
def complete_multipartite_graph(*block_sizes):
"""Returns the complete multipartite graph with the specified block sizes.
Parameters
----------
block_sizes : tuple of integers
The number of vertices in each block of the multipartite graph. The
length of this tuple is the number of blocks.
Returns
-------
G : NetworkX Graph
Returns the complete multipartite graph with the specified block sizes.
For each node, the node attribute ``'block'`` is an integer indicating
which block contains the node.
Examples
--------
Creating a complete tripartite graph, with blocks of one, two, and three
vertices, respectively.
>>> import networkx as nx
>>> G = nx.complete_multipartite_graph(1, 2, 3)
>>> [G.node[u]['block'] for u in G]
[0, 1, 1, 2, 2, 2]
>>> list(G.edges(0))
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
>>> list(G.edges(2))
[(2, 0), (2, 3), (2, 4), (2, 5)]
>>> list(G.edges(4))
[(4, 0), (4, 1), (4, 2)]
Notes
-----
This function generalizes several other graph generator functions.
- If no block sizes are given, this returns the null graph.
- If a single block size ``n`` is given, this returns the empty graph on
``n`` nodes.
- If two block sizes ``m`` and ``n`` are given, this returns the complete
bipartite graph on ``m + n`` nodes.
- If block sizes ``1`` and ``n`` are given, this returns the star graph on
``n + 1`` nodes.
See also
--------
complete_bipartite_graph
"""
G = nx.empty_graph(sum(block_sizes))
# If block_sizes is (n1, n2, n3, ...), create pairs of the form (0, n1),
# (n1, n1 + n2), (n1 + n2, n1 + n2 + n3), etc.
extents = zip([0] + list(accumulate(block_sizes)), accumulate(block_sizes))
blocks = [range(start, end) for start, end in extents]
for (i, block) in enumerate(blocks):
G.add_nodes_from(block, block=i)
# Across blocks, all vertices should be adjacent. We can use
# itertools.combinations() because the complete multipartite graph is an
# undirected graph.
for block1, block2 in itertools.combinations(blocks, 2):
G.add_edges_from(itertools.product(block1, block2))
G.name = 'complete_multiparite_graph{0}'.format(block_sizes)
return G
| bsd-3-clause |
affo/nova | tools/install_venv_common.py | 333 | 5959 | # Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
"""Provides methods needed by installation script for OpenStack development
virtual environments.
Since this script is used to bootstrap a virtualenv from the system's Python
environment, it should be kept strictly compatible with Python 2.6.
Synced in from openstack-common
"""
from __future__ import print_function
import optparse
import os
import subprocess
import sys
class InstallVenv(object):
def __init__(self, root, venv, requirements,
test_requirements, py_version,
project):
self.root = root
self.venv = venv
self.requirements = requirements
self.test_requirements = test_requirements
self.py_version = py_version
self.project = project
def die(self, message, *args):
print(message % args, file=sys.stderr)
sys.exit(1)
def check_python_version(self):
if sys.version_info < (2, 6):
self.die("Need Python Version >= 2.6")
def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
"""Runs a command in an out-of-process shell.
Returns the output of that command. Working directory is self.root.
"""
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
self.die('Command "%s" failed.\n%s', ' '.join(cmd), output)
return (output, proc.returncode)
def run_command(self, cmd, redirect_output=True, check_exit_code=True):
return self.run_command_with_code(cmd, redirect_output,
check_exit_code)[0]
def get_distro(self):
if (os.path.exists('/etc/fedora-release') or
os.path.exists('/etc/redhat-release')):
return Fedora(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
else:
return Distro(
self.root, self.venv, self.requirements,
self.test_requirements, self.py_version, self.project)
def check_dependencies(self):
self.get_distro().install_virtualenv()
def create_virtualenv(self, no_site_packages=True):
"""Creates the virtual environment and installs PIP.
Creates the virtual environment and installs PIP only into the
virtual environment.
"""
if not os.path.isdir(self.venv):
print('Creating venv...', end=' ')
if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages',
self.venv])
else:
self.run_command(['virtualenv', '-q', self.venv])
print('done.')
else:
print("venv already exists...")
pass
def pip_install(self, *args):
self.run_command(['tools/with_venv.sh',
'pip', 'install', '--upgrade'] + list(args),
redirect_output=False)
def install_dependencies(self):
print('Installing dependencies with pip (this can take a while)...')
# First things first, make sure our venv has the latest pip and
# setuptools and pbr
self.pip_install('pip>=1.4')
self.pip_install('setuptools')
self.pip_install('pbr')
self.pip_install('-r', self.requirements, '-r', self.test_requirements)
def parse_args(self, argv):
"""Parses command-line arguments."""
parser = optparse.OptionParser()
parser.add_option('-n', '--no-site-packages',
action='store_true',
help="Do not inherit packages from global Python "
"install.")
return parser.parse_args(argv[1:])[0]
class Distro(InstallVenv):
def check_cmd(self, cmd):
return bool(self.run_command(['which', cmd],
check_exit_code=False).strip())
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if self.check_cmd('easy_install'):
print('Installing virtualenv via easy_install...', end=' ')
if self.run_command(['easy_install', 'virtualenv']):
print('Succeeded')
return
else:
print('Failed')
self.die('ERROR: virtualenv not found.\n\n%s development'
' requires virtualenv, please install it using your'
' favorite package management tool' % self.project)
class Fedora(Distro):
"""This covers all Fedora-based distributions.
Includes: Fedora, RHEL, CentOS, Scientific Linux
"""
def check_pkg(self, pkg):
return self.run_command_with_code(['rpm', '-q', pkg],
check_exit_code=False)[1] == 0
def install_virtualenv(self):
if self.check_cmd('virtualenv'):
return
if not self.check_pkg('python-virtualenv'):
self.die("Please install 'python-virtualenv'.")
super(Fedora, self).install_virtualenv()
| apache-2.0 |
pferreir/indico | indico/modules/events/editing/operations_test.py | 3 | 3736 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import pytest
from indico.modules.events.editing.models.editable import Editable, EditableType
from indico.modules.events.editing.models.revisions import EditingRevision, FinalRevisionState, InitialRevisionState
def test_cannot_undo_review_old_rev(dummy_contribution, dummy_user):
from indico.modules.events.editing.operations import InvalidEditableState, undo_review
editable = Editable(contribution=dummy_contribution, type=EditableType.paper)
rev1 = EditingRevision(editable=editable, submitter=dummy_user,
initial_state=InitialRevisionState.ready_for_review,
final_state=FinalRevisionState.needs_submitter_confirmation)
rev2 = EditingRevision(editable=editable, submitter=dummy_user,
initial_state=InitialRevisionState.needs_submitter_confirmation,
final_state=FinalRevisionState.needs_submitter_changes)
rev3 = EditingRevision(editable=editable, submitter=dummy_user,
initial_state=InitialRevisionState.ready_for_review)
with pytest.raises(InvalidEditableState):
undo_review(rev1)
with pytest.raises(InvalidEditableState):
undo_review(rev2)
undo_review(rev3)
@pytest.mark.parametrize(('is1', 'fs1', 'ok1', 'is2', 'fs2', 'ok2'), (
(InitialRevisionState.ready_for_review, FinalRevisionState.accepted, True,
None, None, None),
(InitialRevisionState.ready_for_review, FinalRevisionState.rejected, True,
None, None, None),
(InitialRevisionState.ready_for_review, FinalRevisionState.needs_submitter_changes, True,
None, None, None),
(InitialRevisionState.ready_for_review, FinalRevisionState.needs_submitter_confirmation, True,
InitialRevisionState.needs_submitter_confirmation, FinalRevisionState.none, False),
(InitialRevisionState.ready_for_review, FinalRevisionState.needs_submitter_confirmation, False,
InitialRevisionState.needs_submitter_confirmation, FinalRevisionState.accepted, True),
(InitialRevisionState.ready_for_review, FinalRevisionState.needs_submitter_confirmation, False,
InitialRevisionState.needs_submitter_confirmation, FinalRevisionState.needs_submitter_changes, True),
(InitialRevisionState.ready_for_review, FinalRevisionState.needs_submitter_changes, False,
InitialRevisionState.ready_for_review, FinalRevisionState.none, False),
))
def test_can_undo_review(db, dummy_contribution, dummy_user, is1, fs1, ok1, is2, fs2, ok2):
from indico.modules.events.editing.operations import InvalidEditableState, undo_review
editable = Editable(contribution=dummy_contribution, type=EditableType.paper)
rev1 = EditingRevision(editable=editable, submitter=dummy_user, initial_state=is1, final_state=fs1)
if is2 is not None:
rev2 = EditingRevision(editable=editable, submitter=dummy_user, initial_state=is2, final_state=fs2)
db.session.flush()
if ok1:
undo_review(rev1)
else:
pytest.raises(InvalidEditableState, undo_review, rev1)
if is2 is not None:
if ok2:
undo_review(rev2)
else:
pytest.raises(InvalidEditableState, undo_review, rev2)
db.session.expire(editable) # so a deleted revision shows up in the relationship
if ok1:
assert rev1.final_state == FinalRevisionState.none
assert len(editable.revisions) == 1
elif ok2:
assert rev2.final_state == FinalRevisionState.none
assert len(editable.revisions) == 2
| mit |
luistorresm/odoo | addons/account_check_writing/report/__init__.py | 446 | 1066 | # -*- 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 check_print
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/build/android/pylib/junit/test_runner.py | 1 | 2459 | # 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 json
import os
import tempfile
from devil.utils import cmd_helper
from pylib import constants
from pylib.results import json_results
class JavaTestRunner(object):
"""Runs java tests on the host."""
def __init__(self, args):
self._coverage_dir = args.coverage_dir
self._package_filter = args.package_filter
self._runner_filter = args.runner_filter
self._test_filter = args.test_filter
self._test_suite = args.test_suite
def SetUp(self):
pass
def RunTest(self, _test):
"""Runs junit tests from |self._test_suite|."""
with tempfile.NamedTemporaryFile() as json_file:
java_script = os.path.join(
constants.GetOutDirectory(), 'bin', 'helper', self._test_suite)
command = [java_script]
# Add Jar arguments.
jar_args = ['-test-jars', self._test_suite + '.jar',
'-json-results-file', json_file.name]
if self._test_filter:
jar_args.extend(['-gtest-filter', self._test_filter])
if self._package_filter:
jar_args.extend(['-package-filter', self._package_filter])
if self._runner_filter:
jar_args.extend(['-runner-filter', self._runner_filter])
command.extend(['--jar-args', '"%s"' % ' '.join(jar_args)])
# Add JVM arguments.
jvm_args = []
# TODO(mikecase): Add a --robolectric-dep-dir arg to test runner.
# Have this arg set by GN in the generated test runner scripts.
jvm_args += [
'-Drobolectric.dependency.dir=%s' %
os.path.join(constants.GetOutDirectory(),
'lib.java', 'third_party', 'robolectric')]
if self._coverage_dir:
if not os.path.exists(self._coverage_dir):
os.makedirs(self._coverage_dir)
elif not os.path.isdir(self._coverage_dir):
raise Exception('--coverage-dir takes a directory, not file path.')
jvm_args.append('-Demma.coverage.out.file=%s' % os.path.join(
self._coverage_dir, '%s.ec' % self._test_suite))
if jvm_args:
command.extend(['--jvm-args', '"%s"' % ' '.join(jvm_args)])
return_code = cmd_helper.RunCmd(command)
results_list = json_results.ParseResultsFromJson(
json.loads(json_file.read()))
return (results_list, return_code)
def TearDown(self):
pass
| gpl-3.0 |
hassoon3/odoo | addons/website_mail_group/models/mail_group.py | 321 | 2678 | # -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.safe_eval import safe_eval as eval
from openerp.addons.website.models.website import slug
class MailGroup(osv.Model):
_inherit = 'mail.group'
def message_get_email_values(self, cr, uid, id, notif_mail=None, context=None):
res = super(MailGroup, self).message_get_email_values(cr, uid, id, notif_mail=notif_mail, context=context)
group = self.browse(cr, uid, id, context=context)
base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
headers = {}
if res.get('headers'):
try:
headers = eval(res['headers'])
except Exception:
pass
headers.update({
'List-Archive': '<%s/groups/%s>' % (base_url, slug(group)),
'List-Subscribe': '<%s/groups>' % (base_url),
'List-Unsubscribe': '<%s/groups?unsubscribe>' % (base_url,),
})
res['headers'] = repr(headers)
return res
class MailMail(osv.Model):
_inherit = 'mail.mail'
def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
""" Short-circuit parent method for mail groups, replace the default
footer with one appropriate for mailing-lists."""
if mail.model == 'mail.group' and mail.res_id:
# no super() call on purpose, no private links that could be quoted!
group = self.pool['mail.group'].browse(cr, uid, mail.res_id, context=context)
base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
vals = {
'maillist': _('Mailing-List'),
'post_to': _('Post to'),
'unsub': _('Unsubscribe'),
'mailto': 'mailto:%s@%s' % (group.alias_name, group.alias_domain),
'group_url': '%s/groups/%s' % (base_url, slug(group)),
'unsub_url': '%s/groups?unsubscribe' % (base_url,),
}
footer = """_______________________________________________
%(maillist)s: %(group_url)s
%(post_to)s: %(mailto)s
%(unsub)s: %(unsub_url)s
""" % vals
body = tools.append_content_to_html(mail.body, footer, container_tag='div')
return body
else:
return super(MailMail, self).send_get_mail_body(cr, uid, mail,
partner=partner,
context=context)
| agpl-3.0 |
jetty840/ReplicatorG | skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/analyze_plugins/analyze_utilities/zoom_in.py | 8 | 1715 | """
This page is in the table of contents.
Zoom in is a mouse tool to zoom in the display at the point where the mouse was clicked, increasing the scale by a factor of two.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from skeinforge_application.skeinforge_plugins.analyze_plugins.analyze_utilities.mouse_tool_base import MouseToolBase
from fabmetheus_utilities import settings
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GPL 3.0'
def getNewMouseTool():
"Get a new mouse tool."
return ZoomIn()
class ZoomIn( MouseToolBase ):
"The zoom in mouse tool."
def button1( self, event, shift = False ):
"Print line text and connection line."
scaleSetting = self.window.repository.scale
scaleSetting.value *= self.getMultiplier()
delta = complex( float( event.x ) / float( self.window.screenSize.real ), float( event.y ) / float( self.window.screenSize.imag ) ) - self.window.canvasScreenCenter
delta *= 1.0 - 1.0 / self.getMultiplier()
scrollPaneCenter = self.window.getScrollPaneCenter() + delta
self.window.updateNewDestroyOld( scrollPaneCenter )
def click(self, event=None):
"Set the window mouse tool to this."
self.window.destroyMouseToolRaiseMouseButtons()
self.window.mouseTool = self
self.mouseButton['relief'] = settings.Tkinter.SUNKEN
def getReset( self, window ):
"Reset the mouse tool to default."
self.setWindowItems( window )
self.mouseButton = None
return self
def getMultiplier(self):
"Get the scale multiplier."
return 2.0
| gpl-2.0 |
gymnasium/xblock-leaderboard | leaderboards/tests/integration/test_forum.py | 3 | 1247 | from ddt import ddt, unpack, data
from selenium.common.exceptions import NoSuchElementException
from urlparse import urlparse
from xblockutils.base_test import SeleniumBaseTest
from .forum_scenarios import forum_scenarios
@ddt
class LeaderboardTestCase(SeleniumBaseTest):
module_name = __name__
default_css_selector = 'div.forum_leaderboard_block'
@unpack
@data(*forum_scenarios)
def test_options(self, page, links, ol):
self.go_to_page(page)
line_items = [
item for item in
self.browser.find_elements_by_css_selector('.forum-leaderboard li')
]
item_text = [item.text for item in line_items]
self.assertEqual(item_text, ol)
parsed_url = urlparse(self.browser.current_url)
base_url = "{}://{}".format(parsed_url.scheme, parsed_url.netloc)
page_links = []
for item in line_items:
try:
page_links.append(item.find_element_by_css_selector('a').get_attribute('href'))
except NoSuchElementException:
page_links.append(None)
links = [(base_url + link) if link else None for link in links]
self.assertEqual(
page_links,
links,
)
| agpl-3.0 |
Badg/py_hypergolix | hypergolix/lawyer.py | 2 | 7975 | '''
LICENSING
-------------------------------------------------
hypergolix: A python Golix client.
Copyright (C) 2016 Muterra, Inc.
Contributors
------------
Nick Badger
badg@muterra.io | badg@nickbadger.com | nickbadger.com
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 USA
------------------------------------------------------
'''
# External dependencies
import logging
import collections
import weakref
import queue
import threading
import traceback
import asyncio
import loopa
import pathlib
from golix import ThirdParty
from golix import SecondParty
from golix import Ghid
from golix import Secret
from golix import ParseError
from golix import SecurityError
from golix.crypto_utils import generate_ghidlist_parser
from golix._getlow import GIDC
from golix._getlow import GEOC
from golix._getlow import GOBS
from golix._getlow import GOBD
from golix._getlow import GDXX
from golix._getlow import GARQ
# Internal dependencies
from .persistence import _GidcLite
from .persistence import _GeocLite
from .persistence import _GobsLite
from .persistence import _GobdLite
from .persistence import _GdxxLite
from .persistence import _GarqLite
from .gao import GAO
from .hypothetical import API
from .hypothetical import public_api
from .hypothetical import fixture_api
from .hypothetical import fixture_noop
from .hypothetical import fixture_return
from .exceptions import HypergolixException
from .exceptions import RemoteNak
from .exceptions import MalformedGolixPrimitive
from .exceptions import VerificationFailure
from .exceptions import UnboundContainer
from .exceptions import InvalidIdentity
from .exceptions import DoesNotExist
from .exceptions import AlreadyDebound
from .exceptions import InvalidTarget
from .exceptions import StillBoundWarning
from .exceptions import RequestError
from .exceptions import InconsistentAuthor
from .exceptions import IllegalDynamicFrame
from .exceptions import IntegrityError
from .exceptions import UnavailableUpstream
from .utils import weak_property
from .utils import readonly_property
from .utils import TruthyLock
from .utils import SetMap
from .utils import WeakSetMap
from .utils import _generate_threadnames
# ###############################################
# Boilerplate
# ###############################################
logger = logging.getLogger(__name__)
# Control * imports.
__all__ = [
# 'PersistenceCore',
]
# ###############################################
# Lib
# ###############################################
class LawyerCore(metaclass=API):
''' Enforces authorship requirements, including both having a known
entity as author/recipient and consistency for eg. bindings and
debindings.
Threadsafe.
'''
_librarian = weak_property('__librarian')
@fixture_api
def __init__(self, librarian, *args, **kwargs):
super(LawyerCore.__fixture__, self).__init__(*args, **kwargs)
self._librarian = librarian
def assemble(self, librarian):
# Call before using.
self._librarian = librarian
@fixture_return(True)
@public_api
async def _validate_author(self, obj):
try:
author = await self._librarian.summarize(obj.author)
except KeyError as exc:
raise InvalidIdentity('Unknown author: ' +
str(obj.author)) from exc
else:
if not isinstance(author, _GidcLite):
raise InvalidIdentity('Invalid author: ' + str(author))
return True
async def validate_gidc(self, obj):
''' GIDC need no validation.
'''
return True
async def validate_geoc(self, obj):
''' Ensure author is known and valid.
'''
return (await self._validate_author(obj))
async def validate_gobs(self, obj):
''' Ensure author is known and valid.
'''
return (await self._validate_author(obj))
async def validate_gobd(self, obj):
''' Ensure author is known and valid, and consistent with the
previous author for the binding (if it already exists).
'''
await self._validate_author(obj)
if obj.counter > 0:
try:
existing = await self._librarian.summarize(obj.ghid)
except KeyError:
logger.warning(str(obj) + ' previous binding missing; ' +
'cannot validate author self-consistency.')
else:
if existing.author != obj.author:
raise InconsistentAuthor('Existing author for ' +
str(obj) + ': ' +
str(existing.author) +
' (existing) vs ' +
str(obj.author) + ' (attempted)')
return True
async def validate_gdxx(self, obj, target_obj=None):
''' Ensure author is known and valid, and consistent with the
previous author for the binding.
If other is not None, specifically checks it against that object
instead of obtaining it from librarian.
'''
await self._validate_author(obj)
try:
if target_obj is None:
existing = await self._librarian.summarize(obj.target)
else:
existing = target_obj
except KeyError:
logger.debug(str(obj) + ' target missing from librarian; ' +
'cannot validate author self-consistency: ' +
str(obj.target))
else:
if isinstance(existing, _GarqLite):
if existing.recipient != obj.author:
raise InconsistentAuthor('Existing author for ' +
str(obj) + ': ' +
str(existing.recipient) +
' (existing) vs ' +
str(obj.author) + ' (attempted)')
else:
if existing.author != obj.author:
raise InconsistentAuthor('Existing author for ' +
str(obj) + ': ' +
str(existing.author) +
' (existing) vs ' +
str(obj.author) + ' (attempted)')
return True
async def validate_garq(self, obj):
''' Validate recipient.
'''
try:
recipient = await self._librarian.summarize(obj.recipient)
except KeyError as exc:
raise InvalidIdentity('Unknown recipient: ' +
str(obj.recipient)) from exc
else:
if not isinstance(recipient, _GidcLite):
raise InvalidIdentity('Invalid recipient: ' + str(recipient))
return True
| unlicense |
Integral-Technology-Solutions/ConfigNOW-4.3 | Lib/xml/dom/TreeWalker.py | 3 | 6802 | ########################################################################
#
# File Name: TreeWalker.py
#
# Documentation: http://docs.4suite.com/4DOM/TreeWalker.py.html
#
"""
Tree Walker from DOM Level 2. Allows multi-directional iteration over nodes.
WWW: http://4suite.com/4DOM e-mail: support@4suite.com
Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserved.
See http://4suite.com/COPYRIGHT for license and copyright information
"""
from NodeFilter import NodeFilter
from xml.dom import NoModificationAllowedErr
from xml.dom import NotSupportedErr
class TreeWalker:
def __init__(self, root, whatToShow, filter, expandEntityReferences):
self.__dict__['__root'] = root
self.__dict__['__whatToShow'] = whatToShow
self.__dict__['__filter'] = filter
self.__dict__['__expandEntityReferences'] = expandEntityReferences
self.__dict__['__currentNode'] = root
### Attribute Access Methods -- xxx.attr ###
def __getattr__(self, name):
attrFunc = self._readComputedAttrs.get(name)
if attrFunc:
return attrFunc(self)
def __setattr__(self, name, value):
#Make sure attribute is not read-only
if name in self.__class__._readOnlyAttrs:
raise NoModificationAllowedErr()
#If it's computed execute that function
attrFunc = self.__class__._writeComputedAttrs.get(name)
if attrFunc:
attrFunc(self, value)
#Otherwise, just set the attribute
else:
self.__dict__[name] = value
### Attribute Methods -- xxx._get_attr() ###
def _get_root(self):
return self.__dict__['__root']
def _get_filter(self):
return self.__dict__['__filter']
def _get_whatToShow(self):
return self.__dict__['__whatToShow']
def _get_expandEntityReferences(self):
return self.__dict__['__expandEntityReferences']
def _get_currentNode(self):
return self.__dict__['__currentNode']
def _set_currentNode(self, value):
if value == None:
raise NotSupportedErr()
self.__dict__['__currentNode'] = value
### Methods ###
def parentNode(self):
next_node = None
if self.__dict__['__currentNode'] != self.__dict__['__root']:
next_node = self.__dict__['__currentNode']._get_parentNode()
while next_node and next_node != self.__dict__['__root'] \
and not (self.__checkWhatToShow(next_node) \
and self.__checkFilter(next_node) == NodeFilter.FILTER_ACCEPT):
next_node = next_node._get_parentNode()
if next_node:
self.__dict__['__currentNode'] = next_node
return next_node
def firstChild(self):
next_node = None
if self.__checkFilter(self.__dict__['__currentNode']) != NodeFilter.FILTER_REJECT:
next_node = self.__dict__['__currentNode']._get_firstChild()
while next_node and not (self.__checkWhatToShow(next_node) \
and self.__checkFilter(next_node) == NodeFilter.FILTER_ACCEPT):
next_node = next_node._get_nextSibling()
if next_node:
self.__dict__['__currentNode'] = next_node
return next_node
def lastChild(self):
next_node = None
if self.__checkFilter(self.__dict__['__currentNode']) != NodeFilter.FILTER_REJECT:
next_node = self.__dict__['__currentNode']._get_lastChild()
while next_node and not (self.__checkWhatToShow(next_node) \
and self.__checkFilter(next_node) == NodeFilter.FILTER_ACCEPT):
next_node = next_node._get_previousSibling()
if next_node:
self.__dict__['__currentNode'] = next_node
return next_node
def previousSibling(self):
prev_node = None
if self.__dict__['__currentNode'] != self.__root:
prev_node = self.__dict__['__currentNode']._get_previousSibling()
while prev_node and not (self.__checkWhatToShow(prev_node) \
and self.__checkFilter(prev_node) == NodeFilter.FILTER_ACCEPT):
prev_node = prev_node._get_previousSibling()
if prev_node:
self.__dict__['__currentNode'] = prev_node
return prev_node
def nextSibling(self):
next_node = None
if self.__dict__['__currentNode'] != self.__root:
next_node = self.__dict__['__currentNode']._get_nextSibling()
while next_node and not (self.__checkWhatToShow(next_node) and self.__checkFilter(next_node) == NodeFilter.FILTER_ACCEPT):
next_node = next_node._get_nextSibling()
if next_node:
self.__dict__['__currentNode'] = next_node
return next_node
def nextNode(self):
next_node = self.__advance()
while next_node and not (self.__checkWhatToShow(next_node) and self.__checkFilter(next_node) == NodeFilter.FILTER_ACCEPT):
next_node = self.__advance()
return next_node
def previousNode(self):
prev_node = self.__regress()
while prev_node and not (self.__checkWhatToShow(prev_node) and self.__checkFilter(prev_node) == NodeFilter.FILTER_ACCEPT):
prev_node = self.__regress()
return prev_node
def __advance(self):
if self.firstChild():
return self.__dict__['__currentNode']
if self.nextSibling():
return self.__dict__['__currentNode']
if self.parentNode():
return self.nextSibling()
return None
def __regress(self):
if self.previousSibling():
self.lastChild()
return self.__dict__['__currentNode']
if self.parentNode():
return self.__dict__['__currentNode']
return None
def __checkWhatToShow(self, node):
show_bit = 1 << (node._get_nodeType() - 1)
return self.__dict__['__whatToShow'] & show_bit
def __checkFilter(self, node):
if self.__dict__['__filter']:
return self.__dict__['__filter'].acceptNode(node)
else:
return NodeFilter.FILTER_ACCEPT
### Attribute Access Mappings ###
_readComputedAttrs = {'root':_get_root,
'whatToShow':_get_whatToShow,
'filter':_get_filter,
'expandEntityReferences':_get_expandEntityReferences,
'currentNode':_get_currentNode
}
_writeComputedAttrs = {'currentNode': _set_currentNode
}
# Create the read-only list of attributes
_readOnlyAttrs = filter(lambda k,m=_writeComputedAttrs: not m.has_key(k),
_readComputedAttrs.keys())
| mit |
rameshvs/nipype | nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py | 5 | 5518 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.slicer.registration.brainsfit import BRAINSFit
def test_BRAINSFit_inputs():
input_map = dict(NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_00 ',
),
NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_01 ',
),
NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02=dict(argstr='--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ',
),
ROIAutoClosingSize=dict(argstr='--ROIAutoClosingSize %f',
),
ROIAutoDilateSize=dict(argstr='--ROIAutoDilateSize %f',
),
args=dict(argstr='%s',
),
backgroundFillValue=dict(argstr='--backgroundFillValue %f',
),
bsplineTransform=dict(argstr='--bsplineTransform %s',
hash_files=False,
),
costFunctionConvergenceFactor=dict(argstr='--costFunctionConvergenceFactor %f',
),
costMetric=dict(argstr='--costMetric %s',
),
debugLevel=dict(argstr='--debugLevel %d',
),
environ=dict(nohash=True,
usedefault=True,
),
failureExitCode=dict(argstr='--failureExitCode %d',
),
fixedBinaryVolume=dict(argstr='--fixedBinaryVolume %s',
),
fixedVolume=dict(argstr='--fixedVolume %s',
),
fixedVolumeTimeIndex=dict(argstr='--fixedVolumeTimeIndex %d',
),
forceMINumberOfThreads=dict(argstr='--forceMINumberOfThreads %d',
),
gui=dict(argstr='--gui ',
),
histogramMatch=dict(argstr='--histogramMatch ',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
initialTransform=dict(argstr='--initialTransform %s',
),
initializeTransformMode=dict(argstr='--initializeTransformMode %s',
),
interpolationMode=dict(argstr='--interpolationMode %s',
),
linearTransform=dict(argstr='--linearTransform %s',
hash_files=False,
),
maskInferiorCutOffFromCenter=dict(argstr='--maskInferiorCutOffFromCenter %f',
),
maskProcessingMode=dict(argstr='--maskProcessingMode %s',
),
maxBSplineDisplacement=dict(argstr='--maxBSplineDisplacement %f',
),
maximumStepLength=dict(argstr='--maximumStepLength %f',
),
medianFilterSize=dict(argstr='--medianFilterSize %s',
sep=',',
),
minimumStepLength=dict(argstr='--minimumStepLength %s',
sep=',',
),
movingBinaryVolume=dict(argstr='--movingBinaryVolume %s',
),
movingVolume=dict(argstr='--movingVolume %s',
),
movingVolumeTimeIndex=dict(argstr='--movingVolumeTimeIndex %d',
),
numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d',
),
numberOfIterations=dict(argstr='--numberOfIterations %s',
sep=',',
),
numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d',
),
numberOfSamples=dict(argstr='--numberOfSamples %d',
),
numberOfThreads=dict(argstr='--numberOfThreads %d',
),
outputFixedVolumeROI=dict(argstr='--outputFixedVolumeROI %s',
hash_files=False,
),
outputMovingVolumeROI=dict(argstr='--outputMovingVolumeROI %s',
hash_files=False,
),
outputTransform=dict(argstr='--outputTransform %s',
hash_files=False,
),
outputVolume=dict(argstr='--outputVolume %s',
hash_files=False,
),
outputVolumePixelType=dict(argstr='--outputVolumePixelType %s',
),
permitParameterVariation=dict(argstr='--permitParameterVariation %s',
sep=',',
),
projectedGradientTolerance=dict(argstr='--projectedGradientTolerance %f',
),
promptUser=dict(argstr='--promptUser ',
),
relaxationFactor=dict(argstr='--relaxationFactor %f',
),
removeIntensityOutliers=dict(argstr='--removeIntensityOutliers %f',
),
reproportionScale=dict(argstr='--reproportionScale %f',
),
scaleOutputValues=dict(argstr='--scaleOutputValues ',
),
skewScale=dict(argstr='--skewScale %f',
),
splineGridSize=dict(argstr='--splineGridSize %s',
sep=',',
),
strippedOutputTransform=dict(argstr='--strippedOutputTransform %s',
hash_files=False,
),
terminal_output=dict(mandatory=True,
nohash=True,
),
transformType=dict(argstr='--transformType %s',
sep=',',
),
translationScale=dict(argstr='--translationScale %f',
),
useAffine=dict(argstr='--useAffine ',
),
useBSpline=dict(argstr='--useBSpline ',
),
useCachingOfBSplineWeightsMode=dict(argstr='--useCachingOfBSplineWeightsMode %s',
),
useExplicitPDFDerivativesMode=dict(argstr='--useExplicitPDFDerivativesMode %s',
),
useRigid=dict(argstr='--useRigid ',
),
useScaleSkewVersor3D=dict(argstr='--useScaleSkewVersor3D ',
),
useScaleVersor3D=dict(argstr='--useScaleVersor3D ',
),
writeTransformOnFailure=dict(argstr='--writeTransformOnFailure ',
),
)
inputs = BRAINSFit.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_BRAINSFit_outputs():
output_map = dict(bsplineTransform=dict(),
linearTransform=dict(),
outputFixedVolumeROI=dict(),
outputMovingVolumeROI=dict(),
outputTransform=dict(),
outputVolume=dict(),
strippedOutputTransform=dict(),
)
outputs = BRAINSFit.output_spec()
for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| bsd-3-clause |
GbalsaC/bitnamiP | common/lib/capa/capa/customrender.py | 104 | 5661 | """
This has custom renderers: classes that know how to render certain problem tags (e.g. <math> and
<solution>) to html.
These tags do not have state, so they just get passed the system (for access to render_template),
and the xml element.
"""
import logging
import re
from cgi import escape as cgi_escape
from lxml import etree
import xml.sax.saxutils as saxutils
from .registry import TagRegistry
log = logging.getLogger(__name__)
registry = TagRegistry()
#-----------------------------------------------------------------------------
class MathRenderer(object):
tags = ['math']
def __init__(self, system, xml):
r"""
Render math using latex-like formatting.
Examples:
<math>$\displaystyle U(r)=4 U_0 $</math>
<math>$r_0$</math>
We convert these to [mathjax]...[/mathjax] and [mathjaxinline]...[/mathjaxinline]
TODO: use shorter tags (but this will require converting problem XML files!)
"""
self.system = system
self.xml = xml
mathstr = re.sub(r'\$(.*)\$', r'[mathjaxinline]\1[/mathjaxinline]', xml.text)
mtag = 'mathjax'
if r'\displaystyle' not in mathstr:
mtag += 'inline'
else:
mathstr = mathstr.replace(r'\displaystyle', '')
self.mathstr = mathstr.replace('mathjaxinline]', '%s]' % mtag)
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
# TODO: why are there nested html tags here?? Why are there html tags at all, in fact?
html = '<html><html>%s</html><html>%s</html></html>' % (
self.mathstr, saxutils.escape(self.xml.tail))
try:
xhtml = etree.XML(html)
except Exception as err:
if self.system.DEBUG:
msg = '<html><div class="inline-error"><p>Error %s</p>' % (
str(err).replace('<', '<'))
msg += ('<p>Failed to construct math expression from <pre>%s</pre></p>' %
html.replace('<', '<'))
msg += "</div></html>"
log.error(msg)
return etree.XML(msg)
else:
raise
return xhtml
registry.register(MathRenderer)
#-----------------------------------------------------------------------------
class SolutionRenderer(object):
"""
A solution is just a <span>...</span> which is given an ID, that is used for displaying an
extended answer (a problem "solution") after "show answers" is pressed.
Note that the solution content is NOT rendered and returned in the HTML. It is obtained by an
ajax call.
"""
tags = ['solution']
def __init__(self, system, xml):
self.system = system
self.id = xml.get('id')
def get_html(self):
context = {'id': self.id}
html = self.system.render_template("solutionspan.html", context)
return etree.XML(html)
registry.register(SolutionRenderer)
#-----------------------------------------------------------------------------
class TargetedFeedbackRenderer(object):
"""
A targeted feedback is just a <span>...</span> that is used for displaying an
extended piece of feedback to students if they incorrectly answered a question.
"""
tags = ['targetedfeedback']
def __init__(self, system, xml):
self.system = system
self.xml = xml
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
html = '<section class="targeted-feedback-span"><span>{}</span></section>'.format(etree.tostring(self.xml))
try:
xhtml = etree.XML(html)
except Exception as err: # pylint: disable=broad-except
if self.system.DEBUG:
msg = """
<html>
<div class="inline-error">
<p>Error {err}</p>
<p>Failed to construct targeted feedback from <pre>{html}</pre></p>
</div>
</html>
""".format(err=cgi_escape(err), html=cgi_escape(html))
log.error(msg)
return etree.XML(msg)
else:
raise
return xhtml
registry.register(TargetedFeedbackRenderer)
#-----------------------------------------------------------------------------
class ClarificationRenderer(object):
"""
A clarification appears as an inline icon which reveals more information when the user
hovers over it.
e.g. <p>Enter the ROA <clarification>Return on Assets</clarification> for 2015:</p>
"""
tags = ['clarification']
def __init__(self, system, xml):
self.system = system
# Get any text content found inside this tag prior to the first child tag. It may be a string or None type.
initial_text = xml.text if xml.text else ''
self.inner_html = initial_text + ''.join(etree.tostring(element) for element in xml) # pylint: disable=no-member
self.tail = xml.tail
def get_html(self):
"""
Return the contents of this tag, rendered to html, as an etree element.
"""
context = {'clarification': self.inner_html}
html = self.system.render_template("clarification.html", context)
xml = etree.XML(html) # pylint: disable=no-member
# We must include any text that was following our original <clarification>...</clarification> XML node.:
xml.tail = self.tail
return xml
registry.register(ClarificationRenderer)
| agpl-3.0 |
DanteOnline/free-art | venv/lib/python3.4/site-packages/pip/_vendor/colorama/initialise.py | 485 | 1917 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = None
orig_stderr = None
wrapped_stdout = None
wrapped_stderr = None
atexit_done = False
def reset_all():
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
AnsiToWin32(orig_stdout).reset_all()
def init(autoreset=False, convert=None, strip=None, wrap=True):
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
global orig_stdout, orig_stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
if sys.stdout is None:
wrapped_stdout = None
else:
sys.stdout = wrapped_stdout = \
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
if sys.stderr is None:
wrapped_stderr = None
else:
sys.stderr = wrapped_stderr = \
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
global atexit_done
if not atexit_done:
atexit.register(reset_all)
atexit_done = True
def deinit():
if orig_stdout is not None:
sys.stdout = orig_stdout
if orig_stderr is not None:
sys.stderr = orig_stderr
@contextlib.contextmanager
def colorama_text(*args, **kwargs):
init(*args, **kwargs)
try:
yield
finally:
deinit()
def reinit():
if wrapped_stdout is not None:
sys.stdout = wrapped_stdout
if wrapped_stderr is not None:
sys.stderr = wrapped_stderr
def wrap_stream(stream, convert, strip, autoreset, wrap):
if wrap:
wrapper = AnsiToWin32(stream,
convert=convert, strip=strip, autoreset=autoreset)
if wrapper.should_wrap():
stream = wrapper.stream
return stream
| gpl-3.0 |
abtink/openthread | tools/harness-automation/cases_R140/router_5_3_11.py | 18 | 1878 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 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.
# 3. Neither the name of the copyright holder 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 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.
#
from autothreadharness.harness_case import HarnessCase
import unittest
class Router_5_3_11(HarnessCase):
role = HarnessCase.ROLE_ROUTER
case = '5 3 11'
golden_devices_required = 2
def on_dialog(self, dialog, title):
pass
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
t-k-/beautiful-soup | bs4/dammit.py | 408 | 29302 | # -*- coding: utf-8 -*-
"""Beautiful Soup bonus library: Unicode, Dammit
This library converts a bytestream to Unicode through any means
necessary. It is heavily based on code from Mark Pilgrim's Universal
Feed Parser. It works best on XML and XML, but it does not rewrite the
XML or HTML to reflect a new encoding; that's the tree builder's job.
"""
import codecs
from htmlentitydefs import codepoint2name
import re
import logging
import string
# Import a library to autodetect character encodings.
chardet_type = None
try:
# First try the fast C implementation.
# PyPI package: cchardet
import cchardet
def chardet_dammit(s):
return cchardet.detect(s)['encoding']
except ImportError:
try:
# Fall back to the pure Python implementation
# Debian package: python-chardet
# PyPI package: chardet
import chardet
def chardet_dammit(s):
return chardet.detect(s)['encoding']
#import chardet.constants
#chardet.constants._debug = 1
except ImportError:
# No chardet available.
def chardet_dammit(s):
return None
# Available from http://cjkpython.i18n.org/.
try:
import iconv_codec
except ImportError:
pass
xml_encoding_re = re.compile(
'^<\?.*encoding=[\'"](.*?)[\'"].*\?>'.encode(), re.I)
html_meta_re = re.compile(
'<\s*meta[^>]+charset\s*=\s*["\']?([^>]*?)[ /;\'">]'.encode(), re.I)
class EntitySubstitution(object):
"""Substitute XML or HTML entities for the corresponding characters."""
def _populate_class_variables():
lookup = {}
reverse_lookup = {}
characters_for_re = []
for codepoint, name in list(codepoint2name.items()):
character = unichr(codepoint)
if codepoint != 34:
# There's no point in turning the quotation mark into
# ", unless it happens within an attribute value, which
# is handled elsewhere.
characters_for_re.append(character)
lookup[character] = name
# But we do want to turn " into the quotation mark.
reverse_lookup[name] = character
re_definition = "[%s]" % "".join(characters_for_re)
return lookup, reverse_lookup, re.compile(re_definition)
(CHARACTER_TO_HTML_ENTITY, HTML_ENTITY_TO_CHARACTER,
CHARACTER_TO_HTML_ENTITY_RE) = _populate_class_variables()
CHARACTER_TO_XML_ENTITY = {
"'": "apos",
'"': "quot",
"&": "amp",
"<": "lt",
">": "gt",
}
BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
"&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
")")
AMPERSAND_OR_BRACKET = re.compile("([<>&])")
@classmethod
def _substitute_html_entity(cls, matchobj):
entity = cls.CHARACTER_TO_HTML_ENTITY.get(matchobj.group(0))
return "&%s;" % entity
@classmethod
def _substitute_xml_entity(cls, matchobj):
"""Used with a regular expression to substitute the
appropriate XML entity for an XML special character."""
entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)]
return "&%s;" % entity
@classmethod
def quoted_attribute_value(self, value):
"""Make a value into a quoted XML attribute, possibly escaping it.
Most strings will be quoted using double quotes.
Bob's Bar -> "Bob's Bar"
If a string contains double quotes, it will be quoted using
single quotes.
Welcome to "my bar" -> 'Welcome to "my bar"'
If a string contains both single and double quotes, the
double quotes will be escaped, and the string will be quoted
using double quotes.
Welcome to "Bob's Bar" -> "Welcome to "Bob's bar"
"""
quote_with = '"'
if '"' in value:
if "'" in value:
# The string contains both single and double
# quotes. Turn the double quotes into
# entities. We quote the double quotes rather than
# the single quotes because the entity name is
# """ whether this is HTML or XML. If we
# quoted the single quotes, we'd have to decide
# between ' and &squot;.
replace_with = """
value = value.replace('"', replace_with)
else:
# There are double quotes but no single quotes.
# We can use single quotes to quote the attribute.
quote_with = "'"
return quote_with + value + quote_with
@classmethod
def substitute_xml(cls, value, make_quoted_attribute=False):
"""Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will become &. If you want ampersands
that appear to be part of an entity definition to be left
alone, use substitute_xml_containing_entities() instead.
:param make_quoted_attribute: If True, then the string will be
quoted, as befits an attribute value.
"""
# Escape angle brackets and ampersands.
value = cls.AMPERSAND_OR_BRACKET.sub(
cls._substitute_xml_entity, value)
if make_quoted_attribute:
value = cls.quoted_attribute_value(value)
return value
@classmethod
def substitute_xml_containing_entities(
cls, value, make_quoted_attribute=False):
"""Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign will
become <, the greater-than sign will become >, and any
ampersands that are not part of an entity defition will
become &.
:param make_quoted_attribute: If True, then the string will be
quoted, as befits an attribute value.
"""
# Escape angle brackets, and ampersands that aren't part of
# entities.
value = cls.BARE_AMPERSAND_OR_BRACKET.sub(
cls._substitute_xml_entity, value)
if make_quoted_attribute:
value = cls.quoted_attribute_value(value)
return value
@classmethod
def substitute_html(cls, s):
"""Replace certain Unicode characters with named HTML entities.
This differs from data.encode(encoding, 'xmlcharrefreplace')
in that the goal is to make the result more readable (to those
with ASCII displays) rather than to recover from
errors. There's absolutely nothing wrong with a UTF-8 string
containg a LATIN SMALL LETTER E WITH ACUTE, but replacing that
character with "é" will make it more readable to some
people.
"""
return cls.CHARACTER_TO_HTML_ENTITY_RE.sub(
cls._substitute_html_entity, s)
class EncodingDetector:
"""Suggests a number of possible encodings for a bytestring.
Order of precedence:
1. Encodings you specifically tell EncodingDetector to try first
(the override_encodings argument to the constructor).
2. An encoding declared within the bytestring itself, either in an
XML declaration (if the bytestring is to be interpreted as an XML
document), or in a <meta> tag (if the bytestring is to be
interpreted as an HTML document.)
3. An encoding detected through textual analysis by chardet,
cchardet, or a similar external library.
4. UTF-8.
5. Windows-1252.
"""
def __init__(self, markup, override_encodings=None, is_html=False):
self.override_encodings = override_encodings or []
self.chardet_encoding = None
self.is_html = is_html
self.declared_encoding = None
# First order of business: strip a byte-order mark.
self.markup, self.sniffed_encoding = self.strip_byte_order_mark(markup)
def _usable(self, encoding, tried):
if encoding is not None:
encoding = encoding.lower()
if encoding not in tried:
tried.add(encoding)
return True
return False
@property
def encodings(self):
"""Yield a number of encodings that might work for this markup."""
tried = set()
for e in self.override_encodings:
if self._usable(e, tried):
yield e
# Did the document originally start with a byte-order mark
# that indicated its encoding?
if self._usable(self.sniffed_encoding, tried):
yield self.sniffed_encoding
# Look within the document for an XML or HTML encoding
# declaration.
if self.declared_encoding is None:
self.declared_encoding = self.find_declared_encoding(
self.markup, self.is_html)
if self._usable(self.declared_encoding, tried):
yield self.declared_encoding
# Use third-party character set detection to guess at the
# encoding.
if self.chardet_encoding is None:
self.chardet_encoding = chardet_dammit(self.markup)
if self._usable(self.chardet_encoding, tried):
yield self.chardet_encoding
# As a last-ditch effort, try utf-8 and windows-1252.
for e in ('utf-8', 'windows-1252'):
if self._usable(e, tried):
yield e
@classmethod
def strip_byte_order_mark(cls, data):
"""If a byte-order mark is present, strip it and return the encoding it implies."""
encoding = None
if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == b'\xff\xfe') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == b'\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == b'\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == b'\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
return data, encoding
@classmethod
def find_declared_encoding(cls, markup, is_html=False, search_entire_document=False):
"""Given a document, tries to find its declared encoding.
An XML encoding is declared at the beginning of the document.
An HTML encoding is declared in a <meta> tag, hopefully near the
beginning of the document.
"""
if search_entire_document:
xml_endpos = html_endpos = len(markup)
else:
xml_endpos = 1024
html_endpos = max(2048, int(len(markup) * 0.05))
declared_encoding = None
declared_encoding_match = xml_encoding_re.search(markup, endpos=xml_endpos)
if not declared_encoding_match and is_html:
declared_encoding_match = html_meta_re.search(markup, endpos=html_endpos)
if declared_encoding_match is not None:
declared_encoding = declared_encoding_match.groups()[0].decode(
'ascii')
if declared_encoding:
return declared_encoding.lower()
return None
class UnicodeDammit:
"""A class for detecting the encoding of a *ML document and
converting it to a Unicode string. If the source encoding is
windows-1252, can replace MS smart quotes with their HTML or XML
equivalents."""
# This dictionary maps commonly seen values for "charset" in HTML
# meta tags to the corresponding Python codec names. It only covers
# values that aren't in Python's aliases and can't be determined
# by the heuristics in find_codec.
CHARSET_ALIASES = {"macintosh": "mac-roman",
"x-sjis": "shift-jis"}
ENCODINGS_WITH_SMART_QUOTES = [
"windows-1252",
"iso-8859-1",
"iso-8859-2",
]
def __init__(self, markup, override_encodings=[],
smart_quotes_to=None, is_html=False):
self.smart_quotes_to = smart_quotes_to
self.tried_encodings = []
self.contains_replacement_characters = False
self.is_html = is_html
self.detector = EncodingDetector(markup, override_encodings, is_html)
# Short-circuit if the data is in Unicode to begin with.
if isinstance(markup, unicode) or markup == '':
self.markup = markup
self.unicode_markup = unicode(markup)
self.original_encoding = None
return
# The encoding detector may have stripped a byte-order mark.
# Use the stripped markup from this point on.
self.markup = self.detector.markup
u = None
for encoding in self.detector.encodings:
markup = self.detector.markup
u = self._convert_from(encoding)
if u is not None:
break
if not u:
# None of the encodings worked. As an absolute last resort,
# try them again with character replacement.
for encoding in self.detector.encodings:
if encoding != "ascii":
u = self._convert_from(encoding, "replace")
if u is not None:
logging.warning(
"Some characters could not be decoded, and were "
"replaced with REPLACEMENT CHARACTER.")
self.contains_replacement_characters = True
break
# If none of that worked, we could at this point force it to
# ASCII, but that would destroy so much data that I think
# giving up is better.
self.unicode_markup = u
if not u:
self.original_encoding = None
def _sub_ms_char(self, match):
"""Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character."""
orig = match.group(1)
if self.smart_quotes_to == 'ascii':
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get(orig)
if type(sub) == tuple:
if self.smart_quotes_to == 'xml':
sub = '&#x'.encode() + sub[1].encode() + ';'.encode()
else:
sub = '&'.encode() + sub[0].encode() + ';'.encode()
else:
sub = sub.encode()
return sub
def _convert_from(self, proposed, errors="strict"):
proposed = self.find_codec(proposed)
if not proposed or (proposed, errors) in self.tried_encodings:
return None
self.tried_encodings.append((proposed, errors))
markup = self.markup
# Convert smart quotes to HTML if coming from an encoding
# that might have them.
if (self.smart_quotes_to is not None
and proposed in self.ENCODINGS_WITH_SMART_QUOTES):
smart_quotes_re = b"([\x80-\x9f])"
smart_quotes_compiled = re.compile(smart_quotes_re)
markup = smart_quotes_compiled.sub(self._sub_ms_char, markup)
try:
#print "Trying to convert document to %s (errors=%s)" % (
# proposed, errors)
u = self._to_unicode(markup, proposed, errors)
self.markup = u
self.original_encoding = proposed
except Exception as e:
#print "That didn't work!"
#print e
return None
#print "Correct encoding: %s" % proposed
return self.markup
def _to_unicode(self, data, encoding, errors="strict"):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
return unicode(data, encoding, errors)
@property
def declared_html_encoding(self):
if not self.is_html:
return None
return self.detector.declared_encoding
def find_codec(self, charset):
value = (self._codec(self.CHARSET_ALIASES.get(charset, charset))
or (charset and self._codec(charset.replace("-", "")))
or (charset and self._codec(charset.replace("-", "_")))
or (charset and charset.lower())
or charset
)
if value:
return value.lower()
return None
def _codec(self, charset):
if not charset:
return charset
codec = None
try:
codecs.lookup(charset)
codec = charset
except (LookupError, ValueError):
pass
return codec
# A partial mapping of ISO-Latin-1 to HTML entities/XML numeric entities.
MS_CHARS = {b'\x80': ('euro', '20AC'),
b'\x81': ' ',
b'\x82': ('sbquo', '201A'),
b'\x83': ('fnof', '192'),
b'\x84': ('bdquo', '201E'),
b'\x85': ('hellip', '2026'),
b'\x86': ('dagger', '2020'),
b'\x87': ('Dagger', '2021'),
b'\x88': ('circ', '2C6'),
b'\x89': ('permil', '2030'),
b'\x8A': ('Scaron', '160'),
b'\x8B': ('lsaquo', '2039'),
b'\x8C': ('OElig', '152'),
b'\x8D': '?',
b'\x8E': ('#x17D', '17D'),
b'\x8F': '?',
b'\x90': '?',
b'\x91': ('lsquo', '2018'),
b'\x92': ('rsquo', '2019'),
b'\x93': ('ldquo', '201C'),
b'\x94': ('rdquo', '201D'),
b'\x95': ('bull', '2022'),
b'\x96': ('ndash', '2013'),
b'\x97': ('mdash', '2014'),
b'\x98': ('tilde', '2DC'),
b'\x99': ('trade', '2122'),
b'\x9a': ('scaron', '161'),
b'\x9b': ('rsaquo', '203A'),
b'\x9c': ('oelig', '153'),
b'\x9d': '?',
b'\x9e': ('#x17E', '17E'),
b'\x9f': ('Yuml', ''),}
# A parochial partial mapping of ISO-Latin-1 to ASCII. Contains
# horrors like stripping diacritical marks to turn á into a, but also
# contains non-horrors like turning “ into ".
MS_CHARS_TO_ASCII = {
b'\x80' : 'EUR',
b'\x81' : ' ',
b'\x82' : ',',
b'\x83' : 'f',
b'\x84' : ',,',
b'\x85' : '...',
b'\x86' : '+',
b'\x87' : '++',
b'\x88' : '^',
b'\x89' : '%',
b'\x8a' : 'S',
b'\x8b' : '<',
b'\x8c' : 'OE',
b'\x8d' : '?',
b'\x8e' : 'Z',
b'\x8f' : '?',
b'\x90' : '?',
b'\x91' : "'",
b'\x92' : "'",
b'\x93' : '"',
b'\x94' : '"',
b'\x95' : '*',
b'\x96' : '-',
b'\x97' : '--',
b'\x98' : '~',
b'\x99' : '(TM)',
b'\x9a' : 's',
b'\x9b' : '>',
b'\x9c' : 'oe',
b'\x9d' : '?',
b'\x9e' : 'z',
b'\x9f' : 'Y',
b'\xa0' : ' ',
b'\xa1' : '!',
b'\xa2' : 'c',
b'\xa3' : 'GBP',
b'\xa4' : '$', #This approximation is especially parochial--this is the
#generic currency symbol.
b'\xa5' : 'YEN',
b'\xa6' : '|',
b'\xa7' : 'S',
b'\xa8' : '..',
b'\xa9' : '',
b'\xaa' : '(th)',
b'\xab' : '<<',
b'\xac' : '!',
b'\xad' : ' ',
b'\xae' : '(R)',
b'\xaf' : '-',
b'\xb0' : 'o',
b'\xb1' : '+-',
b'\xb2' : '2',
b'\xb3' : '3',
b'\xb4' : ("'", 'acute'),
b'\xb5' : 'u',
b'\xb6' : 'P',
b'\xb7' : '*',
b'\xb8' : ',',
b'\xb9' : '1',
b'\xba' : '(th)',
b'\xbb' : '>>',
b'\xbc' : '1/4',
b'\xbd' : '1/2',
b'\xbe' : '3/4',
b'\xbf' : '?',
b'\xc0' : 'A',
b'\xc1' : 'A',
b'\xc2' : 'A',
b'\xc3' : 'A',
b'\xc4' : 'A',
b'\xc5' : 'A',
b'\xc6' : 'AE',
b'\xc7' : 'C',
b'\xc8' : 'E',
b'\xc9' : 'E',
b'\xca' : 'E',
b'\xcb' : 'E',
b'\xcc' : 'I',
b'\xcd' : 'I',
b'\xce' : 'I',
b'\xcf' : 'I',
b'\xd0' : 'D',
b'\xd1' : 'N',
b'\xd2' : 'O',
b'\xd3' : 'O',
b'\xd4' : 'O',
b'\xd5' : 'O',
b'\xd6' : 'O',
b'\xd7' : '*',
b'\xd8' : 'O',
b'\xd9' : 'U',
b'\xda' : 'U',
b'\xdb' : 'U',
b'\xdc' : 'U',
b'\xdd' : 'Y',
b'\xde' : 'b',
b'\xdf' : 'B',
b'\xe0' : 'a',
b'\xe1' : 'a',
b'\xe2' : 'a',
b'\xe3' : 'a',
b'\xe4' : 'a',
b'\xe5' : 'a',
b'\xe6' : 'ae',
b'\xe7' : 'c',
b'\xe8' : 'e',
b'\xe9' : 'e',
b'\xea' : 'e',
b'\xeb' : 'e',
b'\xec' : 'i',
b'\xed' : 'i',
b'\xee' : 'i',
b'\xef' : 'i',
b'\xf0' : 'o',
b'\xf1' : 'n',
b'\xf2' : 'o',
b'\xf3' : 'o',
b'\xf4' : 'o',
b'\xf5' : 'o',
b'\xf6' : 'o',
b'\xf7' : '/',
b'\xf8' : 'o',
b'\xf9' : 'u',
b'\xfa' : 'u',
b'\xfb' : 'u',
b'\xfc' : 'u',
b'\xfd' : 'y',
b'\xfe' : 'b',
b'\xff' : 'y',
}
# A map used when removing rogue Windows-1252/ISO-8859-1
# characters in otherwise UTF-8 documents.
#
# Note that \x81, \x8d, \x8f, \x90, and \x9d are undefined in
# Windows-1252.
WINDOWS_1252_TO_UTF8 = {
0x80 : b'\xe2\x82\xac', # €
0x82 : b'\xe2\x80\x9a', # ‚
0x83 : b'\xc6\x92', # ƒ
0x84 : b'\xe2\x80\x9e', # „
0x85 : b'\xe2\x80\xa6', # …
0x86 : b'\xe2\x80\xa0', # †
0x87 : b'\xe2\x80\xa1', # ‡
0x88 : b'\xcb\x86', # ˆ
0x89 : b'\xe2\x80\xb0', # ‰
0x8a : b'\xc5\xa0', # Š
0x8b : b'\xe2\x80\xb9', # ‹
0x8c : b'\xc5\x92', # Œ
0x8e : b'\xc5\xbd', # Ž
0x91 : b'\xe2\x80\x98', # ‘
0x92 : b'\xe2\x80\x99', # ’
0x93 : b'\xe2\x80\x9c', # “
0x94 : b'\xe2\x80\x9d', # ”
0x95 : b'\xe2\x80\xa2', # •
0x96 : b'\xe2\x80\x93', # –
0x97 : b'\xe2\x80\x94', # —
0x98 : b'\xcb\x9c', # ˜
0x99 : b'\xe2\x84\xa2', # ™
0x9a : b'\xc5\xa1', # š
0x9b : b'\xe2\x80\xba', # ›
0x9c : b'\xc5\x93', # œ
0x9e : b'\xc5\xbe', # ž
0x9f : b'\xc5\xb8', # Ÿ
0xa0 : b'\xc2\xa0', #
0xa1 : b'\xc2\xa1', # ¡
0xa2 : b'\xc2\xa2', # ¢
0xa3 : b'\xc2\xa3', # £
0xa4 : b'\xc2\xa4', # ¤
0xa5 : b'\xc2\xa5', # ¥
0xa6 : b'\xc2\xa6', # ¦
0xa7 : b'\xc2\xa7', # §
0xa8 : b'\xc2\xa8', # ¨
0xa9 : b'\xc2\xa9', # ©
0xaa : b'\xc2\xaa', # ª
0xab : b'\xc2\xab', # «
0xac : b'\xc2\xac', # ¬
0xad : b'\xc2\xad', #
0xae : b'\xc2\xae', # ®
0xaf : b'\xc2\xaf', # ¯
0xb0 : b'\xc2\xb0', # °
0xb1 : b'\xc2\xb1', # ±
0xb2 : b'\xc2\xb2', # ²
0xb3 : b'\xc2\xb3', # ³
0xb4 : b'\xc2\xb4', # ´
0xb5 : b'\xc2\xb5', # µ
0xb6 : b'\xc2\xb6', # ¶
0xb7 : b'\xc2\xb7', # ·
0xb8 : b'\xc2\xb8', # ¸
0xb9 : b'\xc2\xb9', # ¹
0xba : b'\xc2\xba', # º
0xbb : b'\xc2\xbb', # »
0xbc : b'\xc2\xbc', # ¼
0xbd : b'\xc2\xbd', # ½
0xbe : b'\xc2\xbe', # ¾
0xbf : b'\xc2\xbf', # ¿
0xc0 : b'\xc3\x80', # À
0xc1 : b'\xc3\x81', # Á
0xc2 : b'\xc3\x82', # Â
0xc3 : b'\xc3\x83', # Ã
0xc4 : b'\xc3\x84', # Ä
0xc5 : b'\xc3\x85', # Å
0xc6 : b'\xc3\x86', # Æ
0xc7 : b'\xc3\x87', # Ç
0xc8 : b'\xc3\x88', # È
0xc9 : b'\xc3\x89', # É
0xca : b'\xc3\x8a', # Ê
0xcb : b'\xc3\x8b', # Ë
0xcc : b'\xc3\x8c', # Ì
0xcd : b'\xc3\x8d', # Í
0xce : b'\xc3\x8e', # Î
0xcf : b'\xc3\x8f', # Ï
0xd0 : b'\xc3\x90', # Ð
0xd1 : b'\xc3\x91', # Ñ
0xd2 : b'\xc3\x92', # Ò
0xd3 : b'\xc3\x93', # Ó
0xd4 : b'\xc3\x94', # Ô
0xd5 : b'\xc3\x95', # Õ
0xd6 : b'\xc3\x96', # Ö
0xd7 : b'\xc3\x97', # ×
0xd8 : b'\xc3\x98', # Ø
0xd9 : b'\xc3\x99', # Ù
0xda : b'\xc3\x9a', # Ú
0xdb : b'\xc3\x9b', # Û
0xdc : b'\xc3\x9c', # Ü
0xdd : b'\xc3\x9d', # Ý
0xde : b'\xc3\x9e', # Þ
0xdf : b'\xc3\x9f', # ß
0xe0 : b'\xc3\xa0', # à
0xe1 : b'\xa1', # á
0xe2 : b'\xc3\xa2', # â
0xe3 : b'\xc3\xa3', # ã
0xe4 : b'\xc3\xa4', # ä
0xe5 : b'\xc3\xa5', # å
0xe6 : b'\xc3\xa6', # æ
0xe7 : b'\xc3\xa7', # ç
0xe8 : b'\xc3\xa8', # è
0xe9 : b'\xc3\xa9', # é
0xea : b'\xc3\xaa', # ê
0xeb : b'\xc3\xab', # ë
0xec : b'\xc3\xac', # ì
0xed : b'\xc3\xad', # í
0xee : b'\xc3\xae', # î
0xef : b'\xc3\xaf', # ï
0xf0 : b'\xc3\xb0', # ð
0xf1 : b'\xc3\xb1', # ñ
0xf2 : b'\xc3\xb2', # ò
0xf3 : b'\xc3\xb3', # ó
0xf4 : b'\xc3\xb4', # ô
0xf5 : b'\xc3\xb5', # õ
0xf6 : b'\xc3\xb6', # ö
0xf7 : b'\xc3\xb7', # ÷
0xf8 : b'\xc3\xb8', # ø
0xf9 : b'\xc3\xb9', # ù
0xfa : b'\xc3\xba', # ú
0xfb : b'\xc3\xbb', # û
0xfc : b'\xc3\xbc', # ü
0xfd : b'\xc3\xbd', # ý
0xfe : b'\xc3\xbe', # þ
}
MULTIBYTE_MARKERS_AND_SIZES = [
(0xc2, 0xdf, 2), # 2-byte characters start with a byte C2-DF
(0xe0, 0xef, 3), # 3-byte characters start with E0-EF
(0xf0, 0xf4, 4), # 4-byte characters start with F0-F4
]
FIRST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[0][0]
LAST_MULTIBYTE_MARKER = MULTIBYTE_MARKERS_AND_SIZES[-1][1]
@classmethod
def detwingle(cls, in_bytes, main_encoding="utf8",
embedded_encoding="windows-1252"):
"""Fix characters from one encoding embedded in some other encoding.
Currently the only situation supported is Windows-1252 (or its
subset ISO-8859-1), embedded in UTF-8.
The input must be a bytestring. If you've already converted
the document to Unicode, you're too late.
The output is a bytestring in which `embedded_encoding`
characters have been converted to their `main_encoding`
equivalents.
"""
if embedded_encoding.replace('_', '-').lower() not in (
'windows-1252', 'windows_1252'):
raise NotImplementedError(
"Windows-1252 and ISO-8859-1 are the only currently supported "
"embedded encodings.")
if main_encoding.lower() not in ('utf8', 'utf-8'):
raise NotImplementedError(
"UTF-8 is the only currently supported main encoding.")
byte_chunks = []
chunk_start = 0
pos = 0
while pos < len(in_bytes):
byte = in_bytes[pos]
if not isinstance(byte, int):
# Python 2.x
byte = ord(byte)
if (byte >= cls.FIRST_MULTIBYTE_MARKER
and byte <= cls.LAST_MULTIBYTE_MARKER):
# This is the start of a UTF-8 multibyte character. Skip
# to the end.
for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES:
if byte >= start and byte <= end:
pos += size
break
elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8:
# We found a Windows-1252 character!
# Save the string up to this point as a chunk.
byte_chunks.append(in_bytes[chunk_start:pos])
# Now translate the Windows-1252 character into UTF-8
# and add it as another, one-byte chunk.
byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte])
pos += 1
chunk_start = pos
else:
# Go on to the next character.
pos += 1
if chunk_start == 0:
# The string is unchanged.
return in_bytes
else:
# Store the final chunk.
byte_chunks.append(in_bytes[chunk_start:])
return b''.join(byte_chunks)
| mit |
koparasy/faultinjection-gem5 | src/arch/x86/isa/insts/simd128/floating_point/data_transfer/__init__.py | 91 | 2383 | # Copyright (c) 2007 The Hewlett-Packard Development Company
# 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: Gabe Black
categories = ["move",
"move_with_duplication",
"move_non_temporal",
"move_mask"]
microcode = '''
# SSE instructions
'''
for category in categories:
exec "import %s as cat" % category
microcode += cat.microcode
| bsd-3-clause |
mwindau/praktikum | v351/dreieck.py | 1 | 1188 | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
from scipy.optimize import curve_fit
oberwelle3, amplitude3 = np.genfromtxt('Rohdaten/dreieckspannung.txt',unpack=True)
plt.plot(oberwelle3, amplitude3,'k.',label="Messdaten")
#plt.legend(loc='best')
plt.grid()
#plt.xlim(0,1.5)
plt.xscale('log')
plt.yscale('log')
plt.xlabel(r'Oberwellen')
plt.ylabel(r'$\mathrm{U}/V$')
plt.tight_layout()
#plt.show()
#plt.savefig('build/50ohm.pdf')
####################
newX = np.logspace(-4, 1, base=10) # Makes a nice domain for the fitted curves.
# This avoids the sorting and the swarm of lines.
# Let's fit an exponential function.
# This looks like a line on a lof-log plot.
def myExpFunc(x, a, b):
return a * np.power(x, b)
popt, pcov = curve_fit(myExpFunc, oberwelle3, amplitude3)
plt.plot(newX, myExpFunc(newX, *popt), 'r-',
label="Fit".format(*popt))
plt.xlim(10**-2, 10**1)
plt.ylim(10**-0.5, 10**1)
print('Exponential Fit: y = (a*(x**b))')
print('\ta = popt[0] = {0}\n\tb = popt[1] = {1}'.format(*popt))
####################
plt.legend(loc='best')
#plt.show()
plt.savefig('build/dreieckspannung.pdf')
| mit |
FHannes/intellij-community | python/lib/Lib/compiler/symbols.py | 100 | 14538 | """Module symbol-table generator"""
from compiler import ast
from compiler.consts import SC_LOCAL, SC_GLOBAL, SC_FREE, SC_CELL, SC_UNKNOWN
from compiler.misc import mangle
import types
import sys
MANGLE_LEN = 256
class Scope:
# XXX how much information do I need about each name?
def __init__(self, name, module, klass=None):
self.name = name
self.module = module
self.defs = {}
self.uses = {}
self.globals = {}
self.params = {}
self.frees = {}
self.cells = {}
self.children = []
# nested is true if the class could contain free variables,
# i.e. if it is nested within another function.
self.nested = None
self.generator = None
self.klass = None
if klass is not None:
for i in range(len(klass)):
if klass[i] != '_':
self.klass = klass[i:]
break
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.name)
def mangle(self, name):
if self.klass is None:
return name
return mangle(name, self.klass)
def add_def(self, name):
self.defs[self.mangle(name)] = 1
def add_use(self, name):
self.uses[self.mangle(name)] = 1
def add_global(self, name):
name = self.mangle(name)
if self.uses.has_key(name) or self.defs.has_key(name):
pass # XXX warn about global following def/use
if self.params.has_key(name):
raise SyntaxError, "%s in %s is global and parameter" % \
(name, self.name)
self.globals[name] = 1
self.module.add_def(name)
def add_param(self, name):
name = self.mangle(name)
self.defs[name] = 1
self.params[name] = 1
def get_names(self):
d = {}
d.update(self.defs)
d.update(self.uses)
d.update(self.globals)
return d.keys()
def add_child(self, child):
self.children.append(child)
def get_children(self):
return self.children
def DEBUG(self):
print >> sys.stderr, self.name, self.nested and "nested" or ""
print >> sys.stderr, "\tglobals: ", self.globals
print >> sys.stderr, "\tcells: ", self.cells
print >> sys.stderr, "\tdefs: ", self.defs
print >> sys.stderr, "\tuses: ", self.uses
print >> sys.stderr, "\tfrees:", self.frees
def check_name(self, name):
"""Return scope of name.
The scope of a name could be LOCAL, GLOBAL, FREE, or CELL.
"""
if self.globals.has_key(name):
return SC_GLOBAL
if self.cells.has_key(name):
return SC_CELL
if self.defs.has_key(name):
return SC_LOCAL
if self.nested and (self.frees.has_key(name) or
self.uses.has_key(name)):
return SC_FREE
if self.nested:
return SC_UNKNOWN
else:
return SC_GLOBAL
def get_free_vars(self):
if not self.nested:
return ()
free = {}
free.update(self.frees)
for name in self.uses.keys():
if not (self.defs.has_key(name) or
self.globals.has_key(name)):
free[name] = 1
return free.keys()
def handle_children(self):
for child in self.children:
frees = child.get_free_vars()
globals = self.add_frees(frees)
for name in globals:
child.force_global(name)
def force_global(self, name):
"""Force name to be global in scope.
Some child of the current node had a free reference to name.
When the child was processed, it was labelled a free
variable. Now that all its enclosing scope have been
processed, the name is known to be a global or builtin. So
walk back down the child chain and set the name to be global
rather than free.
Be careful to stop if a child does not think the name is
free.
"""
self.globals[name] = 1
if self.frees.has_key(name):
del self.frees[name]
for child in self.children:
if child.check_name(name) == SC_FREE:
child.force_global(name)
def add_frees(self, names):
"""Process list of free vars from nested scope.
Returns a list of names that are either 1) declared global in the
parent or 2) undefined in a top-level parent. In either case,
the nested scope should treat them as globals.
"""
child_globals = []
for name in names:
sc = self.check_name(name)
if self.nested:
if sc == SC_UNKNOWN or sc == SC_FREE \
or isinstance(self, ClassScope):
self.frees[name] = 1
elif sc == SC_GLOBAL:
child_globals.append(name)
elif isinstance(self, FunctionScope) and sc == SC_LOCAL:
self.cells[name] = 1
elif sc != SC_CELL:
child_globals.append(name)
else:
if sc == SC_LOCAL:
self.cells[name] = 1
elif sc != SC_CELL:
child_globals.append(name)
return child_globals
def get_cell_vars(self):
return self.cells.keys()
class ModuleScope(Scope):
__super_init = Scope.__init__
def __init__(self):
self.__super_init("global", self)
class FunctionScope(Scope):
pass
class GenExprScope(Scope):
__super_init = Scope.__init__
__counter = 1
def __init__(self, module, klass=None):
i = self.__counter
self.__counter += 1
self.__super_init("generator expression<%d>"%i, module, klass)
self.add_param('.0')
def get_names(self):
keys = Scope.get_names(self)
return keys
class LambdaScope(FunctionScope):
__super_init = Scope.__init__
__counter = 1
def __init__(self, module, klass=None):
i = self.__counter
self.__counter += 1
self.__super_init("lambda.%d" % i, module, klass)
class ClassScope(Scope):
__super_init = Scope.__init__
def __init__(self, name, module):
self.__super_init(name, module, name)
class SymbolVisitor:
def __init__(self):
self.scopes = {}
self.klass = None
# node that define new scopes
def visitModule(self, node):
scope = self.module = self.scopes[node] = ModuleScope()
self.visit(node.node, scope)
visitExpression = visitModule
def visitFunction(self, node, parent):
if node.decorators:
self.visit(node.decorators, parent)
parent.add_def(node.name)
for n in node.defaults:
self.visit(n, parent)
scope = FunctionScope(node.name, self.module, self.klass)
if parent.nested or isinstance(parent, FunctionScope):
scope.nested = 1
self.scopes[node] = scope
self._do_args(scope, node.argnames)
self.visit(node.code, scope)
self.handle_free_vars(scope, parent)
def visitGenExpr(self, node, parent):
scope = GenExprScope(self.module, self.klass);
if parent.nested or isinstance(parent, FunctionScope) \
or isinstance(parent, GenExprScope):
scope.nested = 1
self.scopes[node] = scope
self.visit(node.code, scope)
self.handle_free_vars(scope, parent)
def visitGenExprInner(self, node, scope):
for genfor in node.quals:
self.visit(genfor, scope)
self.visit(node.expr, scope)
def visitGenExprFor(self, node, scope):
self.visit(node.assign, scope, 1)
self.visit(node.iter, scope)
for if_ in node.ifs:
self.visit(if_, scope)
def visitGenExprIf(self, node, scope):
self.visit(node.test, scope)
def visitLambda(self, node, parent, assign=0):
# Lambda is an expression, so it could appear in an expression
# context where assign is passed. The transformer should catch
# any code that has a lambda on the left-hand side.
assert not assign
for n in node.defaults:
self.visit(n, parent)
scope = LambdaScope(self.module, self.klass)
if parent.nested or isinstance(parent, FunctionScope):
scope.nested = 1
self.scopes[node] = scope
self._do_args(scope, node.argnames)
self.visit(node.code, scope)
self.handle_free_vars(scope, parent)
def _do_args(self, scope, args):
for name in args:
if type(name) == types.TupleType:
self._do_args(scope, name)
else:
scope.add_param(name)
def handle_free_vars(self, scope, parent):
parent.add_child(scope)
scope.handle_children()
def visitClass(self, node, parent):
parent.add_def(node.name)
for n in node.bases:
self.visit(n, parent)
scope = ClassScope(node.name, self.module)
if parent.nested or isinstance(parent, FunctionScope):
scope.nested = 1
if node.doc is not None:
scope.add_def('__doc__')
scope.add_def('__module__')
self.scopes[node] = scope
prev = self.klass
self.klass = node.name
self.visit(node.code, scope)
self.klass = prev
self.handle_free_vars(scope, parent)
# name can be a def or a use
# XXX a few calls and nodes expect a third "assign" arg that is
# true if the name is being used as an assignment. only
# expressions contained within statements may have the assign arg.
def visitName(self, node, scope, assign=0):
if assign:
scope.add_def(node.name)
else:
scope.add_use(node.name)
# operations that bind new names
def visitFor(self, node, scope):
self.visit(node.assign, scope, 1)
self.visit(node.list, scope)
self.visit(node.body, scope)
if node.else_:
self.visit(node.else_, scope)
def visitFrom(self, node, scope):
for name, asname in node.names:
if name == "*":
continue
scope.add_def(asname or name)
def visitImport(self, node, scope):
for name, asname in node.names:
i = name.find(".")
if i > -1:
name = name[:i]
scope.add_def(asname or name)
def visitGlobal(self, node, scope):
for name in node.names:
scope.add_global(name)
def visitAssign(self, node, scope):
"""Propagate assignment flag down to child nodes.
The Assign node doesn't itself contains the variables being
assigned to. Instead, the children in node.nodes are visited
with the assign flag set to true. When the names occur in
those nodes, they are marked as defs.
Some names that occur in an assignment target are not bound by
the assignment, e.g. a name occurring inside a slice. The
visitor handles these nodes specially; they do not propagate
the assign flag to their children.
"""
for n in node.nodes:
self.visit(n, scope, 1)
self.visit(node.expr, scope)
def visitAssName(self, node, scope, assign=1):
scope.add_def(node.name)
def visitAssAttr(self, node, scope, assign=0):
self.visit(node.expr, scope, 0)
def visitSubscript(self, node, scope, assign=0):
self.visit(node.expr, scope, 0)
for n in node.subs:
self.visit(n, scope, 0)
def visitSlice(self, node, scope, assign=0):
self.visit(node.expr, scope, 0)
if node.lower:
self.visit(node.lower, scope, 0)
if node.upper:
self.visit(node.upper, scope, 0)
def visitAugAssign(self, node, scope):
# If the LHS is a name, then this counts as assignment.
# Otherwise, it's just use.
self.visit(node.node, scope)
if isinstance(node.node, ast.Name):
self.visit(node.node, scope, 1) # XXX worry about this
self.visit(node.expr, scope)
# prune if statements if tests are false
_const_types = types.StringType, types.IntType, types.FloatType
def visitIf(self, node, scope):
for test, body in node.tests:
if isinstance(test, ast.Const):
if type(test.value) in self._const_types:
if not test.value:
continue
self.visit(test, scope)
self.visit(body, scope)
if node.else_:
self.visit(node.else_, scope)
# a yield statement signals a generator
def visitYield(self, node, scope):
scope.generator = 1
self.visit(node.value, scope)
def list_eq(l1, l2):
return sorted(l1) == sorted(l2)
if __name__ == "__main__":
import sys
from compiler import parseFile, walk
import symtable
def get_names(syms):
return [s for s in [s.get_name() for s in syms.get_symbols()]
if not (s.startswith('_[') or s.startswith('.'))]
for file in sys.argv[1:]:
print file
f = open(file)
buf = f.read()
f.close()
syms = symtable.symtable(buf, file, "exec")
mod_names = get_names(syms)
tree = parseFile(file)
s = SymbolVisitor()
walk(tree, s)
# compare module-level symbols
names2 = s.scopes[tree].get_names()
if not list_eq(mod_names, names2):
print
print "oops", file
print sorted(mod_names)
print sorted(names2)
sys.exit(-1)
d = {}
d.update(s.scopes)
del d[tree]
scopes = d.values()
del d
for s in syms.get_symbols():
if s.is_namespace():
l = [sc for sc in scopes
if sc.name == s.get_name()]
if len(l) > 1:
print "skipping", s.get_name()
else:
if not list_eq(get_names(s.get_namespace()),
l[0].get_names()):
print s.get_name()
print sorted(get_names(s.get_namespace()))
print sorted(l[0].get_names())
sys.exit(-1)
| apache-2.0 |
mdrumond/tensorflow | tensorflow/tools/dist_test/python/mnist_replica.py | 44 | 10714 | # 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.
# ==============================================================================
"""Distributed MNIST training and validation, with model replicas.
A simple softmax model with one hidden layer is defined. The parameters
(weights and biases) are located on one parameter server (ps), while the ops
are executed on two worker nodes by default. The TF sessions also run on the
worker node.
Multiple invocations of this script can be done in parallel, with different
values for --task_index. There should be exactly one invocation with
--task_index, which will create a master session that carries out variable
initialization. The other, non-master, sessions will wait for the master
session to finish the initialization before proceeding to the training stage.
The coordination between the multiple worker invocations occurs due to
the definition of the parameters on the same ps devices. The parameter updates
from one worker is visible to all other workers. As such, the workers can
perform forward computation and gradient calculation in parallel, which
should lead to increased training speed for the simple model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import sys
import tempfile
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
flags = tf.app.flags
flags.DEFINE_string("data_dir", "/tmp/mnist-data",
"Directory for storing mnist data")
flags.DEFINE_boolean("download_only", False,
"Only perform downloading of data; Do not proceed to "
"session preparation, model definition or training")
flags.DEFINE_integer("task_index", None,
"Worker task index, should be >= 0. task_index=0 is "
"the master worker task the performs the variable "
"initialization ")
flags.DEFINE_integer("num_gpus", 1,
"Total number of gpus for each machine."
"If you don't use GPU, please set it to '0'")
flags.DEFINE_integer("replicas_to_aggregate", None,
"Number of replicas to aggregate before parameter update"
"is applied (For sync_replicas mode only; default: "
"num_workers)")
flags.DEFINE_integer("hidden_units", 100,
"Number of units in the hidden layer of the NN")
flags.DEFINE_integer("train_steps", 200,
"Number of (global) training steps to perform")
flags.DEFINE_integer("batch_size", 100, "Training batch size")
flags.DEFINE_float("learning_rate", 0.01, "Learning rate")
flags.DEFINE_boolean("sync_replicas", False,
"Use the sync_replicas (synchronized replicas) mode, "
"wherein the parameter updates from workers are aggregated "
"before applied to avoid stale gradients")
flags.DEFINE_boolean(
"existing_servers", False, "Whether servers already exists. If True, "
"will use the worker hosts via their GRPC URLs (one client process "
"per worker host). Otherwise, will create an in-process TensorFlow "
"server.")
flags.DEFINE_string("ps_hosts","localhost:2222",
"Comma-separated list of hostname:port pairs")
flags.DEFINE_string("worker_hosts", "localhost:2223,localhost:2224",
"Comma-separated list of hostname:port pairs")
flags.DEFINE_string("job_name", None,"job name: worker or ps")
FLAGS = flags.FLAGS
IMAGE_PIXELS = 28
def main(unused_argv):
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
if FLAGS.download_only:
sys.exit(0)
if FLAGS.job_name is None or FLAGS.job_name == "":
raise ValueError("Must specify an explicit `job_name`")
if FLAGS.task_index is None or FLAGS.task_index =="":
raise ValueError("Must specify an explicit `task_index`")
print("job name = %s" % FLAGS.job_name)
print("task index = %d" % FLAGS.task_index)
#Construct the cluster and start the server
ps_spec = FLAGS.ps_hosts.split(",")
worker_spec = FLAGS.worker_hosts.split(",")
# Get the number of workers.
num_workers = len(worker_spec)
cluster = tf.train.ClusterSpec({
"ps": ps_spec,
"worker": worker_spec})
if not FLAGS.existing_servers:
# Not using existing servers. Create an in-process server.
server = tf.train.Server(
cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)
if FLAGS.job_name == "ps":
server.join()
is_chief = (FLAGS.task_index == 0)
if FLAGS.num_gpus > 0:
# Avoid gpu allocation conflict: now allocate task_num -> #gpu
# for each worker in the corresponding machine
gpu = (FLAGS.task_index % FLAGS.num_gpus)
worker_device = "/job:worker/task:%d/gpu:%d" % (FLAGS.task_index, gpu)
elif FLAGS.num_gpus == 0:
# Just allocate the CPU to worker server
cpu = 0
worker_device = "/job:worker/task:%d/cpu:%d" % (FLAGS.task_index, cpu)
# The device setter will automatically place Variables ops on separate
# parameter servers (ps). The non-Variable ops will be placed on the workers.
# The ps use CPU and workers use corresponding GPU
with tf.device(
tf.train.replica_device_setter(
worker_device=worker_device,
ps_device="/job:ps/cpu:0",
cluster=cluster)):
global_step = tf.Variable(0, name="global_step", trainable=False)
# Variables of the hidden layer
hid_w = tf.Variable(
tf.truncated_normal(
[IMAGE_PIXELS * IMAGE_PIXELS, FLAGS.hidden_units],
stddev=1.0 / IMAGE_PIXELS),
name="hid_w")
hid_b = tf.Variable(tf.zeros([FLAGS.hidden_units]), name="hid_b")
# Variables of the softmax layer
sm_w = tf.Variable(
tf.truncated_normal(
[FLAGS.hidden_units, 10],
stddev=1.0 / math.sqrt(FLAGS.hidden_units)),
name="sm_w")
sm_b = tf.Variable(tf.zeros([10]), name="sm_b")
# Ops: located on the worker specified with FLAGS.task_index
x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS])
y_ = tf.placeholder(tf.float32, [None, 10])
hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)
hid = tf.nn.relu(hid_lin)
y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))
cross_entropy = -tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))
opt = tf.train.AdamOptimizer(FLAGS.learning_rate)
if FLAGS.sync_replicas:
if FLAGS.replicas_to_aggregate is None:
replicas_to_aggregate = num_workers
else:
replicas_to_aggregate = FLAGS.replicas_to_aggregate
opt = tf.train.SyncReplicasOptimizer(
opt,
replicas_to_aggregate=replicas_to_aggregate,
total_num_replicas=num_workers,
name="mnist_sync_replicas")
train_step = opt.minimize(cross_entropy, global_step=global_step)
if FLAGS.sync_replicas:
local_init_op = opt.local_step_init_op
if is_chief:
local_init_op = opt.chief_init_op
ready_for_local_init_op = opt.ready_for_local_init_op
# Initial token and chief queue runners required by the sync_replicas mode
chief_queue_runner = opt.get_chief_queue_runner()
sync_init_op = opt.get_init_tokens_op()
init_op = tf.global_variables_initializer()
train_dir = tempfile.mkdtemp()
if FLAGS.sync_replicas:
sv = tf.train.Supervisor(
is_chief=is_chief,
logdir=train_dir,
init_op=init_op,
local_init_op=local_init_op,
ready_for_local_init_op=ready_for_local_init_op,
recovery_wait_secs=1,
global_step=global_step)
else:
sv = tf.train.Supervisor(
is_chief=is_chief,
logdir=train_dir,
init_op=init_op,
recovery_wait_secs=1,
global_step=global_step)
sess_config = tf.ConfigProto(
allow_soft_placement=True,
log_device_placement=False,
device_filters=["/job:ps", "/job:worker/task:%d" % FLAGS.task_index])
# The chief worker (task_index==0) session will prepare the session,
# while the remaining workers will wait for the preparation to complete.
if is_chief:
print("Worker %d: Initializing session..." % FLAGS.task_index)
else:
print("Worker %d: Waiting for session to be initialized..." %
FLAGS.task_index)
if FLAGS.existing_servers:
server_grpc_url = "grpc://" + worker_spec[FLAGS.task_index]
print("Using existing server at: %s" % server_grpc_url)
sess = sv.prepare_or_wait_for_session(server_grpc_url,
config=sess_config)
else:
sess = sv.prepare_or_wait_for_session(server.target, config=sess_config)
print("Worker %d: Session initialization complete." % FLAGS.task_index)
if FLAGS.sync_replicas and is_chief:
# Chief worker will start the chief queue runner and call the init op.
sess.run(sync_init_op)
sv.start_queue_runners(sess, [chief_queue_runner])
# Perform training
time_begin = time.time()
print("Training begins @ %f" % time_begin)
local_step = 0
while True:
# Training feed
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)
train_feed = {x: batch_xs, y_: batch_ys}
_, step = sess.run([train_step, global_step], feed_dict=train_feed)
local_step += 1
now = time.time()
print("%f: Worker %d: training step %d done (global step: %d)" %
(now, FLAGS.task_index, local_step, step))
if step >= FLAGS.train_steps:
break
time_end = time.time()
print("Training ends @ %f" % time_end)
training_time = time_end - time_begin
print("Training elapsed time: %f s" % training_time)
# Validation feed
val_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
val_xent = sess.run(cross_entropy, feed_dict=val_feed)
print("After %d training step(s), validation cross entropy = %g" %
(FLAGS.train_steps, val_xent))
if __name__ == "__main__":
tf.app.run()
| apache-2.0 |
internaphosting/netman | tests/adapters/unified_tests/ip_management_test.py | 3 | 5621 | # Copyright 2015 Internap.
#
# 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 hamcrest import equal_to, assert_that, has_length
from netaddr import IPNetwork
from netman.core.objects.access_groups import IN, OUT
from netman.core.objects.exceptions import UnknownVlan, UnknownIP, \
IPNotAvailable, Conflict
from tests.adapters.configured_test_case import ConfiguredTestCase, skip_on_switches
class IpManagementTest(ConfiguredTestCase):
__test__ = False
@skip_on_switches("juniper", "juniper_qfx_copper", "dell", "dell_telnet", "dell10g", "dell10g_telnet", "juniper_mx", "arista_http")
def test_adding_and_removing_ip_basic(self):
self.client.add_vlan(2345)
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("2.2.2.2/24"))
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.2/24"))
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.3/24"))
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.4/24"))
vlans = self.client.get_vlans()
vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)
assert_that(vlan2345.ips, has_length(5))
assert_that(str(vlan2345.ips[0]), equal_to("1.1.1.1/24"))
assert_that(str(vlan2345.ips[1]), equal_to("1.1.1.2/24"))
assert_that(str(vlan2345.ips[2]), equal_to("1.1.1.3/24"))
assert_that(str(vlan2345.ips[3]), equal_to("1.1.1.4/24"))
assert_that(str(vlan2345.ips[4]), equal_to("2.2.2.2/24"))
self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("1.1.1.3/24"))
vlans = self.client.get_vlans()
vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)
assert_that(vlan2345.ips, has_length(3))
assert_that(str(vlan2345.ips[0]), equal_to("1.1.1.2/24"))
assert_that(str(vlan2345.ips[1]), equal_to("1.1.1.4/24"))
assert_that(str(vlan2345.ips[2]), equal_to("2.2.2.2/24"))
self.client.remove_vlan(2345)
@skip_on_switches("juniper", "juniper_qfx_copper", "dell", "dell_telnet", "dell10g", "dell10g_telnet", "juniper_mx", "arista_http")
def test_adding_unavailable_ips_and_various_errors(self):
self.client.add_vlan(2345)
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
with self.assertRaises(UnknownVlan):
self.client.add_ip_to_vlan(3333, ip_network=IPNetwork("1.1.1.1/24"))
# TODO(jprovost) Unify switch adapters to raise the same exception
# multiple exceptions: IPNotAvailable, IPAlreadySet
with self.assertRaises(Conflict):
self.client.add_ip_to_vlan(2345, ip_network=IPNetwork("1.1.1.1/24"))
self.client.add_vlan(2999)
with self.assertRaises(IPNotAvailable):
self.client.add_ip_to_vlan(2999, ip_network=IPNetwork("1.1.1.1/24"))
with self.assertRaises(IPNotAvailable):
self.client.add_ip_to_vlan(2999, ip_network=IPNetwork("1.1.1.2/24"))
self.client.remove_vlan(2999)
with self.assertRaises(UnknownVlan):
self.client.remove_ip_from_vlan(1111, ip_network=IPNetwork("1.1.1.1/24"))
with self.assertRaises(UnknownIP):
self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("2.2.2.2/24"))
with self.assertRaises(UnknownIP):
self.client.remove_ip_from_vlan(2345, ip_network=IPNetwork("1.1.1.1/30"))
self.client.remove_vlan(2345)
@skip_on_switches("juniper", "juniper_qfx_copper", "dell", "dell_telnet", "dell10g", "dell10g_telnet", "juniper_mx", "arista_http")
def test_handling_access_groups(self):
self.client.add_vlan(2345)
self.client.set_vlan_access_group(2345, direction=IN, name="my-group")
self.client.set_vlan_access_group(2345, direction=OUT, name="your-group")
vlans = self.client.get_vlans()
vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)
assert_that(vlan2345.access_groups[IN], equal_to("my-group"))
assert_that(vlan2345.access_groups[OUT], equal_to("your-group"))
self.client.unset_vlan_access_group(2345, direction=IN)
self.client.unset_vlan_access_group(2345, direction=OUT)
vlans = self.client.get_vlans()
vlan2345 = next(vlan for vlan in vlans if vlan.number == 2345)
assert_that(vlan2345.access_groups[IN], equal_to(None))
assert_that(vlan2345.access_groups[OUT], equal_to(None))
self.client.remove_vlan(2345)
# all covered cases
# add an ip
# add a second ip
# add the same ip - error
# add the same ip, different subnet - error
# add ip in the same subnet as another ip in the same port
# add the same ip in the same subnet as another ip in the same port - error
# add ip belonging to another port - error
# add ip with a different subnet belonging to another port - error
# add ip in a subnet belonging to another port - error
# remove ip
# remove secondary ip
# remove ip with secondaries
| apache-2.0 |
sahildua2305/eden | modules/hs/utils/dictionary.py | 50 | 1538 | class Dictionary (dict):
def __init__ (self):
self._keys = []
#self._sorted = True
dict.__init__(self)
def keys (self):
return self._keys
def update (self, pairs):
try:
for key, value in pairs.iteritems ():
if not self.has_key (key):
self._keys.append (key)
except AttributeError:
for pair in pairs:
if not self.has_key (pair[0]):
self._keys.append (pair[0])
#for key in pairs:
# print key
# try:
# self[key]
# except KeyError:
# self._keys.append (key)
#self._sorted = False
dict.update (self, pairs)
def __iter__ (self):
return DictIterator (self, iter(self._keys))
class DictIterator:
def __init__ (self, dictionary, listIter):
self._dictionary = dictionary
self._listIter = listIter
def __iter__ (self):
return self
def next (self):
key = self._listIter.next ()
return (key, self._dictionary[key])
class DefaultDictionary (Dictionary):
def __init__ (self, default):
self.default = default
Dictionary.__init__ (self)
def __getitem__ (self, item):
try:
return dict.__getitem__ (self, item)
except KeyError:
if not self.default is None:
return self.default
else:
raise KeyError ()
| mit |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_08_01/operations/bgp_service_communities_operations.py | 1 | 4225 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class BgpServiceCommunitiesOperations(object):
"""BgpServiceCommunitiesOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client API version. Constant value: "2017-08-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2017-08-01"
self.config = config
def list(
self, custom_headers=None, raw=False, **operation_config):
"""Gets all the available bgp service communities.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of BgpServiceCommunity
:rtype:
~azure.mgmt.network.v2017_08_01.models.BgpServiceCommunityPaged[~azure.mgmt.network.v2017_08_01.models.BgpServiceCommunity]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(
request, header_parameters, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
deserialized = models.BgpServiceCommunityPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.BgpServiceCommunityPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities'}
| mit |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/bgp_settings_py3.py | 7 | 1386 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class BgpSettings(Model):
"""BGP settings details.
:param asn: The BGP speaker's ASN.
:type asn: long
:param bgp_peering_address: The BGP peering address and BGP identifier of
this BGP speaker.
:type bgp_peering_address: str
:param peer_weight: The weight added to routes learned from this BGP
speaker.
:type peer_weight: int
"""
_attribute_map = {
'asn': {'key': 'asn', 'type': 'long'},
'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
'peer_weight': {'key': 'peerWeight', 'type': 'int'},
}
def __init__(self, *, asn: int=None, bgp_peering_address: str=None, peer_weight: int=None, **kwargs) -> None:
super(BgpSettings, self).__init__(**kwargs)
self.asn = asn
self.bgp_peering_address = bgp_peering_address
self.peer_weight = peer_weight
| mit |
sss/calibre-at-bzr | src/calibre/ebooks/rtf2xml/preamble_div.py | 24 | 22931 | #########################################################################
# #
# #
# copyright 2002 Paul Henry Tremblay #
# #
# 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. #
# #
# #
#########################################################################
import sys, os
from calibre.ebooks.rtf2xml import copy, override_table, list_table
from calibre.ptempfile import better_mktemp
class PreambleDiv:
"""
Break the preamble into divisions.
"""
def __init__(self, in_file,
bug_handler,
copy = None,
no_namespace = None,
run_level = 1,
):
"""
Required:
'file'
Optional:
'copy'-- whether to make a copy of result for debugging
'temp_dir' --where to output temporary results (default is
directory from which the script is run.)
Returns:
nothing
"""
self.__file = in_file
self.__bug_handler = bug_handler
self.__copy = copy
self.__no_namespace = no_namespace
self.__write_to = better_mktemp()
self.__run_level = run_level
def __initiate_values(self):
"""
Set values, including those for the dictionary.
"""
self.__all_lists = {}
self.__page = {
'margin-top' : 72,
'margin-bottom' : 72,
'margin-left' : 90,
'margin-right' : 90,
'gutter' : 0,
}
self.__cb_count = ''
self.__ob_count = ''
self.__state = 'preamble'
self.__rtf_final = ''
self.__close_group_count = ''
self.__found_font_table = 0
self.__list_table_final = ''
self.__override_table_final = ''
self.__revision_table_final = ''
self.__doc_info_table_final = ''
self.__state_dict = {
'default' : self.__default_func,
'rtf_header' : self.__rtf_head_func,
'preamble' : self.__preamble_func,
'font_table' : self.__font_table_func,
'color_table' : self.__color_table_func,
'style_sheet' : self.__style_sheet_func,
'list_table' : self.__list_table_func,
'override_table' : self.__override_table_func,
'revision_table' : self.__revision_table_func,
'doc_info' : self.__doc_info_func,
'body' : self.__body_func,
'ignore' : self.__ignore_func,
'cw<ri<rtf_______' : self.__found_rtf_head_func,
'cw<pf<par-def___' : self.__para_def_func,
'tx<nu<__________' : self.__text_func,
'cw<tb<row-def___' : self.__row_def_func,
'cw<sc<section___' : self.__new_section_func,
'cw<sc<sect-defin' : self.__new_section_func,
'cw<it<font-table' : self.__found_font_table_func,
'cw<it<colr-table' : self.__found_color_table_func,
'cw<ss<style-shet' : self.__found_style_sheet_func,
'cw<it<listtable_' : self.__found_list_table_func,
'cw<it<lovr-table' : self.__found_override_table_func,
'cw<it<revi-table' : self.__found_revision_table_func,
'cw<di<doc-info__' : self.__found_doc_info_func,
'cw<pa<margin-lef' : self.__margin_func,
'cw<pa<margin-rig' : self.__margin_func,
'cw<pa<margin-top' : self.__margin_func,
'cw<pa<margin-bot' : self.__margin_func,
'cw<pa<gutter____' : self.__margin_func,
'cw<pa<paper-widt' : self.__margin_func,
'cw<pa<paper-hght' : self.__margin_func,
# 'cw<tb<columns___' : self.__section_func,
}
self.__margin_dict = {
'margin-lef' : 'margin-left',
'margin-rig' : 'margin-right',
'margin-top' : 'margin-top',
'margin-bot' : 'margin-bottom',
'gutter____' : 'gutter',
'paper-widt' : 'paper-width',
'paper-hght' : 'paper-height',
}
self.__translate_sec = {
'columns___' : 'column',
}
self.__section = {}
# self.__write_obj.write(self.__color_table_final)
self.__color_table_final = ''
self.__style_sheet_final = ''
self.__individual_font = 0
self.__old_font = 0
self.__ob_group = 0 # depth of group
self.__font_table_final = 0
self.__list_table_obj = list_table.ListTable(
run_level = self.__run_level,
bug_handler = self.__bug_handler,
)
def __ignore_func(self, line):
"""
Ignore all lines, until the bracket is found that marks the end of
the group.
"""
if self.__ignore_num == self.__cb_count:
self.__state = self.__previous_state
def __found_rtf_head_func(self, line):
self.__state = 'rtf_header'
def __rtf_head_func(self, line):
if self.__ob_count == '0002':
self.__rtf_final = (
'mi<mk<rtfhed-beg\n' +
self.__rtf_final +
'mi<mk<rtfhed-end\n'
)
self.__state = 'preamble'
elif self.__token_info == 'tx<nu<__________' or \
self.__token_info == 'cw<pf<par-def___':
self.__state = 'body'
self.__rtf_final = (
'mi<mk<rtfhed-beg\n' +
self.__rtf_final +
'mi<mk<rtfhed-end\n'
)
self.__make_default_font_table()
self.__write_preamble()
self.__write_obj.write(line)
else:
self.__rtf_final = self.__rtf_final + line
def __make_default_font_table(self):
"""
If not font table is fount, need to write one out.
"""
self.__font_table_final = 'mi<tg<open______<font-table\n'
self.__font_table_final += 'mi<mk<fonttb-beg\n'
self.__font_table_final += 'mi<mk<fontit-beg\n'
self.__font_table_final += 'cw<ci<font-style<nu<0\n'
self.__font_table_final += 'tx<nu<__________<Times;\n'
self.__font_table_final += 'mi<mk<fontit-end\n'
self.__font_table_final += 'mi<mk<fonttb-end\n'
self.__font_table_final += 'mi<tg<close_____<font-table\n'
def __make_default_color_table(self):
"""
If no color table is found, write a string for a default one
"""
self.__color_table_final = 'mi<tg<open______<color-table\n'
self.__color_table_final += 'mi<mk<clrtbl-beg\n'
self.__color_table_final += 'cw<ci<red_______<nu<00\n'
self.__color_table_final += 'cw<ci<green_____<nu<00\n'
self.__color_table_final += 'cw<ci<blue______<en<00\n'
self.__color_table_final += 'mi<mk<clrtbl-end\n'
self.__color_table_final += 'mi<tg<close_____<color-table\n'
def __make_default_style_table(self):
"""
If not font table is found, make a string for a default one
"""
"""
self.__style_sheet_final = 'mi<tg<open______<style-table\n'
self.__style_sheet_final +=
self.__style_sheet_final +=
self.__style_sheet_final +=
self.__style_sheet_final +=
self.__style_sheet_final +=
self.__style_sheet_final += 'mi<tg<close_____<style-table\n'
"""
self.__style_sheet_final = """mi<tg<open______<style-table
mi<mk<styles-beg
mi<mk<stylei-beg
cw<ci<font-style<nu<0
tx<nu<__________<Normal;
mi<mk<stylei-end
mi<mk<stylei-beg
cw<ss<char-style<nu<0
tx<nu<__________<Default Paragraph Font;
mi<mk<stylei-end
mi<mk<styles-end
mi<tg<close_____<style-table
"""
def __found_font_table_func(self, line):
if self.__found_font_table:
self.__state = 'ignore'
else:
self.__state = 'font_table'
self.__font_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
self.__found_font_table = 1
def __font_table_func(self, line):
"""
Keep adding to the self.__individual_font string until end of group
found. If a bracket is found, check that it is only one bracket deep.
If it is, then set the marker for an individual font. If it is not,
then ignore all data in this group.
cw<ci<font-style<nu<0
"""
if self.__cb_count == self.__close_group_count:
self.__state = 'preamble'
self.__font_table_final = 'mi<tg<open______<font-table\n' + \
'mi<mk<fonttb-beg\n' + self.__font_table_final
self.__font_table_final += \
'mi<mk<fonttb-end\n' + 'mi<tg<close_____<font-table\n'
elif self.__token_info == 'ob<nu<open-brack':
if int(self.__ob_count) == int(self.__close_group_count) + 1:
self.__font_table_final += \
'mi<mk<fontit-beg\n'
self.__individual_font = 1
else:
# ignore
self.__previous_state = 'font_table'
self.__state = 'ignore'
self.__ignore_num = self.__ob_count
elif self.__token_info == 'cb<nu<clos-brack':
if int(self.__cb_count) == int(self.__close_group_count) + 1:
self.__individual_font = 0
self.__font_table_final += \
'mi<mk<fontit-end\n'
elif self.__individual_font:
if self.__old_font and self.__token_info == 'tx<nu<__________':
if ';' in line:
self.__font_table_final += line
self.__font_table_final += 'mi<mk<fontit-end\n'
self.__individual_font = 0
else:
self.__font_table_final += line
elif self.__token_info == 'cw<ci<font-style':
self.__old_font = 1
self.__individual_font = 1
self.__font_table_final += 'mi<mk<fontit-beg\n'
self.__font_table_final += line
def __old_font_func(self, line):
"""
Required:
line --line to parse
Returns:
nothing
Logic:
used for older forms of RTF:
\f3\fswiss\fcharset77 Helvetica-Oblique;\f4\fnil\fcharset77 Geneva;}
Note how each font is not divided by a bracket
"""
def __found_color_table_func(self, line):
"""
all functions that start with __found operate the same. They set the
state, initiate a string, determine the self.__close_group_count, and
set self.__cb_count to zero.
"""
self.__state = 'color_table'
self.__color_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
def __color_table_func(self, line):
if int(self.__cb_count) == int(self.__close_group_count):
self.__state = 'preamble'
self.__color_table_final = 'mi<tg<open______<color-table\n' + \
'mi<mk<clrtbl-beg\n' + self.__color_table_final
self.__color_table_final += \
'mi<mk<clrtbl-end\n' + 'mi<tg<close_____<color-table\n'
else:
self.__color_table_final += line
def __found_style_sheet_func(self, line):
self.__state = 'style_sheet'
self.__style_sheet_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
def __style_sheet_func(self, line):
"""
Same logic as the font_table_func.
"""
if self.__cb_count == self.__close_group_count:
self.__state = 'preamble'
self.__style_sheet_final = 'mi<tg<open______<style-table\n' + \
'mi<mk<styles-beg\n' + self.__style_sheet_final
self.__style_sheet_final += \
'mi<mk<styles-end\n' + 'mi<tg<close_____<style-table\n'
elif self.__token_info == 'ob<nu<open-brack':
if int(self.__ob_count) == int(self.__close_group_count) + 1:
self.__style_sheet_final += \
'mi<mk<stylei-beg\n'
elif self.__token_info == 'cb<nu<clos-brack':
if int(self.__cb_count) == int(self.__close_group_count) + 1:
self.__style_sheet_final += \
'mi<mk<stylei-end\n'
else:
self.__style_sheet_final += line
def __found_list_table_func(self, line):
self.__state = 'list_table'
self.__list_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
def __list_table_func(self, line):
if self.__cb_count == self.__close_group_count:
self.__state = 'preamble'
self.__list_table_final, self.__all_lists =\
self.__list_table_obj.parse_list_table(
self.__list_table_final)
# sys.stderr.write(repr(all_lists))
elif self.__token_info == '':
pass
else:
self.__list_table_final += line
pass
def __found_override_table_func(self, line):
self.__override_table_obj = override_table.OverrideTable(
run_level = self.__run_level,
list_of_lists = self.__all_lists,
)
self.__state = 'override_table'
self.__override_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
# cw<it<lovr-table
def __override_table_func(self, line):
if self.__cb_count == self.__close_group_count:
self.__state = 'preamble'
self.__override_table_final, self.__all_lists =\
self.__override_table_obj.parse_override_table(self.__override_table_final)
elif self.__token_info == '':
pass
else:
self.__override_table_final += line
def __found_revision_table_func(self, line):
self.__state = 'revision_table'
self.__revision_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
def __revision_table_func(self, line):
if int(self.__cb_count) == int(self.__close_group_count):
self.__state = 'preamble'
self.__revision_table_final = 'mi<tg<open______<revision-table\n' + \
'mi<mk<revtbl-beg\n' + self.__revision_table_final
self.__revision_table_final += \
'mi<mk<revtbl-end\n' + 'mi<tg<close_____<revision-table\n'
else:
self.__revision_table_final += line
def __found_doc_info_func(self, line):
self.__state = 'doc_info'
self.__doc_info_table_final = ''
self.__close_group_count = self.__ob_count
self.__cb_count = 0
def __doc_info_func(self, line):
if self.__cb_count == self.__close_group_count:
self.__state = 'preamble'
self.__doc_info_table_final = 'mi<tg<open______<doc-information\n' + \
'mi<mk<doc-in-beg\n' + self.__doc_info_table_final
self.__doc_info_table_final += \
'mi<mk<doc-in-end\n' + 'mi<tg<close_____<doc-information\n'
elif self.__token_info == 'ob<nu<open-brack':
if int(self.__ob_count) == int(self.__close_group_count) + 1:
self.__doc_info_table_final += \
'mi<mk<docinf-beg\n'
elif self.__token_info == 'cb<nu<clos-brack':
if int(self.__cb_count) == int(self.__close_group_count) + 1:
self.__doc_info_table_final += \
'mi<mk<docinf-end\n'
else:
self.__doc_info_table_final += line
def __margin_func(self, line):
"""
Handles lines that describe page info. Add the apporpriate info in the
token to the self.__margin_dict dicitonary.
"""
info = line[6:16]
changed = self.__margin_dict.get(info)
if changed == None:
print 'woops!'
else:
self.__page[changed] = line[20:-1]
#cw<pa<margin-lef<nu<1728
def __print_page_info(self):
self.__write_obj.write('mi<tg<empty-att_<page-definition')
for key in self.__page.keys():
self.__write_obj.write(
'<%s>%s' % (key, self.__page[key])
)
self.__write_obj.write('\n')
#mi<tg<open-att__<footn
def __print_sec_info(self):
"""
Check if there is any section info. If so, print it out.
If not, print out an empty tag to satisfy the dtd.
"""
if len(self.__section.keys()) == 0:
self.__write_obj.write(
'mi<tg<open______<section-definition\n'
)
else:
self.__write_obj.write(
'mi<tg<open-att__<section-definition')
keys = self.__section.keys()
for key in keys:
self.__write_obj.write(
'<%s>%s' % (key, self.__section[key])
)
self.__write_obj.write('\n')
def __section_func(self, line):
"""
Add info pertaining to section to the self.__section dictionary, to be
printed out later.
"""
info = self.__translate_sec.get(line[6:16])
if info == None:
sys.stderr.write ('woops!\n')
else:
self.__section[info] = 'true'
def __body_func(self, line):
self.__write_obj.write(line)
def __default_func(self, line):
# either in preamble or in body
pass
def __para_def_func(self, line):
# if self.__ob_group == 1
# this tells dept of group
if self.__cb_count == '0002':
self.__state = 'body'
self.__write_preamble()
self.__write_obj.write(line)
def __text_func(self, line):
"""
If the cb_count is less than 1, you have hit the body
For older RTF
Newer RTF should never have to use this function
"""
if self.__cb_count == '':
cb_count = '0002'
else:
cb_count = self.__cb_count
# ignore previous lines
# should be
# if self.__ob_group == 1
# this tells dept of group
if cb_count == '0002':
self.__state = 'body'
self.__write_preamble()
self.__write_obj.write(line)
def __row_def_func(self, line):
# if self.__ob_group == 1
# this tells dept of group
if self.__cb_count == '0002':
self.__state = 'body'
self.__write_preamble()
self.__write_obj.write(line)
def __new_section_func(self, line):
"""
This is new. The start of a section marks the end of the preamble
"""
if self.__cb_count == '0002':
self.__state = 'body'
self.__write_preamble()
else:
sys.stderr.write('module is preamble_div\n')
sys.stderr.write('method is __new_section_func\n')
sys.stderr.write('bracket count should be 2?\n')
self.__write_obj.write(line)
def __write_preamble(self):
"""
Write all the strings, which represent all the data in the preamble.
Write a body and section beginning.
"""
if self.__no_namespace:
self.__write_obj.write(
'mi<tg<open______<doc\n'
)
else:
self.__write_obj.write(
'mi<tg<open-att__<doc<xmlns>http://rtf2xml.sourceforge.net/\n')
self.__write_obj.write('mi<tg<open______<preamble\n')
self.__write_obj.write(self.__rtf_final)
if not self.__color_table_final:
self.__make_default_color_table()
if not self.__font_table_final:
self.__make_default_font_table()
self.__write_obj.write(self.__font_table_final)
self.__write_obj.write(self.__color_table_final)
if not self.__style_sheet_final:
self.__make_default_style_table()
self.__write_obj.write(self.__style_sheet_final)
self.__write_obj.write(self.__list_table_final)
self.__write_obj.write(self.__override_table_final)
self.__write_obj.write(self.__revision_table_final)
self.__write_obj.write(self.__doc_info_table_final)
self.__print_page_info()
self.__write_obj.write('ob<nu<open-brack<0001\n')
self.__write_obj.write('ob<nu<open-brack<0002\n')
self.__write_obj.write('cb<nu<clos-brack<0002\n')
self.__write_obj.write('mi<tg<close_____<preamble\n')
self.__write_obj.write('mi<tg<open______<body\n')
# self.__write_obj.write('mi<tg<open-att__<section<num>1\n')
# self.__print_sec_info()
# self.__write_obj.write('mi<tg<open______<headers-and-footers\n')
# self.__write_obj.write('mi<mk<head_foot_<\n')
# self.__write_obj.write('mi<tg<close_____<headers-and-footers\n')
self.__write_obj.write('mi<mk<body-open_\n')
def __preamble_func(self, line):
"""
Check if the token info belongs to the dictionary. If so, take the
appropriate action.
"""
action = self.__state_dict.get(self.__token_info)
if action:
action(line)
def make_preamble_divisions(self):
self.__initiate_values()
read_obj = open(self.__file, 'r')
self.__write_obj = open(self.__write_to, 'w')
line_to_read = 1
while line_to_read:
line_to_read = read_obj.readline()
line = line_to_read
self.__token_info = line[:16]
if self.__token_info == 'ob<nu<open-brack':
self.__ob_count = line[-5:-1]
self.__ob_group += 1
if self.__token_info == 'cb<nu<clos-brack':
self.__cb_count = line[-5:-1]
self.__ob_group -= 1
action = self.__state_dict.get(self.__state)
if action == None:
print self.__state
action(line)
read_obj.close()
self.__write_obj.close()
copy_obj = copy.Copy(bug_handler = self.__bug_handler)
if self.__copy:
copy_obj.copy_file(self.__write_to, "preamble_div.data")
copy_obj.rename(self.__write_to, self.__file)
os.remove(self.__write_to)
return self.__all_lists
| gpl-3.0 |
samthor/intellij-community | python/helpers/pydev/pydevd_attach_to_process/winappdbg/win32/shell32.py | 102 | 14007 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder 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.
"""
Wrapper for shell32.dll in ctypes.
"""
# TODO
# * Add a class wrapper to SHELLEXECUTEINFO
# * More logic into ShellExecuteEx
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import LocalFree
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Constants ----------------------------------------------------------------
SEE_MASK_DEFAULT = 0x00000000
SEE_MASK_CLASSNAME = 0x00000001
SEE_MASK_CLASSKEY = 0x00000003
SEE_MASK_IDLIST = 0x00000004
SEE_MASK_INVOKEIDLIST = 0x0000000C
SEE_MASK_ICON = 0x00000010
SEE_MASK_HOTKEY = 0x00000020
SEE_MASK_NOCLOSEPROCESS = 0x00000040
SEE_MASK_CONNECTNETDRV = 0x00000080
SEE_MASK_NOASYNC = 0x00000100
SEE_MASK_DOENVSUBST = 0x00000200
SEE_MASK_FLAG_NO_UI = 0x00000400
SEE_MASK_UNICODE = 0x00004000
SEE_MASK_NO_CONSOLE = 0x00008000
SEE_MASK_ASYNCOK = 0x00100000
SEE_MASK_HMONITOR = 0x00200000
SEE_MASK_NOZONECHECKS = 0x00800000
SEE_MASK_WAITFORINPUTIDLE = 0x02000000
SEE_MASK_FLAG_LOG_USAGE = 0x04000000
SE_ERR_FNF = 2
SE_ERR_PNF = 3
SE_ERR_ACCESSDENIED = 5
SE_ERR_OOM = 8
SE_ERR_DLLNOTFOUND = 32
SE_ERR_SHARE = 26
SE_ERR_ASSOCINCOMPLETE = 27
SE_ERR_DDETIMEOUT = 28
SE_ERR_DDEFAIL = 29
SE_ERR_DDEBUSY = 30
SE_ERR_NOASSOC = 31
SHGFP_TYPE_CURRENT = 0
SHGFP_TYPE_DEFAULT = 1
CSIDL_DESKTOP = 0x0000
CSIDL_INTERNET = 0x0001
CSIDL_PROGRAMS = 0x0002
CSIDL_CONTROLS = 0x0003
CSIDL_PRINTERS = 0x0004
CSIDL_PERSONAL = 0x0005
CSIDL_FAVORITES = 0x0006
CSIDL_STARTUP = 0x0007
CSIDL_RECENT = 0x0008
CSIDL_SENDTO = 0x0009
CSIDL_BITBUCKET = 0x000a
CSIDL_STARTMENU = 0x000b
CSIDL_MYDOCUMENTS = CSIDL_PERSONAL
CSIDL_MYMUSIC = 0x000d
CSIDL_MYVIDEO = 0x000e
CSIDL_DESKTOPDIRECTORY = 0x0010
CSIDL_DRIVES = 0x0011
CSIDL_NETWORK = 0x0012
CSIDL_NETHOOD = 0x0013
CSIDL_FONTS = 0x0014
CSIDL_TEMPLATES = 0x0015
CSIDL_COMMON_STARTMENU = 0x0016
CSIDL_COMMON_PROGRAMS = 0x0017
CSIDL_COMMON_STARTUP = 0x0018
CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019
CSIDL_APPDATA = 0x001a
CSIDL_PRINTHOOD = 0x001b
CSIDL_LOCAL_APPDATA = 0x001c
CSIDL_ALTSTARTUP = 0x001d
CSIDL_COMMON_ALTSTARTUP = 0x001e
CSIDL_COMMON_FAVORITES = 0x001f
CSIDL_INTERNET_CACHE = 0x0020
CSIDL_COOKIES = 0x0021
CSIDL_HISTORY = 0x0022
CSIDL_COMMON_APPDATA = 0x0023
CSIDL_WINDOWS = 0x0024
CSIDL_SYSTEM = 0x0025
CSIDL_PROGRAM_FILES = 0x0026
CSIDL_MYPICTURES = 0x0027
CSIDL_PROFILE = 0x0028
CSIDL_SYSTEMX86 = 0x0029
CSIDL_PROGRAM_FILESX86 = 0x002a
CSIDL_PROGRAM_FILES_COMMON = 0x002b
CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c
CSIDL_COMMON_TEMPLATES = 0x002d
CSIDL_COMMON_DOCUMENTS = 0x002e
CSIDL_COMMON_ADMINTOOLS = 0x002f
CSIDL_ADMINTOOLS = 0x0030
CSIDL_CONNECTIONS = 0x0031
CSIDL_COMMON_MUSIC = 0x0035
CSIDL_COMMON_PICTURES = 0x0036
CSIDL_COMMON_VIDEO = 0x0037
CSIDL_RESOURCES = 0x0038
CSIDL_RESOURCES_LOCALIZED = 0x0039
CSIDL_COMMON_OEM_LINKS = 0x003a
CSIDL_CDBURN_AREA = 0x003b
CSIDL_COMPUTERSNEARME = 0x003d
CSIDL_PROFILES = 0x003e
CSIDL_FOLDER_MASK = 0x00ff
CSIDL_FLAG_PER_USER_INIT = 0x0800
CSIDL_FLAG_NO_ALIAS = 0x1000
CSIDL_FLAG_DONT_VERIFY = 0x4000
CSIDL_FLAG_CREATE = 0x8000
CSIDL_FLAG_MASK = 0xff00
#--- Structures ---------------------------------------------------------------
# typedef struct _SHELLEXECUTEINFO {
# DWORD cbSize;
# ULONG fMask;
# HWND hwnd;
# LPCTSTR lpVerb;
# LPCTSTR lpFile;
# LPCTSTR lpParameters;
# LPCTSTR lpDirectory;
# int nShow;
# HINSTANCE hInstApp;
# LPVOID lpIDList;
# LPCTSTR lpClass;
# HKEY hkeyClass;
# DWORD dwHotKey;
# union {
# HANDLE hIcon;
# HANDLE hMonitor;
# } DUMMYUNIONNAME;
# HANDLE hProcess;
# } SHELLEXECUTEINFO, *LPSHELLEXECUTEINFO;
class SHELLEXECUTEINFO(Structure):
_fields_ = [
("cbSize", DWORD),
("fMask", ULONG),
("hwnd", HWND),
("lpVerb", LPSTR),
("lpFile", LPSTR),
("lpParameters", LPSTR),
("lpDirectory", LPSTR),
("nShow", ctypes.c_int),
("hInstApp", HINSTANCE),
("lpIDList", LPVOID),
("lpClass", LPSTR),
("hkeyClass", HKEY),
("dwHotKey", DWORD),
("hIcon", HANDLE),
("hProcess", HANDLE),
]
def __get_hMonitor(self):
return self.hIcon
def __set_hMonitor(self, hMonitor):
self.hIcon = hMonitor
hMonitor = property(__get_hMonitor, __set_hMonitor)
LPSHELLEXECUTEINFO = POINTER(SHELLEXECUTEINFO)
#--- shell32.dll --------------------------------------------------------------
# LPWSTR *CommandLineToArgvW(
# LPCWSTR lpCmdLine,
# int *pNumArgs
# );
def CommandLineToArgvW(lpCmdLine):
_CommandLineToArgvW = windll.shell32.CommandLineToArgvW
_CommandLineToArgvW.argtypes = [LPVOID, POINTER(ctypes.c_int)]
_CommandLineToArgvW.restype = LPVOID
if not lpCmdLine:
lpCmdLine = None
argc = ctypes.c_int(0)
vptr = ctypes.windll.shell32.CommandLineToArgvW(lpCmdLine, byref(argc))
if vptr == NULL:
raise ctypes.WinError()
argv = vptr
try:
argc = argc.value
if argc <= 0:
raise ctypes.WinError()
argv = ctypes.cast(argv, ctypes.POINTER(LPWSTR * argc) )
argv = [ argv.contents[i] for i in compat.xrange(0, argc) ]
finally:
if vptr is not None:
LocalFree(vptr)
return argv
def CommandLineToArgvA(lpCmdLine):
t_ansi = GuessStringType.t_ansi
t_unicode = GuessStringType.t_unicode
if isinstance(lpCmdLine, t_ansi):
cmdline = t_unicode(lpCmdLine)
else:
cmdline = lpCmdLine
return [t_ansi(x) for x in CommandLineToArgvW(cmdline)]
CommandLineToArgv = GuessStringType(CommandLineToArgvA, CommandLineToArgvW)
# HINSTANCE ShellExecute(
# HWND hwnd,
# LPCTSTR lpOperation,
# LPCTSTR lpFile,
# LPCTSTR lpParameters,
# LPCTSTR lpDirectory,
# INT nShowCmd
# );
def ShellExecuteA(hwnd = None, lpOperation = None, lpFile = None, lpParameters = None, lpDirectory = None, nShowCmd = None):
_ShellExecuteA = windll.shell32.ShellExecuteA
_ShellExecuteA.argtypes = [HWND, LPSTR, LPSTR, LPSTR, LPSTR, INT]
_ShellExecuteA.restype = HINSTANCE
if not nShowCmd:
nShowCmd = 0
success = _ShellExecuteA(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd)
success = ctypes.cast(success, c_int)
success = success.value
if not success > 32: # weird! isn't it?
raise ctypes.WinError(success)
def ShellExecuteW(hwnd = None, lpOperation = None, lpFile = None, lpParameters = None, lpDirectory = None, nShowCmd = None):
_ShellExecuteW = windll.shell32.ShellExecuteW
_ShellExecuteW.argtypes = [HWND, LPWSTR, LPWSTR, LPWSTR, LPWSTR, INT]
_ShellExecuteW.restype = HINSTANCE
if not nShowCmd:
nShowCmd = 0
success = _ShellExecuteW(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd)
success = ctypes.cast(success, c_int)
success = success.value
if not success > 32: # weird! isn't it?
raise ctypes.WinError(success)
ShellExecute = GuessStringType(ShellExecuteA, ShellExecuteW)
# BOOL ShellExecuteEx(
# __inout LPSHELLEXECUTEINFO lpExecInfo
# );
def ShellExecuteEx(lpExecInfo):
if isinstance(lpExecInfo, SHELLEXECUTEINFOA):
ShellExecuteExA(lpExecInfo)
elif isinstance(lpExecInfo, SHELLEXECUTEINFOW):
ShellExecuteExW(lpExecInfo)
else:
raise TypeError("Expected SHELLEXECUTEINFOA or SHELLEXECUTEINFOW, got %s instead" % type(lpExecInfo))
def ShellExecuteExA(lpExecInfo):
_ShellExecuteExA = windll.shell32.ShellExecuteExA
_ShellExecuteExA.argtypes = [LPSHELLEXECUTEINFOA]
_ShellExecuteExA.restype = BOOL
_ShellExecuteExA.errcheck = RaiseIfZero
_ShellExecuteExA(byref(lpExecInfo))
def ShellExecuteExW(lpExecInfo):
_ShellExecuteExW = windll.shell32.ShellExecuteExW
_ShellExecuteExW.argtypes = [LPSHELLEXECUTEINFOW]
_ShellExecuteExW.restype = BOOL
_ShellExecuteExW.errcheck = RaiseIfZero
_ShellExecuteExW(byref(lpExecInfo))
# HINSTANCE FindExecutable(
# __in LPCTSTR lpFile,
# __in_opt LPCTSTR lpDirectory,
# __out LPTSTR lpResult
# );
def FindExecutableA(lpFile, lpDirectory = None):
_FindExecutableA = windll.shell32.FindExecutableA
_FindExecutableA.argtypes = [LPSTR, LPSTR, LPSTR]
_FindExecutableA.restype = HINSTANCE
lpResult = ctypes.create_string_buffer(MAX_PATH)
success = _FindExecutableA(lpFile, lpDirectory, lpResult)
success = ctypes.cast(success, ctypes.c_void_p)
success = success.value
if not success > 32: # weird! isn't it?
raise ctypes.WinError(success)
return lpResult.value
def FindExecutableW(lpFile, lpDirectory = None):
_FindExecutableW = windll.shell32.FindExecutableW
_FindExecutableW.argtypes = [LPWSTR, LPWSTR, LPWSTR]
_FindExecutableW.restype = HINSTANCE
lpResult = ctypes.create_unicode_buffer(MAX_PATH)
success = _FindExecutableW(lpFile, lpDirectory, lpResult)
success = ctypes.cast(success, ctypes.c_void_p)
success = success.value
if not success > 32: # weird! isn't it?
raise ctypes.WinError(success)
return lpResult.value
FindExecutable = GuessStringType(FindExecutableA, FindExecutableW)
# HRESULT SHGetFolderPath(
# __in HWND hwndOwner,
# __in int nFolder,
# __in HANDLE hToken,
# __in DWORD dwFlags,
# __out LPTSTR pszPath
# );
def SHGetFolderPathA(nFolder, hToken = None, dwFlags = SHGFP_TYPE_CURRENT):
_SHGetFolderPathA = windll.shell32.SHGetFolderPathA # shfolder.dll in older win versions
_SHGetFolderPathA.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPSTR]
_SHGetFolderPathA.restype = HRESULT
_SHGetFolderPathA.errcheck = RaiseIfNotZero # S_OK == 0
pszPath = ctypes.create_string_buffer(MAX_PATH + 1)
_SHGetFolderPathA(None, nFolder, hToken, dwFlags, pszPath)
return pszPath.value
def SHGetFolderPathW(nFolder, hToken = None, dwFlags = SHGFP_TYPE_CURRENT):
_SHGetFolderPathW = windll.shell32.SHGetFolderPathW # shfolder.dll in older win versions
_SHGetFolderPathW.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPWSTR]
_SHGetFolderPathW.restype = HRESULT
_SHGetFolderPathW.errcheck = RaiseIfNotZero # S_OK == 0
pszPath = ctypes.create_unicode_buffer(MAX_PATH + 1)
_SHGetFolderPathW(None, nFolder, hToken, dwFlags, pszPath)
return pszPath.value
SHGetFolderPath = DefaultStringType(SHGetFolderPathA, SHGetFolderPathW)
# BOOL IsUserAnAdmin(void);
def IsUserAnAdmin():
# Supposedly, IsUserAnAdmin() is deprecated in Vista.
# But I tried it on Windows 7 and it works just fine.
_IsUserAnAdmin = windll.shell32.IsUserAnAdmin
_IsUserAnAdmin.argtypes = []
_IsUserAnAdmin.restype = bool
return _IsUserAnAdmin()
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| apache-2.0 |
CTSRD-SOAAP/chromium-42.0.2311.135 | tools/gyp/test/mac/gyptest-postbuild-fail.py | 88 | 2218 | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that a failing postbuild step lets the build fail.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
# set |match| to ignore build stderr output.
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'],
match = lambda a, b: True)
test.run_gyp('test.gyp', chdir='postbuild-fail')
build_error_code = {
'xcode': [1, 65], # 1 for xcode 3, 65 for xcode 4 (see `man sysexits`)
'make': 2,
'ninja': 1,
'xcode-ninja': [1, 65],
}[test.format]
# If a postbuild fails, all postbuilds should be re-run on the next build.
# In Xcode 3, even if the first postbuild fails the other postbuilds were
# still executed. In Xcode 4, postbuilds are stopped after the first
# failing postbuild. This test checks for the Xcode 4 behavior.
# Ignore this test on Xcode 3.
import subprocess
job = subprocess.Popen(['xcodebuild', '-version'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, err = job.communicate()
if job.returncode != 0:
print out
raise Exception('Error %d running xcodebuild' % job.returncode)
if out.startswith('Xcode 3.'):
test.pass_test()
# Non-bundles
test.build('test.gyp', 'nonbundle', chdir='postbuild-fail',
status=build_error_code)
test.built_file_must_not_exist('static_touch',
chdir='postbuild-fail')
# Check for non-up-to-date-ness by checking if building again produces an
# error.
test.build('test.gyp', 'nonbundle', chdir='postbuild-fail',
status=build_error_code)
# Bundles
test.build('test.gyp', 'bundle', chdir='postbuild-fail',
status=build_error_code)
test.built_file_must_not_exist('dynamic_touch',
chdir='postbuild-fail')
# Check for non-up-to-date-ness by checking if building again produces an
# error.
test.build('test.gyp', 'bundle', chdir='postbuild-fail',
status=build_error_code)
test.pass_test()
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.