def render_grid_file(context, f):
	"""Allow direct use of GridOut GridFS file wrappers as endpoint responses."""

	f.seek(0)  # Ensure we are reading from the beginning.
	response = context.response  # Frequently accessed, so made local.  Useless optimization on Pypy.

	if __debug__:  # We add some useful diagnostic information in development, omitting from production due to sec.
		response.headers['Grid-ID'] = str(f._id)  # The GridFS file ID.
		log.debug("Serving GridFS file.", extra=dict(
				identifier = str(f._id),
				filename = f.filename,
				length = f.length,
				mimetype = f.content_type
			))

	response.conditional_response = True
	response.accept_ranges = 'bytes'  # We allow returns of partial content, if requested.
	response.content_type = f.content_type  # Direct transfer of GridFS-stored MIME type.
	response.content_length = f.length  # The length was pre-computed when the file was uploaded.
	response.content_md5 = response.etag = f.md5  # As was the MD5, used for simple integrity testing.
	response.last_modified = f.metadata.get('modified', None)  # Optional additional metadata.
	response.content_disposition = 'attachment; filename=' + f.name  # Preserve the filename through to the client.

	# Being asked for a range or not determines the streaming style used.
	if context.request.if_range.match_response(response):
		response.body_file = f  # Support seek + limited read.
	else:
		response.app_iter = iter(f)  # Assign the body as a streaming, chunked iterator.

	return True

def
render_grid_file
(
context
,
f
)
:
f
.
seek
(
0
)
response
=
context
.
response
if
__debug__
:
response
.
headers
[
'Grid-ID'
]
=
str
(
f
.
_id
)
log
.
debug
(
"Serving GridFS file."
,
extra
=
dict
(
identifier
=
str
(
f
.
_id
)
,
filename
=
f
.
filename
,
length
=
f
.
length
,
mimetype
=
f
.
content_type
)
)
response
.
conditional_response
=
True
response
.
accept_ranges
=
'bytes'
response
.
content_type
=
f
.
content_type
response
.
content_length
=
f
.
length
response
.
content_md5
=
response
.
etag
=
f
.
md5
response
.
last_modified
=
f
.
metadata
.
get
(
'modified'
,
)
response
.
content_disposition
=
'attachment; filename='
+
f
.
name
if
context
.
request
.
if_range
.
match_response
(
response
)
:
response
.
body_file
=
f
else
:
response
.
app_iter
=
iter
(
f
)
return
True

Allow direct use of GridOut GridFS file wrappers as endpoint responses .


def save(self, obj):
        """ Save to file.
        """
        fd = None
        try:
            fd = open(self.dot_file.absolute_path, "wb")
            obj.save_dot(fd)
        finally:
            if fd is not None:
                fd.close()
#        self.m_time = getmtime(self.adaptee.absolute_path)
        return

def save ( self , obj ) : fd = None try : fd = open ( self . dot_file . absolute_path , "wb" ) obj . save_dot ( fd ) finally : if fd is not None : fd . close ( ) return


def load(self):
        """ Load the file.
        """
        fd = None
        try:
            obj = parse_dot_file( self.dot_file.absolute_path )
        finally:
            if fd is not None:
                fd.close()
        return obj

def load ( self ) : fd = None try : obj = parse_dot_file ( self . dot_file . absolute_path ) finally : if fd is not None : fd . close ( ) return obj


def is_in(self, point_x, point_y):
        """ Test if the point is within this ellipse """

        x = self.x_origin
        y = self.y_origin
        a = self.e_width#/2 # FIXME: Why divide by two
        b = self.e_height#/2

        return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0

def is_in ( self , point_x , point_y ) : x = self . x_origin y = self . y_origin a = self . e_width b = self . e_height return ( ( point_x - x ) ** 2 / ( a ** 2 ) ) + ( ( point_y - y ) ** 2 / ( b ** 2 ) ) < 1.0


def _draw_bounds(self, gc):
        """ Draws the component bounds for testing purposes """

        dx, dy = self.bounds
        x, y = self.position
        gc.rect(x, y, dx, dy)
        gc.stroke_path()

def _draw_bounds ( self , gc ) : dx , dy = self . bounds x , y = self . position gc . rect ( x , y , dx , dy ) gc . stroke_path ( )


def perform(self, event):
        """ Perform the action.
        """
        wizard = NewDotGraphWizard(parent=self.window.control,
            window=self.window, title="New Graph")

        # Open the wizard
        if wizard.open() == OK:
            wizard.finished = True

def
perform
(
self
,
event
)
:
wizard
=
NewDotGraphWizard
(
parent
=
self
.
window
.
control
,
window
=
self
.
window
,
title
=
"New Graph"
)
if
wizard
.
open
(
)
==
OK
:
wizard
.
finished
=
True


def start(self, context):
		"""Construct the SQLAlchemy engine and session factory."""

		if __debug__:
			log.info("Connecting SQLAlchemy database layer.", extra=dict(
					uri = redact_uri(self.uri),
					config = self.config,
					alias = self.alias,
				))

		# Construct the engine.
		engine = self.engine = create_engine(self.uri, **self.config)

		# Construct the session factory.
		self.Session = scoped_session(sessionmaker(bind=engine))

		# Test the connection.
		engine.connect().close()

		# Assign the engine to our database alias.
		context.db[self.alias] = engine

def
start
(
self
,
context
)
:
if
__debug__
:
log
.
info
(
"Connecting SQLAlchemy database layer."
,
extra
=
dict
(
uri
=
redact_uri
(
self
.
uri
)
,
config
=
self
.
config
,
alias
=
self
.
alias
,
)
)
engine
=
self
.
engine
=
create_engine
(
self
.
uri
,
**
self
.
config
)
self
.
Session
=
scoped_session
(
sessionmaker
(
bind
=
engine
)
)
engine
.
connect
(
)
.
close
(
)
context
.
db
[
self
.
alias
]
=
engine

Construct the SQLAlchemy engine and session factory .


def _parse_dot_code_fired(self):
        """ Parses the dot_code string and replaces the existing model.
        """
        parser = GodotDataParser()
        graph  = parser.parse_dot_data(self.dot_code)
        if graph is not None:
            self.model = graph

def _parse_dot_code_fired ( self ) : parser = GodotDataParser ( ) graph = parser . parse_dot_data ( self . dot_code ) if graph is not None : self . model = graph

Parses the dot_code string and replaces the existing model .


def new_model(self, info):
        """ Handles the new Graph action. """

        if info.initialized:
            retval = confirm(parent  = info.ui.control,
                             message = "Replace existing graph?",
                             title   = "New Graph",
                             default = YES)
            if retval == YES:
                self.model = Graph()

def
new_model
(
self
,
info
)
:
if
info
.
initialized
:
retval
=
confirm
(
parent
=
info
.
ui
.
control
,
message
=
"Replace existing graph?"
,
title
=
"New Graph"
,
default
=
YES
)
if
retval
==
YES
:
self
.
model
=
Graph
(
)


def open_file(self, info):
        """ Handles the open action. """

        if not info.initialized: return # Escape.

#        retval = self.edit_traits(parent=info.ui.control, view="file_view")

        dlg = FileDialog( action = "open",
            wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|"
                "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|"
                "All Files (*.*)|*.*|")

        if dlg.open() == OK:
            parser = GodotDataParser()
            model = parser.parse_dot_file(dlg.path)
            if model is not None:
                self.model = model
            else:
                print "error parsing: %s" % dlg.path

            self.save_file = dlg.path

        del dlg


def save(self, info):
        """ Handles saving the current model to the last file.
        """
        save_file = self.save_file

        if not isfile(save_file):
            self.save_as(info)
        else:
            fd = None
            try:
                fd = open(save_file, "wb")
                dot_code = str(self.model)
                fd.write(dot_code)
            finally:
                if fd is not None:
                    fd.close()

def save ( self , info ) : save_file = self . save_file if not isfile ( save_file ) : self . save_as ( info ) else : fd = None try : fd = open ( save_file , "wb" ) dot_code = str ( self . model ) fd . write ( dot_code ) finally : if fd is not None : fd . close ( )

Handles saving the current model to the last file .


def save_as(self, info):
        """ Handles saving the current model to file.
        """
        if not info.initialized:
            return

#        retval = self.edit_traits(parent=info.ui.control, view="file_view")

        dlg = FileDialog( action = "save as",
            wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" \
                "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" \
                "All Files (*.*)|*.*|")

        if dlg.open() == OK:
            fd = None
            try:
                fd = open(dlg.path, "wb")
                dot_code = str(self.model)
                fd.write(dot_code)

                self.save_file = dlg.path

            except:
                error(parent=info.ui.control, title="Save Error",
                      message="An error was encountered when saving\nto %s"
                      % self.file)

            finally:
                if fd is not None:
                    fd.close()

        del dlg

Handles saving the current model to file .


def configure_graph(self, info):
        """ Handles display of the graph dot traits.
        """
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=attr_view)

def configure_graph ( self , info ) : if info . initialized : self . model . edit_traits ( parent = info . ui . control , kind = "live" , view = attr_view )

Handles display of the graph dot traits .


def configure_nodes(self, info):
        """ Handles display of the nodes editor.
        """
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=nodes_view)

def configure_nodes ( self , info ) : if info . initialized : self . model . edit_traits ( parent = info . ui . control , kind = "live" , view = nodes_view )


def configure_edges(self, info):
        """ Handles display of the edges editor.
        """
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=edges_view)

def configure_edges ( self , info ) : if info . initialized : self . model . edit_traits ( parent = info . ui . control , kind = "live" , view = edges_view )


def about_godot(self, info):
        """ Handles displaying a view about Godot.
        """
        if info.initialized:
            self.edit_traits(parent=info.ui.control,
                kind="livemodal", view=about_view)

def about_godot ( self , info ) : if info . initialized : self . edit_traits ( parent = info . ui . control , kind = "livemodal" , view = about_view )


def add_node(self, info):
        """ Handles adding a Node to the graph.
        """
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is None:
            return

        IDs = [v.ID for v in graph.nodes]
        node = Node(ID=make_unique_name("node", IDs))
        graph.nodes.append(node)

        retval = node.edit_traits(parent=info.ui.control, kind="livemodal")

        if not retval.result:
            graph.nodes.remove(node)

def add_node ( self , info ) : if not info . initialized : return graph = self . _request_graph ( info . ui . control ) if graph is None : return IDs = [ v . ID for v in graph . nodes ] node = Node ( ID = make_unique_name ( "node" , IDs ) ) graph . nodes . append ( node ) retval = node . edit_traits ( parent = info . ui . control , kind = "livemodal" ) if not retval . result : graph . nodes . remove ( node )


def add_edge(self, info):
        """ Handles adding an Edge to the graph.
        """
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is None:
            return

        n_nodes = len(graph.nodes)
        IDs = [v.ID for v in graph.nodes]

        if n_nodes == 0:
            tail_node = Node(ID=make_unique_name("node", IDs))
            head_name = make_unique_name("node", IDs + [tail_node.ID])
            head_node = Node(ID=head_name)
        elif n_nodes == 1:
            tail_node = graph.nodes[0]
            head_node = Node(ID=make_unique_name("node", IDs))
        else:
            tail_node = graph.nodes[0]
            head_node = graph.nodes[1]

        edge = Edge(tail_node, head_node, _nodes=graph.nodes)

        retval = edge.edit_traits(parent=info.ui.control, kind="livemodal")

        if retval.result:
            graph.edges.append(edge)

def add_edge ( self , info ) : if not info . initialized : return graph = self . _request_graph ( info . ui . control ) if graph is None : return n_nodes = len ( graph . nodes ) IDs = [ v . ID for v in graph . nodes ] if n_nodes == 0 : tail_node = Node ( ID = make_unique_name ( "node" , IDs ) ) head_name = make_unique_name ( "node" , IDs + [ tail_node . ID ] ) head_node = Node ( ID = head_name ) elif n_nodes == 1 : tail_node = graph . nodes [ 0 ] head_node = Node ( ID = make_unique_name ( "node" , IDs ) ) else : tail_node = graph . nodes [ 0 ] head_node = graph . nodes [ 1 ] edge = Edge ( tail_node , head_node , _nodes = graph . nodes ) retval = edge . edit_traits ( parent = info . ui . control , kind = "livemodal" ) if retval . result : graph . edges . append ( edge )


def add_subgraph(self, info):
        """ Handles adding a Subgraph to the main graph.
        """
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is not None:
            subgraph = Subgraph()#root=graph, parent=graph)
            retval = subgraph.edit_traits(parent = info.ui.control,
                                          kind   = "livemodal")
            if retval.result:
                graph.subgraphs.append(subgraph)

def add_subgraph ( self , info ) : if not info . initialized : return graph = self . _request_graph ( info . ui . control ) if graph is not None : subgraph = Subgraph ( ) retval = subgraph . edit_traits ( parent = info . ui . control , kind = "livemodal" ) if retval . result : graph . subgraphs . append ( subgraph )

Handles adding a Subgraph to the main graph .


def add_cluster(self, info):
        """ Handles adding a Cluster to the main graph. """

        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is not None:
            cluster = Cluster()#root=graph, parent=graph)
            retval = cluster.edit_traits(parent = info.ui.control,
                                         kind   = "livemodal")
            if retval.result:
                graph.clusters.append(cluster)

def add_cluster ( self , info ) : if not info . initialized : return graph = self . _request_graph ( info . ui . control ) if graph is not None : cluster = Cluster ( ) retval = cluster . edit_traits ( parent = info . ui . control , kind = "livemodal" ) if retval . result : graph . clusters . append ( cluster )

Handles adding a Cluster to the main graph .


def _request_graph(self, parent=None):
        """ Displays a dialog for graph selection if more than one exists.
            Returns None if the dialog is canceled.
        """

        if (len(self.all_graphs) > 1) and (self.select_graph):
            retval = self.edit_traits(parent = parent,
                                      view   = "all_graphs_view")
            if not retval.result:
                return None

        if self.selected_graph is not None:
            return self.selected_graph
        else:
            return self.model

def _request_graph ( self , parent = None ) : if ( len ( self . all_graphs ) > 1 ) and ( self . select_graph ) : retval = self . edit_traits ( parent = parent , view = "all_graphs_view" ) if not retval . result : return None if self . selected_graph is not None : return self . selected_graph else : return self . model

Displays a dialog for graph selection if more than one exists . Returns None if the dialog is canceled .


def godot_options(self, info):
        """ Handles display of the options menu. """

        if info.initialized:
            self.edit_traits( parent = info.ui.control,
                              kind   = "livemodal",
                              view   = "options_view" )

def godot_options ( self , info ) : if info . initialized : self . edit_traits ( parent = info . ui . control , kind = "livemodal" , view = "options_view" )


def configure_dot_code(self, info):
        """ Handles display of the dot code in a text editor.
        """
        if not info.initialized:
            return

        self.dot_code = str(self.model)
        retval = self.edit_traits( parent = info.ui.control,
                                   kind   = "livemodal",
                                   view   = "dot_code_view" )

def configure_dot_code ( self , info ) : if not info . initialized : return self . dot_code = str ( self . model ) retval = self . edit_traits ( parent = info . ui . control , kind = "livemodal" , view = "dot_code_view" )

Handles display of the dot code in a text editor .


def on_exit(self, info):
        """ Handles the user attempting to exit Godot.
        """
        if self.prompt_on_exit:# and (not is_ok):
            retval = confirm(parent  = info.ui.control,
                             message = "Exit Godot?",
                             title   = "Confirm exit",
                             default = YES)
            if retval == YES:
                self._on_close( info )
        else:
            self._on_close( info )

def
on_exit
(
self
,
info
)
:
if
self
.
prompt_on_exit
:
retval
=
confirm
(
parent
=
info
.
ui
.
control
,
message
=
"Exit Godot?"
,
title
=
"Confirm exit"
,
default
=
YES
)
if
retval
==
YES
:
self
.
_on_close
(
info
)
else
:
self
.
_on_close
(
info
)

Handles the user attempting to exit Godot .


def move_to_origin(components):
    """ Components are positioned relative to their container. Use this
        method to position the bottom-left corner of the components at
        the origin.
    """
    for component in components:
        if isinstance(component, Ellipse):
            component.x_origin = component.e_width
            component.y_origin = component.e_height

        elif isinstance(component, (Polygon, BSpline)):
            min_x = min( [t[0] for t in component.points] )
            min_y = min( [t[1] for t in component.points] )

            component.points = [
                ( p[0]-min_x, p[1]-min_y ) for p in component.points
            ]

        elif isinstance(component, Text):
            font = str_to_font( str(component.pen.font) )
            component.text_x = 0#-( component.text_w / 2 )
            component.text_y = 0

def move_to_origin ( components ) : for component in components : if isinstance ( component , Ellipse ) : component . x_origin = component . e_width component . y_origin = component . e_height elif isinstance ( component , ( Polygon , BSpline ) ) : min_x = min ( [ t [ 0 ] for t in component . points ] ) min_y = min ( [ t [ 1 ] for t in component . points ] ) component . points = [ ( p [ 0 ] - min_x , p [ 1 ] - min_y ) for p in component . points ] elif isinstance ( component , Text ) : font = str_to_font ( str ( component . pen . font ) ) component . text_x = 0 component . text_y = 0

Components are positioned relative to their container . Use this method to position the bottom - left corner of the components at the origin .


def save_to_file_like(self, flo, format=None, **kwargs):
        """ Save the object to a given file like object in the given format.
        """
        format = self.format if format is None else format
        save = getattr(self, "save_%s" % format, None)
        if save is None:
            raise ValueError("Unknown format '%s'." % format)
        save(flo, **kwargs)

def
save_to_file_like
(
self
,
flo
,
format
=
,
**
kwargs
)
:
format
=
self
.
format
if
format
is
else
format
save
=
getattr
(
self
,
"save_%s"
%
format
,
)
if
save
is
:
raise
ValueError
(
"Unknown format '%s'."
%
format
)
save
(
flo
,
**
kwargs
)

Save the object to a given file like object in the given format .


def load_from_file_like(cls, flo, format=None):
        """ Load the object to a given file like object with the given
            protocol.
        """
        format = self.format if format is None else format
        load = getattr(cls, "load_%s" % format, None)
        if load is None:
            raise ValueError("Unknown format '%s'." % format)
        return load(flo)

def
load_from_file_like
(
cls
,
flo
,
format
=
)
:
format
=
self
.
format
if
format
is
else
format
load
=
getattr
(
cls
,
"load_%s"
%
format
,
)
if
load
is
:
raise
ValueError
(
"Unknown format '%s'."
%
format
)
return
load
(
flo
)

Load the object to a given file like object with the given protocol .


def save_to_file(self, filename, format=None, **kwargs):
        """ Save the object to file given by filename.
        """
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename, 'wb') as fp:
            self.save_to_file_like(fp, format, **kwargs)

def save_to_file ( self , filename , format = None , ** kwargs ) : if format is None : format = format_from_extension ( filename ) with file ( filename , 'wb' ) as fp : self . save_to_file_like ( fp , format , ** kwargs )

Save the object to file given by filename .


def load_from_file(cls, filename, format=None):
        """ Return an instance of the class that is saved in the file with the
            given filename in the specified format.
        """
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename,'rbU') as fp:
            obj = cls.load_from_file_like(fp, format)
            obj.filename = filename
            return obj

def load_from_file ( cls , filename , format = None ) : if format is None : format = format_from_extension ( filename ) with file ( filename , 'rbU' ) as fp : obj = cls . load_from_file_like ( fp , format ) obj . filename = filename return obj

Return an instance of the class that is saved in the file with the given filename in the specified format .


def Alias(name, **metadata):
    """ Syntactically concise alias trait but creates a pair of lambda
    functions for every alias you declare.

    class MyClass(HasTraits):
        line_width = Float(3.0)
        thickness = Alias("line_width")

    """

    return Property(lambda obj: getattr(obj, name),
                    lambda obj, val: setattr(obj, name, val),
                    **metadata)

def Alias ( name , ** metadata ) : return Property ( lambda obj : getattr ( obj , name ) , lambda obj , val : setattr ( obj , name , val ) , ** metadata )

Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare .


def parse(filename, encoding=None):
    """
    !DEMO!
    Simple file parsing generator

    Args:
        filename: absolute or relative path to file on disk
        encoding: encoding string that is passed to open function
    """

    with open(filename, encoding=encoding) as source:
        for line in source:
            for word in line.split():
                yield word

def parse ( filename , encoding = None ) : with open ( filename , encoding = encoding ) as source : for line in source : for word in line . split ( ) : yield word


def startwords(self):
        """
        !DEMO!
        Cached list of keys that can be used to generate sentence.
        """

        if self._start_words is not None:
            return self._start_words
        else:
            self._start_words = list(filter(
                lambda x: str.isupper(x[0][0]) and x[0][-1] not in ['.', '?', '!'],
                self.content.keys()
            ))
            return self._start_words

def startwords ( self ) : if self . _start_words is not None : return self . _start_words else : self . _start_words = list ( filter ( lambda x : str . isupper ( x [ 0 ] [ 0 ] ) and x [ 0 ] [ - 1 ] not in [ '.' , '?' , '!' ] , self . content . keys ( ) ) ) return self . _start_words

!DEMO! Cached list of keys that can be used to generate sentence .


def add_chain(self, name, order):
        """
        Add chain to current shelve file

        Args:
            name: chain name
            order: markov chain order
        """

        if name not in self.chains:
            setattr(self.chains, name, MarkovChain(order=order))
        else:
            raise ValueError("Chain with this name already exists")

def
add_chain
(
self
,
name
,
order
)
:
if
name
not
in
self
.
chains
:
setattr
(
self
.
chains
,
name
,
MarkovChain
(
order
=
order
)
)
else
:
raise
ValueError
(
"Chain with this name already exists"
)


def remove_chain(self, name):
        """
        Remove chain from current shelve file

        Args:
            name: chain name
        """

        if name in self.chains:
            delattr(self.chains, name)
        else:
            raise ValueError("Chain with this name not found")

def
remove_chain
(
self
,
name
)
:
if
name
in
self
.
chains
:
delattr
(
self
.
chains
,
name
)
else
:
raise
ValueError
(
"Chain with this name not found"
)


def build_chain(self, source, chain):
        """
        Build markov chain from source on top of existin chain

        Args:
            source: iterable which will be used to build chain
            chain: MarkovChain in currently loaded shelve file that
                   will be extended by source
        """

        for group in WalkByGroup(source, chain.order+1):
            pre = group[:-1]
            res = group[-1]

            if pre not in chain.content:
                chain.content[pre] = {res: 1}
            else:
                if res not in chain.content[pre]:
                    chain.content[pre][res] = 1
                else:
                    chain.content[pre][res] += 1

        chain.decache()

def build_chain ( self , source , chain ) : for group in WalkByGroup ( source , chain . order + 1 ) : pre = group [ : - 1 ] res = group [ - 1 ] if pre not in chain . content : chain . content [ pre ] = { res : 1 } else : if res not in chain . content [ pre ] : chain . content [ pre ] [ res ] = 1 else : chain . content [ pre ] [ res ] += 1 chain . decache ( )


def generate_sentence(self, chain):
        """
        !DEMO!
        Demo function that shows how to generate a simple sentence starting with
        uppercase letter without lenght limit.

        Args:
            chain: MarkovChain that will be used to generate sentence
        """

        def weighted_choice(choices):
            total_weight = sum(weight for val, weight in choices)
            rand = random.uniform(0, total_weight)

            upto = 0
            for val, weight in choices:
                if upto + weight >= rand:
                    return val
                upto += weight

        sentence = list(random.choice(chain.startwords))

        while not sentence[-1][-1] in ['.', '?', '!']:
            sentence.append(
                weighted_choice(
                    chain.content[tuple(sentence[-2:])].items()
                )
            )

        return ' '.join(sentence)

def
generate_sentence
(
self
,
chain
)
:
def
weighted_choice
(
choices
)
:
total_weight
=
sum
(
weight
for
val
,
weight
in
choices
)
rand
=
random
.
uniform
(
0
,
total_weight
)
upto
=
0
for
val
,
weight
in
choices
:
if
upto
+
weight
>=
rand
:
return
val
upto
+=
weight
sentence
=
list
(
random
.
choice
(
chain
.
startwords
)
)
while
not
sentence
[
1
]
[
1
]
in
[
'.'
,
'?'
,
'!'
]
:
sentence
.
append
(
weighted_choice
(
chain
.
content
[
tuple
(
sentence
[
2
:
]
)
]
.
items
(
)
)
)
return
' '
.
join
(
sentence
)

!DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit .


def create(self, prog=None, format=None):
        """ Creates and returns a representation of the graph using the
            Graphviz layout program given by 'prog', according to the given
            format.

            Writes the graph to a temporary dot file and processes it with
            the program given by 'prog' (which defaults to 'dot'), reading
            the output and returning it as a string if the operation is
            successful. On failure None is returned.
        """
        prog = self.program if prog is None else prog
        format = self.format if format is None else format

        # Make a temporary file ...
        tmp_fd, tmp_name = tempfile.mkstemp()
        os.close( tmp_fd )
        # ... and save the graph to it.
        dot_fd = file( tmp_name, "w+b" )
        self.save_dot( dot_fd )
        dot_fd.close()

        # Get the temporary file directory name.
        tmp_dir = os.path.dirname( tmp_name )

        # TODO: Shape image files (See PyDot). Important.

        # Process the file using the layout program, specifying the format.
        p = subprocess.Popen(
            ( self.programs[ prog ], '-T'+format, tmp_name ),
            cwd=tmp_dir,
            stderr=subprocess.PIPE, stdout=subprocess.PIPE)

        stderr = p.stderr
        stdout = p.stdout

        # Make sense of the standard output form the process.
        stdout_output = list()
        while True:
            data = stdout.read()
            if not data:
                break
            stdout_output.append(data)
        stdout.close()

        if stdout_output:
            stdout_output = ''.join(stdout_output)

        # Similarly so for any standard error.
        if not stderr.closed:
            stderr_output = list()
            while True:
                data = stderr.read()
                if not data:
                    break
                stderr_output.append(data)
            stderr.close()

            if stderr_output:
                stderr_output = ''.join(stderr_output)

        #pid, status = os.waitpid(p.pid, 0)
        status = p.wait()

        if status != 0 :
            logger.error("Program terminated with status: %d. stderr " \
                "follows: %s" % ( status, stderr_output ) )
        elif stderr_output:
            logger.error( "%s", stderr_output )

        # TODO: Remove shape image files from the temporary directory.

        # Remove the temporary file.
        os.unlink(tmp_name)

        return stdout_output

Creates and returns a representation of the graph using the Graphviz layout program given by prog according to the given format .


def add_node(self, node_or_ID, **kwds):
        """ Adds a node to the graph.
        """
        if not isinstance(node_or_ID, Node):
            nodeID = str( node_or_ID )
            if nodeID in self.nodes:
                node = self.nodes[ self.nodes.index(nodeID) ]
            else:
                if self.default_node is not None:
                    node = self.default_node.clone_traits(copy="deep")
                    node.ID = nodeID
                else:
                    node = Node(nodeID)
                self.nodes.append( node )
        else:
            node = node_or_ID
            if node in self.nodes:
                node = self.nodes[ self.nodes.index(node_or_ID) ]
            else:
                self.nodes.append( node )

        node.set( **kwds )

        return node

def add_node ( self , node_or_ID , ** kwds ) : if not isinstance ( node_or_ID , Node ) : nodeID = str ( node_or_ID ) if nodeID in self . nodes : node = self . nodes [ self . nodes . index ( nodeID ) ] else : if self . default_node is not None : node = self . default_node . clone_traits ( copy = "deep" ) node . ID = nodeID else : node = Node ( nodeID ) self . nodes . append ( node ) else : node = node_or_ID if node in self . nodes : node = self . nodes [ self . nodes . index ( node_or_ID ) ] else : self . nodes . append ( node ) node . set ( ** kwds ) return node


def delete_node(self, node_or_ID):
        """ Removes a node from the graph.
        """
        if isinstance(node_or_ID, Node):
#            name = node_or_ID.ID
            node = node_or_ID
        else:
#            name = node_or_ID
            node = self.get_node(node_or_ID)
            if node is None:
                raise ValueError("Node %s does not exists" % node_or_ID)

#        try:
#            del self.nodes[name]
#        except:
#            raise ValueError("Node %s does not exists" % name)

#        self.nodes = [n for n in self.nodes if n.ID != name]
#        idx = self.nodes.index(name)
#        return self.nodes.pop(idx)

        self.nodes.remove(node)

def
delete_node
(
self
,
node_or_ID
)
:
if
isinstance
(
node_or_ID
,
Node
)
:
node
=
node_or_ID
else
:
node
=
self
.
get_node
(
node_or_ID
)
if
node
is
:
raise
ValueError
(
"Node %s does not exists"
%
node_or_ID
)
self
.
nodes
.
remove
(
node
)


def get_node(self, ID):
        """ Returns the node with the given ID or None.
        """
        for node in self.nodes:
            if node.ID == str(ID):
                return node
        return None

def get_node ( self , ID ) : for node in self . nodes : if node . ID == str ( ID ) : return node return None

Returns the node with the given ID or None .


def delete_edge(self, tail_node_or_ID, head_node_or_ID):
        """ Removes an edge from the graph. Returns the deleted edge or None.
        """
        if isinstance(tail_node_or_ID, Node):
            tail_node = tail_node_or_ID
        else:
            tail_node = self.get_node(tail_node_or_ID)

        if isinstance(head_node_or_ID, Node):
            head_node = head_node_or_ID
        else:
            head_node = self.get_node(head_node_or_ID)

        if (tail_node is None) or (head_node is None):
            return None

        for i, edge in enumerate(self.edges):
            if (edge.tail_node == tail_node) and (edge.head_node == head_node):
                edge = self.edges.pop(i)
                return edge

        return None

def delete_edge ( self , tail_node_or_ID , head_node_or_ID ) : if isinstance ( tail_node_or_ID , Node ) : tail_node = tail_node_or_ID else : tail_node = self . get_node ( tail_node_or_ID ) if isinstance ( head_node_or_ID , Node ) : head_node = head_node_or_ID else : head_node = self . get_node ( head_node_or_ID ) if ( tail_node is None ) or ( head_node is None ) : return None for i , edge in enumerate ( self . edges ) : if ( edge . tail_node == tail_node ) and ( edge . head_node == head_node ) : edge = self . edges . pop ( i ) return edge return None

Removes an edge from the graph . Returns the deleted edge or None .


def add_edge(self, tail_node_or_ID, head_node_or_ID, **kwds):
        """ Adds an edge to the graph.
        """
        tail_node = self.add_node(tail_node_or_ID)
        head_node = self.add_node(head_node_or_ID)

        # Only top level graphs are directed and/or strict.
        if "directed" in self.trait_names():
            directed = self.directed
        else:
            directed = False

        if self.default_edge is not None:
            edge = self.default_edge.clone_traits(copy="deep")
            edge.tail_node = tail_node
            edge.head_node = head_node
            edge.conn = "->" if directed else "--"
            edge.set( **kwds )
        else:
            edge = Edge(tail_node, head_node, directed, **kwds)

        if "strict" in self.trait_names():
            if not self.strict:
                self.edges.append(edge)
            else:
                self.edges.append(edge)
                # FIXME: Implement strict graphs.
#                raise NotImplementedError
        else:
            self.edges.append(edge)

def add_edge ( self , tail_node_or_ID , head_node_or_ID , ** kwds ) : tail_node = self . add_node ( tail_node_or_ID ) head_node = self . add_node ( head_node_or_ID ) if "directed" in self . trait_names ( ) : directed = self . directed else : directed = False if self . default_edge is not None : edge = self . default_edge . clone_traits ( copy = "deep" ) edge . tail_node = tail_node edge . head_node = head_node edge . conn = "->" if directed else "--" edge . set ( ** kwds ) else : edge = Edge ( tail_node , head_node , directed , ** kwds ) if "strict" in self . trait_names ( ) : if not self . strict : self . edges . append ( edge ) else : self . edges . append ( edge ) else : self . edges . append ( edge )


def add_subgraph(self, subgraph_or_ID):
        """ Adds a subgraph to the graph.
        """
        if not isinstance(subgraph_or_ID, (godot.subgraph.Subgraph,
                                           godot.cluster.Cluster)):
            subgraphID = str( subgraph_or_ID )
            if subgraph_or_ID.startswith("cluster"):
                subgraph = godot.cluster.Cluster(ID=subgraphID)
            else:
                subgraph = godot.subgraph.Subgraph(ID=subgraphID)
        else:
            subgraph = subgraph_or_ID

        subgraph.default_node = self.default_node
        subgraph.default_edge = self.default_edge
#        subgraph.level = self.level + 1
#        subgraph.padding += self.padding

        if isinstance(subgraph, godot.subgraph.Subgraph):
            self.subgraphs.append(subgraph)
        elif isinstance(subgraph, godot.cluster.Cluster):
            self.clusters.append(subgraph)
        else:
            raise

        return subgraph

def add_subgraph ( self , subgraph_or_ID ) : if not isinstance ( subgraph_or_ID , ( godot . subgraph . Subgraph , godot . cluster . Cluster ) ) : subgraphID = str ( subgraph_or_ID ) if subgraph_or_ID . startswith ( "cluster" ) : subgraph = godot . cluster . Cluster ( ID = subgraphID ) else : subgraph = godot . subgraph . Subgraph ( ID = subgraphID ) else : subgraph = subgraph_or_ID subgraph . default_node = self . default_node subgraph . default_edge = self . default_edge if isinstance ( subgraph , godot . subgraph . Subgraph ) : self . subgraphs . append ( subgraph ) elif isinstance ( subgraph , godot . cluster . Cluster ) : self . clusters . append ( subgraph ) else : raise return subgraph


def _program_changed(self, new):
        """ Handles the Graphviz layout program selection changing.
        """
        progs = self.progs

        if not progs.has_key(prog):
            logger.warning( 'GraphViz\'s executable "%s" not found' % prog )

        if not os.path.exists( progs[prog] ) or not \
            os.path.isfile( progs[prog] ):
            logger.warning( "GraphViz's executable '%s' is not a "
                "file or doesn't exist" % progs[prog] )

def
_program_changed
(
self
,
new
)
:
progs
=
self
.
progs
if
not
progs
.
has_key
(
prog
)
:
logger
.
warning
(
'GraphViz\'s executable "%s" not found'
%
prog
)
if
not
os
.
path
.
exists
(
progs
[
prog
]
)
or
not
os
.
path
.
isfile
(
progs
[
prog
]
)
:
logger
.
warning
(
"GraphViz's executable '%s' is not a "
"file or doesn't exist"
%
progs
[
prog
]
)

Handles the Graphviz layout program selection changing .


def _set_node_lists(self, new):
        """ Maintains each edge's list of available nodes.
        """
        for edge in self.edges:
            edge._nodes = self.nodes

def _set_node_lists ( self , new ) : for edge in self . edges : edge . _nodes = self . nodes

Maintains each edge s list of available nodes .


def parse_dot_file(filename):
    """ Parses a DOT file and returns a Godot graph.
    """
    parser = GodotDataParser()
    graph  = parser.parse_dot_file(filename)
    del parser

    return graph

def parse_dot_file ( filename ) : parser = GodotDataParser ( ) graph = parser . parse_dot_file ( filename ) del parser return graph

Parses a DOT file and returns a Godot graph .


def parse_dot_file(self, file_or_filename):
        """ Returns a graph given a file or a filename.
        """
        if isinstance(file_or_filename, basestring):
            file = None
            try:
                file = open(file_or_filename, "rb")
                data = file.read()
            except:
                print "Could not open %s." % file_or_filename
                return None
            finally:
                if file is not None:
                    file.close()
        else:
            file = file_or_filename
            data = file.read()

        return self.parse_dot_data(data)

def
parse_dot_file
(
self
,
file_or_filename
)
:
if
isinstance
(
file_or_filename
,
basestring
)
:
file
=
try
:
file
=
open
(
file_or_filename
,
"rb"
)
data
=
file
.
read
(
)
except
:
print
"Could not open %s."
%
file_or_filename
return
finally
:
if
file
is
not
:
file
.
close
(
)
else
:
file
=
file_or_filename
data
=
file
.
read
(
)
return
self
.
parse_dot_data
(
data
)

Returns a graph given a file or a filename .


def build_top_graph(self,tokens):
        """ Build a Godot graph instance from parsed data.
        """
        # Get basic graph information.
        strict = tokens[0] == 'strict'
        graphtype = tokens[1]
        directed = graphtype == 'digraph'
        graphname = tokens[2]
        # Build the graph
        graph = Graph(ID=graphname, strict=strict, directed=directed)
        self.graph = self.build_graph(graph, tokens[3])

def build_top_graph ( self , tokens ) : strict = tokens [ 0 ] == 'strict' graphtype = tokens [ 1 ] directed = graphtype == 'digraph' graphname = tokens [ 2 ] graph = Graph ( ID = graphname , strict = strict , directed = directed ) self . graph = self . build_graph ( graph , tokens [ 3 ] )

Build a Godot graph instance from parsed data .


def build_graph(self, graph, tokens):
        """ Builds a Godot graph.
        """
        subgraph = None

        for element in tokens:
            cmd = element[0]
            if cmd == ADD_NODE:
                cmd, nodename, opts = element
                graph.add_node(nodename, **opts)

            elif cmd == ADD_EDGE:
                cmd, src, dest, opts = element
                srcport = destport = ""
                if isinstance(src,tuple):
                    srcport = src[1]
                    src = src[0]
                if isinstance(dest,tuple):
                    destport = dest[1]
                    dest = dest[0]

                graph.add_edge(src, dest, tailport=srcport, headport=destport,
                               **opts)

            elif cmd in [ADD_GRAPH_TO_NODE_EDGE,
                         ADD_GRAPH_TO_GRAPH_EDGE,
                         ADD_NODE_TO_GRAPH_EDGE]:
                cmd, src, dest, opts = element
                srcport = destport = ""

                if isinstance(src,tuple):
                    srcport = src[1]

                if isinstance(dest,tuple):
                    destport = dest[1]

                if not (cmd == ADD_NODE_TO_GRAPH_EDGE):
                    if cmd == ADD_GRAPH_TO_NODE_EDGE:
                        src = subgraph
                    else:
                        src = prev_subgraph
                        dest = subgraph
                else:
                    dest = subgraph

                src_is_graph = isinstance(src, (Subgraph, Cluster))
                dst_is_graph = isinstance(dst, (Subgraph, Cluster))

                if src_is_graph:
                    src_nodes = src.nodes
                else:
                    src_nodes = [src]
                if dst_is_graph:
                    dst_nodes = dst.nodes
                else:
                    dst_nodes = [dst]

                for src_node in src_nodes:
                    for dst_node in dst_nodes:
                        graph.add_edge(from_node=src_node, to_node=dst_node,
                                       tailport=srcport, headport=destport,
                                       **kwds)

            elif cmd == SET_GRAPH_ATTR:
                graph.set( **element[1] )

            elif cmd == SET_DEF_NODE_ATTR:
                graph.default_node.set( **element[1] )

            elif cmd == SET_DEF_EDGE_ATTR:
                graph.default_edge.set( **element[1] )

            elif cmd == SET_DEF_GRAPH_ATTR:
                graph.default_graph.set( **element[1] )

            elif cmd == ADD_SUBGRAPH:
                cmd, name, elements = element
                if subgraph:
                    prev_subgraph = subgraph
                if name.startswith("cluster"):
                    cluster = Cluster(ID=name)
                    cluster = self.build_graph(cluster, elements)
                    graph.add_cluster(cluster)
                else:
                    subgraph = Subgraph(ID=name)
                    subgraph = self.build_graph(subgraph, elements)
                    graph.add_subgraph(subgraph)

        return graph

def build_graph ( self , graph , tokens ) : subgraph = None for element in tokens : cmd = element [ 0 ] if cmd == ADD_NODE : cmd , nodename , opts = element graph . add_node ( nodename , ** opts ) elif cmd == ADD_EDGE : cmd , src , dest , opts = element srcport = destport = "" if isinstance ( src , tuple ) : srcport = src [ 1 ] src = src [ 0 ] if isinstance ( dest , tuple ) : destport = dest [ 1 ] dest = dest [ 0 ] graph . add_edge ( src , dest , tailport = srcport , headport = destport , ** opts ) elif cmd in [ ADD_GRAPH_TO_NODE_EDGE , ADD_GRAPH_TO_GRAPH_EDGE , ADD_NODE_TO_GRAPH_EDGE ] : cmd , src , dest , opts = element srcport = destport = "" if isinstance ( src , tuple ) : srcport = src [ 1 ] if isinstance ( dest , tuple ) : destport = dest [ 1 ] if not ( cmd == ADD_NODE_TO_GRAPH_EDGE ) : if cmd == ADD_GRAPH_TO_NODE_EDGE : src = subgraph else : src = prev_subgraph dest = subgraph else : dest = subgraph src_is_graph = isinstance ( src , ( Subgraph , Cluster ) ) dst_is_graph = isinstance ( dst , ( Subgraph , Cluster ) ) if src_is_graph : src_nodes = src . nodes else : src_nodes = [ src ] if dst_is_graph : dst_nodes = dst . nodes else : dst_nodes = [ dst ] for src_node in src_nodes : for dst_node in dst_nodes : graph . add_edge ( from_node = src_node , to_node = dst_node , tailport = srcport , headport = destport , ** kwds ) elif cmd == SET_GRAPH_ATTR : graph . set ( ** element [ 1 ] ) elif cmd == SET_DEF_NODE_ATTR : graph . default_node . set ( ** element [ 1 ] ) elif cmd == SET_DEF_EDGE_ATTR : graph . default_edge . set ( ** element [ 1 ] ) elif cmd == SET_DEF_GRAPH_ATTR : graph . default_graph . set ( ** element [ 1 ] ) elif cmd == ADD_SUBGRAPH : cmd , name , elements = element if subgraph : prev_subgraph = subgraph if name . startswith ( "cluster" ) : cluster = Cluster ( ID = name ) cluster = self . build_graph ( cluster , elements ) graph . add_cluster ( cluster ) else : subgraph = Subgraph ( ID = name ) subgraph = self . build_graph ( subgraph , elements ) graph . add_subgraph ( subgraph ) return graph


def get_time_units_and_multiplier(seconds):
    """
    Given a duration in seconds, determines the best units and multiplier to
    use to display the time. Return value is a 2-tuple of units and multiplier.
    """
    for cutoff, units, multiplier in units_table:
        if seconds < cutoff:
            break
    return units, multiplier

def get_time_units_and_multiplier ( seconds ) : for cutoff , units , multiplier in units_table : if seconds < cutoff : break return units , multiplier

Given a duration in seconds determines the best units and multiplier to use to display the time . Return value is a 2 - tuple of units and multiplier .


def format_duration(seconds):
    """Formats a number of seconds using the best units."""
    units, divider = get_time_units_and_multiplier(seconds)
    seconds *= divider
    return "%.3f %s" % (seconds, units)

def
format_duration
(
seconds
)
:
units
,
divider
=
get_time_units_and_multiplier
(
seconds
)
seconds
*=
divider
return
"%.3f %s"
%
(
seconds
,
units
)

Formats a number of seconds using the best units .


def on_path(self, new):
        """ Handle the file path changing.
        """
        self.name = basename(new)
        self.graph = self.editor_input.load()

def on_path ( self , new ) : self . name = basename ( new ) self . graph = self . editor_input . load ( )


def create_ui(self, parent):
        """ Creates the toolkit-specific control that represents the
            editor. 'parent' is the toolkit-specific control that is
            the editor's parent.
        """
        self.graph = self.editor_input.load()

        view = View(Item(name="graph", editor=graph_tree_editor,
                show_label=False),
            id="godot.graph_editor", kind="live", resizable=True)

        ui = self.edit_traits(view=view, parent=parent, kind="subpanel")

        return ui

def create_ui ( self , parent ) : self . graph = self . editor_input . load ( ) view = View ( Item ( name = "graph" , editor = graph_tree_editor , show_label = False ) , id = "godot.graph_editor" , kind = "live" , resizable = True ) ui = self . edit_traits ( view = view , parent = parent , kind = "subpanel" ) return ui

Creates the toolkit - specific control that represents the editor . parent is the toolkit - specific control that is the editor s parent .


def nsplit(seq, n=2):
    """ Split a sequence into pieces of length n

    If the length of the sequence isn't a multiple of n, the rest is discarded.
    Note that nsplit will split strings into individual characters.

    Examples:
    >>> nsplit("aabbcc")
    [("a", "a"), ("b", "b"), ("c", "c")]
    >>> nsplit("aabbcc",n=3)
    [("a", "a", "b"), ("b", "c", "c")]

    # Note that cc is discarded
    >>> nsplit("aabbcc",n=4)
    [("a", "a", "b", "b")]

    """

    return [xy for xy in itertools.izip(*[iter(seq)]*n)]

def nsplit ( seq , n = 2 ) : return [ xy for xy in itertools . izip ( * [ iter ( seq ) ] * n ) ]


def windows(iterable, length=2, overlap=0, padding=True):
    """ Code snippet from Python Cookbook, 2nd Edition by David Ascher,
    Alex Martelli and Anna Ravenscroft; O'Reilly 2005

    Problem: You have an iterable s and need to make another iterable whose
    items are sublists (i.e., sliding windows), each of the same given length,
    over s' items, with successive windows overlapping by a specified amount.

    """

    it = iter(iterable)
    results = list(itertools.islice(it, length))
    while len(results) == length:
        yield results
        results = results[length-overlap:]
        results.extend(itertools.islice(it, length-overlap))
    if padding and results:
        results.extend(itertools.repeat(None, length-len(results)))
        yield results

def windows ( iterable , length = 2 , overlap = 0 , padding = True ) : it = iter ( iterable ) results = list ( itertools . islice ( it , length ) ) while len ( results ) == length : yield results results = results [ length - overlap : ] results . extend ( itertools . islice ( it , length - overlap ) ) if padding and results : results . extend ( itertools . repeat ( None , length - len ( results ) ) ) yield results

Code snippet from Python Cookbook 2nd Edition by David Ascher Alex Martelli and Anna Ravenscroft ; O Reilly 2005


def main():
    """ Runs Godot.
    """
    application = GodotApplication( id="godot",
        plugins=[CorePlugin(),
                 PuddlePlugin(),
                 WorkbenchPlugin(),
                 ResourcePlugin(),
                 GodotPlugin()] )

    application.run()

def main ( ) : application = GodotApplication ( id = "godot" , plugins = [ CorePlugin ( ) , PuddlePlugin ( ) , WorkbenchPlugin ( ) , ResourcePlugin ( ) , GodotPlugin ( ) ] ) application . run ( )


def get_children ( self, object ):
        """ Gets the object's children.
        """
        children = []
        children.extend( object.subgraphs )
        children.extend( object.clusters )
        children.extend( object.nodes )
        children.extend( object.edges )
        return children

def get_children ( self , object ) : children = [ ] children . extend ( object . subgraphs ) children . extend ( object . clusters ) children . extend ( object . nodes ) children . extend ( object . edges ) return children


def append_child ( self, object, child ):
        """ Appends a child to the object's children.
        """
        if isinstance( child, Subgraph ):
            object.subgraphs.append( child )

        elif isinstance( child, Cluster ):
            object.clusters.append( child )

        elif isinstance( child, Node ):
            object.nodes.append( child )

        elif isinstance( child, Edge ):
            object.edges.append( child )

        else:
            pass

def append_child ( self , object , child ) : if isinstance ( child , Subgraph ) : object . subgraphs . append ( child ) elif isinstance ( child , Cluster ) : object . clusters . append ( child ) elif isinstance ( child , Node ) : object . nodes . append ( child ) elif isinstance ( child , Edge ) : object . edges . append ( child ) else : pass

Appends a child to the object s children .


def insert_child ( self, object, index, child ):
        """ Inserts a child into the object's children.
        """
        if isinstance( child, Subgraph ):
            object.subgraphs.insert( index, child )

        elif isinstance( child, Cluster ):
            object.clusters.insert( index, child )

        elif isinstance( child, Node ):
            object.nodes.insert( index, child )

        elif isinstance( child, Edge ):
            object.edges.insert( index, child )

        else:
            pass

def insert_child ( self , object , index , child ) : if isinstance ( child , Subgraph ) : object . subgraphs . insert ( index , child ) elif isinstance ( child , Cluster ) : object . clusters . insert ( index , child ) elif isinstance ( child , Node ) : object . nodes . insert ( index , child ) elif isinstance ( child , Edge ) : object . edges . insert ( index , child ) else : pass

Inserts a child into the object s children .


def delete_child ( self, object, index ):
        """ Deletes a child at a specified index from the object's children.
        """
        if isinstance( child, Subgraph ):
            object.subgraphs.pop(index)

        elif isinstance( child, Cluster ):
            object.clusters.pop( index )

        elif isinstance( child, Node ):
            object.nodes.pop( index )

        elif isinstance( child, Edge ):
            object.edges.pop( index )

        else:
            pass

def delete_child ( self , object , index ) : if isinstance ( child , Subgraph ) : object . subgraphs . pop ( index ) elif isinstance ( child , Cluster ) : object . clusters . pop ( index ) elif isinstance ( child , Node ) : object . nodes . pop ( index ) elif isinstance ( child , Edge ) : object . edges . pop ( index ) else : pass

Deletes a child at a specified index from the object s children .


def when_children_replaced ( self, object, listener, remove ):
        """ Sets up or removes a listener for children being replaced on a
            specified object.
        """
        object.on_trait_change( listener, "subgraphs", remove = remove,
                                dispatch = "fast_ui" )
        object.on_trait_change( listener, "clusters", remove = remove,
                                dispatch = "fast_ui" )
        object.on_trait_change( listener, "nodes", remove = remove,
                                dispatch = "fast_ui" )
        object.on_trait_change( listener, "edges", remove = remove,
                                dispatch = "fast_ui" )

def when_children_replaced ( self , object , listener , remove ) : object . on_trait_change ( listener , "subgraphs" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "clusters" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "nodes" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "edges" , remove = remove , dispatch = "fast_ui" )

Sets up or removes a listener for children being replaced on a specified object .


def when_children_changed ( self, object, listener, remove ):
        """ Sets up or removes a listener for children being changed on a
            specified object.
        """
        object.on_trait_change( listener, "subgraphs_items",
                                remove = remove, dispatch = "fast_ui" )
        object.on_trait_change( listener, "clusters_items",
                                remove = remove, dispatch = "fast_ui" )
        object.on_trait_change( listener, "nodes_items",
                                remove = remove, dispatch = "fast_ui" )
        object.on_trait_change( listener, "edges_items",
                                remove = remove, dispatch = "fast_ui" )

def when_children_changed ( self , object , listener , remove ) : object . on_trait_change ( listener , "subgraphs_items" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "clusters_items" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "nodes_items" , remove = remove , dispatch = "fast_ui" ) object . on_trait_change ( listener , "edges_items" , remove = remove , dispatch = "fast_ui" )

Sets up or removes a listener for children being changed on a specified object .


def get_label ( self, object ):
        """ Gets the label to display for a specified object.
        """
        label = self.label
        if label[:1] == '=':
            return label[1:]

        label = xgetattr( object, label, '' )

        if self.formatter is None:
            return label

        return self.formatter( object, label )

def get_label ( self , object ) : label = self . label if label [ : 1 ] == '=' : return label [ 1 : ] label = xgetattr ( object , label , '' ) if self . formatter is None : return label return self . formatter ( object , label )

Gets the label to display for a specified object .


def set_label ( self, object, label ):
        """ Sets the label for a specified object.
        """
        label_name = self.label
        if label_name[:1] != '=':
            xsetattr( object, label_name, label )

def set_label ( self , object , label ) : label_name = self . label if label_name [ : 1 ] != '=' : xsetattr ( object , label_name , label )


def when_label_changed ( self, object, listener, remove ):
        """ Sets up or removes a listener for the label being changed on a
            specified object.
        """
        label = self.label
        if label[:1] != '=':
            object.on_trait_change( listener, label, remove = remove,
                                    dispatch = 'ui' )

def when_label_changed ( self , object , listener , remove ) : label = self . label if label [ : 1 ] != '=' : object . on_trait_change ( listener , label , remove = remove , dispatch = 'ui' )

Sets up or removes a listener for the label being changed on a specified object .


def init ( self, parent ):
        """ Finishes initialising the editor by creating the underlying toolkit
            widget.
        """
        self._graph = graph = Graph()
        ui = graph.edit_traits(parent=parent, kind="panel")
        self.control = ui.control

def init ( self , parent ) : self . _graph = graph = Graph ( ) ui = graph . edit_traits ( parent = parent , kind = "panel" ) self . control = ui . control

Finishes initialising the editor by creating the underlying toolkit widget .


def update_editor ( self ):
        """ Updates the editor when the object trait changes externally to the
            editor.
        """
        object = self.value
        # Graph the new object...
        canvas = self.factory.canvas
        if canvas is not None:
            for nodes_name in canvas.node_children:
                node_children = getattr(object, nodes_name)
                self._add_nodes(node_children)

            for edges_name in canvas.edge_children:
                edge_children = getattr(object, edges_name)
                self._add_edges(edge_children)

        # ...then listen for changes.
        self._add_listeners()

def update_editor ( self ) : object = self . value canvas = self . factory . canvas if canvas is not None : for nodes_name in canvas . node_children : node_children = getattr ( object , nodes_name ) self . _add_nodes ( node_children ) for edges_name in canvas . edge_children : edge_children = getattr ( object , edges_name ) self . _add_edges ( edge_children ) self . _add_listeners ( )

Updates the editor when the object trait changes externally to the editor .


def _add_listeners ( self ):
        """ Adds the event listeners for a specified object.
        """
        object = self.value
        canvas = self.factory.canvas
        if canvas is not None:
            for name in canvas.node_children:
                object.on_trait_change(self._nodes_replaced, name)
                object.on_trait_change(self._nodes_changed, name + "_items")

            for name in canvas.edge_children:
                object.on_trait_change(self._edges_replaced, name)
                object.on_trait_change(self._edges_changed, name + "_items")
        else:
            raise ValueError("Graph canvas not set for graph editor.")

Adds the event listeners for a specified object .


def _nodes_replaced(self, object, name, old, new):
        """ Handles a list of nodes being set.
        """
        self._delete_nodes(old)
        self._add_nodes(new)

def _nodes_replaced ( self , object , name , old , new ) : self . _delete_nodes ( old ) self . _add_nodes ( new )


def _nodes_changed(self, object, name, undefined, event):
        """ Handles addition and removal of nodes.
        """
        self._delete_nodes(event.removed)
        self._add_nodes(event.added)

def _nodes_changed ( self , object , name , undefined , event ) : self . _delete_nodes ( event . removed ) self . _add_nodes ( event . added )


def _add_nodes(self, features):
        """ Adds a node to the graph for each item in 'features' using
            the GraphNodes from the editor factory.
        """
        graph = self._graph

        if graph is not None:
            for feature in features:
                for graph_node in self.factory.nodes:
                    if feature.__class__ in graph_node.node_for:
                        graph.add_node( id(feature), **graph_node.dot_attr )
                        break

        graph.arrange_all()

def _add_nodes ( self , features ) : graph = self . _graph if graph is not None : for feature in features : for graph_node in self . factory . nodes : if feature . __class__ in graph_node . node_for : graph . add_node ( id ( feature ) , ** graph_node . dot_attr ) break graph . arrange_all ( )

Adds a node to the graph for each item in features using the GraphNodes from the editor factory .


def _edges_replaced(self, object, name, old, new):
        """ Handles a list of edges being set.
        """
        self._delete_edges(old)
        self._add_edges(new)

def _edges_replaced ( self , object , name , old , new ) : self . _delete_edges ( old ) self . _add_edges ( new )


def _edges_changed(self, object, name, undefined, event):
        """ Handles addition and removal of edges.
        """
        self._delete_edges(event.removed)
        self._add_edges(event.added)

def _edges_changed ( self , object , name , undefined , event ) : self . _delete_edges ( event . removed ) self . _add_edges ( event . added )


def _add_edges(self, features):
        """ Adds an edge to the graph for each item in 'features' using
            the GraphEdges from the editor factory.
        """
        graph = self._graph

        if graph is not None:
            for feature in features:
                for graph_edge in self.factory.edges:
                    if feature.__class__ in graph_edge.edge_for:
                        tail_feature = getattr(feature, graph_edge.tail_name)
                        head_feature = getattr(feature, graph_edge.head_name)

                        graph.add_edge( id(tail_feature), id(head_feature),
                            **graph_edge.dot_attr )

                        break

        graph.arrange_all()

def _add_edges ( self , features ) : graph = self . _graph if graph is not None : for feature in features : for graph_edge in self . factory . edges : if feature . __class__ in graph_edge . edge_for : tail_feature = getattr ( feature , graph_edge . tail_name ) head_feature = getattr ( feature , graph_edge . head_name ) graph . add_edge ( id ( tail_feature ) , id ( head_feature ) , ** graph_edge . dot_attr ) break graph . arrange_all ( )

Adds an edge to the graph for each item in features using the GraphEdges from the editor factory .


def _parse_xdot_directive(self, name, new):
        """ Handles parsing Xdot drawing directives.
        """
        parser = XdotAttrParser()
        components = parser.parse_xdot_data(new)

        # The absolute coordinate of the drawing container wrt graph origin.
        x1 = min( [c.x for c in components] )
        y1 = min( [c.y for c in components] )

        print "X1/Y1:", name, x1, y1

        # Components are positioned relative to their container. This
        # function positions the bottom-left corner of the components at
        # their origin rather than relative to the graph.
#        move_to_origin( components )

        for c in components:
            if isinstance(c, Ellipse):
                component.x_origin -= x1
                component.y_origin -= y1
#                c.position = [ c.x - x1, c.y - y1 ]

            elif isinstance(c, (Polygon, BSpline)):
                print "Points:", c.points
                c.points = [ (t[0] - x1, t[1] - y1) for t in c.points ]
                print "Points:", c.points

            elif isinstance(c, Text):
#                font = str_to_font( str(c.pen.font) )
                c.text_x, c.text_y = c.x - x1, c.y - y1

        container = Container(auto_size=True,
            position=[ x1, y1 ],
            bgcolor="yellow")

        container.add( *components )

        if name == "_draw_":
            self.drawing = container
        elif name == "_hdraw_":
            self.arrowhead_drawing = container
        else:
            raise

def _parse_xdot_directive ( self , name , new ) : parser = XdotAttrParser ( ) components = parser . parse_xdot_data ( new ) x1 = min ( [ c . x for c in components ] ) y1 = min ( [ c . y for c in components ] ) print "X1/Y1:" , name , x1 , y1 for c in components : if isinstance ( c , Ellipse ) : component . x_origin -= x1 component . y_origin -= y1 elif isinstance ( c , ( Polygon , BSpline ) ) : print "Points:" , c . points c . points = [ ( t [ 0 ] - x1 , t [ 1 ] - y1 ) for t in c . points ] print "Points:" , c . points elif isinstance ( c , Text ) : c . text_x , c . text_y = c . x - x1 , c . y - y1 container = Container ( auto_size = True , position = [ x1 , y1 ] , bgcolor = "yellow" ) container . add ( * components ) if name == "_draw_" : self . drawing = container elif name == "_hdraw_" : self . arrowhead_drawing = container else : raise

Handles parsing Xdot drawing directives .


def _on_drawing(self, object, name, old, new):
        """ Handles the containers of drawing components being set.
        """
        attrs = [ "drawing", "arrowhead_drawing" ]

        others = [getattr(self, a) for a in attrs \
            if (a != name) and (getattr(self, a) is not None)]

        x, y = self.component.position
        print "POS:", x, y, self.component.position

        abs_x = [d.x + x for d in others]
        abs_y = [d.y + y for d in others]

        print "ABS:", abs_x, abs_y

        # Assume that he new drawing is positioned relative to graph origin.
        x1 = min( abs_x + [new.x] )
        y1 = min( abs_y + [new.y] )

        print "DRAW:", new.position
        new.position = [ new.x - x1, new.y - y1 ]
        print "DRAW:", new.position

#        for i, b in enumerate( others ):
#            self.drawing.position = [100, 100]
#            self.drawing.request_redraw()
#            print "OTHER:", b.position, abs_x[i] - x1
#            b.position = [ abs_x[i] - x1, abs_y[i] - y1 ]
#            b.x = 50
#            b.y = 50
#            print "OTHER:", b.position, abs_x[i], x1

#        for attr in attrs:
#            if attr != name:
#                if getattr(self, attr) is not None:
#                    drawing = getattr(self, attr)
#                    drawing.position = [50, 50]

        if old is not None:
            self.component.remove( old )
        if new is not None:
            self.component.add( new )

        print "POS NEW:", self.component.position
        self.component.position = [ x1, y1 ]
        print "POS NEW:", self.component.position
        self.component.request_redraw()
        print "POS NEW:", self.component.position

def
_on_drawing
(
self
,
object
,
name
,
old
,
new
)
:
attrs
=
[
"drawing"
,
"arrowhead_drawing"
]
others
=
[
getattr
(
self
,
a
)
for
a
in
attrs
if
(
a
!=
name
)
and
(
getattr
(
self
,
a
)
is
not
)
]
x
,
y
=
self
.
component
.
position
print
"POS:"
,
x
,
y
,
self
.
component
.
position
abs_x
=
[
d
.
x
+
x
for
d
in
others
]
abs_y
=
[
d
.
y
+
y
for
d
in
others
]
print
"ABS:"
,
abs_x
,
abs_y
x1
=
min
(
abs_x
+
[
new
.
x
]
)
y1
=
min
(
abs_y
+
[
new
.
y
]
)
print
"DRAW:"
,
new
.
position
new
.
position
=
[
new
.
x
x1
,
new
.
y
y1
]
print
"DRAW:"
,
new
.
position
if
old
is
not
:
self
.
component
.
remove
(
old
)
if
new
is
not
:
self
.
component
.
add
(
new
)
print
"POS NEW:"
,
self
.
component
.
position
self
.
component
.
position
=
[
x1
,
y1
]
print
"POS NEW:"
,
self
.
component
.
position
self
.
component
.
request_redraw
(
)
print
"POS NEW:"
,
self
.
component
.
position

Handles the containers of drawing components being set .


def node_factory(**row_factory_kw):
    """ Give new nodes a unique ID. """

    if "__table_editor__" in row_factory_kw:
        graph = row_factory_kw["__table_editor__"].object
        ID = make_unique_name("n", [node.ID for node in graph.nodes])
        del row_factory_kw["__table_editor__"]
        return godot.node.Node(ID)
    else:
        return godot.node.Node(uuid.uuid4().hex[:6])

def node_factory ( ** row_factory_kw ) : if "__table_editor__" in row_factory_kw : graph = row_factory_kw [ "__table_editor__" ] . object ID = make_unique_name ( "n" , [ node . ID for node in graph . nodes ] ) del row_factory_kw [ "__table_editor__" ] return godot . node . Node ( ID ) else : return godot . node . Node ( uuid . uuid4 ( ) . hex [ : 6 ] )


def edge_factory(**row_factory_kw):
    """ Give new edges a unique ID. """

    if "__table_editor__" in row_factory_kw:
        table_editor = row_factory_kw["__table_editor__"]
        graph = table_editor.object
        ID = make_unique_name("node", [node.ID for node in graph.nodes])

        n_nodes = len(graph.nodes)
        IDs = [v.ID for v in graph.nodes]

        if n_nodes == 0:
            tail_node = godot.Node(ID=make_unique_name("n", IDs))
            head_node = godot.Node(ID=make_unique_name("n", IDs))
        elif n_nodes == 1:
            tail_node = graph.nodes[0]
            head_node = godot.Node(ID=make_unique_name("n", IDs))
        else:
            tail_node = graph.nodes[0]
            head_node = graph.nodes[1]

        return godot.edge.Edge(tail_node, head_node, _nodes=graph.nodes)
    else:
        return None

def edge_factory ( ** row_factory_kw ) : if "__table_editor__" in row_factory_kw : table_editor = row_factory_kw [ "__table_editor__" ] graph = table_editor . object ID = make_unique_name ( "node" , [ node . ID for node in graph . nodes ] ) n_nodes = len ( graph . nodes ) IDs = [ v . ID for v in graph . nodes ] if n_nodes == 0 : tail_node = godot . Node ( ID = make_unique_name ( "n" , IDs ) ) head_node = godot . Node ( ID = make_unique_name ( "n" , IDs ) ) elif n_nodes == 1 : tail_node = graph . nodes [ 0 ] head_node = godot . Node ( ID = make_unique_name ( "n" , IDs ) ) else : tail_node = graph . nodes [ 0 ] head_node = graph . nodes [ 1 ] return godot . edge . Edge ( tail_node , head_node , _nodes = graph . nodes ) else : return None


def prepare(self, context):
		"""Attach this connection's default database to the context using our alias."""

		context.db[self.alias] = MongoEngineProxy(self.connection)

def prepare ( self , context ) : context . db [ self . alias ] = MongoEngineProxy ( self . connection )

Attach this connection s default database to the context using our alias .


def parse_xdot_drawing_directive(self, new):
        """ Parses the drawing directive, updating the node components.
        """
        components = XdotAttrParser().parse_xdot_data(new)

        max_x = max( [c.bounds[0] for c in components] + [1] )
        max_y = max( [c.bounds[1] for c in components] + [1] )

        pos_x = min( [c.x for c in components] )
        pos_y = min( [c.y for c in components] )

        move_to_origin(components)

        container = Container(auto_size=True,
            position=[pos_x-self.pos[0], pos_y-self.pos[1]],
            bgcolor="blue")
#        self.bounds = bounds=[max_x, max_y]

#        container = Container(fit_window=False, auto_size=True, bgcolor="blue")

        container.add( *components )

        self.drawing = container

def parse_xdot_drawing_directive ( self , new ) : components = XdotAttrParser ( ) . parse_xdot_data ( new ) max_x = max ( [ c . bounds [ 0 ] for c in components ] + [ 1 ] ) max_y = max ( [ c . bounds [ 1 ] for c in components ] + [ 1 ] ) pos_x = min ( [ c . x for c in components ] ) pos_y = min ( [ c . y for c in components ] ) move_to_origin ( components ) container = Container ( auto_size = True , position = [ pos_x - self . pos [ 0 ] , pos_y - self . pos [ 1 ] ] , bgcolor = "blue" ) container . add ( * components ) self . drawing = container

Parses the drawing directive updating the node components .


def parse_xdot_label_directive(self, new):
        """ Parses the label drawing directive, updating the label
            components.
        """
        components = XdotAttrParser().parse_xdot_data(new)

        pos_x = min( [c.x for c in components] )
        pos_y = min( [c.y for c in components] )

        move_to_origin(components)

        container = Container(auto_size=True,
            position=[pos_x-self.pos[0], pos_y-self.pos[1]],
            bgcolor="red")

        container.add( *components )

        self.label_drawing = container

def parse_xdot_label_directive ( self , new ) : components = XdotAttrParser ( ) . parse_xdot_data ( new ) pos_x = min ( [ c . x for c in components ] ) pos_y = min ( [ c . y for c in components ] ) move_to_origin ( components ) container = Container ( auto_size = True , position = [ pos_x - self . pos [ 0 ] , pos_y - self . pos [ 1 ] ] , bgcolor = "red" ) container . add ( * components ) self . label_drawing = container

Parses the label drawing directive updating the label components .


def _drawing_changed(self, old, new):
        """ Handles the container of drawing components changing.
        """
        if old is not None:
            self.component.remove( old )
        if new is not None:
#            new.bgcolor="pink"
            self.component.add( new )

        w, h = self.component.bounds
        self.component.position = [ self.pos[0] - (w/2), self.pos[1] - (h/2) ]
#        self.component.position = [ self.pos[0], self.pos[1] ]
        self.component.request_redraw()

def _drawing_changed ( self , old , new ) : if old is not None : self . component . remove ( old ) if new is not None : self . component . add ( new ) w , h = self . component . bounds self . component . position = [ self . pos [ 0 ] - ( w / 2 ) , self . pos [ 1 ] - ( h / 2 ) ] self . component . request_redraw ( )

Handles the container of drawing components changing .


def _on_position_change(self, new):
        """ Handles the poition of the component changing.
        """
        w, h = self.component.bounds
        self.pos = tuple([ new[0] + (w/2), new[1] + (h/2) ])

def _on_position_change ( self , new ) : w , h = self . component . bounds self . pos = tuple ( [ new [ 0 ] + ( w / 2 ) , new [ 1 ] + ( h / 2 ) ] )

Handles the poition of the component changing .


def _pos_changed(self, new):
        """ Handles the Graphviz position attribute changing.
        """
        w, h = self.component.bounds
        self.component.position = [ new[0] - (w/2), new[1] - (h/2) ]
#        self.component.position = list( new )
        self.component.request_redraw()

def _pos_changed ( self , new ) : w , h = self . component . bounds self . component . position = [ new [ 0 ] - ( w / 2 ) , new [ 1 ] - ( h / 2 ) ] self . component . request_redraw ( )

Handles the Graphviz position attribute changing .


def normal_right_down(self, event):
        """ Handles the right mouse button being clicked when the tool is in
        the 'normal' state.

        If the event occurred on this tool's component (or any contained
        component of that component), the method opens a context menu with
        menu items from any tool of the parent component that implements
        MenuItemTool interface i.e. has a get_item() method.

        """

        x = event.x
        y = event.y

        # First determine what component or components we are going to hittest
        # on.  If our component is a container, then we add its non-container
        # components to the list of candidates.
#        candidates = []
        component = self.component
#        if isinstance(component, Container):
#            candidates = get_nested_components(self.component)
#        else:
#            # We don't support clicking on unrecognized components
#            return
#
#        # Hittest against all the candidate and take the first one
#        item = None
#        for candidate, offset in candidates:
#            if candidate.is_in(x-offset[0], y-offset[1]):
#                item = candidate
#                break

        for tool in component.tools:
            component.active_tool = self
            # Do it
            event.handled = True
            component.active_tool = None
            component.request_redraw()

        return

def normal_right_down ( self , event ) : x = event . x y = event . y component = self . component for tool in component . tools : component . active_tool = self event . handled = True component . active_tool = None component . request_redraw ( ) return

Handles the right mouse button being clicked when the tool is in the normal state .


def highlight_info(ctx, style):
    """Outputs the CSS which can be customized for highlighted code"""
    click.secho("The following styles are available to choose from:", fg="green")
    click.echo(list(pygments.styles.get_all_styles()))
    click.echo()
    click.secho(
        f'The following CSS for the "{style}" style can be customized:', fg="green"
    )
    click.echo(pygments.formatters.HtmlFormatter(style=style).get_style_defs())


def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
        """ Draws a closed polygon """

        gc.save_state()
        try:
#            self._draw_bounds(gc)
            if len(self.points) >= 2:
                # Set the drawing parameters.
                gc.set_fill_color(self.pen.fill_color_)
                gc.set_stroke_color(self.pen.color_)
                gc.set_line_width(self.pen.line_width)

                # Draw the path.
                gc.begin_path()
#                x0 = self.points[0][0] - self.x
#                y0 = self.points[0][1] + self.y
#                gc.move_to(x0, y0)
#                offset_points = [(x-self.x, y+self.y) for x, y in self.points]
                gc.lines(self.points)

                gc.close_path()
                if self.filled:
                    gc.draw_path(self.inside_rule_)
                else:
                    gc.stroke_path()
        finally:
            gc.restore_state()

def _draw_mainlayer ( self , gc , view_bounds = None , mode = "default" ) : gc . save_state ( ) try : if len ( self . points ) >= 2 : gc . set_fill_color ( self . pen . fill_color_ ) gc . set_stroke_color ( self . pen . color_ ) gc . set_line_width ( self . pen . line_width ) gc . begin_path ( ) gc . lines ( self . points ) gc . close_path ( ) if self . filled : gc . draw_path ( self . inside_rule_ ) else : gc . stroke_path ( ) finally : gc . restore_state ( )


def is_in(self, point_x, point_y):
        """ Test if a point is within this polygonal region """

        point_array = array(((point_x, point_y),))
        vertices = array(self.points)
        winding = self.inside_rule == "winding"
        result = points_in_polygon(point_array, vertices, winding)
        return result[0]

def is_in ( self , point_x , point_y ) : point_array = array ( ( ( point_x , point_y ) , ) ) vertices = array ( self . points ) winding = self . inside_rule == "winding" result = points_in_polygon ( point_array , vertices , winding ) return result [ 0 ]


def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
        """ Draws the Bezier component """

        if not self.points: return
        gc.save_state()
        try:
            gc.set_fill_color(self.pen.fill_color_)

            gc.set_line_width(self.pen.line_width)
            gc.set_stroke_color(self.pen.color_)

            gc.begin_path()
            start_x, start_y = self.points[0]
            gc.move_to(start_x, start_y)
            for triple in nsplit(self.points[1:], 3):
                x1, y1 = triple[0]
                x2, y2 = triple[1]
                end_x, end_y = triple[2]
                gc.curve_to(x1, y1, x2, y2, end_x, end_y)
                # One point overlap
                gc.move_to(end_x, end_y)
            gc.stroke_path()
        finally:
            gc.restore_state()

def _draw_mainlayer ( self , gc , view_bounds = None , mode = "default" ) : if not self . points : return gc . save_state ( ) try : gc . set_fill_color ( self . pen . fill_color_ ) gc . set_line_width ( self . pen . line_width ) gc . set_stroke_color ( self . pen . color_ ) gc . begin_path ( ) start_x , start_y = self . points [ 0 ] gc . move_to ( start_x , start_y ) for triple in nsplit ( self . points [ 1 : ] , 3 ) : x1 , y1 = triple [ 0 ] x2 , y2 = triple [ 1 ] end_x , end_y = triple [ 2 ] gc . curve_to ( x1 , y1 , x2 , y2 , end_x , end_y ) gc . move_to ( end_x , end_y ) gc . stroke_path ( ) finally : gc . restore_state ( )


def _handle_event(self, event, *args, **kw):
		"""Broadcast an event to the database connections registered."""

		for engine in self.engines.values():
			if hasattr(engine, event):
				getattr(engine, event)(*args, **kw)

def _handle_event ( self , event , * args , ** kw ) : for engine in self . engines . values ( ) : if hasattr ( engine , event ) : getattr ( engine , event ) ( * args , ** kw )

Broadcast an event to the database connections registered .


def run(self):
        """
        Method that gets run when the Worker thread is started.

        When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue.
        """

        while not self.stopper.is_set():
            try:
                item = self.in_queue.get(timeout=5)
            except queue.Empty:
                continue

            try:
                result = self.func(item)
            except TypeError:
                continue
            else:
                self.out_queue.put(result)

def run ( self ) : while not self . stopper . is_set ( ) : try : item = self . in_queue . get ( timeout = 5 ) except queue . Empty : continue try : result = self . func ( item ) except TypeError : continue else : self . out_queue . put ( result )

Method that gets run when the Worker thread is started .


def get_full_page_url(self, page_number, scheme=None):
        """Get the full, external URL for this page, optinally with the passed in URL scheme"""
        args = dict(
            request.view_args,
            _external=True,
        )

        if scheme is not None:
            args['_scheme'] = scheme

        if page_number != 1:
            args['page'] = page_number

        return url_for(request.endpoint, **args)

def get_full_page_url ( self , page_number , scheme = None ) : args = dict ( request . view_args , _external = True , ) if scheme is not None : args [ '_scheme' ] = scheme if page_number != 1 : args [ 'page' ] = page_number return url_for ( request . endpoint , ** args )

Get the full external URL for this page optinally with the passed in URL scheme


def render_prev_next_links(self, scheme=None):
        """Render the rel=prev and rel=next links to a Markup object for injection into a template"""
        output = ''

        if self.has_prev:
            output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme))

        if self.has_next:
            output += '<link rel="next" href="{}" />\n'.format(self.get_full_page_url(self.next, scheme=scheme))

        return Markup(output)

def
render_prev_next_links
(
self
,
scheme
=
)
:
output
=
''
if
self
.
has_prev
:
output
+=
'<link rel="prev" href="{}" />\n'
.
format
(
self
.
get_full_page_url
(
self
.
prev
,
scheme
=
scheme
)
)
if
self
.
has_next
:
output
+=
'<link rel="next" href="{}" />\n'
.
format
(
self
.
get_full_page_url
(
self
.
next
,
scheme
=
scheme
)
)
return
Markup
(
output
)

Render the rel = prev and rel = next links to a Markup object for injection into a template


def render_seo_links(self, scheme=None):
        """Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template"""
        out = self.render_prev_next_links(scheme=scheme)

        if self.total_pages == 1:
            out += self.render_canonical_link(scheme=scheme)

        return out

def render_seo_links ( self , scheme = None ) : out = self . render_prev_next_links ( scheme = scheme ) if self . total_pages == 1 : out += self . render_canonical_link ( scheme = scheme ) return out

Render the rel = canonical rel = prev and rel = next links to a Markup object for injection into a template


def _content_type_matches(candidate, pattern):
    """Is ``candidate`` an exact match or sub-type of ``pattern``?"""
    def _wildcard_compare(type_spec, type_pattern):
        return type_pattern == '*' or type_spec == type_pattern

    return (
        _wildcard_compare(candidate.content_type, pattern.content_type) and
        _wildcard_compare(candidate.content_subtype, pattern.content_subtype)
    )

def _content_type_matches ( candidate , pattern ) : def _wildcard_compare ( type_spec , type_pattern ) : return type_pattern == '*' or type_spec == type_pattern return ( _wildcard_compare ( candidate . content_type , pattern . content_type ) and _wildcard_compare ( candidate . content_subtype , pattern . content_subtype ) )

Is candidate an exact match or sub - type of pattern ?


def select_content_type(requested, available):
    """Selects the best content type.

    :param requested: a sequence of :class:`.ContentType` instances
    :param available: a sequence of :class:`.ContentType` instances
        that the server is capable of producing

    :returns: the selected content type (from ``available``) and the
        pattern that it matched (from ``requested``)
    :rtype: :class:`tuple` of :class:`.ContentType` instances
    :raises: :class:`.NoMatch` when a suitable match was not found

    This function implements the *Proactive Content Negotiation*
    algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
    The input is the `Accept`_ header as parsed by
    :func:`.parse_http_accept_header` and a list of
    parsed :class:`.ContentType` instances.  The ``available`` sequence
    should be a sequence of content types that the server is capable of
    producing.  The selected value should ultimately be used as the
    `Content-Type`_ header in the generated response.

    .. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
    .. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5

    """

    class Match(object):
        """Sorting assistant.

        Sorting matches is a tricky business.  We need a way to
        prefer content types by *specificity*.  The definition of
        *more specific* is a little less than clear.  This class
        treats the strength of a match as the most important thing.
        Wild cards are less specific in all cases.  This is tracked
        by the ``match_type`` attribute.

        If we the candidate and pattern differ only by parameters,
        then the strength is based on the number of pattern parameters
        that match parameters from the candidate.  The easiest way to
        track this is to count the number of candidate parameters that
        are matched by the pattern.  This is what ``parameter_distance``
        tracks.

        The final key to the solution is to order the result set such
        that the most specific matches are first in the list.  This
        is done by carefully choosing values for ``match_type`` such
        that full matches bubble up to the front.  We also need a
        scheme of counting matching parameters that pushes stronger
        matches to the front of the list.  The ``parameter_distance``
        attribute starts at the number of candidate parameters and
        decreases for each matching parameter - the lesser the value,
        the stronger the match.

        """
        WILDCARD, PARTIAL, FULL_TYPE, = 2, 1, 0

        def __init__(self, candidate, pattern):
            self.candidate = candidate
            self.pattern = pattern

            if pattern.content_type == pattern.content_subtype == '*':
                self.match_type = self.WILDCARD
            elif pattern.content_subtype == '*':
                self.match_type = self.PARTIAL
            else:
                self.match_type = self.FULL_TYPE

            self.parameter_distance = len(self.candidate.parameters)
            for key, value in candidate.parameters.items():
                if key in pattern.parameters:
                    if pattern.parameters[key] == value:
                        self.parameter_distance -= 1
                    else:
                        self.parameter_distance += 1

    def extract_quality(obj):
        return getattr(obj, 'quality', 1.0)

    matches = []
    for pattern in sorted(requested, key=extract_quality, reverse=True):
        for candidate in sorted(available):
            if _content_type_matches(candidate, pattern):
                if candidate == pattern:  # exact match!!!
                    if extract_quality(pattern) == 0.0:
                        raise errors.NoMatch  # quality of 0 means NO
                    return candidate, pattern
                matches.append(Match(candidate, pattern))

    if not matches:
        raise errors.NoMatch

    matches = sorted(matches,
                     key=attrgetter('match_type', 'parameter_distance'))
    return matches[0].candidate, matches[0].pattern

def select_content_type ( requested , available ) : class Match ( object ) : WILDCARD , PARTIAL , FULL_TYPE , = 2 , 1 , 0 def __init__ ( self , candidate , pattern ) : self . candidate = candidate self . pattern = pattern if pattern . content_type == pattern . content_subtype == '*' : self . match_type = self . WILDCARD elif pattern . content_subtype == '*' : self . match_type = self . PARTIAL else : self . match_type = self . FULL_TYPE self . parameter_distance = len ( self . candidate . parameters ) for key , value in candidate . parameters . items ( ) : if key in pattern . parameters : if pattern . parameters [ key ] == value : self . parameter_distance -= 1 else : self . parameter_distance += 1 def extract_quality ( obj ) : return getattr ( obj , 'quality' , 1.0 ) matches = [ ] for pattern in sorted ( requested , key = extract_quality , reverse = True ) : for candidate in sorted ( available ) : if _content_type_matches ( candidate , pattern ) : if candidate == pattern : if extract_quality ( pattern ) == 0.0 : raise errors . NoMatch return candidate , pattern matches . append ( Match ( candidate , pattern ) ) if not matches : raise errors . NoMatch matches = sorted ( matches , key = attrgetter ( 'match_type' , 'parameter_distance' ) ) return matches [ 0 ] . candidate , matches [ 0 ] . pattern