Пример #1
0
    def __init__(self, graph=None):
        """
        if graph is not none make a copy of the topological structure of graph
        (i.e. don't use the same id)

        :param graph: the graph to copy, default=None
        :type graph: Graph
        """
        self._vertices = {}
        self._edges = {}
        self._vid_generator = IdGenerator()
        self._eid_generator = IdGenerator()
        if graph is not None:
            dummy = self.extend(graph)
Пример #2
0
    def __init__(self, graph=None):
        """
        if graph is not none make a copy of the topological structure of graph
        (i.e. don't use the same id)

        :param graph: the graph to copy, default=None
        :type graph: Graph
        """
        self._vertices = {}
        self._edges = {}
        self._vid_generator = IdGenerator()
        self._eid_generator = IdGenerator()
        if graph is not None:
            dummy = self.extend(graph)
Пример #3
0
def main():
    # load machine/service id.
    service_id = os.environ.get("SERVICE_ID", 1)
    url_id_generator = IdGenerator(service_id)
    user_id_generator = IdGenerator(service_id)
    snowflake_service = SnowFlakeService(url_id_generator, user_id_generator)

    server = grpc.server(thread_pool=futures.ThreadPoolExecutor(
        max_workers=10))
    snowflake_pb2_grpc.add_SnowFlakeServicer_to_server(snowflake_service,
                                                       server)

    server.add_insecure_port("[::]:%s" %
                             os.environ.get("SNOWFLAKE_SERVICE_PORT", 5000))
    server.start()

    try:
        while True:
            time.sleep(86400)
    except KeyboardInterrupt:
        server.stop(0)
class ClientManager:
    """
    Stores information about clients connected to server.
    """

    def __init__(self, time_func=time):
        self._clients = [] # list of clients
        self._generator = IdGenerator()
        self._time_func = time_func

    def register(self, client_name):
        """
        :param client_name: Name of player who wishes to join game.
        :return: (result, id) pair where result is boolean equal to True
				if player has been accepted.
        """
        if any(c.get_name() == client_name for c in self._clients):
            return False, 'already connected'
        client = Client(self._generator.generate(), client_name, self._time_func)
        self._clients.append(client)
        return True, client.get_id()

    def get_client(self, client_id):
        """
        Returns reference to client (if exists) and refreshes him.
        :param client_id: Id of client.
        :return: Reference to client object or None.
        """
        try:
            self._check_for_disconnected_clients()
            client = next(c for c in self._clients if c.get_id() == client_id)
            return client
        except StopIteration:
            return None

    def _check_for_disconnected_clients(self):
        self._clients = [c for c in self._clients if c.get_time_since_access() < TIMEOUT]

    def get_clients_list(self):
        """Returns clients list"""
        self._check_for_disconnected_clients()
        return [client.get_name() for client in self._clients]

    def refresh_client(self, client_id):
        """
        Updates last client activity time thus defferring his disconnection.
        :param client_id: Id of client.
        """
        client = self.get_client(client_id)
        if client is not None:
            client.refresh()
            return True
        return False
Пример #5
0
class TestIdGenerator(unittest.TestCase):
    def setUp(self):
        self.client = Redis()
        self.client.flushdb()

        self.id_generator = IdGenerator(self.client, 'user::id')

    def test_produce_works(self):
        self.assertEqual(self.id_generator.produce(), 1)
        self.assertEqual(self.id_generator.produce(), 2)

    def test_reserve_return_true_when_produce_not_executed(self):
        self.assertTrue(self.id_generator.reserve(100))

        self.assertEqual(self.id_generator.produce(), 101)

    def test_reserve_return_false_when_produce_already_executed(self):
        self.id_generator.produce()

        self.assertFalse(self.id_generator.reserve(100))
Пример #6
0
class Graph(IGraph, IVertexListGraph, IEdgeListGraph, IMutableVertexGraph,
            IMutableEdgeGraph, IExtendGraph):
    """Directed graph with multiple links in this implementation:
        - vertices are tuple of edge_in, edge_out
        - edges are tuple of source,target

    """
    def __init__(self, graph=None):
        """
        if graph is not none make a copy of the topological structure of graph
        (i.e. don't use the same id)

        :param graph: the graph to copy, default=None
        :type graph: Graph
        """
        self._vertices = {}
        self._edges = {}
        self._vid_generator = IdGenerator()
        self._eid_generator = IdGenerator()
        if graph is not None:
            dummy = self.extend(graph)

    # ##########################################################
    #
    # Graph concept
    #
    # ##########################################################

    def source(self, eid):
        try:
            return self._edges[eid][0]
        except KeyError:
            raise InvalidEdge(eid)

    source.__doc__ = IGraph.source.__doc__

    def target(self, eid):
        try:
            return self._edges[eid][1]
        except KeyError:
            raise InvalidEdge(eid)

    target.__doc__ = IGraph.target.__doc__

    def __contains__(self, vid):
        return self.has_vertex(vid)

    __contains__.__doc__ = IGraph.__contains__.__doc__

    def has_vertex(self, vid):
        return self._vertices.has_key(vid)

    has_vertex.__doc__ = IGraph.has_vertex.__doc__

    def has_edge(self, eid):
        return self._edges.has_key(eid)

    has_edge.__doc__ = IGraph.has_edge.__doc__

    def is_valid(self):
        return True

    is_valid.__doc__ = IGraph.is_valid.__doc__

    # ##########################################################
    #
    # Vertex List Graph Concept
    #
    # ##########################################################

    def vertices(self):
        return iter(self._vertices)

    vertices.__doc__ = IVertexListGraph.vertices.__doc__

    def __iter__(self):
        return iter(self._vertices)

    __iter__.__doc__ = IVertexListGraph.__iter__.__doc__

    def nb_vertices(self):
        return len(self._vertices)

    nb_vertices.__doc__ = IVertexListGraph.nb_vertices.__doc__

    def __len__(self):
        return self.nb_vertices()

    __len__.__doc__ = IVertexListGraph.__len__.__doc__

    def in_neighbors(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        neighbors_list = [self.source(eid) for eid in self._vertices[vid][0]]
        return iter(set(neighbors_list))

    in_neighbors.__doc__ = IVertexListGraph.in_neighbors.__doc__

    def out_neighbors(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        neighbors_list = [self.target(eid) for eid in self._vertices[vid][1]]
        return iter(set(neighbors_list))

    out_neighbors.__doc__ = IVertexListGraph.out_neighbors.__doc__

    def neighbors(self, vid):
        neighbors_list = list(self.in_neighbors(vid))
        neighbors_list.extend(self.out_neighbors(vid))
        return iter(set(neighbors_list))

    neighbors.__doc__ = IVertexListGraph.neighbors.__doc__

    def nb_in_neighbors(self, vid):
        neighbors_set = list(self.in_neighbors(vid))
        return len(neighbors_set)

    nb_in_neighbors.__doc__ = IVertexListGraph.nb_in_neighbors.__doc__

    def nb_out_neighbors(self, vid):
        neighbors_set = list(self.out_neighbors(vid))
        return len(neighbors_set)

    nb_out_neighbors.__doc__ = IVertexListGraph.nb_out_neighbors.__doc__

    def nb_neighbors(self, vid):
        neighbors_set = list(self.neighbors(vid))
        return len(neighbors_set)

    nb_neighbors.__doc__ = IVertexListGraph.nb_neighbors.__doc__

    # ##########################################################
    #
    # Edge List Graph Concept
    #
    # ##########################################################

    def _iteredges(self, vid):
        """
        internal function that perform 'edges' with vid not None
        """
        link_in, link_out = self._vertices[vid]
        for eid in link_in:
            yield eid
        for eid in link_out:
            yield eid

    def edges(self, vid=None):
        if vid is None:
            return iter(self._edges)
        if vid not in self:
            raise InvalidVertex(vid)
        return self._iteredges(vid)

    edges.__doc__ = IEdgeListGraph.edges.__doc__

    def nb_edges(self, vid=None):
        if vid is None:
            return len(self._edges)
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][0]) + len(self._vertices[vid][1])

    nb_edges.__doc__ = IEdgeListGraph.nb_edges.__doc__

    def in_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        for eid in self._vertices[vid][0]:
            yield eid

    in_edges.__doc__ = IEdgeListGraph.in_edges.__doc__

    def out_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        for eid in self._vertices[vid][1]:
            yield eid

    out_edges.__doc__ = IEdgeListGraph.out_edges.__doc__

    def nb_in_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][0])

    nb_in_edges.__doc__ = IEdgeListGraph.nb_in_edges.__doc__

    def nb_out_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][1])

    nb_out_edges.__doc__ = IEdgeListGraph.nb_out_edges.__doc__

    # ##########################################################
    #
    # Mutable Vertex Graph concept
    #
    # ##########################################################

    def add_vertex(self, vid=None):
        vid = self._vid_generator.get_id(vid)
        self._vertices[vid] = (set(), set())
        return vid

    add_vertex.__doc__ = IMutableVertexGraph.add_vertex.__doc__

    def remove_vertex(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        link_in, link_out = self._vertices[vid]
        for edge in list(link_in):
            self.remove_edge(edge)
        for edge in list(link_out):
            self.remove_edge(edge)
        del self._vertices[vid]
        self._vid_generator.release_id(vid)

    remove_vertex.__doc__ = IMutableVertexGraph.remove_vertex.__doc__

    def clear(self):
        self._vertices.clear()
        self._edges.clear()
        self._vid_generator = IdGenerator()
        self._eid_generator = IdGenerator()

    clear.__doc__ = IMutableVertexGraph.clear.__doc__

    # ##########################################################
    #
    # Mutable Edge Graph concept
    #
    # ##########################################################

    def add_edge(self, edge=(None, None), eid=None):
        vs, vt = edge
        if vs not in self:
            raise InvalidVertex(vs)
        if vt not in self:
            raise InvalidVertex(vt)
        eid = self._eid_generator.get_id(eid)
        self._edges[eid] = (vs, vt)
        self._vertices[vs][1].add(eid)
        self._vertices[vt][0].add(eid)
        return eid

    add_edge.__doc__ = IMutableEdgeGraph.add_edge.__doc__

    def remove_edge(self, eid):
        if not self.has_edge(eid):
            raise InvalidEdge(eid)
        vs, vt = self._edges[eid]
        self._vertices[vs][1].remove(eid)
        self._vertices[vt][0].remove(eid)
        del self._edges[eid]
        self._eid_generator.release_id(eid)

    remove_edge.__doc__ = IMutableEdgeGraph.remove_edge.__doc__

    def clear_edges(self):
        self._edges.clear()
        self._eid_generator = IdGenerator()

    clear_edges.__doc__ = IMutableEdgeGraph.clear_edges.__doc__

    # ##########################################################
    #
    # Extend Graph concept
    #
    # ##########################################################

    def extend(self, graph):
        #vertex adding
        trans_vid = {}
        for vid in graph.vertices():
            trans_vid[vid] = self.add_vertex()

        #edge adding
        trans_eid = {}
        for eid in graph.edges():
            sid = trans_vid[graph.source(eid)]
            tid = trans_vid[graph.target(eid)]
            trans_eid[eid] = self.add_edge(edge=(sid, tid))

        return trans_vid, trans_eid

    extend.__doc__ = IExtendGraph.extend.__doc__
Пример #7
0
 def clear_edges(self):
     self._edges.clear()
     self._eid_generator = IdGenerator()
Пример #8
0
 def clear(self):
     self._vertices.clear()
     self._edges.clear()
     self._vid_generator = IdGenerator()
     self._eid_generator = IdGenerator()
 def __init__(self, time_func=time):
     self._clients = [] # list of clients
     self._generator = IdGenerator()
     self._time_func = time_func
Пример #10
0
 def clear(self):
     self._vertices.clear()
     self._edges.clear()
     self._vid_generator=IdGenerator()
     self._eid_generator=IdGenerator()
Пример #11
0
class System:
    order_id_generator = IdGenerator()

    def __init__(self):
        self._orders = []
        self._staff = []

        # This will be the list of sides available to the customer
        self._sides = [
            SideFood("Nuggets - 3 pieces"),
            SideFood("Nuggets - 6 pieces"),
            SideFood("Nuggets - 24 deal"),
            SideFood("Fries Small"),
            SideFood("Fries Medium"),
            SideFood("Fries Large"),
            SideFood("Coke Small"),
            SideFood("Coke Medium")
        ]

        # This will be the list of toppings available to the customer
        self._toppings = [
            Topping("Tomato"),
            Topping("Cheddar Cheese"),
            Topping("Swiss Cheese"),
            Topping("Lettuce"),
            Topping("Tomato Sauce")
        ]

        self._staff.append(StaffUser("jlam", "Jonathan", "123"))
        self._staff.append(StaffUser("mel", "Melody", "abc"))
        self._staff.append(StaffUser("lust", "Lucius", "qwerty"))

        self._stock = {
            # Mains
            "Wrap": 20,
            "Sesame Bun": 10,
            "Muffin Bun": 10,
            "Chicken Patty": 4,
            "Vegetarian Patty": 5,
            "Beef Patty": 4,

            # Toppings
            "Tomato": 14,
            "Cheddar Cheese": 14,
            "Swiss Cheese": 14,
            "Lettuce": 14,
            "Tomato Sauce": 14,

            # Sides
            "Nuggets": 25,
            "Fries": 200,
            "Coke Small": 5,
            "Coke Medium": 3
        }

    @property
    def orders(self):
        return self._orders

    @property
    def staff(self):
        return self._staff

    @property
    def sides(self):
        return self._sides

    @property
    def toppings(self):
        return self._toppings

    def getStock(self, name):
        ''' Returns the amount of stock available
        for a provided item name
        '''
        return self._stock[name]

    def setStock(self, name, num=0, delta=0):
        ''' Updates the stock of a particular food item.
        There are two ways to call this function.
        Either specify the exact amount using the _num_
        parameter. e.g. if a staff is doing a stocktake
        on amount of food.
        Alternatively, use the _delta_ parameter and this
        will subtract the value of delta from the current
        stock. For example, if delta=3, this will subtract
        3 from the stock.
        '''
        if num != 0:
            self._stock[name] = num
        elif delta != 0:
            self._stock[name] -= delta

    def checkValidStock(self, food_item):
        ''' Given a OrderItem food_item, will return no
        value if there is sufficient stock of all
        buns, patties, toppings and sides.
        Will raise an error otherwise
        '''
        name_to_check = food_item.name

        # Burgers - check if buns are available
        if name_to_check == 'Burger':
            if self.getStock(food_item.bunType) < food_item.bunCount:
                raise ValueError

        # Check if there is sufficient (at least one) wrap
        if name_to_check == 'Wrap':
            if self.getStock(name_to_check) < 1:
                raise ValueError

        # Check if toppings and patties avaiable
        if name_to_check == 'Burger' or name_to_check == 'Wrap':
            for topping in food_item.toppings:
                if self.getStock(topping.name) < food_item.stock_cost:
                    raise ValueError
            return

        # Treats Nuggets3p, Nuggets6p, and Nuggets24p the same
        if 'Nuggets' in name_to_check:
            if self.getStock('Nuggets') < food_item.stock_cost:
                raise ValueError
            return

        # Treats small, medium and large fries the same
        if 'Fries' in name_to_check:
            if self.getStock('Fries') < food_item.stock_cost:
                raise ValueError
            return

        # For all other sides
        if self.getStock(name_to_check) < food_item.stock_cost:
            raise ValueError

    def updateStock(self, food_item):
        ''' Updates the stock of a food item.
        For burgers and wraps, it will also
        update the stock of its constituent
        toppings and patties.
        '''
        name_to_check = food_item.name

        # Burgers - check if buns and toppings available
        if name_to_check == 'Burger':
            self.setStock(food_item.bunType, delta=food_item.bunCount)

        if name_to_check == 'Burger' or name_to_check == 'Wrap':
            for topping in food_item.toppings:
                self.setStock(topping.name, delta=1)
            return

        if 'Nuggets' in name_to_check:
            self.setStock('Nuggets', delta=food_item.stock_cost)
            return

        if 'Fries' in name_to_check:
            self.setStock('Fries', delta=food_item.stock_cost)
            return

        # Sides, Wraps
        self.setStock(name_to_check, delta=food_item.stock_cost)

    def addOrder(self, order):
        ''' Adds a provided Order _order_ to the
        System.
        '''
        # Validation
        for food_item in order.mains:
            self.checkValidStock(food_item)
        for food_item in order.sides:
            self.checkValidStock(food_item)

        # Update stock
        for food_item in order.mains:
            self.updateStock(food_item)
        for food_item in order.sides:
            self.updateStock(food_item)

        # Now that the order has been confirmed and verified,
        # we can assign an ID to it.
        order.setId(System.order_id_generator.next())
        self._orders.append(order)

    def getOrder(self, order_id):
        """ Gets an order that matches a
        given order_id. This uses a linear search,
        though a binary search, or hash map would
        be more efficient for real-world implementations.
        """
        for order in self._orders:
            if order.id == order_id:
                return order

    def removeOrder(self, order_id):
        """ Removes an order that matches a
        given order_id. This uses a linear search,
        though a binary search, or hash map would
        be more efficient for real-world implementations.
        """
        for order in self._orders:
            if order.id == order_id:
                self._orders.remove(order)
                return

    def does_username_exist(self, username):
        ''' Checks if a provided username exists in the staff list'''
        for staff in self._staff:
            if staff.username == username:
                return True
        return False

    '''
Пример #12
0
from id_generator import IdGenerator
from algorithm import Person

event_id = IdGenerator()

class Event():
    def __init__(self, location, host, desc):
        self._id = event_id.next()
        self._location = location
        self._host = host
        self._desc = desc
        self._participants = []
        self._attendees = 0
        self._teams = []
    
    def add_participant(self, profile):
        self._participants.append(profile)
        self._attendees += 1
        profile.event.append(self._id)
    
    def remove_participant(self, id):
        for i in self._participants:
            if i.id == id:
                self._participants.remove(i)
                self._attendees -= 1
                break

    @property
    def teams(self):
        return self._teams
Пример #13
0
from id_generator import IdGenerator

profile_id = IdGenerator()


class Login():
    def __init__(self, username, password, user_type):
        self._username = username
        self._password = password
        self._user_type = user_type
        self._id = profile_id.next()

    @property
    def id(self):
        return self._id

    def verify(self, username, password):
        if username == self._username and password == self._password:
            return True
        return False

    @property
    def username(self):
        return self._username
Пример #14
0
class Graph (IGraph,
             IVertexListGraph, IEdgeListGraph,
             IMutableVertexGraph, IMutableEdgeGraph,
             IExtendGraph):
    """Directed graph with multiple links in this implementation:
        - vertices are tuple of edge_in, edge_out
        - edges are tuple of source,target

    """

    def __init__(self, graph=None):
        """
        if graph is not none make a copy of the topological structure of graph
        (i.e. don't use the same id)

        :param graph: the graph to copy, default=None
        :type graph: Graph
        """
        self._vertices = {}
        self._edges = {}
        self._vid_generator = IdGenerator()
        self._eid_generator = IdGenerator()
        if graph is not None:
            dummy = self.extend(graph)

    # ##########################################################
    #
    # Graph concept
    #
    # ##########################################################

    def source(self, eid):
        try:
            return self._edges[eid][0]
        except KeyError:
            raise InvalidEdge(eid)
    source.__doc__=IGraph.source.__doc__

    def target(self, eid):
        try:
            return self._edges[eid][1]
        except KeyError:
            raise InvalidEdge(eid)
    target.__doc__=IGraph.target.__doc__

    def __contains__(self, vid):
        return self.has_vertex(vid)
    __contains__.__doc__=IGraph.__contains__.__doc__

    def has_vertex(self, vid):
        return self._vertices.has_key(vid)
    has_vertex.__doc__=IGraph.has_vertex.__doc__

    def has_edge(self, eid):
        return self._edges.has_key(eid)
    has_edge.__doc__=IGraph.has_edge.__doc__

    def is_valid(self):
        return True
    is_valid.__doc__=IGraph.is_valid.__doc__

    # ##########################################################
    #
    # Vertex List Graph Concept
    #
    # ##########################################################

    def vertices(self):
        return iter(self._vertices)
    vertices.__doc__=IVertexListGraph.vertices.__doc__

    def __iter__(self):
        return iter(self._vertices)
    __iter__.__doc__=IVertexListGraph.__iter__.__doc__

    def nb_vertices(self):
        return len(self._vertices)
    nb_vertices.__doc__=IVertexListGraph.nb_vertices.__doc__

    def __len__(self):
        return self.nb_vertices()
    __len__.__doc__=IVertexListGraph.__len__.__doc__

    def in_neighbors(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        neighbors_list = [self.source(eid) for eid in self._vertices[vid][0]]
        return iter(set(neighbors_list))
    in_neighbors.__doc__=IVertexListGraph.in_neighbors.__doc__

    def out_neighbors(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        neighbors_list = [self.target(eid) for eid in self._vertices[vid][1]]
        return iter(set(neighbors_list))
    out_neighbors.__doc__=IVertexListGraph.out_neighbors.__doc__

    def neighbors(self, vid):
        neighbors_list = list(self.in_neighbors(vid))
        neighbors_list.extend(self.out_neighbors(vid))
        return iter(set(neighbors_list))
    neighbors.__doc__ = IVertexListGraph.neighbors.__doc__

    def nb_in_neighbors(self, vid):
        neighbors_set = list(self.in_neighbors(vid))
        return len(neighbors_set)
    nb_in_neighbors.__doc__ = IVertexListGraph.nb_in_neighbors.__doc__

    def nb_out_neighbors(self, vid):
        neighbors_set = list(self.out_neighbors(vid))
        return len(neighbors_set)
    nb_out_neighbors.__doc__ = IVertexListGraph.nb_out_neighbors.__doc__

    def nb_neighbors(self, vid):
        neighbors_set = list(self.neighbors(vid))
        return len(neighbors_set)
    nb_neighbors.__doc__ = IVertexListGraph.nb_neighbors.__doc__

    # ##########################################################
    #
    # Edge List Graph Concept
    #
    # ##########################################################

    def _iteredges(self, vid):
        """
        internal function that perform 'edges' with vid not None
        """
        link_in, link_out = self._vertices[vid]
        for eid in link_in:
            yield eid
        for eid in link_out:
            yield eid

    def edges(self, vid=None):
        if vid is None:
            return iter(self._edges)
        if vid not in self:
            raise InvalidVertex(vid)
        return self._iteredges(vid)
    edges.__doc__ = IEdgeListGraph.edges.__doc__

    def nb_edges(self, vid=None):
        if vid is None:
            return len(self._edges)
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][0])+len(self._vertices[vid][1])
    nb_edges.__doc__ = IEdgeListGraph.nb_edges.__doc__

    def in_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        for eid in self._vertices[vid][0]:
            yield eid
    in_edges.__doc__=IEdgeListGraph.in_edges.__doc__

    def out_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        for eid in self._vertices[vid][1]:
            yield eid
    out_edges.__doc__=IEdgeListGraph.out_edges.__doc__

    def nb_in_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][0])
    nb_in_edges.__doc__=IEdgeListGraph.nb_in_edges.__doc__

    def nb_out_edges(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        return len(self._vertices[vid][1])
    nb_out_edges.__doc__=IEdgeListGraph.nb_out_edges.__doc__

    # ##########################################################
    #
    # Mutable Vertex Graph concept
    #
    # ##########################################################

    def add_vertex(self, vid=None):
        vid=self._vid_generator.get_id(vid)
        self._vertices[vid]=(set(), set())
        return vid
    add_vertex.__doc__=IMutableVertexGraph.add_vertex.__doc__

    def remove_vertex(self, vid):
        if vid not in self:
            raise InvalidVertex(vid)
        link_in, link_out=self._vertices[vid]
        for edge in list(link_in):
            self.remove_edge(edge)
        for edge in list(link_out):
            self.remove_edge(edge)
        del self._vertices[vid]
        self._vid_generator.release_id(vid)
    remove_vertex.__doc__=IMutableVertexGraph.remove_vertex.__doc__

    def clear(self):
        self._vertices.clear()
        self._edges.clear()
        self._vid_generator=IdGenerator()
        self._eid_generator=IdGenerator()
    clear.__doc__=IMutableVertexGraph.clear.__doc__

    # ##########################################################
    #
    # Mutable Edge Graph concept
    #
    # ##########################################################

    def add_edge(self, edge=(None, None), eid=None):
        vs, vt=edge
        if vs not in self:
            raise InvalidVertex(vs)
        if vt not in self:
            raise InvalidVertex(vt)
        eid = self._eid_generator.get_id(eid)
        self._edges[eid]=(vs, vt)
        self._vertices[vs][1].add(eid)
        self._vertices[vt][0].add(eid)
        return eid
    add_edge.__doc__=IMutableEdgeGraph.add_edge.__doc__

    def remove_edge(self, eid):
        if not self.has_edge(eid):
            raise InvalidEdge(eid)
        vs, vt=self._edges[eid]
        self._vertices[vs][1].remove(eid)
        self._vertices[vt][0].remove(eid)
        del self._edges[eid]
        self._eid_generator.release_id(eid)
    remove_edge.__doc__=IMutableEdgeGraph.remove_edge.__doc__

    def clear_edges(self):
        self._edges.clear()
        self._eid_generator=IdGenerator()
    clear_edges.__doc__=IMutableEdgeGraph.clear_edges.__doc__

    # ##########################################################
    #
    # Extend Graph concept
    #
    # ##########################################################

    def extend(self, graph):
        #vertex adding
        trans_vid={}
        for vid in graph.vertices():
            trans_vid[vid]=self.add_vertex()

        #edge adding
        trans_eid={}
        for eid in graph.edges():
            sid=trans_vid[graph.source(eid)]
            tid=trans_vid[graph.target(eid)]
            trans_eid[eid]=self.add_edge(edge=(sid, tid))

        return trans_vid, trans_eid
    extend.__doc__=IExtendGraph.extend.__doc__
Пример #15
0
 def clear_edges(self):
     self._edges.clear()
     self._eid_generator=IdGenerator()
Пример #16
0
    def setUp(self):
        self.client = Redis()
        self.client.flushdb()

        self.id_generator = IdGenerator(self.client, 'user::id')
Пример #17
0
from id_generator import IdGenerator

team_id = IdGenerator()

class Team:
    def __init__(self, event):
        self._members = []
        self._id = team_id.next()
        self._event_id = event

    def add_member(self, person):
        self._members.append(person)
    
    @property
    def members(self):
        return self._members

    def __repr__(self):
        return str(self._members)
Пример #18
0
from typing import Dict, Optional, List, TypeVar
from fastapi import FastAPI, status, HTTPException
from todo import Todo, TodoKey, TodoValue
from id_generator import IdGenerator, Id
from json_types import JsonObject, JsonList

# Used to generate unique Ids for our `todos` dict keys
id_gen = IdGenerator()
todos: Dict[Id, Todo] = {}

app = FastAPI()

@app.get('/todos')
def index() -> JsonList[Todo]:
    return list(todos.values())

@app.get('/todos/{item_id}')
def show(item_id: Id) -> JsonObject[Optional[Todo]]:
    return { 'item': todos.get(item_id, None) }

@app.post('/todos', status_code=status.HTTP_201_CREATED)
def create(entry: dict) -> JsonObject[int]:
    if 'description' not in entry or 'category' not in entry:
        raise HTTPException(status_code=400, detail='JSON missing "description" or "category" field')

    new_id: Id = id_gen.next()
    todos[new_id] = Todo(entry['description'], entry['category'], new_id)
    return { 'id': new_id }

@app.delete('/todos/{item_id}')
def delete(item_id: int) -> JsonObject[bool]: