text:
"""\
===========================================
Kamaelia component repository introspection
===========================================

This support code scans through a Kamaelia installation detecting components and
picking up relevant information such as doc strings, initializer arguments and
the declared Inboxes and Outboxes.

It not only detects components and prefabs, but also picks up modules, classes
and functions - making this a good source for documentation generation.

Example Usage
-------------

Simple lists of component/prefab names
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Fetch a flat listing of all components. The key is the module path (as a tuple)
and the value is a list of the names of the components found::

    >>> r=Repository.GetAllKamaeliaComponents()
    >>> r[('Kamaelia','Util','Console')]
    ['ConsoleEchoer', 'ConsoleReader']

Fetch a *nested* listing of all components. The leaf is a list of entity names::

    >>> r=Repository.GetAllKamaeliaComponentsNested()
    >>> r['Kamaelia']['Util']['Console']
    ['ConsoleEchoer', 'ConsoleReader']

Fetch a flat listing of all prefabs::

    >>> p=Repository.GetAllKamaeliaPrefabs()
    >>> p[('Kamaelia','File','Reading')]
    ['RateControlledFileReader', 'RateControlledReusableFileReader',
    'ReusableFileReader', 'FixedRateControlledReusableFileReader']

Fetch a *nested* listing of all prefabs::

    >>> p=Repository.GetAllKamaeliaPrefabsNested()
    >>> p['Kamaelia']['File']['Reading']
    ['RateControlledFileReader', 'RateControlledReusableFileReader',
    'ReusableFileReader', 'FixedRateControlledReusableFileReader']

Fetching a flat listing of components as defined in a specific directory (rather
than the current Kamaelia installation)::

    >>> r=Repository.GetAllKamaeliaComponents(baseDir="/data/my-projects/my-components/")

Detailed introspections::
~~~~~~~~~~~~~~~~~~~~~~~~~

We can ask for a complete introspection of the current Kamaelia installation::

   >>> docTree=Repository.ModuleDoc("Kamaelia","/usr/lib/python/site-packages/Kamaelia")
   >>> docTree.resolve(roots={"Kamaelia":docTree})

And look up a particular module::

   >>> m=docTree.find("Util.Console")
   >>> m
  <Repository.ModuleDoc object at 0x40403b0c>

Then find components declared in that module::

   >>> cs=m.listAllComponents()
   >>> cs
   [('ConsoleReader', <Repository.ClassScope object at 0x41511bac>), ('ConsoleEchoer', <Repository.ClassScope object at 0x4115990c>)]
   >>> (name,c)=cs[0]
   >>> name
   'ConsoleReader'
   >>> c
   <Repository.ClassScope object at 0x41511bac>

And look at properties of that component::

    >>> c.module
    'Kamaelia.Util.Console'
    >>> c.inboxes
    {'control': 'NOT USED', 'inbox': 'NOT USED'}
    >>> c.outboxes
    {'outbox': 'Lines that were typed at the console', 'signal': 'NOT USED'}
    >>> print c.doc
    ConsoleReader([prompt][,eol]) -> new ConsoleReader component.

    Component that provides a console for typing in stuff. Each line is output
    from the "outbox" outbox one at a time.

    Keyword arguments:

    - prompt  -- Command prompt (default=">>> ")
    - eol     -- End of line character(s) to put on end of every line outputted (default is newline)

This includes methods defined in it::

    >>> c.listAllFunctions()
    [('main', <Repository.FunctionScope object at 0x4166822c>), ('__init__', <Repository.FunctionScope object at 0x4166224c>)]
    >>> name,f=c.listAllFunctions()[1]
    >>> name
    '__init__'
    >>> f
    <Repository.FunctionScope object at 0x4166224c>

We can look at the docs for the function:

    >>> f.doc
    'x.__init__(...) initializes x; see x.__class__.__doc__ for signature'

We can ask for a string summarising the method's arguments::

    >>> f.argString
    'self[, prompt][, eol]'

Or a list naming each argument, consisting of (argname, summary-representation)
pairs::

    >>> f.args
    [('self', 'self'), ('prompt', '[prompt]'), ('eol', '[eol]')]

Obtaining introspection data
----------------------------

To get a detailed introspection you create a ModuleDoc object. You can
either point it at a specific directory, or just let it introspect the currently
installed Kamaelia repository.

You can specify the module path corresponding to that directory (the "root
name"). The default is simply "Kamaelia". If for example, you point it at the
Kamaelia.Chassis directory; you should explain that the root name is
"Kamaelia.Chassis". Or if, for example, you are using this code to document
Axon, you would specify a root name of "Axon".

After instantiating your ModuleDoc object; remember to call its "resolve" method
to allow it to resolve references to base classes, and determine method the
resolution order for classes.

How are components and prefabs detected?
----------------------------------------

Components and prefabs are detected in sourcefiles by looking for declarations
of an __kamaelia_components__ and __kamaelia_prefabs__ variables, for example::

    __kamaelia_components__ = [ "IcecastClient", "IcecastDemux", "IcecastStreamWriter" ]
    __kamaelia_prefabs__ = [ "IcecastStreamRemoveMetadata" ]

They should be declared individually, at module level, and should consist of a
simple list of strings giving the names of the components/prefabs present.

Structure of detailed introspections
------------------------------------

The introspection is a hierarchy of Scope objects, each representing a delcaration
scope - such as a module, class, function, etc. These are built up to reflect
the structure of the library if it is imported.

* ModuleDoc objects represent each module. They may contain:

    * Other ModuleDoc objects

    * ImportScope objects

    * ClassScope objects (representing classes and components)

    * FunctionScope objects (repesenting functions and prefabs)

    * UnparsedScope objects (anything that wasn't parsed)

ClassScope and FunctionScope objects may also contain any of these. For example,
methods in a class will be represented as FunctionScope objects within the
ClassScope object.

The find() method of any given scope can be used to lookup a symbol in that scope,
or its children. For example, you could call find() on the "Kamaelia.Chassis"
ModuleDoc object with the argument "Graphline.Graphline" to retrieve the graphline
component (its full path is "Kamaelia.Chassis.Graphline.Graphline")

The listAllXXXXX() methods enumerate items - such as classes, functions,
components, prefabs or modules.

Implementation Details
----------------------

This code uses the python compiler.ast module to parse the source of python
files, rather than import them. This allows introspection of code that might not
necessarily run on the system at hand - perhaps because not all dependancies can
be satisfied.

Basic tracking of assignment operations is performed, so the following is fair
game::

    from Axon.Component import component as flurble

    class Boo(flurble):
        pass

    Foo=Boo

However anything more comple is not processed. For example, functions and
classes declared within "if" statement will not be found::

    if 1:
        class WillNotBeDetected:
            pass

        def AlsoWillNotBeDetected():
            pass

The simplified functions that only return lists of component/prefab names (
GetAllKamaeliaComponentsNested, GetAllKamaeliaComponents,
GetAllKamaeliaPrefabsNested and GetAllKamaeliaPrefabs) simply run the full
introspection of the codebase but then throw most of the information away.

"""

import os
import sys

import compiler
from compiler import ast

import __builtin__ as BUILTINS

from os.path import isdir
from os.path import isfile
from os.path import exists
from os.path import join as pathjoin

class Scope(object):
    """\
    Representation of a declaration scope - could be a module, class, function, import, etc.
    Basically something that might contain other symbols.

    """

    def __init__(self, type="Module", ASTChildren=None, imports=None, localModules={}, rootScope=None):
        """\
        Arguments:

        - type          -- Descriptive name saying what kind of scope this is.
        - ASTChildren   -- List of AST nodes for whatever is within this scope. Will be parsed.
        - imports       -- Scope acting as a container/root for tracking any imports. Should be shared between all Scope objects.
        - localModules  -- Dict mapping module names that might be present in the same lexical level as this module, or deeper; mapping them to their full module names. Eg. for Axon.Component this might contain a mapping for "AxonException" to "Axon.AxonException"
        - rootScope     -- Scope object for current lexical root - eg. the Module containing this scope.
        """

        super(Scope,self).__init__()

        self.symbols={}
        self.type=type
        if imports is not None:
            self.imports=imports
        else:
            self.imports=ImportScope("")
        self.localModules=localModules
        if rootScope is not None:
            self.rootScope=rootScope
        else:
            self.rootScope=self

        if ASTChildren is None or ASTChildren==[]:
            return

        # parse the AST
	try:
		ASTChildren=ASTChildren.getChildNodes()   # python 2.3 complains if you try to iterate over the node itself
	except:
		pass

        for node in ASTChildren:
            if isinstance(node, ast.From):
                self._parse_From(node)            # parse "from ... import"s to recognise what symbols are mapped to what imported things
            elif isinstance(node, ast.Import):
                self._parse_Import(node)          # parse resolvesTo to recognise what symbols are mapped to what imported things
            elif isinstance(node, ast.Class):
                self._parse_Class(node)           # classes need to be parsed so we can work out base classes
            elif isinstance(node, ast.Function):
                self._parse_Function(node)
            elif isinstance(node, ast.Assign):
                self._parse_Assign(node)          # parse assignments that map stuff thats been imported to new names
            elif isinstance(node, ast.AugAssign):
                pass                              # definitely ignore these
            else:
                pass                              # ignore everything else for the moment
        return

    def _parse_From(self,node):
        """Parse a 'from ... import' AST node."""
        sourceModule = node.modname
        for (name, destName) in node.names:
            # check if this is actually a local module
            if sourceModule in self.localModules:
                sourceModule=self.localModules[sourceModule]
            mapsTo = ".".join([sourceModule,name])
            if destName == None:
                destName = name

            theImport=self.imports.find(mapsTo)
            self.assign(destName, theImport)

    def _parse_Import(self, node):
        """Parse an import AST node."""
        for (name,destName) in node.names:
            # if module being referred to is in the local directory, map to the full pathame
            if name in self.localModules:
                fullname = self.localModules[name]
            else:
                fullname = name

            # force creation of the import, by looking for it (ImportScope objects do this)
            theImport=self.imports.find(fullname)

            # is it being imported as a particular name, or just as itself? (eg. import Axon.Component as Flurble)
            if destName == None:
                # work out the path to the root of the entity being imported (eg. "Axon.Component" for "import Component.component")
                fullnamesplit = fullname.split(".")
                namesplit=name.split(".")
                assert(namesplit==fullnamesplit[-len(namesplit):])
                head=fullnamesplit[:len(fullnamesplit)-len(namesplit)+1]

                theImport=self.imports.find(".".join(head))
                self.assign(namesplit[0],theImport)
            else:
                self.assign(destName, theImport)

    def _parse_Class(self, node):
        """Parse a class statement AST node"""
        self.assign(node.name, ClassScope(node,self.imports,self.localModules,self.rootScope,self))

    def _parse_Function(self, node):
        """Parse a function 'def' statement AST node"""
        self.assign(node.name, FunctionScope(node,self.imports,self.localModules,self.rootScope))

    def _parse_Assign(self, node):
        for target in node.nodes:
            # for each assignment target, go clamber through mapping against the assignment expression
            # we'll only properly parse things with a direct 1:1 mapping
            # if, for example, the assignment relies on understanding the value being assigned, eg. (a,b) = c
            # then we'll silently fail
            assignments = self._mapAssign(target,node.expr)
            resolvedAssignments = []
            for (target,expr) in assignments:
                if isinstance(expr,str):
                    try:
                        resolved = self.find(expr)
                    except ValueError:
                        resolved = UnparsedScope(ast.Name(expr),self.imports,self.localModules,self.rootScope)
                else:
                    resolved = UnparsedScope(expr,self.imports,self.localModules,self.rootScope)
                resolvedAssignments.append((target,resolved))

            for (target,expr) in resolvedAssignments:
                self.assign(target,expr)

    def _mapAssign(self, target, expr):
        """\
        Correlate each term on the lhs to the respective term on the rhs of the assignment.

        Return a list of pairs (lhs, rhs) not yet resolved - just the names
        """
        assignments = []
        if isinstance(target, ast.AssName):
            targetname = self._parse_Name(target)
            if isinstance(expr, (ast.Name, ast.Getattr)):
                assignments.append( (targetname, self._parse_Name(expr)) )
            else:
                assignments.append( (targetname, expr) )
        elif isinstance(target, (ast.AssTuple, ast.AssList)):
            if isinstance(expr, (ast.Tuple, ast.List)):
                targets = target.nodes
                exprs = expr.nodes
                if len(targets)==len(exprs):
                    for i in range(0,len(targets)):
                        assignments.extend(self._mapAssign(targets[i],exprs[i]))
                else:
                    for i in range(0,len(targets)):
                        assignments.append( (targetname, exprs) )
            else:
                pass # dont know what to do with this term on the lhs of the assignment
        else:
            pass # dont know what to do with this term on the lhs of the assignment
        return assignments

    def _parse_Name(self,node):
        """Parse a name AST node (some combination of Name/AssignName/GetAttr nodes)"""
        if isinstance(node, (ast.Name, ast.AssName)):
            return node.name
        elif isinstance(node, (ast.Getattr, ast.AssAttr)):
            return ".".join([self._parse_Name(node.expr), node.attrname])
        else:
            return ""

    def resolveName(self,provisionalName):
        """\
        Returns the name you suggest this module should have; or a different one
        if this module feels it knows better :-)

        Used by ImportScopes to explain that although they may have been imported into
        one place; they are actually from somewhere else.
        """
        return provisionalName

    def find(self, name, checkRoot=True):
        """\
        Find a given named symbol and return the scope object representing it.
        Returns the found scope object, or raises ValueError if none can be found.

        This operation recurses automatically to subscopes.

        Arguments:

        - name       -- the path name of the thing to find below here.
        - checkRoot  -- Optional. If it isn't found here, check the root scope too? (default=True)
        """
        segmented=name.split(".")
        head=segmented[0]
        tail=".".join(segmented[1:])

        if head in self.symbols:
            found=self.symbols[head]
            if tail=="":
                return found
            else:
                return found.find(tail,checkRoot=False)
        else:
            if checkRoot and self.rootScope != self:
                return self.rootScope.find(name,checkRoot=False)
        raise ValueError("Cannot find it!")

    def locate(self,value):
        """\
        Find where a given scope object is. Returns the pathname leading up to it,
        or raises ValueError if it couldn't be found.

        Effectively the reverse of the find() operation.

        Example::

            >>> myScope.locate(subSubScopeObject)
            'A.B.C'

        Arguments:

        - value  -- The scope object to locate.
        """
        for symbol in self.symbols:
            if value==self.symbols[symbol]:
                return symbol
        for symbol in self.symbols:
            try:
                return symbol+"."+self.symbols[symbol].locate(value)
            except ValueError:
                pass
        raise ValueError("Can't locate it!")

    def assign(self, name, value, checkRoot=True):
        """\
        Sets a given named symbol to be the supplied value. The name can be a
        path (dot separated), in which case it will be followed through to assign
        the symbol at the end of the path.

        ValueError will be raised if the path doesn't exist.

        Example::

            >>> myScope.assign("Flurble", Scope(...))
            >>> myScope.assign("Flurble.Plig", Scope(..))

        Arguments:

        - name       -- the path name of the thing to set
        - value      -- the object to assign as that name (eg. a scope object)
        - checkRoot  -- Optional. Check the root scope too? (default=True)
        """
        segmented=name.split(".")
        head=segmented[0]
        tail=".".join(segmented[1:])

        if tail=="":
            self.symbols[head]=value
        else:
            if head in self.symbols:
                self.symbols[head].assign(tail,value,checkRoot=False)
            else:
                if checkRoot and self.rootScope != self:
                    return self.rootScope.assign(name,value,checkRoot=False)
            raise ValueError("Cannot assign to this!")

    def listAllClasses(self,**options):
        return self.listAllMatching(ClassScope,**options)

    def listAllFunctions(self,**options):
        return self.listAllMatching(FunctionScope,**options)

    def listAllModules(self,**options):
        return self.listAllMatching(ModuleScope,**options)

    def listAllNonImports(self,**options):
        return self.listAllNotMatching((ImportScope,ModuleScope),**options)

    def listAllMatching(self,types, noRecurseTypes=None, recurseDepth=0):
        """\
        Returns a list of (pathName, object) pairs for all children of the
        specified type. Will recurse as deeply as you specify. You can also block
        it from recursing into certain scope types. By default, recusion stops
        at ModuleScope objects.

        Arguments::

        - types           -- tuple of classes that can be returned (default is ModuleScope)
        - noRecurseTypes  -- tuple of classes that will *not* be recursed into (default=none)
        - recurseDepth    -- Optional. Maximum recursion depth (default=0)
        """
        if noRecurseTypes==None:
            noRecurseTypes=(ModuleScope,)
        found=[]
        for symbol in self.symbols:
            item=self.symbols[symbol]
            if isinstance(item,types):
                found.append((symbol,item))
            if recurseDepth>0 and not isinstance(item,noRecurseTypes):
                subfound=item.listAllMatching(types,noRecurseTypes,recurseDepth-1)
                for (name,thing) in subfound:
                    found.append((symbol+"."+name,thing))
        return found

    def listAllNotMatching(self,types, noRecurseTypes=None, recurseDepth=0):
        """\
        Returns a list of (pathName, object) pairs for all children *not* matching the
        specified type. Will recurse as deeply as you specify. You can also block
        it from recursing into certain scope types. By default, recusion stops
        at ModuleScope objects.

        Arguments::

        - types           -- tuple of classes that can *not* be returned (default is ModuleScope)
        - noRecurseTypes  -- tuple of classes that will *not* be recursed into (default=none)
        - recurseDepth    -- Optional. Maximum recursion depth (default=0)
        """
        if noRecurseTypes==None:
            noRecurseTypes=(ModuleScope,)
        found=[]
        for symbol in self.symbols:
            item=self.symbols[symbol]
            if not isinstance(item,types):
                found.append((symbol,item))
            if recurseDepth>0 and not isinstance(item,noRecurseTypes):
                subfound=item.listAllMatching(types,noRecurseTypes,recurseDepth-1)
                for (name,thing) in subfound:
                    found.append((symbol+"."+name,thing))
        return found

    def resolve(self,_resolvePass=None,roots={}):
        """\
        Post processing step for resolving imports, base classes etc.

        Call this method after you have finished instantiating
        your whole tree of Scope objects.

        Arguments:

        - _resolvePass  -- For internal use. Don't specify when calling manually.
        - roots         -- list of master root scope objects - eg. the object representing the top level "Axon" or "Kamaelia" module.
        """
        if _resolvePass==None:
            self.resolve(_resolvePass=1,roots=roots)
            self.resolve(_resolvePass=2,roots=roots)
        else:
            for (name,item) in self.symbols.items():
                try:
                    item.resolve(_resolvePass=_resolvePass,roots=roots)
                except AttributeError:
                    # item doesn't have a 'resolve' method
                    pass

class ModuleScope(Scope):
    """\
    Scope object representing module scopes.
    """
    def __init__(self, AST, localModules={}):
        super(ModuleScope,self).__init__("Module",AST.node.nodes,None,localModules,None)
        self.ast=AST
        if AST.doc is not None:
            self.doc = AST.doc
        else:
            self.doc = ""

class ClassScope(Scope):
    """\
    Scope object representing class scopes.

    Determines what its base classes are, and the method resolution order. A list
    of (name,baseScopeObject) pairs is placed in self.bases. A list of scope objects
    is placed into self.allBasesInMethodResolutionOrder.

    Bases will be a mixture of ClassScope and ImportScope objects.

    These lists won't be properly set until the resolve() post-pocessing method
    has been called.

    Sets the following attributes:

    - doc        -- class's doc string, or the empty string if none.
    - bases      -- list of (name,scope object) pairs describing the class's bases
    - allBasesInMethodResolutionOrder  -- list of scope objects for the bases in method resolution order
    - ast        -- the AST for this
    """
    def __init__(self, AST, imports, localModules, rootScope, parentScope):
        super(ClassScope,self).__init__("Class",AST.code,imports,localModules,rootScope)
        self.ast=AST

        if AST.doc is not None:
            self.doc = AST.doc
        else:
            self.doc = ""

        # parse bases
        self.bases = []
        for baseName in AST.bases:
            parsedBaseName=self._parse_Name(baseName)
            try:
                base=parentScope.find(parsedBaseName)
                resolvedBaseName = base.resolveName(parsedBaseName)
            except ValueError:
                base=None
                resolvedBaseName = parsedBaseName
            self.bases.append((resolvedBaseName,base))

    def resolve(self,_resolvePass=None,roots={}):
        """\
        Resolve pass 1:

        * resolves bases, where passible to ClassScope objects - eg. checking if
          imports actually refer to stuff in this tree of scope objects, and
          dereferening them.

        Resolve pass 2:

        * determines the method resolution order
        """
        super(ClassScope,self).resolve(_resolvePass,roots)
        if _resolvePass==1 and len(roots):
            # resolve bases that are imports that could actually be classes in one of the root hierarchies
            newBases = []
            for baseName,base in self.bases:
                history=[]
                baseNameFrags = baseName.split(".")
                # chase through the (chain of) imports to see if we can find them
                # in the documentation object tree roots provided
                while isinstance(base,ImportScope) or base is None:
                    history.append(baseName)

                    success=False
                    for rootName,rootMod in roots.items():
                        rootNameFrags=rootName.split(".")
                        head=baseNameFrags[:len(rootNameFrags)]
                        tail=baseNameFrags[len(rootNameFrags):]
                        if rootNameFrags == head:
                            try:
                                base=rootMod.find(".".join(tail))
                                baseName=baseName
                                success=True
                            except ValueError:
                                continue
                        if baseName in history:
                            continue

                    if not success:
                        # ok, hit a dead end
                        break
                    if baseName in history:
                        # ok, we've gone circular
                        break

                newBases.append((baseName,base))

            self.bases=newBases

        elif _resolvePass==2:
            # now determine the method resolution order
            self.allBasesInMethodResolutionOrder = _determineMRO(self)
            super(ClassScope,self).resolve(_resolvePass,roots)

def _determineMRO(klass):
    """\
    Pass a ClassScope object representing a class, and this method returns a
    list of scope objects presenting the base classes in method resolution order.

    This function applies the C3 algorithm, as used by python, to determine the
    method resolution order.
    """
    order=[klass]
    if not isinstance(klass,ClassScope):
        return order

    bases=[]
    for baseName,base in klass.bases:
        bases.append(base)

    mergedBases = [_determineMRO(base) for base in bases]
    mergedBases.extend([[base] for base in bases])
    while len(mergedBases) > 0:
        for baselist in mergedBases:
            head = baselist[0]
            foundElsewhere = [True for merged in mergedBases if (head in merged[1:])]
            if foundElsewhere == []:
                order.append(head)
                for baselist in mergedBases:
                    if baselist[0]==head:
                        del baselist[0]
                mergedBases = [baselist for baselist in mergedBases if baselist != []]
                break
        if foundElsewhere:
            raise RuntimeError("FAILURE")
    return order

class FunctionScope(Scope):
    """\
    Scope object representing a declared function.

    Sets the following attributes:

    - doc        -- function's doc string, or the empty string if none.
    - argString  -- string describing the arguments this method takes
    - argNames   -- list of (name, annotatedName) tuples repesenting, in order, the arguments of the method
    - ast        -- the AST for this
    """
    def __init__(self, AST, imports, localModules, rootScope):
        super(FunctionScope,self).__init__("Class",None,imports,localModules,rootScope) # don't bother parsing function innards
        self.ast=AST

        if AST.doc is not None:
            self.doc = AST.doc
        else:
            self.doc = ""

        # parse arguments
        argNames = [(str(argName),str(argName)) for argName in AST.argnames]
        i=-1
        numVar = AST.varargs or 0
        numKW  = AST.kwargs or 0
        for j in range(numKW):
            argNames[i] = ( argNames[i][0], "**"+argNames[i][1] )
            i-=1
        for j in range(numVar):
            argNames[i] = ( argNames[i][0], "*"+argNames[i][1] )
            i-=1
        for j in range(len(AST.defaults)-numVar-numKW):
            argNames[i] = ( argNames[i][0], "["+argNames[i][1]+"]" )
            i-=1

        argStr = ", ".join([arg for (_, arg) in argNames])
        argStr = argStr.replace(", [", "[, ")

        self.args = argNames
        self.argString = argStr

class ImportScope(Scope):
    """\
    Scope object representing an import.

    Sets the following attributes:

    - doc        -- empty string
    - importPathName  -- the full import path name leading to this entity, eg. "Axon.Component"
    """
    def __init__(self,importPathName="",imports=None):
        if importPathName=="" and imports==None:
            imports=self
        super(ImportScope,self).__init__("Module",None,imports,[],None)  # its an opaque imported module, no local modules, etc to concern ourselves with

        self.doc = ""
        self.importPathName=importPathName

    def resolveName(self,provisionalName):
        """Returns the full (real) path name of this import"""
        return self.importPathName

    def find(self,name,checkRoot=False):
        # we assume the symbol exists(!), so if it is referenced, we create a placeholder for it (if one doesn't already exist)
        # shouldn't check in root scope of this parsing, since, as an import, this *is* the new root (its a new module)
        checkRoot=False
        segmented=name.split(".")
        head=segmented[0]
        tail=".".join(segmented[1:])

        if head not in self.symbols:
            if self.importPathName:
                fullname=self.importPathName+"."+head
            else:
                fullname=head
            self.assign(head, ImportScope(fullname,self.imports))

        found=self.symbols[head]
        if tail=="":
            return found
        else:
            return found.find(tail,checkRoot=False)

    def assign(self, name, value, checkRoot=False):
        # we assume the symbol exists(!), so if it is referenced, we create a placeholder for it (if one doesn't already exist)
        checkRoot=False
        segmented=name.split(".")
        head=segmented[0]
        tail=".".join(segmented[1:])

        if tail=="":
            self.symbols[head]=value
        else:
            if head not in self.symbols:
                if self.importPathName:
                    fullname=self.importPathName+"."+head
                else:
                    fullname=head
                self.assign(head, ImportScope(fullname,self.imports))
            self.symbols[head].assign(tail,value,checkRoot=False)

class UnparsedScope(Scope):
    """\
    Scope object representing something that wasn't parsed - eg. a symbol
    that refers to something that isn't a simple class, function etc.

    Sets the following attributes:

    - doc  -- empty string
    - ast  -- the AST tree for this unparsed entity
    """
    def __init__(self, AST, imports, localModules, rootScope):
        super(UnparsedScope,self).__init__("Unparsed",AST,imports,localModules,rootScope)
        self.doc=""
        self.ast=AST

class ModuleDoc(ModuleScope):
    def __init__(self, moduleName, filePath, localModules={}):
        """\
        Arguments:

        - moduleName  -- the full module pathname for this module
        - filePath    -- the full filepath of this module or this subdirectory
        - localModules -- dictionary mapping localmodule pathnames to the global namespace; eg. Chassis -> Kamaelia.Chassis
        """
        self.ignoreFilenames=[".svn","__init__.py"]

        if isdir(filePath):
            subModules,localModules,AST = self.scanSubdirs(filePath,moduleName)

        else:
            subModules = {}
            localModules = localModules
            AST = self.scanSelfOnly(filePath)

        # now we've already done children and have built up localModule name mappings
        # we can initialise ourselves properly (parsing the AST)
        print "Parsing:",moduleName

        super(ModuleDoc,self).__init__(AST,localModules)
        self.localModules = localModules    # just to be safe

        # add "module" attribute to ourselves
        self.module = moduleName

        # go identify __kamaelia_components__ and __kamaelia_prefabs__ and refashion them
        self.identifyComponentsAndPrefabs()
        self.augmentComponentsAndPrefabs()

        # add "module" attribute to all our non import children too
        for (symbol,item) in self.listAllNonImports():
            item.module = moduleName

        # merge subModules into self.symbols
        for name in subModules:
            self.assign(name, subModules[name])

    def scanSubdirs(self, filePath,moduleName):
        subModules={}

        # try to ingest __init__.py
        filename=pathjoin(filePath,"__init__.py")
        if exists(filename):
            AST=compiler.parseFile(filename)
        else:
            AST=compiler.parse("")

        subdirs = [name for name in os.listdir(filePath) if isdir(pathjoin(filePath,name)) and name not in self.ignoreFilenames]
        sourcefiles = [name for name in os.listdir(filePath) if not name in subdirs and name[-3:]==".py" and name not in self.ignoreFilenames]

        localModules={} # we're a subdirectory, ignore what we were passed

        # recurse througth directory contents, doing subdirectories first
        # ignore localModules we were passed; and build our own as the localModules of all children
        for subDir in subdirs:
            subModName=moduleName+"."+subDir
            subMod = ModuleDoc(subModName, pathjoin(filePath,subDir))
            subModules[subDir] = subMod
            # merge the subdir's local modules into our own local modules
            for key in subMod.localModules:
                localModules[subDir+"."+key] = subMod.localModules[key]

        # add localstuff to localModules too
        for file in sourcefiles:
            modName=file[:-3] # strip ".py"
            localModules[modName] = moduleName+"."+modName

        # now go through other module files in this directory with us
        for file in sourcefiles:
            modName=file[:-3]
            mod = ModuleDoc(moduleName+"."+modName, pathjoin(filePath,file), localModules)
            subModules[modName] = mod

        return subModules,localModules,AST

    def scanSelfOnly(self,filePath):
        # ingest file as it stands
        assert(exists(filePath))
        assert(isfile(filePath))
        AST=compiler.parseFile(filePath)
        return AST

    def identifyComponentsAndPrefabs(self):
        try:
            components = self.find("__kamaelia_components__")
            components = _stringsInList(components.ast)
        except (ValueError,TypeError):
            components = []

        try:
            prefabs = self.find("__kamaelia_prefabs__")
            prefabs = _stringsInList(prefabs.ast)
        except (ValueError,TypeError):
            prefabs = []

        self.components = components
        self.prefabs = prefabs

    def augmentComponentsAndPrefabs(self):
        # parse Inbox/Outbox declarations for components
        for name,component in self.listAllComponents():
            component.isComponent=True

            try:
                inboxes = component.find("Inboxes")
                component.inboxes = _parseBoxes(inboxes.ast)
            except ValueError:
                component.inboxes = []

            try:
                outboxes = component.find("Outboxes")
                component.outboxes = _parseBoxes(outboxes.ast)
            except ValueError:
                component.outboxes = []

        # nothing much to do for prefabs
        for name,prefab in self.listAllPrefabs():
            prefab.isPrefab=True

    def listAllComponents(self,**options):
        return [ (name,cls) for (name,cls) in self.listAllClasses(**options) if name in self.components ]

    def listAllPrefabs(self,**options):
        return [ (name,fnc) for (name,fnc) in self.listAllFunctions(**options) if name in self.prefabs ]

    def listAllComponentsAndPrefabs(self,**options):
        return self.listAllComponents(**options) + self.listAllPrefabs(**options)

    def listAllModulesIncSubModules(self):
        modules = [(self.module, self)]
        for (_,m) in self.listAllModules(recurseDepth=0):
            modules.extend(m.listAllModulesIncSubModules())
        return modules

    def listAllComponentsIncSubModules(self):
        components = [(self.module+"."+name, item) for (name,item) in self.listAllComponents(recurseDepth=5)]
        for (_,m) in self.listAllModules(recurseDepth=0):
            components.extend(m.listAllComponentsIncSubModules())
        return components

    def listAllPrefabsIncSubModules(self):
        prefabs = [(self.module+"."+name, item) for (name,item) in self.listAllPrefabs(recurseDepth=5)]
        for (_,m) in self.listAllModules(recurseDepth=0):
            prefabs.extend(m.listAllPrefabsIncSubModules())
        return prefabs

# ------------------------------------------------------------------------------

def _stringsInList(theList):
    # flatten a tree structured list containing strings, or possibly ast nodes
    if isinstance(theList, (ast.Tuple,ast.List)):
        theList = theList.nodes
    elif isinstance(theList, (list,tuple)):
        theList = theList
    else:
        raise TypeError("Not a tuple or list")

    found = []
    for item in theList:
        if isinstance(item,str):
            found.append(item)
        elif isinstance(item, ast.Name):
            found.append(item.name)
        elif isinstance(item,(list,tuple,ast.Node)):
            found.extend(_stringsInList(item))
    return found

def _parseBoxes(node):
    if isinstance(node, ast.Dict):
        return _parseDictBoxes(node)
    elif isinstance(node, ast.List):
        return _parseListBoxes(node)

def _parseDictBoxes(dictNode):
    boxes = []
    for (lhs,rhs) in dictNode.items:
        if isinstance(lhs, ast.Const) and isinstance(rhs, ast.Const):
            name = lhs.value
            desc = rhs.value
            if isinstance(name, str) and isinstance(desc, str):
                boxes.append((name,desc))
    return dict(boxes)

def _parseListBoxes(listNode):
    boxes = []
    for item in listNode.nodes:
        if isinstance(item, ast.Const):
            name = item.value
            if isinstance(name, str):
                boxes.append((name,''))
    return list(boxes)

# ------------------------------------------------------------------------------

# METHODS PROVIDING
# BACKWARD COMPATIBILITY WITH OLD Repository.py

def GetAllKamaeliaComponentsNested(baseDir=None):
    """\
    Return a nested structure of dictionaries. Keys are module names. Values
    are either nested sub-dictionaries, or component names. The structure
    maps directly to the module directory structure.

    If no base-directory is specified, then the current Kamaelia installation
    will be scanned.

    Keyword arguments:

    - baseDir  -- Optional. Top directory of the code base to scan, or None for the current Kamaelia installation (default=None)
    """
    flatList = GetAllKamaeliaComponents(baseDir)
    flatList.sort()
    return _nest(flatList)

def GetAllKamaeliaComponents(baseDir=None):
    """\
    Return a flat dictionary mapping module paths to lists of component names
    contained in that module. Module paths are tuples containing each element
    of the path, eg ("Kamaelia","File","Reading")

    If no base-directory is specified, then the current Kamaelia installation
    will be scanned.

    Keyword arguments:

    - baseDir  -- Optional. Top directory of the code base to scan, or None for the current Kamaelia installation (default=None)
    """
    if baseDir is None:
        import Kamaelia
        baseDir=os.path.dirname(Kamaelia.__file__)

    rDocs = ModuleDoc("Kamaelia",baseDir)

    names = {}
    for name in [name for (name,item) in rDocs.listAllComponentsIncSubModules()]:
        path,name = tuple(name.split(".")[:-1]), name.split(".")[-1]
        names[path] = names.get(path,[]) + [name]
    return names

def GetAllKamaeliaPrefabsNested(baseDir=None):
    """\
    Return a nested structure of dictionaries. Keys are module names. Values
    are either nested sub-dictionaries, or prefab names. The structure
    maps directly to the module directory structure.

    If no base-directory is specified, then the current Kamaelia installation
    will be scanned.

    Keyword arguments:

    - baseDir  -- Optional. Top directory of the code base to scan, or None for the current Kamaelia installation (default=None)
    """
    flatList = GetAllKamaeliaPrefabs(baseDir)
    flatList.sort()
    return _nest(flatList)

def GetAllKamaeliaPrefabs(baseDir=None):
    """\
    Return a flat dictionary mapping module paths to lists of prefab names
    contained in that module. Module paths are tuples containing each element
    of the path, eg ("Kamaelia","File","Reading")

    If no base-directory is specified, then the current Kamaelia installation
    will be scanned.

    Keyword arguments:

    - baseDir  -- Optional. Top directory of the code base to scan, or None for the current Kamaelia installation (default=None)
    """
    if baseDir is None:
        import Kamaelia
        baseDir=os.path.dirname(Kamaelia.__file__)

    rDocs = ModuleDoc("Kamaelia",baseDir)

    names = {}
    for name in [name for (name,item) in rDocs.listAllPrefabsIncSubModules()]:
        path,name = tuple(name.split(".")[:-1]), name.split(".")[-1]
        names[path] = names.get(path,[]) + [name]
    return names

def _nest(flatList):
    nested={}
    for path in flatList:
        leafModuleName=path[-2]
        componentName=path[-1]
        node=nested

        for element in path[:-2]:
            if element in node:
                assert(isinstance(node[element],dict))
            else:
                node[element]=dict()
            node=node[element]

        if leafModuleName in node:
            assert(isinstance(node[leafModuleName],list))
        else:
            node[leafModuleName]=list()
        node[leafModuleName].append(componentName)

    return nested

if __name__ == "__main__":
    file="/home/matteh/kamaelia/trunk/Code/Python/Kamaelia/Kamaelia/File/Reading.py"
    #file="/home/matteh/kamaelia/trunk/Code/Python/Kamaelia/Kamaelia/Chassis/Pipeline.py"
    #file="/home/matteh/kamaelia/trunk/Code/Python/Kamaelia/Kamaelia/Protocol/RTP/NullPayloadRTP.py"
    modDocs = ModuleDoc("Kamaelia.File.Reading",file,{})

    print "MODULE:"
    print modDocs.doc

    print
    print "PREFABS:"
    for (name,item) in modDocs.listAllPrefabs():
        print name,item.argString

    print
    print "COMPONENTS:"
    for (name,item) in modDocs.listAllComponents():
        print name
        print "Inboxes:  ",item.inboxes
        print "Outboxes: ",item.outboxes
        for (name,meth) in item.listAllFunctions():
            print name + "(" + meth.argString + ")"
        print

    import pprint
    pprint.pprint(GetAllKamaeliaComponents(),None,4)
    print
    print "*******************************************************************"
    print
    pprint.pprint(GetAllKamaeliaComponentsNested(),None,4)
    print
    print "*******************************************************************"
    print
    pprint.pprint(GetAllKamaeliaPrefabs(),None,4)
    print
    print "*******************************************************************"
    print
    pprint.pprint(GetAllKamaeliaPrefabsNested(),None,4)
    print
    print "*******************************************************************"


text:
package me.coley.bmf.util.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import me.coley.bmf.ClassNode;
import me.coley.bmf.ClassWriter;
import me.coley.bmf.util.StreamUtil;

/**
 * A utility class for reading information from jar files.
 *
 * @author Matt
 */
public class JarUtil {
    /**
     * Manifest entry name.
     */
    private static final String MANIFEST_ENTRY_NAME = "META-INF/MANIFEST.MF";

    /**
     * Reads all classes in a jar file and stores them in a map of byte arrays.
     *
     * @param file
     * @return
     * @throws ZipException
     * @throws IOException
     */
    public static Map<String, byte[]> readJarClasses(File file) throws ZipException, IOException {
        return readJar(file, new NameFilter() {
            @Override
            public boolean matches(String name) {
                return name.endsWith(".class");
            }

            @Override
            public String filterName(String name) {
                return name.replace(".class", "");
            }
        });
    }

    /**
     * Reads all non-class entries in a jar file and stores them in a map of
     * byte arrays.
     *
     * @param file
     * @return
     * @throws ZipException
     * @throws IOException
     */
    public static Map<String, byte[]> readJarNonClasses(File file) throws ZipException, IOException {
        return readJar(file, new NameFilter() {
            @Override
            public boolean matches(String name) {
                return !name.endsWith(".class");
            }

            @Override
            public String filterName(String name) {
                return name;
            }
        });
    }

    /**
     * Returns a list of entry names based on the given File and NameFilter.
     *
     * @param file
     * @param filter
     * @return
     * @throws ZipException
     * @throws IOException
     */
    public static List<String> getEntryNames(File file, NameFilter filter) throws ZipException, IOException {
        List<String> names = new ArrayList<String>();
        ZipFile zip = new ZipFile(file);
        zip.stream().forEach(new Consumer<ZipEntry>() {
            @Override
            public void accept(ZipEntry entry) {
                String name = entry.getName();
                if (entry.isDirectory() || !filter.matches(name)) {
                    return;
                }
                names.add(filter.filterName(name));
            }
        });
        zip.close();
        return names;
    }

    /**
     * Reads all entries in a jar file and stores them in a map of byte arrays.
     * Certain entries may be excluded bases on the NameFilter parameter.
     *
     * @param file
     * @param filter
     * @return
     * @throws ZipException
     * @throws IOException
     */
    public static Map<String, byte[]> readJar(File file, NameFilter filter) throws ZipException, IOException {
        Map<String, byte[]> entries = new HashMap<>();
        ZipFile zip = new ZipFile(file);
        zip.stream().forEach(new Consumer<ZipEntry>() {
            @Override
            public void accept(ZipEntry entry) {
                String name = entry.getName();
                if (entry.isDirectory() || !filter.matches(name)) {
                    return;
                }
                try {
                    entries.put(filter.filterName(name), StreamUtil.fromStream(zip.getInputStream(entry)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        zip.close();
        return entries;
    }

    /**
     * Creates a new jar file given the original file in, the output file
     * out, and a map of ClassNodes.
     *
     * @param in
     * @param out
     * @param nodes
     */
    public static void writeJar(File in, File out, Map<String, ClassNode> nodes) {
        writeJar(in, out, nodes, null);
    }

    /**
     * Creates a new jar file given the original file in, the output file
     * out, a map of ClassNodes, and a map of non-class entries.
     *
     *
     * @param in
     * @param out
     * @param nodes
     * @param nonClasses
     */
    public static void writeJar(File in, File out, Map<String, ClassNode> nodes, Map<String, byte[]> nonClasses) {
        try {
            FileOutputStream fos = new FileOutputStream(out);
            Manifest manifest = getManifest(in);
            JarOutputStream jos = manifest != null ? new JarOutputStream(fos, manifest) : new JarOutputStream(fos);
            for (ClassNode node : nodes.values()) {
                JarEntry entry = new JarEntry(node.getName() + ".class");
                entry.setTime(System.currentTimeMillis());
                jos.putNextEntry(entry);
                jos.write(ClassWriter.write(node));
            }
            if (nonClasses != null) {
                if ((manifest != null) && nonClasses.containsKey(MANIFEST_ENTRY_NAME)) {
                    nonClasses.remove(MANIFEST_ENTRY_NAME);
                }
                for (String entryName : nonClasses.keySet()) {
                    JarEntry entry = new JarEntry(entryName);
                    entry.setTime(System.currentTimeMillis());
                    jos.putNextEntry(entry);
                    jos.write(nonClasses.get(entryName));
                }
            }
            jos.close();
            fos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Assumes the given file is a jar and retrieves the manifest.
     *
     * @param in
     * @return
     * @throws IOException
     */
    private static Manifest getManifest(File in) throws IOException {
        JarFile jar = new JarFile(in);
        Manifest manifest = jar.getManifest();
        jar.close();
        return manifest;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Minsal\GinecologiaBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController;

class SrgRetornoExtendidoAdminController extends CRUDController
{

}


text:
from __future__ import unicode_literals

import django.db.models.deletion
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('scheduling', '0016_auto_20170116_2251'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='event',
            options={'ordering': ['-starts_at'], 'verbose_name': 'event', 'verbose_name_plural': 'events'},
        ),
        migrations.AlterModelOptions(
            name='mailtemplate',
            options={'ordering': ['organization'], 'verbose_name': 'mail template', 'verbose_name_plural': 'mail templates'},
        ),
        migrations.AlterField(
            model_name='event',
            name='pricegroup',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='billing.PriceGroup', verbose_name='pricegroup'),
        ),
    ]


text:
package ie.dit;

import java.io.IOException;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

public class Main
{
	void matrixMultiplication()
	{
		Matrix a = new Matrix(4, 5);
		a.identity();
		a.setElement(2, 3, 7);
		a.setElement(3, 1, 2);
		a.setElement(3, 0, 4);

		Matrix b = new Matrix(4, 4);
		b.identity();
		b.setElement(2, 3, 1);
		b.setElement(3, 1, 9);
		b.setElement(3, 0, -7);

		//a.mult(b); // Add b to a. This is like a+= b;

		Matrix c = null;
		// Add b to a, without changing a. Instead create a new matrix and return it
		// This is like c = a + b

		try
		{
			c = Matrix.add(a, b); // How to call a static method
		}
		catch(MatrixException e)
		{
			System.out.println(e);
			e.printStackTrace();
		}
		finally
		{
			System.out.println("This always happens");
		}
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
	}

	public void editDistance()
	{
		String sa = "I love DIT";
		String sb = "I love Tunepal";
		System.out.println("Edit distance between: " + sa + " and: " + sb + " is " + EditDistance.minimumEditDistance(sa, sb));

		sa = "Games Fleadh";
		sb = "Imagine Cup";
		System.out.println("Edit distance between: " + sa + " and: " + sb + " is " + EditDistance.minimumEditDistance(sa, sb));

		sa = "AAB";
		sb = "ABC";
		System.out.println("Edit distance between: " + sa + " and: " + sb + " is " + EditDistance.minimumEditDistance(sa, sb));

	}

	public void dictionary()
	{
		Dictionary d = new Dictionary();
		//System.out.println(d);

		//System.out.println(d.findClosest("bread"));
		//System.out.println(d.findClosest("militarry"));

		String[] words = d.findClosest("helo", 10);
		for(int i = 0 ; i < words.length ; i ++)
		{
			System.out.println(words[i]);
		}

	}
	public void strings()
	{
		String s = "I love Star Trek";

		System.out.println(s.length());
		System.out.println(s.contains("love"));
		System.out.println(s.contains("hate"));
		System.out.println(s.startsWith("I love"));
		System.out.println(s.endsWith("cats"));
		System.out.println(s.equals("Hello"));

		String ss = s.substring(7);

		System.out.println(ss);
		// Incorrect way to compare strings
		if (ss == "Star Trek")
		{
			System.out.println("Same");
		}
		else
		{
			System.out.println("Different");
		}
		// Correct way to compare strings
		if (ss.equalsIgnoreCase("Star Trek"))
		{
			System.out.println("Same");
		}
		else
		{
			System.out.println("Different");
		}

		String star = ss.substring(0, 5);
		System.out.println(star.toUpperCase());

	}

	public void transform()
	{
		try
		{
			Vector v = new Vector(5, 10);
			Matrix trans = Matrix.translation(2, -11);

			System.out.println(trans.transform(v));

			Matrix scale = Matrix.scaling(2, 3);

			System.out.println(scale.transform(v));

			Matrix combined = Matrix.mult(scale, trans);

			System.out.println(combined.transform(v));
		}
		catch(MatrixException e)
		{
			e.printStackTrace();
		}
		finally
		{

		}
	}

	public void tuneFinder()
	{
		JFrame tf  = new TuneFinder();

		tf.setVisible(true);
		tf.setSize(1000, 500);

	}
	public void tuneFinder1()
	{
		String[] a = {"MAIN"};
        processing.core.PApplet.runSketch( a, new TuneFinder1());
	}

	public static void main(String[] args)
	{
		Main main = new Main();
		//main.matrixMultiplication();
		//main.editDistance();
		//main.strings();
		//main.dictionary();
		//main.transform();

		main.matrixMultiplication();
		//main.tuneFinder1();

		/*
		float x = 10.0f / 17.0f;
		float y = 0.0f;
		for(int i = 0 ; i < 17 ; i ++)
		{
			y +=x;
		}
		System.out.println(y);
		*/

	}

}


text:
package fr.insee.rmes.api.old;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;

import fr.insee.rmes.modeles.classification.cj.CategorieJuridiqueNiveauIII;

// TODO needs to be transformed into fonctional test

@Ignore
public class ModelTest {

    @Test
    public void testPopulateFromCSV() {

        CategorieJuridiqueNiveauIII cj = new CategorieJuridiqueNiveauIII();
        cj.setCode("7112");
        cj.setUri("http://id.insee.fr/codes/cj/n3/7112");
        cj.setIntitule("mon intitué");
        System.out.println(cj.getCode() + " - " + cj.getIntitule() + " - " + cj.getUri());
        Assertions.assertTrue(true);
    }

}


text:
package edu.cuny.qc.speech.AuToBI.classifier;

/**
 * Created by andrew on 4/2/15.
 */
public class TrainingParameters {
}


text:
<?php

namespace Auth\Listener\Events;

use Auth\Entity\User;
use Laminas\EventManager\Event;

class AuthEvent extends Event
{
    /**
     * User events triggered by eventmanager
     */

    /**
     * a new password was created
     */
    const EVENT_AUTH_NEWPASSWORD   = 'auth.newpassword';

    const EVENT_USER_REGISTERED    = 'auth.user-registered';

    const EVENT_USER_CONFIRMED     = 'auth.user-confirmed';

    protected $userEntity;

    protected $newPassword;

    protected $resetLink;

    protected $user;

    public function setUserEntity($userEntity)
    {
        $this->userEntity = $userEntity;
        return $this;
    }

    public function getUserEntity()
    {
        return $this->userEntity;
    }

    public function setNewPassword($password)
    {
        $this->newPassword = $password;
        return $this;
    }

    public function getNewPassword()
    {
        return $this->newPassword;
    }

    public function setResetLink($resetLink)
    {
        $this->resetLink = $resetLink;
        return $this;
    }

    public function getResetLink()
    {
        return $this->resetLink;
    }

    public function setUser($user)
    {
        $this->user = $user;
        return $this;
    }

    public function getUser()
    {
        return $this->user;
    }
}


text:
apt-get install -y libnet-bluetooth-perl
cpan -i Tie::File::AsHash Proc::Daemon;

#create log dir
mkdir -p /var/log/blue_lock/

#bin
cp -vi bin/blue_lock.pl /usr/bin/
cp -vi bin/screenlock.sh /usr/bin/

#config
cp -vi config/install_config /etc/blue_lock.conf

#lib
cp -vi lib/BlueLock.pm /usr/lib/perl5/

#init.d
cp -vi init.d/blue_lock /etc/init.d
update-rc.d blue_lock defaults


text:
using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System.Reflection;
using System.Xml.Serialization;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.ComponentModel;

namespace QuickGraph.Serialization
{
    public static class XmlReaderExtensions
    {
        public static Boolean[] ReadElementContentAsBooleanArray(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => Convert.ToBoolean(s));
        }

        public static Int32[] ReadElementContentAsInt32Array(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => Convert.ToInt32(s));
        }

        public static Int64[] ReadElementContentAsInt64Array(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => Convert.ToInt64(s));
        }

        public static Single[] ReadElementContentAsSingleArray(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => Convert.ToSingle(s));
        }

        public static Double[] ReadElementContentAsDoubleArray(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => Convert.ToDouble(s));
        }

        public static String[] ReadElementContentAsStringArray(XmlReader xmlReader, string localName, string namespaceURI)
        {
            return ReadElementContentAsArray(xmlReader, localName, namespaceURI, s => s);
        }

        /// <summary>
        /// Read contents of an XML element as an array of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlReader"></param>
        /// <param name="localName"></param>
        /// <param name="namespaceURI"></param>
        /// <param name="stringToT"></param>
        /// <returns></returns>
        public static T[] ReadElementContentAsArray<T>(XmlReader xmlReader, string localName, string namespaceURI,
                                                        Func<string, T> stringToT)
        {
            var str = xmlReader.ReadElementContentAsString(localName, namespaceURI);

            if (str == "null")
                return null;

            if (str.Length > 0 && str[str.Length - 1] == ' ')
            {
                str = str.Remove(str.Length - 1);
            }

            var strArray = str.Split(new char[1] { ' ' });

            var array = new T[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                array[i] = stringToT(strArray[i]);
            }
            return array;
        }
    }

    /// <summary>
    /// A GraphML ( http://graphml.graphdrawing.org/ ) format deserializer.
    /// </summary>
    /// <typeparam name="TVertex">type of a vertex</typeparam>
    /// <typeparam name="TEdge">type of an edge</typeparam>
    /// <typeparam name="TGraph">type of the graph</typeparam>
    /// <remarks>
    /// <para>
    /// Custom vertex, edge and graph attributes can be specified by
    /// using the <see cref="System.Xml.Serialization.XmlAttributeAttribute"/>
    /// attribute on properties (field not suppored).
    /// </para>
    /// <para>
    /// The serializer uses LCG (lightweight code generation) to generate the
    /// methods that writes the attributes to avoid paying the price of
    /// Reflection on each vertex/edge. Since nothing is for free, the first
    /// time you will use the serializer *on a particular pair of types*, it
    /// will have to bake that method.
    /// </para>
    /// <para>
    /// Hyperedge, nodes, nested graphs not supported.
    /// </para>
    /// </remarks>
    public sealed class GraphMLDeserializer<TVertex, TEdge, TGraph>
        : SerializerBase<TVertex, TEdge>
        where TEdge : IEdge<TVertex>
        where TGraph : IMutableVertexAndEdgeSet<TVertex, TEdge>
    {
        #region Compiler
        delegate void ReadVertexAttributesDelegate(
            XmlReader reader,
            string namespaceUri,
            TVertex v);
        delegate void ReadEdgeAttributesDelegate(
            XmlReader reader,
            string namespaceUri,
            TEdge e);
        delegate void ReadGraphAttributesDelegate(
            XmlReader reader,
            string namespaceUri,
            TGraph g);

        static class ReadDelegateCompiler
        {
            public static readonly ReadVertexAttributesDelegate VertexAttributesReader;
            public static readonly ReadEdgeAttributesDelegate EdgeAttributesReader;
            public static readonly ReadGraphAttributesDelegate GraphAttributesReader;
            public static readonly Action<TVertex> SetVertexDefault;
            public static readonly Action<TEdge> SetEdgeDefault;
            public static readonly Action<TGraph> SetGraphDefault;

            static ReadDelegateCompiler()
            {
                VertexAttributesReader =
                    (ReadVertexAttributesDelegate)CreateReadDelegate(
                    typeof(ReadVertexAttributesDelegate),
                    typeof(TVertex)
                    //,"id"
                    );
                EdgeAttributesReader =
                    (ReadEdgeAttributesDelegate)CreateReadDelegate(
                    typeof(ReadEdgeAttributesDelegate),
                    typeof(TEdge)
                    //,"id", "source", "target"
                    );
                GraphAttributesReader =
                    (ReadGraphAttributesDelegate)CreateReadDelegate(
                    typeof(ReadGraphAttributesDelegate),
                    typeof(TGraph)
                    );
                SetVertexDefault =
                    (Action<TVertex>)CreateSetDefaultDelegate(
                        typeof(Action<TVertex>),
                        typeof(TVertex)
                    );
                SetEdgeDefault =
                    (Action<TEdge>)CreateSetDefaultDelegate(
                        typeof(Action<TEdge>),
                        typeof(TEdge)
                    );
                SetGraphDefault =
                    (Action<TGraph>)CreateSetDefaultDelegate(
                        typeof(Action<TGraph>),
                        typeof(TGraph)
                    );
            }

            static class Metadata
            {
                public static readonly MethodInfo ReadToFollowingMethod =
                    typeof(XmlReader).GetMethod(
                        "ReadToFollowing",
                        BindingFlags.Instance | BindingFlags.Public);
                        // bcz: , null, new Type[] { typeof(string), typeof(string) }, null);
                public static readonly MethodInfo GetAttributeMethod =
                    typeof(XmlReader).GetMethod(
                        "GetAttribute",
                        BindingFlags.Instance | BindingFlags.Public);
                        // bcz: , null, new Type[] { typeof(string) },  null);
                public static readonly PropertyInfo NameProperty =
                    typeof(XmlReader).GetProperty("Name");
                public static readonly PropertyInfo NamespaceUriProperty =
                    typeof(XmlReader).GetProperty("NamespaceUri");
                public static readonly MethodInfo StringEqualsMethod =
                    typeof(string).GetMethod(
                        "op_Equality",
                        BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                        // bcz: ,null,  new Type[] { typeof(string), typeof(string) }, null);
                public static readonly ConstructorInfo ArgumentExceptionCtor =
                    typeof(ArgumentException).GetConstructor(new Type[] { typeof(string) });

                private static readonly Dictionary<Type, MethodInfo> ReadContentMethods;

                static Metadata()
                {
                    ReadContentMethods = new Dictionary<Type, MethodInfo>();
                    ReadContentMethods.Add(typeof(bool), typeof(XmlReader).GetMethod("ReadElementContentAsBoolean", new Type[] { typeof(string), typeof(string) }));
                    ReadContentMethods.Add(typeof(int), typeof(XmlReader).GetMethod("ReadElementContentAsInt", new Type[] { typeof(string), typeof(string) }));
                    ReadContentMethods.Add(typeof(long), typeof(XmlReader).GetMethod("ReadElementContentAsLong", new Type[] { typeof(string), typeof(string) }));
                    ReadContentMethods.Add(typeof(float), typeof(XmlReader).GetMethod("ReadElementContentAsFloat", new Type[] { typeof(string), typeof(string) }));
                    ReadContentMethods.Add(typeof(double), typeof(XmlReader).GetMethod("ReadElementContentAsDouble", new Type[] { typeof(string), typeof(string) }));
                    ReadContentMethods.Add(typeof(string), typeof(XmlReader).GetMethod("ReadElementContentAsString", new Type[] { typeof(string), typeof(string) }));

                    var readerExtensions = typeof(XmlReaderExtensions);
                    ReadContentMethods.Add(typeof(Boolean[]), readerExtensions.GetMethod("ReadElementContentAsBooleanArray"));
                    ReadContentMethods.Add(typeof(Int32[]), readerExtensions.GetMethod("ReadElementContentAsInt32Array"));
                    ReadContentMethods.Add(typeof(Int64[]), readerExtensions.GetMethod("ReadElementContentAsInt64Array"));
                    ReadContentMethods.Add(typeof(Single[]), readerExtensions.GetMethod("ReadElementContentAsSingleArray"));
                    ReadContentMethods.Add(typeof(Double[]), readerExtensions.GetMethod("ReadElementContentAsDoubleArray"));
                    ReadContentMethods.Add(typeof(String[]), readerExtensions.GetMethod("ReadElementContentAsStringArray"));

                    ReadContentMethods.Add(typeof(IList<Boolean>), readerExtensions.GetMethod("ReadElementContentAsBooleanArray"));
                    ReadContentMethods.Add(typeof(IList<Int32>), readerExtensions.GetMethod("ReadElementContentAsInt32Array"));
                    ReadContentMethods.Add(typeof(IList<Int64>), readerExtensions.GetMethod("ReadElementContentAsInt64Array"));
                    ReadContentMethods.Add(typeof(IList<Single>), readerExtensions.GetMethod("ReadElementContentAsSingleArray"));
                    ReadContentMethods.Add(typeof(IList<Double>), readerExtensions.GetMethod("ReadElementContentAsDoubleArray"));
                    ReadContentMethods.Add(typeof(IList<String>), readerExtensions.GetMethod("ReadElementContentAsStringArray"));
                }

                public static bool TryGetReadContentMethod(Type type, out MethodInfo method)
                {
                    Contract.Requires(type != null);

                    bool result = ReadContentMethods.TryGetValue(type, out method);
                    Contract.Assert(!result || method != null, type.FullName);
                    return result;
                }
            }

            public static Delegate CreateSetDefaultDelegate(
                Type delegateType,
                Type elementType
                )
            {//bcz :
                throw new NotImplementedException();
                //Contract.Requires(delegateType != null);
                //Contract.Requires(elementType != null);

                //var method = new DynamicMethod(
                //    "Set" + elementType.Name + "Default",
                //    typeof(void),
                //    new Type[] { elementType },
                //    elementType.Module
                //    );
                //var gen = method.GetILGenerator();

                //// we need to create the swicth for each property
                //foreach (var kv in SerializationHelper.GetAttributeProperties(elementType))
                //{
                //    var property = kv.Property;
                //    var defaultValueAttribute = Attribute.GetCustomAttribute(property, typeof(DefaultValueAttribute))
                //        as DefaultValueAttribute;
                //    if (defaultValueAttribute == null)
                //        continue;
                //    var setMethod = property.GetSetMethod();
                //    if (setMethod == null)
                //        throw new InvalidOperationException("property " + property.Name + " is not settable");
                //    if (property.PropertyType.IsArray)
                //    {
                //        throw new NotImplementedException("Default values for array types are not implemented");
                //    }
                //    var value = defaultValueAttribute.Value;
                //    if (value != null &&
                //        value.GetType() != property.PropertyType)
                //        throw new InvalidOperationException("invalid default value type of property " + property.Name);
                //    gen.Emit(OpCodes.Ldarg_0);
                //    switch (Type.GetTypeCode(property.PropertyType))
                //    {
                //        case TypeCode.Int32:
                //            gen.Emit(OpCodes.Ldc_I4, (int)value);
                //            break;
                //        case TypeCode.Int64:
                //            gen.Emit(OpCodes.Ldc_I8, (long)value);
                //            break;
                //        case TypeCode.Single:
                //            gen.Emit(OpCodes.Ldc_R4, (float)value);
                //            break;
                //        case TypeCode.Double:
                //            gen.Emit(OpCodes.Ldc_R8, (double)value);
                //            break;
                //        case TypeCode.String:
                //            gen.Emit(OpCodes.Ldstr, (string)value);
                //            break;
                //        case TypeCode.Boolean:
                //            gen.Emit((bool)value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                //            break;
                //        default:
                //            throw new InvalidOperationException("unsupported type " + property.PropertyType);
                //    }
                //    gen.EmitCall(setMethod.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setMethod, null);
                //}
                //gen.Emit(OpCodes.Ret);

                ////let's bake the method
                //return method.CreateDelegate(delegateType);
            }

            public static Delegate CreateReadDelegate(
                Type delegateType,
                Type elementType
                //,params string[] ignoredAttributes
                )
            {//bcz :
                throw new NotImplementedException();
                //Contract.Requires(delegateType != null);
                //Contract.Requires(elementType != null);

                //var method = new DynamicMethod(
                //    "Read" + elementType.Name,
                //    typeof(void),
                //    //          reader, namespaceUri
                //    new Type[] { typeof(XmlReader), typeof(string), elementType },
                //    elementType.Module
                //    );
                //var gen = method.GetILGenerator();

                //var key = gen.DeclareLocal(typeof(string));

                //gen.Emit(OpCodes.Ldarg_0);
                //gen.Emit(OpCodes.Ldstr, "key");
                //gen.EmitCall(OpCodes.Callvirt, Metadata.GetAttributeMethod, null);
                //gen.Emit(OpCodes.Stloc_0);

                ////// if (String.Equals(key, "id")) continue;
                ////foreach (string ignoredAttribute in ignoredAttributes)
                ////{
                ////    gen.Emit(OpCodes.Ldloc_0);
                ////    gen.Emit(OpCodes.Ldstr, ignoredAttribute);
                ////    gen.EmitCall(OpCodes.Call, Metadata.StringEqualsMethod, null);
                ////    gen.Emit(OpCodes.Brtrue, doWhile);
                ////}

                //// we need to create the swicth for each property
                //var next = gen.DefineLabel();
                //var @return = gen.DefineLabel();
                //bool first = true;
                //foreach (var kv in SerializationHelper.GetAttributeProperties(elementType))
                //{
                //    var property = kv.Property;

                //    if (!first)
                //    {
                //        gen.MarkLabel(next);
                //        next = gen.DefineLabel();
                //    }
                //    first = false;

                //    // if (!key.Equals("foo"))
                //    gen.Emit(OpCodes.Ldloc_0);
                //    gen.Emit(OpCodes.Ldstr, kv.Name);
                //    gen.EmitCall(OpCodes.Call, Metadata.StringEqualsMethod, null);
                //    // if false jump to next
                //    gen.Emit(OpCodes.Brfalse, next);

                //    // do our stuff
                //    MethodInfo readMethod = null;
                //    if (!Metadata.TryGetReadContentMethod(property.PropertyType, out readMethod))
                //        throw new ArgumentException(String.Format("Property {0} has a non-supported type", property.Name));

                //    // do we have a set method ?
                //    var setMethod = property.GetSetMethod();
                //    if (setMethod == null)
                //        throw new ArgumentException(String.Format("Property {0}.{1} has not set method", property.DeclaringType, property.Name));
                //    // reader.ReadXXX
                //    gen.Emit(OpCodes.Ldarg_2); // element
                //    gen.Emit(OpCodes.Ldarg_0); // reader
                //    gen.Emit(OpCodes.Ldstr, "data");
                //    gen.Emit(OpCodes.Ldarg_1); // namespace uri
                //    // When writing scalar values we call member methods of XmlReader, while for array values
                //    // we call our own static methods.  These two types of methods seem to need different opcode.
                //    var opcode = readMethod.DeclaringType == typeof(XmlReaderExtensions) ? OpCodes.Call : OpCodes.Callvirt;
                //    gen.EmitCall(opcode, readMethod, null);
                //    gen.EmitCall(OpCodes.Callvirt, setMethod, null);

                //    // jump to do while
                //    gen.Emit(OpCodes.Br, @return);
                //}

                //// we don't know this parameter.. we throw
                //gen.MarkLabel(next);
                //gen.Emit(OpCodes.Ldloc_0);
                //gen.Emit(OpCodes.Newobj, Metadata.ArgumentExceptionCtor);
                //gen.Emit(OpCodes.Throw);

                //gen.MarkLabel(@return);
                //gen.Emit(OpCodes.Ret);

                ////let's bake the method
                //return method.CreateDelegate(delegateType);
            }
        }
        #endregion

        public void Deserialize(
            XmlReader reader,
            TGraph visitedGraph,
            IdentifiableVertexFactory<TVertex> vertexFactory,
            IdentifiableEdgeFactory<TVertex, TEdge> edgeFactory)
        {
            Contract.Requires(reader != null);
            Contract.Requires(visitedGraph != null);
            Contract.Requires(vertexFactory != null);
            Contract.Requires(edgeFactory != null);

            var worker = new ReaderWorker(
                this,
                reader,
                visitedGraph,
                vertexFactory,
                edgeFactory);
            worker.Deserialize();
        }

        class ReaderWorker
        {
            private readonly GraphMLDeserializer<TVertex, TEdge, TGraph> serializer;
            private readonly XmlReader reader;
            private readonly TGraph visitedGraph;
            private readonly IdentifiableVertexFactory<TVertex> vertexFactory;
            private readonly IdentifiableEdgeFactory<TVertex, TEdge> edgeFactory;
            private string graphMLNamespace = "";

            public ReaderWorker(
                GraphMLDeserializer<TVertex, TEdge, TGraph> serializer,
                XmlReader reader,
                TGraph visitedGraph,
                IdentifiableVertexFactory<TVertex> vertexFactory,
                IdentifiableEdgeFactory<TVertex, TEdge> edgeFactory
                )
            {
                Contract.Requires(serializer != null);
                Contract.Requires(reader != null);
                Contract.Requires(visitedGraph != null);
                Contract.Requires(vertexFactory != null);
                Contract.Requires(edgeFactory != null);

                this.serializer = serializer;
                this.reader = reader;
                this.visitedGraph = visitedGraph;
                this.vertexFactory = vertexFactory;
                this.edgeFactory = edgeFactory;
            }

            public GraphMLDeserializer<TVertex, TEdge, TGraph> Serializer
            {
                get { return this.serializer; }
            }

            public XmlReader Reader
            {
                get { return this.reader; }
            }

            public TGraph VisitedGraph
            {
                get { return this.visitedGraph; }
            }

            public void Deserialize()
            {
                this.ReadHeader();
                this.ReadGraphHeader();
                this.ReadElements();
            }

            private void ReadHeader()
            {
                // read flow until we hit the graphml node
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element &&
                        reader.Name == "graphml")
                    {
                        this.graphMLNamespace = reader.NamespaceURI;
                        return;
                    }
                }

                throw new ArgumentException("graphml node not found");
            }

            private void ReadGraphHeader()
            {
                if (!this.Reader.ReadToDescendant("graph", this.graphMLNamespace))
                    throw new ArgumentException("graph node not found");
            }

            private void ReadElements()
            {
                Contract.Requires(
                    this.Reader.Name == "graph" &&
                    this.Reader.NamespaceURI == this.graphMLNamespace,
                    "incorrect reader position");

                ReadDelegateCompiler.SetGraphDefault(this.VisitedGraph);

                var vertices = new Dictionary<string, TVertex>(StringComparer.Ordinal);

                // read vertices or edges
                var reader = this.Reader;
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element &&
                        reader.NamespaceURI == this.graphMLNamespace)
                    {
                        switch (reader.Name)
                        {
                            case "node":
                                this.ReadVertex(vertices);
                                break;
                            case "edge":
                                this.ReadEdge(vertices);
                                break;
                            case "data":
                                GraphMLDeserializer<TVertex, TEdge, TGraph>.ReadDelegateCompiler.GraphAttributesReader(this.Reader, this.graphMLNamespace, this.VisitedGraph);
                                break;
                            default:
                                throw new InvalidOperationException(String.Format("invalid reader position {0}:{1}", this.Reader.NamespaceURI, this.Reader.Name));
                        }
                    }
                }
            }

            private void ReadEdge(Dictionary<string, TVertex> vertices)
            {
                Contract.Requires(vertices != null);
                Contract.Assert(
                    this.Reader.NodeType == XmlNodeType.Element &&
                    this.Reader.Name == "edge" &&
                    this.Reader.NamespaceURI == this.graphMLNamespace);

                // get subtree
                using (var subReader = this.Reader.ReadSubtree())
                {
                    // read id
                    string id = ReadAttributeValue(this.Reader, "id");
                    string sourceid = ReadAttributeValue(this.Reader, "source");
                    TVertex source;
                    if (!vertices.TryGetValue(sourceid, out source))
                        throw new ArgumentException("Could not find vertex " + sourceid);
                    string targetid = ReadAttributeValue(this.Reader, "target");
                    TVertex target;
                    if (!vertices.TryGetValue(targetid, out target))
                        throw new ArgumentException("Could not find vertex " + targetid);

                    var edge = this.edgeFactory(source, target, id);
                    ReadDelegateCompiler.SetEdgeDefault(edge);

                    // read data
                    while (subReader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "data" &&
                            reader.NamespaceURI == this.graphMLNamespace)
                            ReadDelegateCompiler.EdgeAttributesReader(subReader, this.graphMLNamespace, edge);
                    }

                    this.VisitedGraph.AddEdge(edge);
                }
            }

            private void ReadVertex(Dictionary<string, TVertex> vertices)
            {
                Contract.Requires(vertices != null);
                Contract.Assert(
                    this.Reader.NodeType == XmlNodeType.Element &&
                    this.Reader.Name == "node" &&
                    this.Reader.NamespaceURI == this.graphMLNamespace);

                // get subtree
                using (var subReader = this.Reader.ReadSubtree())
                {
                    // read id
                    string id = ReadAttributeValue(this.Reader, "id");
                    // create new vertex
                    TVertex vertex = vertexFactory(id);
                    // apply defaults
                    ReadDelegateCompiler.SetVertexDefault(vertex);
                    // read data
                    while (subReader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "data" &&
                            reader.NamespaceURI == this.graphMLNamespace)
                            ReadDelegateCompiler.VertexAttributesReader(subReader, this.graphMLNamespace, vertex);
                    }
                    // add to graph
                    this.VisitedGraph.AddVertex(vertex);
                    vertices.Add(id, vertex);
                }
            }

            private static string ReadAttributeValue(XmlReader reader, string attributeName)
            {
                Contract.Requires(reader != null);
                Contract.Requires(attributeName != null);
                reader.MoveToAttribute(attributeName);
                if (!reader.ReadAttributeValue())
                    throw new ArgumentException("missing " + attributeName + " attribute");
                return reader.Value;
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// Tax Authority Model
    /// </summary>
    public class TaxAuthorityModel
    {
        /// <summary>
        /// The unique ID number of this tax authority.
        /// </summary>
        public Int32 id { get; set; }

        /// <summary>
        /// The friendly name of this tax authority.
        /// </summary>
        public String name { get; set; }

        /// <summary>
        /// The type of this tax authority.
        /// </summary>
        public Int32? taxAuthorityTypeId { get; set; }

        /// <summary>
        /// The unique ID number of the jurisdiction for this tax authority.
        /// </summary>
        public Int32? jurisdictionId { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
package com.composum.sling.core.security;

import com.composum.sling.core.AbstractSlingBean;
import com.composum.sling.core.BeanContext;
import com.composum.sling.core.Restricted;
import com.composum.sling.core.servlet.SetupServlet;
import com.composum.sling.core.util.RequestUtil;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Restricted(key = SetupServlet.SERVICE_KEY)
public class SetupConfiguration extends AbstractSlingBean {

    @Restricted(key = SetupServlet.SERVICE_KEY)
    public class ScriptBean extends AbstractSlingBean implements Comparable<ScriptBean> {

        private final ConfigurationSet.ConfigScript script;

        public ScriptBean(ConfigurationSet.ConfigScript script) {
            this.script = script;
            initialize(SetupConfiguration.this.context,
                    SetupConfiguration.this.context.getResolver().getResource(script.getPath()));
        }

        @NotNull
        public String getScriptUrl() {
            return getRequest().getContextPath() + "/bin/browser.html" + getScript().getScriptPath();
        }

        @NotNull
        public ConfigurationSet.ConfigScript getScript() {
            return script;
        }

        @Override
        public int compareTo(@NotNull ScriptBean other) {
            return script.compareTo(other.script);
        }
    }

    @Restricted(key = SetupServlet.SERVICE_KEY)
    public class ConfigBean extends AbstractSlingBean implements Comparable<ConfigBean> {

        private final ConfigurationSet.Configuration config;
        private final List<ScriptBean> scripts;

        public ConfigBean(ConfigurationSet.Configuration config, List<ScriptBean> scripts) {
            this.config = config;
            this.scripts = scripts;
            initialize(SetupConfiguration.this.context,
                    SetupConfiguration.this.context.getResolver().getResource(config.getPath()));
        }

        @NotNull
        public ConfigurationSet.Configuration getConfig() {
            return config;
        }

        @NotNull
        public List<ScriptBean> getScripts() {
            return scripts;
        }

        @Override
        public int compareTo(@NotNull ConfigBean other) {
            return config.compareTo(other.config);
        }
    }

    private transient Collection<String> categories;
    private transient List<ConfigBean> matchingSet;
    private transient ConfigurationSet configurationSet;

    public Collection<String> getCategories() {
        if (categories == null) {
            categories = getConfigurationSet().getScriptCategories().keySet();
        }
        return categories;
    }

    public List<ConfigBean> getMatchingSet() {
        if (matchingSet == null) {
            matchingSet = new ArrayList<>();
            String[] parameter = getRequest().getParameterValues("category");
            Collection<String> categories = parameter == null || parameter.length == 0 ? getCategories() : Arrays.asList(parameter);
            ConfigurationSet configurationSet = getConfigurationSet();
            for (ConfigurationSet.Configuration configuration : configurationSet.getConfigurations().values()) {
                List<ScriptBean> scripts = new ArrayList<>();
                for (ConfigurationSet.ConfigScript script : configuration.getScripts().values()) {
                    if (configuration.matches(categories) || script.matches(categories)) {
                        scripts.add(new ScriptBean(script));
                    }
                }
                if (scripts.size() > 0) {
                    Collections.sort(scripts);
                    matchingSet.add(new ConfigBean(scripts.get(0).getScript().getConfiguration(), scripts));
                }
            }
            Collections.sort(matchingSet);
        }
        return matchingSet;
    }

    @NotNull
    public ConfigurationSet getConfigurationSet() {
        if (configurationSet == null) {
            SlingHttpServletRequest request = getRequest();
            if (RequestUtil.checkSelector(request, "refresh")) {
                ConfigurationSet.clear(request);
            }
            configurationSet = ConfigurationSet.instance(request);
        }
        return configurationSet;
    }

    public SetupConfiguration(BeanContext context, Resource resource) {
        super(context, resource);
    }

    public SetupConfiguration(BeanContext context) {
        super(context);
    }

    public SetupConfiguration() {
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Hello World | Reid's Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.">
<meta name="keywords" content="java,spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Hello World">
<meta property="og:url" content="http://yoursite.com/2017/12/21/hello-world/index.html">
<meta property="og:site_name" content="Reid's Blog">
<meta property="og:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/2017/12/21/hello-world/bg.jpg">
<meta property="og:updated_time" content="2018-01-03T14:41:05.675Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hello World">
<meta name="twitter:description" content="Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.">
<meta name="twitter:image" content="http://yoursite.com/2017/12/21/hello-world/bg.jpg">

    <link rel="alternate" href="/atom.xml" title="Reid's Blog" type="application/atom+xml">

    <link rel="icon" href="/favicon.png">

    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="/css/style.css">

    Hello World

          Reid Zhou

        <time datetime="2017-12-21T13:34:06.584Z">2017/12/21</time>

java

spring

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1

$ hexo new "My New Post"

More info: Writing

Run server

1

$ hexo server

More info: Server

Generate static files

1

$ hexo generate

More info: Generating

Deploy to remote sites

1

$ hexo deploy

More info: Deployment

    Share

标签

java

spring

归档

一月 2018

十二月 2017

最新文章

            Hello World

            Hello World

      © 2018 Reid Zhou

      Powered by Hexo


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _defineProperty2 = require("babel-runtime/helpers/defineProperty");

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends2 = require("babel-runtime/helpers/extends");

var _extends3 = _interopRequireDefault(_extends2);

var _flowRight2 = require("lodash/flowRight");

var _flowRight3 = _interopRequireDefault(_flowRight2);

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _constants = require("./constants");

var _enhanceElement = require("./enhanceElement");

var _enhanceElement2 = _interopRequireDefault(_enhanceElement);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var controlledPropTypes = {
  // NOTICE!!!!!!
  //
  // Only expose those with getters & setters in the table as controlled props.
  //
  // [].map.call($0.querySelectorAll("tr>td>code", function(it){ return it.textContent; })
  //    .filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); })
  //
  // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Skeleton
}; /* global google */

var defaultUncontrolledPropTypes = (0, _enhanceElement.addDefaultPrefixToPropTypes)(controlledPropTypes);

var eventMap = {
  // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Skeleton
  // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; })
};

var publicMethodMap = {
  // Public APIs
  //
  // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Skeleton
  //
  // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; })
  //    .filter(function(it){ return it.match(/^get/) && !it.match(/Map$/); })
  // END - Public APIs
};

var controlledPropUpdaterMap = {};

function getInstanceFromComponent(component) {
  return component.state[_constants.SKELETON];
}

exports.default = (0, _flowRight3.default)(_react2.default.createClass, (0, _enhanceElement2.default)(getInstanceFromComponent, publicMethodMap, eventMap, controlledPropUpdaterMap))({
  displayName: "Skeleton",

  propTypes: (0, _extends3.default)({}, controlledPropTypes, defaultUncontrolledPropTypes),

  contextTypes: (0, _defineProperty3.default)({}, _constants.MAP, _react.PropTypes.object),

  getInitialState: function getInitialState() {
    // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Skeleton
    var skeleton = new google.maps.Skeleton((0, _extends3.default)({
      map: this.context[_constants.MAP]
    }, (0, _enhanceElement.collectUncontrolledAndControlledProps)(defaultUncontrolledPropTypes, controlledPropTypes, this.props)));
    return (0, _defineProperty3.default)({}, _constants.SKELETON, skeleton);
  },
  componentWillUnmount: function componentWillUnmount() {
    var skeleton = getInstanceFromComponent(this);
    if (skeleton) {
      skeleton.setMap(null);
    }
  },
  render: function render() {
    return false;
  }
});


text:
<!DOCTYPE html>

			<title>Ласкаво просимо <?php echo $_SESSION['users']['login']; ?></title>
   					 <meta charset=utf-8>
   					 <meta name="author" content="Arkan Denys">
					 <meta name="keywords" content="" />
					 <meta name="description" content="" />

	<link rel="stylesheet" href="http://<?php echo DOMAIN;?>/content/template/default/styles/style.css" type="text/css" media="all">

    <link rel='shortcut icon' href=http://<?php echo DOMAIN;?>/favicon.ico>

    <link rel="sitemap" type="application/xml" title="Sitemap" href="http://<?php echo DOMAIN;?>/sitemap.xml">
	<link rel="meta" type="application/rdf+xml" title="Dublin" href="http://<?php echo DOMAIN;?>/dublin.rdf">
	<link rel="search" type="application/opensearchdescription+xml" title="Website" href="http://<?php echo DOMAIN;?>/opensearch.xml" >

⇧

⇩

Ви увійшли як: <?php echo $_SESSION['users']['login']; ?>
 <a href="?logout=<?php echo $_SESSION['users']['login']?>">
<?php
if($_SESSION['users']['login'] == "admin"):?>

<?php endif; ?>