Esempio n. 1
0
    def mincut(self):
        """Returns a minimum cut of the graph. 
               Implements the Stoer/Wagner algorithm. The graph is interpreted 
               as a undirected graph, by adding the weights of co-edges. 
               Returns (value, edges, g1, g2) 
               where value is the weight of the cut, 
               edges is the set of cut edges, 
               g1 and g2 are disjoint sets of vertices.
            """
        # create graph of one-clusters
        graph = Graph()
        for edge in self.edges():
            (v1, v2) = edge
            g1 = ImmutableSet([v1])
            g2 = ImmutableSet([v2])
            graph.add_edge(g1, g2)

        # Stoer/Wagner algorithm
        mincutvalue = None
        mincut = ImmutableSet()
        while len(graph.vertices()) > 1:
            (phasecut, phasecutvalue) = self._mincutphase(graph)
            if mincutvalue == None or phasecutvalue < mincutvalue:
                mincutvalue = phasecutvalue
                mincut = phasecut

        # rewrite output
        g1 = mincut
        g2 = ImmutableSet(self.vertices()).difference(g1)
        edges = Set()
        for v in g1:
            for k in self.adjacent_vertices(v):
                if k in g2:
                    if self.has_edge(v, k):
                        edges.add((v, k))
                    if self.has_edge(k, v):
                        edges.add((k, v))
        for v in g2:
            for k in self.adjacent_vertices(v):
                if k in g1:
                    if self.has_edge(v, k):
                        edges.add((v, k))
                    if self.has_edge(k, v):
                        edges.add((k, v))

        return (mincutvalue, ImmutableSet(edges), g1, g2)
Esempio n. 2
0
 def __init__(self, vars):
     """Create a new cluster
     
        keyword args:
         vars - list of variables 
     """ 
     self.vars = ImmutableSet(vars)
     self.overconstrained = False
Esempio n. 3
0
    def degenerateFromSequence(self, sequence):
        """Returns least degenerate symbol corresponding to chars in sequence.

        First tries to look up in self.InverseDegenerates. Then disambiguates
        and tries to look up in self.InverseDegenerates. Then tries converting
        the case (tries uppercase before lowercase). Raises TypeError if 
        conversion fails.
        """
        symbols = ImmutableSet(sequence)
        # check if symbols are already known
        inv_degens = self.InverseDegenerates
        result = inv_degens.get(symbols, None)
        if result:
            return result
        # then, try converting the symbols
        degens = self.All
        converted = Set()
        for sym in symbols:
            for char in degens[sym]:
                converted.add(char)
        symbols = ImmutableSet(converted)
        result = inv_degens.get(symbols, None)
        if result:
            return result
        # then, try converting case
        symbols = ImmutableSet([s.upper() for s in symbols])
        result = inv_degens.get(symbols, None)
        if result:
            return result
        symbols = ImmutableSet([s.lower() for s in symbols])
        result = inv_degens.get(symbols, None)
        if result:
            return result
        # finally, try to find the minimal subset containing the symbols
        lengths = {}
        for i in inv_degens:
            if symbols.issubset(i):
                lengths[len(i)] = i
        if lengths:  # found at least some matches
            sorted = lengths.keys()
            sorted.sort()
            return inv_degens[lengths[sorted[0]]]

        # if we got here, nothing worked
        raise TypeError, "Cannot find degenerate char for symbols: %s" % symbols
Esempio n. 4
0
 def add(self, pattern, endpoint, **kw):
     if self._patterns.has_key(pattern):
         raise Exception('duplicate pattern', pattern)
     self._endpoints[(endpoint, ImmutableSet(
         make_variables(pattern)))] = make_url_for(pattern)
     self._patterns[pattern] = (re.compile(make_pattern(pattern)), endpoint,
                                kw)
     self._pattern_selector = re.compile(
         make_selector(self._patterns.iterkeys()))
Esempio n. 5
0
class Analex:
#############################################################################
##  Conjunto de palabras reservadas para comprobar si un identificador es PR
#############################################################################
 PR = ImmutableSet(["PROGRAMA", "VAR", "VECTOR","DE", "ENTERO", "REAL", "BOOLEANO", "PROC", "FUNCION", "INICIO", "FIN", "SI", "ENTONCES", "SINO", "MIENTRAS", "HACER", "LEE", "ESCRIBE", "Y", "O", "NO", "CIERTO","FALSO"])

 ############################################################################
 #
 #  Funcion: __init__
 #  Tarea:  Constructor de la clase
 #  Prametros:  flujo:  flujo de caracteres de entrada
 #  Devuelve: --
 #
 ############################################################################
 def __init__(self):
    #Debe completarse con  los campos de la clase que se consideren necesarios

    self.nlinea=1 #contador de lineas para identificar errores

 ############################################################################
 #
 #  Funcion: Analiza
 #  Tarea:  Identifica los diferentes componentes lexicos
 #  Prametros:  --
 #  Devuelve: Devuelve un componente lexico
 #
 ############################################################################
 def Analiza(self):
  
  ch=leerCaracter
  if ch==" ":
       # quitar todos los caracteres blancos 
       #buscar el siguiente componente lexico que sera devuelto )
  elif ch== "+":
   # debe crearse un objeto de la clasee OpAdd que sera devuelto
  elif  #asi con todos los simbolos y operadores del lenguaje
   return componentes.CorCi()
  elif ch == "{":
   #Saltar todos los caracteres del comentario 
   # y encontrar el siguiente componente lexico
  elif ch == "}":
   print "ERROR: Comentario no abierto" # tenemos un comentario no abierto
   return self.Analiza()
  elif ch==":":
    #Comprobar con el siguiente caracter si es una definicion de la declaracion o el operador de asignacion
  elif  
    #Completar los operadores y categorias lexicas que faltan
  elif ch es un caracter
    #leer entrada hasta que no sea un caracter valido de un identificador
    #devolver el ultimo caracter a la entrada
    # Comprobar si es un identificador o PR y devolver el objeto correspondiente
  elif ch es numero:
    #Leer todos los elementos que forman el numero 
    # devolver el ultimo caracter que ya no pertenece al numero a la entrada
    # Devolver un objeto de la categoria correspondiente 
  elif ch== "\n":
Esempio n. 6
0
def evalRiskCycleExit(cycNode, nodeSet):

    #    print "--- evalRiskCycleExit --- "
    #    print "cycNode = " + str(cycNode)
    #    print "nodeSet: " + str(nodeSet)

    cycleSet, entryNodes, paths = cycleData[cycNode]

    #    print "cycleSet = " + str(cycleSet)
    #    print "entryNodes = " + str(entryNodes)
    #    print "paths = " + str(paths)
    #    print "nodeSet = " + str(nodeSet)

    #    print "* PATHS *"
    #    for pk in paths:
    #        print str(pk) + ": " + str(paths[pk])
    #    print "* NODESET -- " + str(nodeSet) + " *"

    nodePaths = {}
    allPaths = []

    for n in nodeSet:
        nodePaths[n] = paths[abs(n)]
        allPaths.extend(paths[abs(n)])

#    print "relevant paths = " + str(allPaths)

# Find d-separating set over paths
    seenSet = Set([])
    dSet = Set([])
    for pp in allPaths:  # for all paths
        # Add nodes seen multiple times
        dSet.update(pp & seenSet)
        # Track all AND-nodes appearing in paths to m
        seenSet.update(pp.difference(orNodes))
    qSet = entryNodes & seenSet  # Get all entry nodes leading to m
    dSet.difference_update(qSet)  # Remove entry nodes from d-separating set
    # Remove d-separating nodes with probability 1
    for d in dSet.copy():
        if irv[d] == 1:
            dSet.remove(d)

#    print "d-separating set = " + str(dSet)
#    print "relevant entry nodes = " + str(qSet)

    qSumSet = getSummationValues(qSet.copy())
    #    print qSumSet

    answer = evalCycleNodeset(dSet.copy(), 1, Set([]), qSumSet, nodeSet,
                              nodePaths)
    phi[ImmutableSet(nodeSet)] = answer
    #    print "phi of " + str(nodeSet) + " is " + str(answer)

    #    print "\nQuitting..."
    #    sys.exit(0)
    return answer
Esempio n. 7
0
 def test_constructor2(self):
     inner = ImmutableSet([1])
     outer = Set([inner])
     element = list(outer).pop()
     outer.remove(inner)
     self.assertEqual(type(element), ImmutableSet)
     outer.add(inner)        # Rebuild set of sets with .add method
     outer.remove(inner)
     self.assertEqual(outer, Set())   # Verify that remove worked
     outer.discard(inner)    # Absence of KeyError indicates working fine
Esempio n. 8
0
 def getConfAsSet(self, inputConf):
     from sets import ImmutableSet
     confSet = set()
     bitShift = 0
     while bitShift <= self.inputSize:
         if 1 << bitShift in self.bitToElement and (1 << bitShift
                                                    & inputConf):
             confSet.add(self.bitToElement[1 << bitShift])
         bitShift += 1
     return ImmutableSet(confSet)
Esempio n. 9
0
 def __init__(self, variables):
     """Create a new balloon
     
        keyword args:
         vars - collection of PointVar's
     """
     if len(variables) < 3:
         raise StandardError, "balloon must have at least three variables"
     self.vars = ImmutableSet(variables)
     self.overconstrained = False
Esempio n. 10
0
 def __init__(self, vocab, nlp):
     self.vocab = vocab
     self.features = {}
     self.chunks = defaultdict(int)
     self.AcceptedPOSTags = ImmutableSet([
         nlp.vocab.strings['JJ'], nlp.vocab.strings['VB'],
         nlp.vocab.strings['RB'], nlp.vocab.strings['RBR'],
         nlp.vocab.strings['JJR'], nlp.vocab.strings['JJS'],
         nlp.vocab.strings['RBS'], nlp.vocab.strings['VBN'],
         nlp.vocab.strings['VBD'], nlp.vocab.strings['VBP']
     ])
Esempio n. 11
0
def generatePowerset(theSet):
    '''
    Generates powerset of a given set.
    Original code found at http://stackoverflow.com/questions/18826571/python-powerset-of-a-given-set-with-generators
    '''
    powerSet = set()
    from itertools import chain, combinations
    for subset in chain.from_iterable(
            combinations(theSet, r) for r in range(len(theSet) + 1)):
        powerSet.add(ImmutableSet(subset))
    return powerSet
Esempio n. 12
0
class SimplexBirth:  # An object that contains a set of landmarks that define a simplex, and a birth time measured in integer units. IMPORTANT: two SimplexBirths are considered equal iff they have the same landmark set, regardless of birth time.

    include_birth_time = False

    def __init__(self, landmark_list, birth_time, keep_sorted_list):
        if (keep_sorted_list):
            self.sll = sorted(landmark_list)
        else:
            self.sll = None
        self.landmark_set = ImmutableSet(landmark_list)
        self.birth_time = birth_time

    def __eq__(self, other):  # For hashing
        if SimplexBirth.include_birth_time:
            return self.birth_time == other.birth_time and self.landmark_set.__eq__(
                other.landmark_set)
        else:
            return self.landmark_set.__eq__(other.landmark_set)

    def __cmp__(self, other):  # For sorting
        if self.birth_time < other.birth_time:
            return -1
        elif self.birth_time > other.birth_time:
            return 1
        else:
            if len(self.landmark_set) < len(other.landmark_set):
                return -1
            elif len(self.landmark_set) > len(other.landmark_set):
                return 1
            else:
                if self.sll is None:
                    return 0
                for i in xrange(len(self.sll)):
                    if self.sll[i] < other.sll[i]:
                        return -1
                    elif self.sll[i] > other.sll[i]:
                        return 1
                return 0

    def __hash__(self):
        return self.landmark_set.__hash__()
Esempio n. 13
0
    def __init__(self, **kwargs):
        """
    Initializes the rate limiter with provided buckets.

    Parameters
    ----------
    **kwargs : Bucket
        Each named parameter's key is the bucket's name and the value is the
        Bucket itself.
    """
        self._buckets = kwargs
        self._exhausted = ImmutableSet()
Esempio n. 14
0
    def compatibleWithBase(self, base):
        messagenames = (ImmutableSet(self.messages.keys())
                        | ImmutableSet(base.messages.keys()))

        compatibility = Same()
        for name in messagenames:
            selfmessage = self.messages.get(name, None)
            basemessage = base.messages.get(name, None)

            if not selfmessage:
                c = Older("missing message %s, did you mean to deprecate?" %
                          name)
            elif not basemessage:
                c = Newer("added message %s" % name)
            else:
                c = selfmessage.compatibleWithBase(basemessage)
                c.prefix("in message %s: " % name)

            compatibility = compatibility.combine(c)

        return compatibility
Esempio n. 15
0
			def process_and_get_line_number(s):
				#nonlocal line_number
				if s in line_map:
					return line_map[s]
				else:
					dimension = len(s) - 1
					if dimension > dimension_cutoff:
						for subset in itertools.combinations(s, dimension_cutoff + 1): # Take all subsets of size dimension_cutoff + 1
							process_and_get_line_number(ImmutableSet(subset))
					elif dimension > 0:
						subsets_line_numbers = []
						for e in s:
							subsets_line_numbers.append(process_and_get_line_number(ImmutableSet(s - Set([e]))))
						output_file.write("\n" + str(dimension))
						for l in subsets_line_numbers:
							output_file.write(" " + str(l))
						line_map[s] = Context.line_number
						Context.line_number += 1
						return Context.line_number - 1
					else:
						raise Exception("Should have already added single point for base case: " + str(s))
Esempio n. 16
0
 def testOptionsAndHashing(self):
     r1 = Requirement.parse("Twisted[foo,bar]>=1.2")
     r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")
     r3 = Requirement.parse("Twisted[BAR,FOO]>=1.2.0")
     self.assertEqual(r1,r2)
     self.assertEqual(r1,r3)
     self.assertEqual(r1.extras, ("foo","bar"))
     self.assertEqual(r2.extras, ("bar","foo"))  # extras are normalized
     self.assertEqual(hash(r1), hash(r2))
     self.assertEqual(
         hash(r1), hash(("twisted", ((">=",parse_version("1.2")),),
                         ImmutableSet(["foo","bar"])))
     )
Esempio n. 17
0
        def __init__(self, verts, fid):
            self.verts = verts
            vertset = ImmutableSet(
                (self.verts[0].id, self.verts[1].id, self.verts[2].id))
            for vert in self.verts:
                vert.faces[self.getHashableSet()] = self

            self.id = fid

            self.edges = []
            self.RefactorArea()

            self.dead = False
Esempio n. 18
0
 def __init__(self, expr):
     self.expr = expr
     self.pos = 0
     self.nstates = 0
     self.expect = {}
     self.successor = {}
     self.alphabet = Set()
     self.initial, penultimate, epsilon = self.expression()
     final = self.newstate(None)
     for state in penultimate:
         self.successor[state].add(final)
     self.final = ImmutableSet([final])
     if epsilon:
         self.final = self.final | self.initial
    def _draw_links(self):
        todraw = set([])
        for a in self.nodes:
            for b in a.tsnodes:
                todraw.add(ImmutableSet([a, b.node]))

        for a, b in todraw:
            pa, pb = transform(a.pos), transform(b.pos)
            pygame.gfxdraw.line(self.screen, pa[0], pa[1], pb[0], pb[1],
                                self._COL_LINK)
            dist = self.font_dist.render('%.1fm' % vlen(vsub(b.pos, a.pos)),
                                         True, self._COL_TEXT)
            v = vsub(pb, pa)
            mid = vadd(pa, vscale(vnorm(v), vlen(v) / 2.0))
            self.screen.blit(dist, map(int, mid))
Esempio n. 20
0
 def __init__(self, nlp):
     self.counts = defaultdict(lambda: defaultdict(int))
     self.tags = {}
     self.Verbs = ImmutableSet([
         nlp.vocab.strings['VB'], nlp.vocab.strings['VBN'],
         nlp.vocab.strings['VBD'], nlp.vocab.strings['VBP']
     ])
     self.Adj = ImmutableSet([
         nlp.vocab.strings['JJ'], nlp.vocab.strings['JJR'],
         nlp.vocab.strings['JJS']
     ])
     self.Nouns = ImmutableSet([nlp.vocab.strings['NN']])
     self.Adverbs = ImmutableSet([
         nlp.vocab.strings['RB'], nlp.vocab.strings['RBR'],
         nlp.vocab.strings['RBS']
     ])
     self.AcceptedPOSTags = ImmutableSet([
         nlp.vocab.strings['JJ'], nlp.vocab.strings['NN'],
         nlp.vocab.strings['VB'], nlp.vocab.strings['RB'],
         nlp.vocab.strings['RBR'], nlp.vocab.strings['JJR'],
         nlp.vocab.strings['JJS'], nlp.vocab.strings['RBS'],
         nlp.vocab.strings['VBN'], nlp.vocab.strings['VBD'],
         nlp.vocab.strings['VBP']
     ])
Esempio n. 21
0
def computeAllMHSHelper(setDescription, constraints, misSet, currPath, paths):
    #paths holds all previously visited paths of the hitting set tree
    #currPath is the current. If any previous path is a subset of this one
    #the we have already computed all MIS that would be found in the current path's subtree.
    for path in paths:
        if path in currPath:
            return

    #if the current set of constraints is consistent
    #Then there cannot be anymore MIS in its subtree
    #so we add the current path to the set of paths enumerated and return.
    if setDescription.isConsistent(constraints):
        paths.add(currPath)
        return
    #In order to avoid redundant MIS computations
    #We check the current set of MIS misSet
    #If it is possible to find any of the already computed MIS in the current iteration
    #(it does not share an element in the currPath) then we just use that MIS
    #and continue down the tree
    currentMIS = ImmutableSet()
    for mis in misSet:
        if len(mis.intersection(currPath)) == 0:
            currentMIS = mis
            break
    #If not MIS matches the previous description, we will need to
    #compute a new one.
    if currentMIS == ImmutableSet():
        currentMIS = computeSingleMIS(setDescription, constraints)
        misSet.add(currentMIS)

    #iterate through the children of the current path
    for element in currentMIS:
        childPath = currPath.union(set(element))
        computeAllMHSHelper(setDescription,
                            constraints - ImmutableSet(element), misSet,
                            childPath, paths)
Esempio n. 22
0
        def __init__(self, v1, v2):
            self.v1 = v1
            self.v2 = v2
            vertset = ImmutableSet((self.v1.id, self.v2.id))

            self.v1.edges[vertset] = self
            self.v2.edges[vertset] = self

            # Get faces common for both v1 and v2
            self.faces = []
            self.collapsed_faces = {}

            self.RefactorLength()

            self.dead = False
Esempio n. 23
0
def computeAllMIS(setDescription, constraints):
    '''
    Taken from 'A Hybrid Diagnosis Approach Combining Black-Box
    and White-Box Reasoning'. This attempts to find all Minimal Inconsistent Subset of Constraints.
    @param setDescription- A set of rules linking several items together. 
    Think of this as boolean equation in Conjunctive Normal Form.
    @param Constraints- a set of items we would like to include.
    Think of this as an assignment for the previous boolean equation.
    '''
    misSet = set()
    currPath = ImmutableSet()
    paths = set()
    LogarithmicExtraction.newRun = True
    computeAllMHSHelper(setDescription, constraints, misSet, currPath, paths)
    return misSet
def computeSingleMIS(setDescription, constraints):
    '''
    Taken from 'A Hybrid Diagnosis Approach Combining Black-Box
    and White-Box Reasoning'. This attempts to find the Minimal Subset of Constraints
    that will be inconsistent for the given Set Description.
    @param setDescription- A set of rules linking several items together. 
    Think of this as boolean equation in Conjunctive Normal Form.
    @param Constraints- a set of items we would like to include.
    Think of this as a value assignment for the previous boolean equation.
    '''
    potentialMIS = computeSingleMISHelper(setDescription, ImmutableSet(), constraints)
    
    #The Euler Implementation does not correctly compute the MIS for a set description
    #where everything is always inconsistent (an empty set is inconsistent)
    #This makes sense, but this library also considers this set description,
    #so we must check the empty configuration here.
    global newRun
    if newRun == True and len(potentialMIS) == 1 \
        and not setDescription.isConsistent(ImmutableSet()):
        newRun = False
        return ImmutableSet()
    else:
        newRun = False
        return potentialMIS
Esempio n. 25
0
	def filter_and_build():
		g2 = None
		if reentry_filter:
			g2 = g.copy()
			to_remove = Set()
			for l1 in xrange(number_of_vertices):
				l2 = l1 + 2
				while l2 < number_of_vertices and g2.has_edge(l1, l2):
					to_remove.add(ImmutableSet([l1, l2]))
					l2 += 1
			for edge in to_remove:
				g2.remove_edge(*tuple(edge)) # May cause weird things to happen because removing edges doesn't remove them from the filtration.
		else:
			g2 = g
		for clique in nx.find_cliques(g2):
			filtration.add(SimplexBirth(clique, q, sort_output))
def solution1(arr, S):
    """
    Same but using sets.
    >>> solution1([3, 7 , 1, 8, -3, 0, 2, 7, -4, -2], -8)
    [2, 4, 8, 9]
    """
    pairs = defaultdict(list)  # sum -> list of pairs of index
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            pairs[arr[i] + arr[j]].append(ImmutableSet([i, j]))
    for k in pairs.keys():
        if not pairs.get(S - k):
            continue
        for t1, t2 in zip(pairs[k], pairs[S - k]):
            if len(t1.union(t2)) == 4:
                return sorted(list(t1.union(t2)))
Esempio n. 27
0
        def __init__(self, v1, v2):
            self.v1 = v1
            self.v2 = v2
            vertset = ImmutableSet((self.v1.id, self.v2.id))
            self.v1.edges[vertset] = self
            self.v2.edges[vertset] = self

            # Get faces common for both v1 and v2
            self.faces = []
            #for key in filter(self.v1.faces.__contains__, self.v2.faces):
            #	face = self.v1.faces[key]
            #self.faces[ImmutableSet((face.verts[0].id, face.verts[1].id, face.verts[2].id))] = face
            #	self.faces.append(face)

            self.collapsed_faces = {}

            self.RefactorLength()

            self.dead = False
Esempio n. 28
0
 def base(self):
     """Parse a subexpression that can be starred: single letter or group."""
     if self.pos == len(self.expr) or self.expr[self.pos] == ')':
         return self.epsilon()
     if self.expr[self.pos] == '(':
         self.pos += 1
         ret = self.expression()
         if self.pos == len(self.expr) or self.expr[self.pos] != ')':
             raise LanguageError("Close paren expected at char " +
                                 str(self.pos))
         self.pos += 1
         return ret
     if self.expr[self.pos] == '\\':
         self.pos += 1
         if self.pos == len(self.expr):
             raise RegExpError("Character expected after backslash")
     self.alphabet.add(self.expr[self.pos])
     state = self.newstate(self.expr[self.pos])
     self.pos += 1
     state = ImmutableSet([state])
     return state, state, False
def computeSingleMISHelper(setDescription, currentConstraints, constraintsToAdd):
    if len(constraintsToAdd) <= 1:
        return constraintsToAdd
    
    constraintsToAddLeft = ImmutableSet(random.sample(constraintsToAdd, len(constraintsToAdd)/2))
    constraintsToAddRight = constraintsToAdd - constraintsToAddLeft
    
    #If either subset unioned with the current constraints is inconsistent
    #then an MIS exists in the subset of them
    if not setDescription.isConsistent( currentConstraints.union(constraintsToAddLeft) ):
        return computeSingleMISHelper(setDescription, currentConstraints, constraintsToAddLeft)
    if not setDescription.isConsistent( currentConstraints.union(constraintsToAddRight)):
        return computeSingleMISHelper(setDescription, currentConstraints, constraintsToAddRight)
    
    #If both subsets unioned with the current constraints is consistent
    #Then an MIS of the current constraints must use elements from both subsets. 
    #This will find such an MIS
    potentialSolutionLeft = computeSingleMISHelper(setDescription, 
                                                   currentConstraints.union(constraintsToAddRight), constraintsToAddLeft)
    potentialSolutionRight = computeSingleMISHelper(setDescription,
                                                    currentConstraints.union(potentialSolutionLeft), constraintsToAddRight)
    return potentialSolutionLeft.union(potentialSolutionRight)    
Esempio n. 30
0
 def __new__(cls, para_types, res_type, strict=False):
     if not strict and not __debug__:
         # decorator: identity, does nothing
         return lambda func: func
     # create watchdog instance:
     watchdog = object.__new__(cls)
     # assign function signature to instance & add to cache if needed:
     signature = para_types, res_type
     if signature not in Watchdog.signatures:
         # unknown signature: check and insert
         if not isinstance(para_types, tuple):
             raise ValueError('Parameter #1 must be a tuple')
         allow_types = [TypeType, ClassType]
         for entry in para_types:
             if type(entry) not in allow_types:
                 msg = 'Parameter #1 must contain only Types and/or Classes'
                 raise ValueError(msg)
         if type(res_type) not in allow_types:
             raise ValueError('Parameter #2 must be a Type or Class')
         Watchdog.signatures |= ImmutableSet([signature])
     watchdog.signature = signature
     # returns the decorator(not the watchdog class-instance):
     return watchdog.check
Esempio n. 31
0
 def __hash__(self):
     return frozenset.__hash__(self)
Esempio n. 32
0
 def __new__(cls, iterable=None):
     self = ImmutableSet.__new__(cls, iterable)
     ImmutableSet.__init__(self, iterable)
     return self
Esempio n. 33
0
class Analex:
    #############################################################################
    # Conjunto de palabras reservadas para comprobar si un identificador es PR
    #############################################################################
    PR = ImmutableSet(["PROGRAMA", "VAR", "VECTOR", "DE", "ENTERO", "REAL", "BOOLEANO", "PROC", "FUNCION", "INICIO",
                       "FIN", "SI", "ENTONCES", "SINO", "MIENTRAS", "HACER", "LEE", "ESCRIBE", "Y", "O", "NO", "CIERTO", "FALSO"])

    ############################################################################
    #
    #  Funcion: __init__
    #  Tarea:  Constructor de la clase
    #  Prametros:  flujo:  flujo de caracteres de entrada
    #  Devuelve: --
    #
    ############################################################################
    def __init__(self, flujo):
        # Debe completarse con  los campos de la clase que se consideren necesarios

        self.nlinea = 1  # contador de lineas para identificar errores
        self.flujo = flujo
        self.eof = False
    ############################################################################
    #
    #  Funcion: Analiza
    #  Tarea:  Identifica los diferentes componentes lexicos
    #  Prametros:  --
    #  Devuelve: Devuelve un componente lexico
    #
    ############################################################################

    def Analiza(self):

        ch = self.flujo.siguiente()

        if ch == " ":
            # quitar todos los caracteres blancos
            return self.Analiza()
            # buscar el siguiente componente lexico que sera devuelto )
        elif ch == "+":
            return componentes.OpAdd("SimSum", self.nlinea)

        elif ch == "-":
            return componentes.OpAdd("SimRest", self.nlinea)
         # debe crearse un objeto de la clasee OpAdd que sera devuelto

        elif ch == "*":
            return componentes.OpMult("SimMult", self.nlinea)

        elif ch == "/":
            return componentes.OpMult("SimDiv", self.nlinea)

        elif ch == "[":
            return componentes.CorAp()

        elif ch == "]":  # asi con todos los simbolos y operadores del lenguaje
            return componentes.CorCi()

        elif ch == "{":
            # Saltar todos los caracteres del comentario
            while(ch != "}"):
                ch = self.flujo.siguiente()

            # Comprobamos que hemos cerrado el comentario
            if ch != "}":
                print "ERROR: Comentario no cerrado"  # tenemos un comentario no cerrado

            # y encontrar el siguiente componente lexico
            return self.Analiza()

        elif ch == "}":
            print "ERROR: Comentario no abierto"  # tenemos un comentario no abierto
            return self.Analiza()

        elif ch == ":":
            # Comprobar con el siguiente caracter si es una definicion de la declaracion o el operador de asignacion
            ch = self.flujo.siguiente()

            if ch == '=':
                return componentes.OpAsigna()

            else:
                self.flujo.devuelve(ch)
                return componentes.DosPtos()

        elif ch == '(':
            return componentes.ParentAp()

        elif ch == ')':
            return componentes.ParentCi()

        elif ch == '.':
            return componentes.Punto()

        elif ch == ',':
            return componentes.Coma()

        elif ch == ';':
            return componentes.PtoComa()

        elif ch == ':':
            return componentes.DosPtos()

        elif ch == "=":
            return componentes.OpRel("SimIgual", self.nlinea)

        elif ch == "<":
            ch = self.flujo.siguiente()

            if ch == ">":
                return componentes.OpRel("SimDist", self.nlinea)
            elif ch == "=":
                return componentes.OpRel("SimMenIgual", self.nlinea)
            else:
                self.flujo.devuelve(ch)
                return componentes.OpRel("SimMenor", self.nlinea)

        elif ch == ">":
            ch = self.flujo.siguiente()
            if ch == "=":
                return componentes.OpRel("SimMayIgual", self.nlinea)
            else:
                self.flujo.devuelve(ch)
                return componentes.OpRel("SimMayor", self.nlinea)

        elif ch.isalpha():
            # leer entrada hasta que no sea un caracter valido de un identificador
            cadena = "" + ch

            ch = self.flujo.siguiente()

            while ch.isalnum():
                cadena = cadena + ch
                ch = self.flujo.siguiente()

            # devolver el ultimo caracter a la entrada
            self.flujo.devuelve(ch)

            # Comprobar si es un identificador o PR y devolver el objeto correspondiente
            if(cadena in Analex.PR):
                return componentes.PR(cadena, self.nlinea)
            else:
                return componentes.Identif(cadena, self.nlinea)

        elif ch.isdigit():
            # Leer todos los elementos que forman el numero
            numero = "" + ch
            puntoDetectado = 0
            ch = self.flujo.siguiente()

            while ch.isdigit():
                numero = numero + ch
                ch = self.flujo.siguiente()

            # Es un entero
            if ch != ".":
                self.flujo.devuelve(ch)
                return componentes.Numero(numero, self.nlinea, "ENTERO")

            # Puede ser un real
            else:
                real = numero + ch
                ch = self.flujo.siguiente()

                #Guardamos el numero de digitos decimales
                digitosDecimales = 0

                # Comprobamos que lo siguiente del punto sea un digito
                while ch.isdigit():
                    digitosDecimales += 1
                    real = real + ch
                    ch = self.flujo.siguiente()

                # devolver el ultimo caracter que ya no pertenece al numero a la entrada
                self.flujo.devuelve(ch)

                # No es un valor de tipo de real. Devolvemos el tipo entero
                if digitosDecimales == 0:
                    self.flujo.devuelve(ch) #Devolvemos el caracter decimal al flujo de entrada
                    return componentes.Numero(numero, self.nlinea, "ENTERO")

                # Es un valor real. Devolvemos el tipo real
                else:
                    return componentes.Numero(real, self.nlinea, "REAL")

        elif ch == "\n":
            # incrementa el numero de linea ya que acabamos de saltar a otra
            self.nlinea += 1
            # devolver el siguiente componente encontrado
            return self.Analiza()

        elif ch != "":
            return self.Analiza()
        
        else:
            if self.eof:
                return
            else:
                self.eof = True
                return componentes.EOF()

    def siguiente(self):
        return self.Analiza()
Esempio n. 34
0
 def __eq__(self, other):
     if isinstance(other, frozenset):
         return frozenset.__eq__(self, other)
     else:
         return other in self