rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'ars': ars }, request)
'ars': prefixes }, request)
def dashboard(request): '''The user's dashboard.''' handle = request.session[ 'handle' ] # ... pick out data for the dashboard and return it # my parents # the resources that my parents have given me # the resources that I have accepted from my parents # my children # the resources that I have given my children # my ro...
try: self.queue.remove(self) except ValueError: pass
for i in xrange(len(self.queue) - 1, -1, -1): if self.queue[i] is self: del self.queue[i]
def cancel(self): """ Cancel a timer, if it was set. """ if self.gc_debug: self.trace("Canceling %r" % self) try: self.queue.remove(self) except ValueError: pass
self.close()
self.handle_close()
def handle_read(self): """ Asyncore says socket is readable. Make sure there's no TLS write already in progress, retry previous read operation if we had one that was waiting for more input, otherwise try to read some data, and handle all the weird OpenSSL exceptions that the TLS code throws. """ assert self.retry_writ...
self.close()
self.handle_close()
def initiate_send(self): """ Initiate a write operation. This is just a wrapper around the asynchat method, to handle all the whacky TLS exceptions. """ assert self.retry_read is None and self.retry_write is None, "%r: TLS I/O already in progress, r %r w %r" % (self, self.retry_read, self.retry_write) try: asynchat.as...
def __init__(self, handlers, port = 80, host = "", cert = None, key = None, ta = None, dynamic_ta = None, af = supported_address_families[0]):
def __init__(self, handlers, port = default_tcp_port, host = "", cert = None, key = None, ta = None, dynamic_ta = None, af = supported_address_families[0]):
def __init__(self, handlers, port = 80, host = "", cert = None, key = None, ta = None, dynamic_ta = None, af = supported_address_families[0]): self.log("Listener cert %r key %r ta %r dynamic_ta %r" % (cert, key, ta, dynamic_ta)) asyncore.dispatcher.__init__(self) self.handlers = handlers self.cert = cert self.key = key...
hostport = (u.hostname or "localhost", u.port or 80)
hostport = (u.hostname or "localhost", u.port or default_tcp_port)
def client(msg, client_key, client_cert, server_ta, url, callback, errback): """ Open client HTTPS connection, send a message, set up callbacks to handle response. """ u = urlparse.urlparse(url) if (u.scheme not in ("", "https") or u.username is not None or u.password is not None or u.params != "" or u.query != ...
self.log("Connecting to AF %r sockaddr %r" % (self.af, self.address))
self.log("Connecting to AF %s host %s port %s addr %s" % (self.af, self.host, self.port, self.address))
def gotaddrinfo(self, addrinfo): """ Got address data from DNS, create socket and request connection. """ try: self.af, self.address = random.choice(addrinfo) self.log("Connecting to AF %r sockaddr %r" % (self.af, self.address)) self.create_socket(self.af, socket.SOCK_STREAM) self.connect((self.address, self.port)) exc...
print "Usage: %s [--mark] --input maildir --output mhfolder" % sys.argv[0]
print "Usage: %s [--mark] [--kill] [--tag tag]] [--unseen] --input maildir --output mhfolder" % sys.argv[0]
def usage(ok): print "Usage: %s [--mark] --input maildir --output mhfolder" % sys.argv[0] print __doc__ sys.exit(0 if ok else 1)
opts, argv = getopt.getopt(sys.argv[1:], "hi:kmo:?", ["help", "input=", "kill", "mark", "output="])
opts, argv = getopt.getopt(sys.argv[1:], "hi:kmo:t:u?", ["help", "input=", "kill", "mark", "output=", "tag=", "unseen"])
def usage(ok): print "Usage: %s [--mark] --input maildir --output mhfolder" % sys.argv[0] print __doc__ sys.exit(0 if ok else 1)
if "S" not in srcmsg.get_flags(): assert not srcmsg.is_multipart() and srcmsg.get_content_type() == "application/x-rpki" payload = srcmsg.get_payload(decode = True) cms = POW.derRead(POW.CMS_MESSAGE, payload) txt = cms.verify(POW.X509Store(), None, POW.CMS_NOCRL | POW.CMS_NO_SIGNER_CERT_VERIFY | POW.CMS_NO_ATTR_VERIFY ...
if unseen_only and "S" in srcmsg.get_flags(): continue assert not srcmsg.is_multipart() and srcmsg.get_content_type() == "application/x-rpki" payload = srcmsg.get_payload(decode = True) cms = POW.derRead(POW.CMS_MESSAGE, payload) txt = cms.verify(POW.X509Store(), None, POW.CMS_NOCRL | POW.CMS_NO_SIGNER_CERT_VERIFY | PO...
def publication(): msg["X-RPKI-Left-Right-Type"] = xml.get("type") msg["Subject"] = "Publication %s" % xml.get("type")
HTTP(S) server stream.
HTTP server stream.
def handle_close(self): """ Wrapper around asynchat connection close handler, so that we can log the event. """ self.log("Close event in HTTP stream handler") asynchat.async_chat.handle_close(self)
Listener for incoming HTTP(S) connections.
Listener for incoming HTTP connections.
def send_message(self, code, reason = "OK", body = None): """ Queue up reply message. If both parties agree that connection is persistant, and if no error occurred, restart this stream to listen for next message; otherwise, queue up a close event for this stream so it will shut down once the reply has been sent. """ s...
HTTP(S) client stream.
HTTP client stream.
def handle_error(self): """ Asyncore signaled an error, pass it along or log it. """ if sys.exc_info()[0] in (SystemExit, rpki.async.ExitNow): raise self.log("Error in HTTP listener", rpki.log.warn) rpki.log.traceback()
self.state = "opening"
self.set_state("opening")
def __init__(self, queue, hostport): self.log("Creating new connection to %r" % (hostport,)) http_stream.__init__(self) self.queue = queue self.host = hostport[0] self.port = hostport[1] self.state = "opening" self.expect_close = not want_persistent_client
rpki.adns.getaddrinfo(self.gotaddrinfo, self.dns_error, self.host, supported_address_families(enable_ipv6_clients))
families = supported_address_families(enable_ipv6_clients) self.log("Starting ADNS lookup for %s in families %r" % (self.host, families)) rpki.adns.getaddrinfo(self.gotaddrinfo, self.dns_error, self.host, families)
def start(self): """ Create socket and request a connection. """ if not use_adns: self.gotaddrinfo([(socket.AF_INET, self.host)]) elif self.host == "localhost": self.gotaddrinfo(localhost_addrinfo()) else: import rpki.adns # This should move to start of file once we've decided to inflict it on all user...
set.add(pdu.self_handle)
seen.add(pdu.self_handle)
def usage(rc): print 'usage: %s [ -hvV ] [ --help ] [ --verbose ] [ --version ]' % basename(sys.argv[0],) sys.exit(rc)
from __future__ import with_statement import os import os.path import csv import math import rpki.myrpki from rpki.resource_set import resource_range_ipv4 from rpki.ipaddrs import v4addr import settings def form_to_conf(data): """Write out a myrpki.conf based on the given form data.""" handle = data['handle'] confdir...
def configure_resources(handle): # write out the .csv files and invoke the myrpki command line tool output_asns(handle) output_prefixes(handle) output_roas(handle) #invoke_rpki(handle.handle, ['configure_daemons'])
self.queue.sort()
self.queue.sort(key = lambda x: x.when)
def set(self, when): """ Set a timer. Argument can be a datetime, to specify an absolute time, or a timedelta, to specify an offset time. """ if self.gc_debug: self.trace("Setting %r to %r" % (self, when)) if isinstance(when, rpki.sundial.timedelta): self.when = rpki.sundial.now() + when else: self.when = when assert ...
return cmp(self.when, other.when)
return cmp(id(self), id(other))
def __cmp__(self, other): return cmp(self.when, other.when)
for i in xrange(len(self.queue) - 1, -1, -1): if self.queue[i] is self: del self.queue[i]
try: while True: self.queue.remove(self) except ValueError: pass
def cancel(self): """ Cancel a timer, if it was set. """ if self.gc_debug: self.trace("Canceling %r" % self) for i in xrange(len(self.queue) - 1, -1, -1): if self.queue[i] is self: del self.queue[i]
def __init__(self, gski, uri, asnum, date, asn1):
def __init__(self, uri, asnum, date, asn1):
def __init__(self, gski, uri, asnum, date, asn1): assert len(asn1[0]) <= self.addr_type.bits x = 0L for y in asn1[0]: x = (x << 1) | y x <<= (self.addr_type.bits - len(asn1[0])) self.gski = gski self.uri = uri self.asn = asnum self.date = date self.prefix = self.addr_type(x) self.prefixlen = len(asn1[0]) self.max_prefi...
self.gski = gski
def __init__(self, gski, uri, asnum, date, asn1): assert len(asn1[0]) <= self.addr_type.bits x = 0L for y in asn1[0]: x = (x << 1) | y x <<= (self.addr_type.bits - len(asn1[0])) self.gski = gski self.uri = uri self.asn = asnum self.date = date self.prefix = self.addr_type(x) self.prefixlen = len(asn1[0]) self.max_prefi...
gski = f[:-4]
def __init__(self, rcynic_dir): for root, dirs, files in os.walk(rcynic_dir): for f in files: if f.endswith(".roa"): gski = f[:-4] path = os.path.join(root, f) uri = "rsync://" + path[len(rcynic_dir):].lstrip("/") roa = rpki.x509.ROA(DER_file = path) version, asnum, asn1 = roa.extract().get() assert version == 0, "ROA ...
self.append(afi_map[afi](gski, uri, asnum, notBefore.strftime("%Y%m%d"), addr))
self.append(afi_map[afi](uri, asnum, notBefore.strftime("%Y%m%d"), addr))
def __init__(self, rcynic_dir): for root, dirs, files in os.walk(rcynic_dir): for f in files: if f.endswith(".roa"): gski = f[:-4] path = os.path.join(root, f) uri = "rsync://" + path[len(rcynic_dir):].lstrip("/") roa = rpki.x509.ROA(DER_file = path) version, asnum, asn1 = roa.extract().get() assert version == 0, "ROA ...
open(os.path.join(output, r.gski), "w").write(str(r))
r.write(output)
def usage(code = 1): f = sys.stderr if code else sys.stdout f.write("Usage: %s [options] rcynic-data/authenticated\n\nOptions:\n" % sys.argv[0]) for opt in options: f.write(" --" + ((opt[:-1] + " argument") if "=" in opt else opt) + "\n") f.write(__doc__) sys.exit(code)
ar = h5.oArchive("foo.h5")
ar = h5.oArchive("test.h5")
def write(): ar = h5.oArchive("foo.h5") ar.write("/int", 9) ar.write("/double", 9.123) ar.write("/cplx", complex(1, 2)) ar.write("/str", "test") ar.write("/np/int", np.array([1, 2, 3]))
ar = h5.iArchive("foo.h5")
ar = h5.iArchive("test.h5")
def read(): ar = h5.iArchive("foo.h5") i = ar.read("/int") d = ar.read("/double")
c = ar.read("/cplx")
def read(): ar = h5.iArchive("foo.h5") i = ar.read("/int") d = ar.read("/double")
if type(i) != int or type(d) != float or type(s) != str:
if type(i) != int or type(d) != float or type(c) != complex or type(s) != str:
def read(): ar = h5.iArchive("foo.h5") i = ar.read("/int") d = ar.read("/double")
return int(values[0])
return db.Key.from_path('AppEngineDbInvocation', int(values[0]))
def generate_key(self, i, values): return int(values[0])
bulkloader.Loader.__init__(self, 'DbUser', [('email', str)
bulkloader.Loader.__init__(self, 'AppEngineDbUser', [('openid', str), ('email', str)
def __init__(self): bulkloader.Loader.__init__(self, 'DbUser', [('email', str) ])
class DbUserExporter(bulkloader.Exporter):
class AppEngineDbUserExporter(bulkloader.Exporter):
def __init__(self): bulkloader.Loader.__init__(self, 'DbUser', [('email', str) ])
bulkloader.Exporter.__init__(self, 'DbUser', [ ('__key__', lambda x: x.to_path()[1], None), ('email', str, None)
bulkloader.Exporter.__init__(self, 'AppEngineDbUser', [ ('__key__', lambda x: x.to_path()[1], ''), ('email', str, '')
def __init__(self): bulkloader.Exporter.__init__(self, 'DbUser', [ ('__key__', lambda x: x.to_path()[1], None), ('email', str, None) ])
class DbInvocation(db.Model): who = db.ReferenceProperty(DbUser)
class AppEngineDbInvocation(db.Model): who = db.ReferenceProperty(AppEngineDbUser)
def __init__(self): bulkloader.Exporter.__init__(self, 'DbUser', [ ('__key__', lambda x: x.to_path()[1], None), ('email', str, None) ])
class DbInvocationLoader(bulkloader.Loader):
class AppEngineDbInvocationLoader(bulkloader.Loader):
def __init__(self): bulkloader.Exporter.__init__(self, 'DbUser', [ ('__key__', lambda x: x.to_path()[1], None), ('email', str, None) ])
bulkloader.Loader.__init__(self, 'DbInvocation', [('who', db.Key), ('startTime', long), ('endTime', long)
bulkloader.Loader.__init__(self, 'AppEngineDbInvocation', [('pk', int), ('who', lambda x: db.Key.from_path('AppEngineDbUser', x)), ('startTime', long), ('endTime', long)
def __init__(self): bulkloader.Loader.__init__(self, 'DbInvocation', [('who', db.Key), ('startTime', long), ('endTime', long) ])
class DbInvocationExporter(bulkloader.Exporter):
class AppEngineDbInvocationExporter(bulkloader.Exporter):
def __init__(self): bulkloader.Loader.__init__(self, 'DbInvocation', [('who', db.Key), ('startTime', long), ('endTime', long) ])
bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('__key__', lambda x: x.to_path()[1], None), ('who', lambda x: x.to_path()[1], None), ('startTime', str, None),
bulkloader.Exporter.__init__(self, 'AppEngineDbInvocation', [ ('__key__', lambda x: x.to_path()[1], ''), ('who', lambda x: x.to_path()[1], ''), ('startTime', str, ''),
def __init__(self): bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('__key__', lambda x: x.to_path()[1], None), ('who', lambda x: x.to_path()[1], None), ('startTime', str, None), ('endTime', str, '') ])
class DbIssue(db.Model):
class AppEngineDbIssue(db.Model):
def __init__(self): bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('__key__', lambda x: x.to_path()[1], None), ('who', lambda x: x.to_path()[1], None), ('startTime', str, None), ('endTime', str, '') ])
class DbIssueLoader(bulkloader.Loader):
class AppEngineDbIssueLoader(bulkloader.Loader):
def __init__(self): bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('__key__', lambda x: x.to_path()[1], None), ('who', lambda x: x.to_path()[1], None), ('startTime', str, None), ('endTime', str, '') ])
bulkloader.Loader.__init__(self, 'DbIssue', [('bugPattern', str), ('priority', int), ('primaryClass', str), ('firstSeen', long), ('lastSeen', long), ('bugLink', str)
bulkloader.Loader.__init__(self, 'AppEngineDbIssue', [('issueHash', str), ('bugPattern', str), ('priority', int), ('primaryClass', str), ('firstSeen', long), ('lastSeen', long), ('bugLink', str), ('bugLinkType', str)
def __init__(self): bulkloader.Loader.__init__(self, 'DbIssue', [('bugPattern', str), ('priority', int), ('primaryClass', str), ('firstSeen', long), ('lastSeen', long), ('bugLink', str) ])
class DbIssueExporter(bulkloader.Exporter):
return entity def generate_key(self, i, values): return db.Key.from_path('AppEngineDbInvocation', int(values[0])) class AppEngineDbIssueExporter(bulkloader.Exporter):
def __init__(self): bulkloader.Loader.__init__(self, 'DbIssue', [('bugPattern', str), ('priority', int), ('primaryClass', str), ('firstSeen', long), ('lastSeen', long), ('bugLink', str) ])
bulkloader.Exporter.__init__(self, 'DbIssue', [ ('__key__', lambda x: x.to_path()[1], None), ('bugPattern', str, None), ('priority', str, None), ('primaryClass', str, None), ('firstSeen', str, None), ('lastSeen', str, 0), ('bugLink', str, '')
bulkloader.Exporter.__init__(self, 'AppEngineDbIssue', [('__key__', lambda x: x.to_path()[1], ''), ('bugPattern', str, ''), ('priority', str, ''), ('primaryClass', str, ''), ('firstSeen', str, ''), ('lastSeen', str, ''), ('bugLink', str, ''), ('bugLinkType', str, '')
def __init__(self): bulkloader.Exporter.__init__(self, 'DbIssue', [ ('__key__', lambda x: x.to_path()[1], None), ('bugPattern', str, None), ('priority', str, None), ('primaryClass', str, None), ('firstSeen', str, None), ('lastSeen', str, 0), ('bugLink', str, '') ])
class DbEvaluation(db.Model): who = db.ReferenceProperty(DbUser)
class AppEngineDbEvaluation(db.Model): who = db.ReferenceProperty(AppEngineDbUser)
def __init__(self): bulkloader.Exporter.__init__(self, 'DbIssue', [ ('__key__', lambda x: x.to_path()[1], None), ('bugPattern', str, None), ('priority', str, None), ('primaryClass', str, None), ('firstSeen', str, None), ('lastSeen', str, 0), ('bugLink', str, '') ])
invocation = db.ReferenceProperty(DbInvocation)
invocation = db.ReferenceProperty(AppEngineDbInvocation)
def __init__(self): bulkloader.Exporter.__init__(self, 'DbIssue', [ ('__key__', lambda x: x.to_path()[1], None), ('bugPattern', str, None), ('priority', str, None), ('primaryClass', str, None), ('firstSeen', str, None), ('lastSeen', str, 0), ('bugLink', str, '') ])
class DbEvaluationLoader(bulkloader.Loader):
class AppEngineDbEvaluationLoader(bulkloader.Loader):
def __init__(self): bulkloader.Exporter.__init__(self, 'DbIssue', [ ('__key__', lambda x: x.to_path()[1], None), ('bugPattern', str, None), ('priority', str, None), ('primaryClass', str, None), ('firstSeen', str, None), ('lastSeen', str, 0), ('bugLink', str, '') ])
bulkloader.Loader.__init__(self, 'DbEvaluation',
bulkloader.Loader.__init__(self, 'AppEngineDbEvaluation',
def __init__(self): bulkloader.Loader.__init__(self, 'DbEvaluation', [('who', str), ('designation', str), ('comment', str), ('when', long), ('invocation', db.Key) ])
class DbEvaluationExporter(bulkloader.Exporter):
class AppEngineDbEvaluationExporter(bulkloader.Exporter):
def __init__(self): bulkloader.Loader.__init__(self, 'DbEvaluation', [('who', str), ('designation', str), ('comment', str), ('when', long), ('invocation', db.Key) ])
bulkloader.Exporter.__init__(self, 'DbEvaluation', [ ('who', lambda x: x.to_path()[1], None),
bulkloader.Exporter.__init__(self, 'AppEngineDbEvaluation', [ ('who', lambda x: x.to_path()[1], ''),
def __init__(self): bulkloader.Exporter.__init__(self, 'DbEvaluation', [ ('who', lambda x: x.to_path()[1], None), ('designation', str, ''), ('comment', str, ''), ('__key__', lambda x: x.to_path()[1], None), ('when', str, None), ('invocation', lambda x: x.to_path()[1], None), ])
('__key__', lambda x: x.to_path()[1], None), ('when', str, None), ('invocation', lambda x: x.to_path()[1], None),
('__key__', lambda x: x.to_path()[1], ''), ('when', str, ''), ('invocation', lambda x: x.to_path()[1], ''),
def __init__(self): bulkloader.Exporter.__init__(self, 'DbEvaluation', [ ('who', lambda x: x.to_path()[1], None), ('designation', str, ''), ('comment', str, ''), ('__key__', lambda x: x.to_path()[1], None), ('when', str, None), ('invocation', lambda x: x.to_path()[1], None), ])
loaders = [DbUserLoader, DbIssueLoader, DbEvaluationLoader, DbInvocationLoader]
loaders = [AppEngineDbUserLoader, AppEngineDbIssueLoader, AppEngineDbEvaluationLoader, AppEngineDbInvocationLoader]
def __init__(self): bulkloader.Exporter.__init__(self, 'DbEvaluation', [ ('who', lambda x: x.to_path()[1], None), ('designation', str, ''), ('comment', str, ''), ('__key__', lambda x: x.to_path()[1], None), ('when', str, None), ('invocation', lambda x: x.to_path()[1], None), ])
exporters = [DbUserExporter, DbIssueExporter, DbEvaluationExporter, DbInvocationExporter]
exporters = [AppEngineDbUserExporter, AppEngineDbIssueExporter, AppEngineDbEvaluationExporter, AppEngineDbInvocationExporter]
def __init__(self): bulkloader.Exporter.__init__(self, 'DbEvaluation', [ ('who', lambda x: x.to_path()[1], None), ('designation', str, ''), ('comment', str, ''), ('__key__', lambda x: x.to_path()[1], None), ('when', str, None), ('invocation', lambda x: x.to_path()[1], None), ])
[ ('who', lambda x: x.to_path()[1], None),
[ ('__key__', lambda x: x.to_path()[1], None) ('who', lambda x: x.to_path()[1], None),
def __init__(self): bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('who', lambda x: x.to_path()[1], None), ('startTime', str, None), ('endTime', str, '') ])
[ ('__key__', lambda x: x.to_path()[1], None)
[ ('__key__', lambda x: x.to_path()[1], None),
def __init__(self): bulkloader.Exporter.__init__(self, 'DbInvocation', [ ('__key__', lambda x: x.to_path()[1], None) ('who', lambda x: x.to_path()[1], None), ('startTime', str, None), ('endTime', str, '') ])
pass
def afterSetUp(self): super(FunctionalTestCase, self).afterSetUp() provideAdapter(GeoStyleManager, (PortalContent,), IGeoCustomFeatureStyle) def tearDown(self): from zope.component import getGlobalSiteManager gsm = getGlobalSiteManager() gsm.unregisterAdapter(GeoStyleManager, (PortalContent,), IGeoCustomFeatureStyle...
def setup_product(): """Set up the package and its dependencies.""" fiveconfigure.debug_mode = True from collective.geo import contentlocations zcml.load_config('configure.zcml', contentlocations) fiveconfigure.debug_mode = False
def __init__( self, *args, **kwargs ): super(SlideInLTransition, self ).__init__( *args, **kwargs)
def init(self):
def __init__( self, *args, **kwargs ): super(SlideInLTransition, self ).__init__( *args, **kwargs)
self.init()
self.in_scene.position=( -self.width,0)
def __init__( self, *args, **kwargs ): super(SlideInLTransition, self ).__init__( *args, **kwargs)
def init(self): self.in_scene.position=( -self.width,0)
def init(self): self.in_scene.position=( -self.width,0)
Incoming scene
Incoming scene, the one that remains visible when the transition ends.
def __init__(self, dst, duration=1.25, src=None): '''Initializes the transition
self.in_scene = dst
envelope = scene.Scene() envelope.add(dst, name='dst') self.in_scene = envelope
def __init__(self, dst, duration=1.25, src=None): '''Initializes the transition
src = src.in_scene self.out_scene = src self.duration = duration
envelope = scene.Scene() envelope.add(src, name='src') self.out_scene = envelope self.duration = duration
def __init__(self, dst, duration=1.25, src=None): '''Initializes the transition
It removes both the incoming and the outgoing scenes from the transition scene, and restores the outgoing scene's attributes like: position, visible and scale.
Envelopes are discarded and the dst scene will be the one runned by director
def finish(self): '''Called when the time is over. It removes both the incoming and the outgoing scenes from the transition scene, and restores the outgoing scene's attributes like: position, visible and scale. ''' self.remove( self.in_scene ) self.remove( self.out_scene ) self.restore_out() director.replace( self.in_s...
self.remove( self.in_scene ) self.remove( self.out_scene ) self.restore_out() director.replace( self.in_scene )
dst = self.in_scene.get('dst') src = self.out_scene.get('src') director.replace( dst )
def finish(self): '''Called when the time is over. It removes both the incoming and the outgoing scenes from the transition scene, and restores the outgoing scene's attributes like: position, visible and scale. ''' self.remove( self.in_scene ) self.remove( self.out_scene ) self.restore_out() director.replace( self.in_s...
def restore_out( self ): '''Restore the position, visible and scale attributes of the outgoing scene to the original values''' self.out_scene.visible = True self.out_scene.position = (0,0) self.out_scene.scale = 1
def restore_out( self ): '''Restore the position, visible and scale attributes of the outgoing scene to the original values''' self.out_scene.visible = True self.out_scene.position = (0,0) self.out_scene.scale = 1
self.remove( self.in_scene ) self.restore_out() director.replace( self.in_scene )
dst = self.in_scene.get('dst') director.replace( dst )
def finish(self): '''Called when the time is over. It removes both the incoming and the outgoing scenes from the transition scene, and restores the outgoing scene's attributes like: position, visible and scale. ''' self.remove( self.in_scene ) self.restore_out() director.replace( self.in_scene )
self._window_original_width = self.window.width self._window_original_height = self.window.height
self._window_virtual_width = self.window.width self._window_virtual_height = self.window.height
def init(self, *args, **kwargs): """Initializes the Director creating the main window. Keyword arguments are passed to pyglet.window.Window().
return ( self._window_original_width, self._window_original_height)
return ( self._window_virtual_width, self._window_virtual_height)
def get_window_size( self ): """Returns the size of the window when it was created, and not the actual size of the window.
x_diff = self._window_original_width / float( self.window.width - self._offset_x * 2 ) y_diff = self._window_original_height / float( self.window.height - self._offset_y * 2 ) adjust_x = (self.window.width * x_diff - self._window_original_width ) / 2 adjust_y = (self.window.height * y_diff - self._window_original_heig...
x_diff = self._window_virtual_width / float( self.window.width - self._offset_x * 2 ) y_diff = self._window_virtual_height / float( self.window.height - self._offset_y * 2 ) adjust_x = (self.window.width * x_diff - self._window_virtual_width ) / 2 adjust_y = (self.window.height * y_diff - self._window_virtual_height )...
def get_virtual_coordinates( self, x, y ): """Transforms coordinates that belongs the *real* window size, to the coordinates that belongs to the *virtual* window.
h_relation = self.window.height / float(self._window_original_height) should_width = h_relation * self._window_original_width self._offset_x = (self.window.width - should_width) / 2
def scaled_resize_window( self, width, height): """One of two possible methods that are called when the main window is resized.
width, height = self.window.width, self.window.height ow, oh = self.get_window_size() glViewport(0, 0, width, height)
vw, vh = self.get_window_size() glViewport(self._offset_x, self._offset_y, self._usable_width, self._usable_height)
def set_projection(self): '''Sets a 3D projection mantaining the aspect ratio of the original window size'''
gluPerspective(60, 1.0*width/height, 0.1, 3000.0)
gluPerspective(60, self._usable_width/float(self._usable_height), 0.1, 3000.0)
def set_projection(self): '''Sets a 3D projection mantaining the aspect ratio of the original window size'''
gluLookAt( ow/2.0, oh/2.0, oh/1.1566, ow / 2.0, oh / 2.0, 0, 0.0, 1.0, 0.0
gluLookAt( vw/2.0, vh/2.0, vh/1.1566, vw/2.0, vh/2.0, 0, 0.0, 1.0, 0.0
def set_projection(self): '''Sets a 3D projection mantaining the aspect ratio of the original window size'''
if dx and dy:
if dx or dy:
def get_neighbors(self, cell, diagonals=False): '''Get all cells touching the sides of the nominated cell.
return Vector2(other.x - self[0], other.y - self[1])
return Vector2(other[0] - self.x, other[1] - self.y)
def __rsub__(self, other): if isinstance(other, Vector2): return Vector2(other.x - self.x, other.y - self.y) else: assert hasattr(other, '__len__') and len(other) == 2 return Vector2(other.x - self[0], other.y - self[1])
return Vector3(other.x - self[0], other.y - self[1], other.z - self[2])
return Vector3(other[0] - self.x, other[1] - self.y, other[2] - self.z)
def __rsub__(self, other): if isinstance(other, Vector3): return Vector3(other.x - self.x, other.y - self.y, other.z - self.z) else: assert hasattr(other, '__len__') and len(other) == 3 return Vector3(other.x - self[0], other.y - self[1], other.z - self[2])
id = c_uint(0)
id = GLuint(0)
def __init__ (self): """Create a new framebuffer object""" id = c_uint(0) glGenFramebuffersEXT (1, byref(id)) self._id = id.value
'''A class of MapLayer that has a regular array of Cells.
'''A regularly tesselated map that allows access to its cells by index (i, j).
def _update_sprite_set(self): # update the sprites set keep = set() for cell in self.get_visible_cells(): cx, cy = key = cell.origin[:2] keep.add(key) if cell.tile is None: continue if key not in self._sprites: self._sprites[key] = pyglet.sprite.Sprite(cell.tile.image, x=cx, y=cy, batch=self.batch) s = self._sprites[ke...
allowing [i][j] addressing: +---+---+---+ | d | e | f | +---+---+---+ | a | b | c | +---+---+---+
allowing [i][j] addressing:: +---+---+---+ | d | e | f | +---+---+---+ | a | b | c | +---+---+---+
def get_cell(self, i, j): ''' Return Cell at cell pos=(i, j).
and cells[0][1] = 'd'
(and thus the cell at (0,0) is 'a' and (1, 1) is 'd')
def get_cell(self, i, j): ''' Return Cell at cell pos=(i, j).
Additional attributes extending MapBase: edge_length -- length of an edge in pixels
Calculated attributes: edge_length -- length of an edge in pixels = int(th / math.sqrt(3)) tw -- with of a "tile" in pixels = edge_length * 2
def __init__(self, i, j, width, height, properties, tile): Rect.__init__(self, i*width, j*height, width, height) Cell.__init__(self, i, j, width, height, properties, tile)
increasing up, such that a map: /d\ /h\
increasing up, such that a map:: /d\ /h\
def __init__(self, i, j, width, height, properties, tile): Rect.__init__(self, i*width, j*height, width, height) Cell.__init__(self, i, j, width, height, properties, tile)
'''Get the Cell at pixel px=(x,y).
'''Get the Cell at pixel (x,y).
def get_at_pixel(self, x, y): '''Get the Cell at pixel px=(x,y). Return None if out of bounds.''' # XXX update my docstring s = self.edge_length # map is divided into columns of # s/2 (shared), s, s/2(shared), s, s/2 (shared), ... x = x // (s/2 + s) if x % 2: # every second cell is up one y -= self.th // 2 y = y // sel...
print 'LOOKING UP', (x, y), 'with edge_length', self.edge_length
def get_at_pixel(self, x, y): '''Get the Cell at pixel px=(x,y). Return None if out of bounds.''' # XXX update my docstring s = self.edge_length # map is divided into columns of # s/2 (shared), s, s/2(shared), s, s/2 (shared), ... x = x // (s/2 + s) if x % 2: # every second cell is up one y -= self.th // 2 y = y // sel...
y = y // self.th
print 'shift y=', y
def get_at_pixel(self, x, y): '''Get the Cell at pixel px=(x,y). Return None if out of bounds.''' # XXX update my docstring s = self.edge_length # map is divided into columns of # s/2 (shared), s, s/2(shared), s, s/2 (shared), ... x = x // (s/2 + s) if x % 2: # every second cell is up one y -= self.th // 2 y = y // sel...
''' def __init__(self, id, tw, th, cells, origin=None, properties=None): HexMap.__init__(self, id, tw, th, cells, origin, properties)
The Layer has a calculated attribute: edge_length -- length of an edge in pixels = int(th / math.sqrt(3)) tw -- with of a "tile" in pixels = edge_length * 2 Hexmaps store their cells in an offset array, column-major with y increasing up, such that a map: /d\ /h\ /b\_/f\_/ \_/c\_/g\ /a\_/e\_/ \_/ \_/ has cell...
def get_neighbor(self, cell, direction): '''Get the neighbor HexCell in the given direction which is one of self.UP, self.DOWN, self.UP_LEFT, self.UP_RIGHT, self.DOWN_LEFT or self.DOWN_RIGHT.
super(TransitionScene, self).__init__()
def __init__(self, dst, duration=1.25, src=None): '''Initializes the transition
if keyp in (key.PAGEDOWN,):
if keyp in (key.RIGHT,):
def on_key_press(self, keyp, mod): if keyp in (key.PAGEDOWN,): self.next_scene() elif keyp in (key.PAGEUP,): self.prev_scene()
elif keyp in (key.PAGEUP,):
elif keyp in (key.LEFT,):
def on_key_press(self, keyp, mod): if keyp in (key.PAGEDOWN,): self.next_scene() elif keyp in (key.PAGEUP,): self.prev_scene()
"Tiles"
"Tiles",
def on_key_press(self, keyp, mod): if keyp in (key.F1,): director.push( self.target )
width, height = director.window.width, director.window.height glViewport(0, 0, width, height)
glViewport(director._offset_x, director._offset_y, director._usable_width, director._usable_height)
def _set_3d_projection(cls): width, height = director.window.width, director.window.height
gluPerspective(60, 1.0*width/height, 0.1, 3000.0)
gluPerspective(60, 1.0*director._usable_width/director._usable_height, 0.1, 3000.0)
def _set_3d_projection(cls): width, height = director.window.width, director.window.height
def test_delete(self):
def test_remove_action(self):
def test_delete(self): node = CocosNode() self.assertTrue(len(node.actions)==0) action = ac.Action() node.do(action) self.assertTrue(len(node.actions)==1) node.remove_action(action) self.assertTrue(len(node.actions)==0)
if self.particle_count == 0 and self.auto_remove_on_finish == True:
if (not self.active and self.particle_count == 0 and self.auto_remove_on_finish == True):
def step( self, delta ):
self.manager.do(actions.ScaleTo(self._desired_scale, .1))
self.manager.do(cocos.actions.ScaleTo(self._desired_scale, .1))
def on_mouse_scroll(self, x, y, dx, dy): if dy < 0: if self._desired_scale < .2: return True self._desired_scale -= .1 elif dy > 0: if self._desired_scale > 2: return True self._desired_scale += .1 if dy: self.manager.do(actions.ScaleTo(self._desired_scale, .1)) return True
self.map_layer = level_to_edit.find(tiles.MapLayer).next()[1] self.tileset = level_to_edit.findall(tiles.TileSet).next()[1]
self.map_layer = level_to_edit.find(cocos.tiles.MapLayer).next()[1] self.tileset = level_to_edit.findall(cocos.tiles.TileSet).next()[1]
def __init__(self, level_to_edit): super(TileSetLayer, self).__init__() self.level_to_edit = level_to_edit self.map_layer = level_to_edit.find(tiles.MapLayer).next()[1] self.tileset = level_to_edit.findall(tiles.TileSet).next()[1] self.batch = pyglet.graphics.Batch()
for k,v in level_to_edit.find(tiles.MapLayer):
for k,v in level_to_edit.find(cocos.tiles.MapLayer):
def __init__(self, level_to_edit): super(TileSetLayer, self).__init__() self.level_to_edit = level_to_edit self.map_layer = level_to_edit.find(tiles.MapLayer).next()[1] self.tileset = level_to_edit.findall(tiles.TileSet).next()[1] self.batch = pyglet.graphics.Batch()
for id, ts in self.level_to_edit.findall(tiles.TileSet):
for id, ts in self.level_to_edit.findall(cocos.tiles.TileSet):
def __init__(self, level_to_edit): super(TileSetLayer, self).__init__() self.level_to_edit = level_to_edit self.map_layer = level_to_edit.find(tiles.MapLayer).next()[1] self.tileset = level_to_edit.findall(tiles.TileSet).next()[1] self.batch = pyglet.graphics.Batch()
self.manager = tiles.ScrollingManager()
self.manager = cocos.layer.ScrollingManager()
def __init__(self, edit_level_xml): super(EditorScene, self).__init__()
level_to_edit = tiles.load(edit_level_xml)
level_to_edit = cocos.tiles.load(edit_level_xml)
def __init__(self, edit_level_xml): super(EditorScene, self).__init__()
for id, layer in level_to_edit.find(tiles.MapLayer):
for id, layer in level_to_edit.find(cocos.tiles.MapLayer):
def __init__(self, edit_level_xml): super(EditorScene, self).__init__()