示例#1
0
class ValidFakeDatabase:

    # initializes dummy data to return
  def __init__(self):
    self.dateA = datetime.datetime(2013, 8, 4, 12, 30, 45)
	self.dateB = datetime.datetime(1999, 7, 6, 12, 30, 45)
    self.paperA = Paper("12345", "The Health Benefits of the All-Bacon Diet", ["4445", "666", "123"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], "Bacon is actually one of the healthiest foods of all time.  This is an abstract!  For the full article, download the PDF.", "1234", self.dateA, datetime.datetime.now(), "1111", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Alan Turing", "Shia Leboeuf", "Andrew Davidson"])
    self.paperB = Paper("90210", "The Dangers of Coding While Hungry", ["12068", "7797", "4326"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], " Abstracts never seem to be simple or contain useful information.", "444", self.dateA, datetime.datetime.now(), "6677", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])
    self.paperC = Paper("666", "The Struggles of Eating a Giordano's Pizza Alone", ["567", "2213", "989"], ["6237", "3177", "432"], "Abstracts are the SparkNotes of the academic world.", "12534434", self.dateB, datetime.datetime.now(), "2345", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Prentice Hall", ["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])

    self.authorA = Author("55555", "Shia Leboeuf", "4444", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorB = Author("43216", "Andrew Davidson", "1", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorC = Author("6542", "William Shakespeare", "11542", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorD = Author("64632", "Edsger Dijkstra", "147", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorE = Author("63421", "Alan Turing", "40000", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])

    self.tagA = Tag("Genetics", "40000", ["0", "1"])
    self.tagB = Tag("Bioinformatics", "12345", ["0", "1"])
    self.tagC = Tag("Search Engines", "5555", ["2", "3"])
    self.tagD = Tag("Artificial Intelligence", "42", ["2", "3"])
    
    self.publisherA = Publisher("1233", "Your Favorite Publisher",0)
    self.publisherB = Publisher("3468", "Prentice Hall",0)
    self.publisherC = Publisher("8372", "Rose-Hulman",0)

    self.userA = User("0","Otis Redding", ["1", "3"],["Andrew Davidson","Jonathan Jenkins"], [self.paperA, self.paperB, self.paperC], [self.authorA, self.authorB, self.authorC], [self.tagA, self.tagC, self.tagB, self.tagD], "45", "005792830123")
    def getEBookInfo(self):
        title = input("Enter the book title:")
        location = input("Enter the location code:")
        try:
            yearPub = int(input("Enter int value for the year of publication:"))
        except ValueError as e:
            print("*** Input type error, publication year set to 0 ***")
            yearPub = 0
        authors = []
        authorName = input("Enter one author for the book(you can add more late):")
        author = Author(authorName)
        authors.append(author)
        publisherName = input("Enter the publisher:")
        publisher = Publisher(publisherName)
        try:
            pages = int(input("Enter int value for the number of pages:"))
        except ValueError as e:
            print("*** Input type error, total pages set to 0 ***")
            pages = 0
        try:
            size = float(input("Enter decimal value for the size in MB of the e-book:"))
        except ValueError as e:
            print("*** Input type error, size set to 0.0 ***")
            size = 0.0
        print()

        addBook = ElectronicBook(title, location, yearPub, authors, publisher, pages, size)
        return addBook
示例#3
0
	def __init__(self):
		rospy.init_node('communication_manager',anonymous=False,disable_signals=True)	
		pubsubport = rospy.get_param('~pubsubport')
		self.publisher=Publisher(pubsubport)	
		thread = threading.Thread(target=self.publisher.run, args=())
        	thread.daemon = True                            # Daemonize thread
        	thread.start()
示例#4
0
def publish(msg, room, token):
    publisher = Publisher(room=room, token=token)
    publisher.start()
    publisher.publish(msg)
    _, data = publisher.recv()
    if not data == b'publish successful':
        raise Exception(data)
    publisher.stop()
 def testRemoveSubscriber1(self):
     # tests to see if subscriber in list is removed
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     pub.removeSubscriber(dum2)
     self.assertEqual(len(pub.getSubscriberList()), 1)
示例#6
0
def register(address, port, init_topic):
	publisher = Publisher(address, port, init_topic)
	publisher.register_handler()
	logfile_name = './Output/' + publisher.myID + '-publisher.log'
	with open(logfile_name, 'w') as log:
		log.write('ID: %s \n' % publisher.myID)
		log.write('Init Topic: %s\n' % publisher.init_topic)
		log.write('Connection Info: tcp://' + address + ':' + port + '\n')
	return publisher
 def testGetSubscriberList(self):
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     list1 = pub.getSubscriberList()
     list2 = [dum1, dum2]
     self.assertCountEqual(list1, list2)
示例#8
0
 def __init__(self,
              context=None,
              fuser=None,
              socket_nr=5555,
              debug_time=-1):
     DataBoss.__init__(self, fuser, debug_time)
     self.context = context
     if self.context is None:
         self.context = zmq.Context()
     self.publisher = Publisher(context=self.context, socket_nr=socket_nr)
 def testRemoveSubscriber2(self):
     # tests to make sure nothing is removed since not in list
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     notAdded = BigDummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     pub.removeSubscriber(notAdded)
     self.assertEqual(len(pub.getSubscriberList()), 2)
示例#10
0
def main():
    """Main entry point to the program."""

    # Get the location of the AMQP broker (RabbitMQ server) from
    # an environment variable
    amqp_url = os.environ['AMQP_URL']
    LOGGER.info('URL: %s' % (amqp_url, ))

    # Connect to localhost:5672 as guest with the password guest and virtual host "/" (%2F)
    Publisher(amqp_url, on_connection_complete=publish_events)
示例#11
0
 def start_collection(self):
     iot = IoT()
     self.publisher = Publisher(self.drone_id, self.server_ip,
                                self.server_port, self.username,
                                self.password)
     sensor = iot.get_sensor(self.sensor_type)
     while True:
         self.send_data(sensor.get_data())
         self.count -= 1
         if self.count == 0:
             break
         time.sleep(self.interval)
示例#12
0
    def process_message_status(self, message):
        self.info("Publish .. creating publish instance, queue," \
  "exchange: (%s, %s) " % ('DLR_QUEUE', 'DLR_QUEUE'))
        message['exchange'] = 'DLR_QUEUE'
        message['reference'] = message.get('ref_no')

        publisher = Publisher('DLR_QUEUE', 'DLR_QUEUE')

        self.logger.info("Publish calling publish status : %r" % message)
        publisher.publish(message, 'DLR_QUEUE')

        self.info("POST: DLR Queued successfully with message: %r " % message)
示例#13
0
    def process_withdrawal_status(self, message):
        self.info("Publish .. creating publish instance, queue," \
  "exchange: (%s, %s) " % ('WITHDRAWAL_STATUS', 'WITHDRAWAL_STATUS'))
        message['exchange'] = 'WITHDRAWAL_STATUS'
        publisher = Publisher('WITHDRAWAL_STATUS', 'WITHDRAWAL_STATUS')

        self.logger.info("Publish calling publish status : %r" % message)
        publisher.publish(message, 'WITHDRAWAL_STATUS')

        self.info(
            "POST: Withdraw status Queued successfully with message: %r " %
            message)
示例#14
0
    def get(self):
        message = self.get_message_dict()
        self.logger.info("Publish .. creating publish instance, queue," \
            "exchange: (%s, %s) " % (self.QUEUE_NAME, self.EXCHANGE_NAME))
        publisher = Publisher(self.QUEUE_NAME, self.EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        q_message = self.get_queue_message(message)
        publisher.publish(q_message, self.ROUTING_KEY)

        self.info("GET: Task Queued successfully with message: %r " % message)
        return self.response(message.get('TransID'), 201,
                             'Transaction queued succcess'), 200
示例#15
0
def main():
    pub = Publisher(['lunch', 'dinner'])
    bob = Subscriber('Bob')
    alice = Subscriber('Alice')
    john = Subscriber('John')

    pub.register("lunch", bob)
    pub.register("dinner", alice)
    pub.register("lunch", john)
    pub.register("dinner", john)

    pub.dispatch("lunch", "It's lunchtime!")
    pub.dispatch("dinner", "Dinner is served")
示例#16
0
    def get(self):
        message = self.get_message_dict()
        self.logger.info("Publish .. creating publish instance, queue," \
            "exchange: (%s, %s) " % (self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME))

        message['exchange'] = self.SMS_EXCHANGE_NAME
        publisher = Publisher(self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        publisher.publish(message, self.SMS_ROUTING_KEY)

        self.info("GET: Task Queued successfully with message: %r " % message)
        return self.response()
示例#17
0
    def daily_news(self):
        # get all articles
        paper_bundle = Paper_Boy().get_the_paper()

        # add the statistics
        Analyzer(paper_bundle).fill_stats()

        # write tweets
        tweets = Writer(paper_bundle).write_all_tweets()

        # publish tweets
        publisher = Publisher()
        for tweet in tweets:
            publisher.post_tweet(tweet)

        return tweets
示例#18
0
    def post(self):
        message = self.get_message_dict()
        self.info("Received inbox post request ==> %r" % (message, ))
        if not message or not message.get('short_code'):
            return {
                'response_code': 400,
                'response_desc': 'Missing MSISDN on POST'
            }, 400
        message['exchange'] = self.SMS_EXCHANGE_NAME
        publisher = Publisher(self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        publisher.publish(message, self.SMS_ROUTING_KEY)

        self.info("POST: Task Queued successfully with message: %r " % message)
        return self.response()
def unitTest12(ip, address):
    topics = {
        1: 'animals',
        2: 'countries',
        3: 'foods',
        4: 'countries',
        5: 'phones',
        6: 'universities',
        7: 'phones',
        8: 'laptops',
        9: 'foods',
        10: 'laptops',
        11: 'laptops',
        12: 'animals'
    }
    topic = topics[random.randint(1, 12)]
    publisher = Publisher(ip, address, '5556', '6002', topic)
    publisher.register()
示例#20
0
    def post(self):
        message = self.get_message_dict()
        if not message or not message.get('TransID'):
            return {
                'response_code': 400,
                'response_desc': 'Missing transaction ID'
            }, 400
        message['exchange'] = self.EXCHANGE_NAME
        publisher = Publisher(self.QUEUE_NAME, self.EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r => Q = %s, EX=%s" %
                         (message, self.QUEUE_NAME, self.EXCHANGE_NAME))

        q_message = self.get_queue_message(message)
        publisher.publish(q_message, self.ROUTING_KEY)

        self.info("POST: Task Queued successfully with message: %r " % message)
        return self.response(message.get('TransID'), 201, 'Succcess')
示例#21
0
def main():
    args = sys.argv[1:]

    # if len(args) != 3:
    #     print('python init.py [publisher|subscriber|server] <host> <port>')

    #     return

    host = 'localhost'
    port = 8000

    if args[0] == 'publisher':
        client = Publisher(host, port)

        try:
            client.menu_loop()
        except KeyboardInterrupt:
            print('\nBye')

        return

    if args[0] == 'subscriber':
        client = Subscriber(host, port)

        try:
            client.menu_loop()
        except KeyboardInterrupt:
            print('\nBye')

        return

    if args[0] == 'server':
        server = Server('server/newsletter.db')

        print('Serving...')

        try:
            server.serve(host, port)
        except KeyboardInterrupt:
            print('\nBye')

        return

    print('Bad argument')
def unitTest12(ip, address, zk_address):
    topics = {
        1: 'animals',
        2: 'countries',
        3: 'foods',
        4: 'countries',
        5: 'phones',
        6: 'universities',
        7: 'phones',
        8: 'laptops',
        9: 'foods',
        10: 'laptops',
        11: 'laptops',
        12: 'animals'
    }
    topic = topics[random.randint(1, 12)]
    publisher = Publisher(zk_address, topic)
    input_file = './Input/' + topic + '.txt'
    print(input_file)
    publisher.main(topic, input_file)
示例#23
0
    def HandleAddPublisher(self, command):
        """This function handles the case where the client wishes to add a publisher to the sensor mesh"""

        print "Handling Add Publisher..."

        # The client screwed up the packet do nothing, return failure.
        if not command.Payload or command.Payload == "":
            print "Client tried to add a publisher, but did not provide an identifier."
            return Command().CreateFromParams(Command.FAILURE, command.TransactionID, 0, Command.INVALID_COMMAND)

        # RQ 15b
        # If the publisher already exists in the network.
        if Pubs.has_key(command.Payload):
            print "Client " + str(self.client_address) + " tried to add publisher that already exists."
            return Command().CreateFromParams(Command.FAILURE, command.TransactionID, 0, Command.PUB_ALREADY_EXISTS)

        # Actually add the publisher to the dictionary.
        Pubs[command.Payload] = Publisher(command.Payload, self.request, self.client_address, self.GetNextPort(), command.SensorType)
        print "Added publisher: ID=" + command.Payload + " from " + str(self.client_address)

        # RQ 15c
        # Return success.
        return Command().CreateFromParams(Command.SUCCESS, command.TransactionID, 0, Pubs[command.Payload].BroadcastPort)
示例#24
0
    def getPrintedBookInfo(self):
        title = input("Enter the book title:")
        location = input("Enter the location code:")
        try:
            yearPub = int(input("Enter int value for the year of publication:"))
        except ValueError as e:
            print("*** Input type error, publication year set to 0 ***")
            yearPub = 0
        authors = []
        authorName = input("Enter one author for the book(you can add more late):")
        author = Author(authorName)
        authors.append(author)
        publisherName = input("Enter the publisher:")
        publisher = Publisher(publisherName)
        try:
            pages = int(input("Enter int value for the number of pages:"))
        except ValueError as e:
            print("*** Input type error, total pages set to 0 ***")
            pages = 0
        type = input("Enter the type(hard cover or paperback):")
        print()

        addBook = PrintedBook(title, location, yearPub, authors, publisher, pages, type)
        return addBook
 def getPublisher(self, publisherID):
   name = self.redisDB.get("Publisher:"+publisherID+":Name")
   if name == None:
     return None
   viewCount = self.redisDB.get("Publisher:"+publisherID+":ViewCount")
   return Publisher(publisherID, name, viewCount)
}
dict3 = {
    'topic_channel': [],
    'topic_key': topic_key3,
    'publisher': None,
    'subscriber_lst': []
}

topic_dict = {'topic1': dict1, 'topic2': dict2, 'topic3': dict3}
authentication_manager = AuthenticationManager({}, source_dict)

# ------------------------------Creating three publishers ------------------------------------------------

pub1_client_conn = Connection()
pub1_server_conn = Connection()
pub1 = Publisher(pub1_server_conn, pub1_client_conn, "topic1", 'publisher1',
                 "source1", "trusted_keys/trusted1", 'trusted_keys')

pub2_client_conn = Connection()
pub2_server_conn = Connection()
pub2 = Publisher(pub2_server_conn, pub2_client_conn, "topic2", 'publisher2',
                 "source2", "trusted_keys/trusted2", 'trusted_keys')

pub3_client_conn = Connection()
pub3_server_conn = Connection()
pub3 = Publisher(pub3_server_conn, pub3_client_conn, "topic3", 'publisher3',
                 "source3", "trusted_keys/trusted3", 'trusted_keys')

pub1_AS_thread = AuthenticationServerThread(pub1_server_conn, pub1_client_conn,
                                            authentication_manager)
pub1_AS_thread.start()
pub1.start()
示例#27
0
from operator import attrgetter

from Publisher import Publisher
from Steam import Steam
from Game import Game

bethesda = Publisher("Bethesda", "Maryland, USA")
eaGames = Publisher("Electronic Arts", "California, USA")

bethesda = Publisher("Bethesda", "Maryland, USA")
eaGames = Publisher("Electronic Arts", "California, USA")
skyrim = Game("Skyrim", "Action RPG", 94.0, "11/12/2010", bethesda)
fallout = Game("Fallout 4", "Action RPG", 84.0, "10/11/2015", bethesda)
fifa = Game("Fifa", "Sports", 85.7, "11/09/2018", eaGames)
nba = Game("NBA", "Sports", 75.9, "11/11/2018", eaGames)
myVideoGame = Game(name="The best game ever", genre="Chess", raiting=54.5)

bethesda.addGame(skyrim)

games = [skyrim, fifa, myVideoGame]
steam = Steam(games)
steam.addGame(nba)
steam.addGame(fallout)

bethesdaGames = steam.getGamesFromPublisher("Bethesda")
print("Bethesda games:\n")
for game in bethesdaGames:
    print(game)

print("--------------------------------------------")
示例#28
0
    num_detections = inference.get_model_detected_objects()

    camera = PiCamera()
    camera.resolution = (IM_WIDTH, IM_HEIGHT)
    camera.framerate = 10
    rawCapture = PiRGBArray(camera, size=(IM_WIDTH, IM_HEIGHT))
    rawCapture.truncate(0)

    # Initialize frame rate calculation
    collector = Collector()
    frame_rate_calc = collector.frame_rate_calc
    freq = collector.freq
    font = collector.font

    # Initialize publisher service.
    publisher = Publisher()

    for frame1 in camera.capture_continuous(rawCapture,
                                            format="bgr",
                                            use_video_port=True):

        t1 = cv2.getTickCount()

        # Acquire frame and expand frame dimensions to have shape:
        # [1, None, None, 3]
        # i.e. a single-column array, where each item in the column
        # has the pixel RGB value
        frame = np.copy(frame1.array)
        frame.setflags(write=1)
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame_expanded = np.expand_dims(frame_rgb, axis=0)
 def testAddSubscriber1(self):
     # tests that a valid object is added
     pub = Publisher()
     dum = Dummy()
     pub.addSubscriber(dum)
     self.assertEqual(len(pub.getSubscriberList()), 1)
 def testAddSubscriber2(self):
     # tests to make sure invalid object not added
     pub = Publisher()
     dum = BigDummy()
     pub.addSubscriber(dum)
     self.assertEqual(len(pub.getSubscriberList()), 0)