def __init__(self):
        self.colorChangedEvent = Event()
        self.gestureEvent = Event()
        self.colorChangedEvent.append(self.onColorChanged)
        self.gestureEvent.append(self.onGestureRecognized)
        self.mainWindowRefresh = None
        if systemIsWindows:
            global resolution
            self.camera = cv2.VideoCapture(default_camera)
            height = self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
            width = self.camera.get(cv2.CAP_PROP_FRAME_WIDTH)
            resolution = (width, height)
        else:
            self.camera = PiCamera(resolution=resolution, framerate=framerate)
            self.rawCapture = PiRGBArray(self.camera, size=resolution)
            time.sleep(0.1)
            self.Bluetoothplayer = Bluetoothplayer()

        self.HandRecognizer = HandRecognizer()
        self.GestureRecognizer = GestureRecognizer(resolution,
                                                   self.gestureEvent)
        self.FrameDrawing = FrameDrawing()
        # UI-Elements:
        self.window = None
        self.colorPickerButton = None
        self.imageContainer = None
        self.initUI()
Esempio n. 2
0
 def interpolate(self, index, viewloc):
     """Find where the lightcone of viewloc intersects the worldline joining
     the events prev and post.  Return an interpolated event at that
     intersection point, which is what viewloc would see as it watches the
     worldline.
     Using convention prev=1, post=2, veiwloc=v:
         parametrized worldline is x=(t-t1)*v_i+x1 for v_i=(x2-x1)/(t2-t1)
         find t where distance b/w x, viewloc is delta-t*c
     """
     prev = self.eventlist[index]
     post = self.eventlist[(index + 1) % self.len]
     v_i = (post.space - prev.space) / (post.t - prev.t)
     #quadratic formula components
     a = np.sum(v_i**2) - self.univ.lightspeed**2
     b = (2 * np.sum(v_i * (prev.space - prev.t * v_i - viewloc.space)) +
          2 * viewloc.t * self.univ.lightspeed**2)
     c = (np.sum((prev.space - prev.t * v_i - viewloc.space)**2) -
          (viewloc.t * self.univ.lightspeed)**2)
     pos = (-1 * b + np.sqrt(b**2 - 4 * a * c)) / (2 * a)
     neg = (-1 * b - np.sqrt(b**2 - 4 * a * c)) / (2 * a)
     #use correct component for time, then use time to find spatial location
     inter_t = (pos if prev.t <= pos <= post.t else neg)
     inter_x = (inter_t - prev.t) * v_i + prev.space
     #interpolate the description of the event too, according to its own class methods
     percentage = (inter_t - prev.t) / (post.t - prev.t)
     inter_descrip = prev.phystype.interpolate(prev.descrip, post.descrip,
                                               percentage)
     return Event(prev.phystype, inter_descrip, inter_t, inter_x)
Esempio n. 3
0
 def prune(self):
     """Gets rid of events so far in the past that they can't be seen again"""
     crossingtime = 2 * self.univ.radius / self.univ.lightspeed
     #if freshest event was added to worldline so long ago it's now out of
     #sight in the past, delete the whole worldline
     if self.univ.clock - self.eventlist[self.future - 1].t > crossingtime:
         self.univ.del_worldline(self.key)
         print("worldline with key", self.key, "lost in the past")
         return
     #if the event at self.oldest is stale, we will interpolate it to bring
     #it up to snuff, since it might be a valuable endcap for interpolation.
     #Unless the NEXT one is ALSO stale, in which case we should update THAT...
     while self.univ.clock - crossingtime > self.eventlist[self.oldest].t:
         plusone = (self.oldest + 1) % self.len
         if self.univ.clock - crossingtime > self.eventlist[plusone].t:
             #next Event is ALSO stale, so move on to repairing THAT one
             self.oldest = plusone
         else:
             #next Event is fine, so interpolate this one to repair it (and don't move self.oldest)
             t = self.univ.clock - crossingtime
             e0 = self.eventlist[self.oldest]
             e1 = self.eventlist[plusone]
             percentage = (t - e0.t) / (e1.t - e0.t)
             newspace = percentage * (e1.space - e0.space) + e0.space
             newdescrip = e0.phystype.interpolate(e0.descrip, e1.descrip,
                                                  percentage)
             self.eventlist[self.oldest] = Event(e0.phystype, newdescrip, t,
                                                 newspace)
Esempio n. 4
0
 def add_to_best_server(task, now):
     if system.has_idle_core():
         server, core = system.get_idle_core()
         core.set_busy()
         task.start_core_service_time = now
         add_to_right_time_place(
             Event(EventType.departure_of_core, now + core.get_next_service_time(), task, server, core))
         return
     min_index = -1
     min_length = math.inf
     for index in range(len(system.servers)):
         if system.servers[index].queue_length() < min_length:
             min_length = system.servers[index].queue_length()
             min_index = index
     else:
         system.servers[min_index].add_to_queue(task, now)
Esempio n. 5
0
 def __init__(self, t, x, v, univ, isghost=False):
     """If isghost, the Physical is built as normal but without informing
     the Universe or building a Worldline for it."""
     self.univ = univ
     self.loc = Location(t, x)
     self.v = np.array(v, dtype=float)
     #Finished with descriptive fields. Now add to Universe
     self.linekey = None
     self.key = None
     if not isghost:
         firstevent = Event(type(self), self.compress(), self.loc.t,
                            self.loc.space)
         worldline = Worldline(
             univ, firstevent
         )  #build new Worldline (it adds itself to to univ.History)
         self.linekey = worldline.key
         self.sensor = Sensor(self.loc, univ, ownkey=self.linekey)
         self.key = univ.add_physical(self)
Esempio n. 6
0
def extract(url):
	try:
		req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
		print("Extracting...")
		s = urlopen(req).read()
		soup = bs.BeautifulSoup(s,'lxml')
		info = soup.find(class_='mn-section mn-event-detail-listing')
		
		try:
			event = Event()
			myStr = ""
			for i in range(14):
				myStr+= random.choice(string.ascii_letters + string.digits)
			event.id=myStr

			event.title = info.find(class_='mn-event-content').text
			event.link = url
			description = info.find(itemprop='description').text
			event.description = description
			#event.short_description = description[:92]+"..."
			event.date = datetime.strptime(info.find(class_='mn-event-day').text, '%B %d, %Y').strftime('%Y-%m-%d')
			#event.category = event.categoryFinder(description)
			location = info.find(itemprop='name').text
			event.address, event.city, event.lat, event.lng = event.addressFinder(location)
			if(type(event.lat)!=str):
				event.lat = str(event.lat)
				event.lng = str(event.lng)
				print("SUCCESS\n")
				table.put_item(Item=event.toJSON())
			else:
				event.address, event.city, event.lat, event.lng = event.addressFinderBasic(location)
				if(type(event.lat)!=str):
					event.lat = str(event.lat)
					event.lng = str(event.lng)
					print("Success\n")
					table.put_item(Item=event.toJSON())
				else:
					print("address failure\n")
		except:
			print("Event error",url,"\n")
	except:
		print("Page error", url,"\n")
Esempio n. 7
0
def extract(url):
    base = "https://www.active.com"
    sleep(0.2)
    try:
        if (url[:3] == "http"):
            req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        else:
            req = Request(base + url, headers={'User-Agent': 'Mozilla/5.0'})
        s = urlopen(req).read()
        soup = bs.BeautifulSoup(s, 'lxml')
        info = soup.find(id='body-container')
        #print("\n-----> Extracting: ",base+url)
        try:
            event = Event()
            myStr = ""
            for i in range(14):
                myStr += random.choice(string.ascii_letters + string.digits)
            event.id = myStr

            event.title = info.h1.text
            event.link = base + url
            print("Title: ", event.title)
            description = info.find(class_='asset-summary span8').text
            event.description = description
            date = info.h5.text
            event.date = event.dateFinder(date)
            location = info.find(class_='ed-address-text').text
            event.address, event.city, event.lat, event.lng = event.addressFinder(
                location)
            if (type(event.lat) != str):
                event.lat = str(event.lat)
                event.lng = str(event.lng)
                print("SUCCESS")
                table.put_item(Item=event.toJSON())
            else:
                event.address, event.city, event.lat, event.lng = event.addressFinderBasic(
                    location)
                if (type(event.lat) != str):
                    event.lat = str(event.lat)
                    event.lng = str(event.lng)
                    print("Success")
                    table.put_item(Item=event.toJSON())
                else:
                    print("address failure")
        except:
            print("Error")
    except:
        print("Page error", base + url)
Esempio n. 8
0
text = Text('en')
address = Address('en')

now = datetime.datetime.now()


def random_date(start, end):
    """Generate a random datetime between `start` and `end`"""
    return start + datetime.timedelta(
        # Get a random amount of seconds between `start` and `end`
        seconds=random.randint(0, int((end - start).total_seconds())), )


for i in range(50):
    event = Event()
    myID = ""
    for i in range(14):
        myID += random.choice(string.ascii_letters + string.digits)
    images = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"]
    event.id = myID
    event.title = text.sentence()
    event.link = "https://google.com"
    event.description = text.quote()
    event.date = str(random_date(now, now + datetime.timedelta(600)))
    event.category = text.words(quantity=4)
    event.address = address.address()
    event.city = address.city()
    event.lat = str(round(random.uniform(37, 40.8), 7))
    event.lng = str(round(random.uniform(-108.9, -102.2), 7))
    event.image = random.choice(images)
Esempio n. 9
0
def extract(url):
    sleep(0.2)
    try:
        if (url[:3] == "http"):
            req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        else:
            req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        s = urlopen(req).read()
        soup = bs.BeautifulSoup(s, 'lxml')
        info = soup.find(class_='full m-event-detail clearfix')
        #print("\n-----> Extracting: ",base+url)
        try:
            event = Event()
            myStr = ""
            for i in range(14):
                myStr += random.choice(string.ascii_letters + string.digits)
            event.id = myStr

            event.title = info.h1.text
            event.link = url
            description = info.find(class_='m-event-detail-description').text
            event.description = description
            date = info.find(class_="m-date__singleDate").text
            event.date = event.dateFinder(date)
            #location = "18300 W Alameda Pkwy, Morrison, CO 80465"
            event.lng = "-105.2048546"
            event.lat = "39.6664666"
            event.city = "Morrison"
            event.address = "8300 W Alameda Pkwy"
            print("\n\n Item: ", event.title)
            table.put_item(Item=event.toJSON())
        except:
            print("Info error", url)
    except:
        print("Page error", url)
Esempio n. 10
0
 def GetStatusAsEvent(self):
     return Event(type(self), self.compress(), self.loc.t, self.loc.space)
Esempio n. 11
0
def simulate(number_of_warm_up_task, max_number_of_tasks, task_generator, system, statistical_data):
    global FEL

    def add_to_right_time_place(event):
        temp_stack = []
        put = False
        while FEL:
            e = FEL.pop()
            if e.time > event.time:
                FEL.append(e)
                FEL.append(event)
                put = True
                break
            elif e.time < event.time:
                temp_stack.append(e)
            else:
                if event.event_type > e.event_type:
                    FEL.append(e)
                    FEL.append(event)
                    put = True
                    break
                else:
                    temp_stack.append(e)
        if not put:
            FEL.append(event)
        while temp_stack:
            FEL.append(temp_stack.pop())

    def add_to_best_server(task, now):
        if system.has_idle_core():
            server, core = system.get_idle_core()
            core.set_busy()
            task.start_core_service_time = now
            add_to_right_time_place(
                Event(EventType.departure_of_core, now + core.get_next_service_time(), task, server, core))
            return
        min_index = -1
        min_length = math.inf
        for index in range(len(system.servers)):
            if system.servers[index].queue_length() < min_length:
                min_length = system.servers[index].queue_length()
                min_index = index
        else:
            system.servers[min_index].add_to_queue(task, now)

    def get_next_scheduler_task(now):
        if system.scheduler.queue_length() != 0:
            return system.scheduler.pop_of_queue(now)
        return None

    def remove_all_passed_deadlines(now):
        removed_task = system.remove_passed_deadlines(now)
        statistical_data.update_removed_tasks(removed_task)

    task = task_generator.get_next_task()
    add_to_right_time_place(Event(EventType.arrival_to_scheduler, task.arrival_time, task))

    warm_up_passed = False
    start_main_simulation_time = -1

    max_task_number = 0
    while FEL:  # future event list
        event = FEL.pop()
        now = event.time
        remove_all_passed_deadlines(now)
        if event.event_type is EventType.arrival_to_scheduler:
            task = task_generator.get_next_task()
            max_task_number += 1
            add_to_right_time_place(Event(EventType.arrival_to_scheduler, task.arrival_time, task))
            if system.scheduler.is_idle:
                system.scheduler.set_busy()
                event.task.start_scheduler_service_time = now
                add_to_right_time_place(Event(EventType.departure_of_scheduler,
                                              now + system.scheduler.get_next_service_time(), event.task))
            else:
                system.scheduler.add_to_queue(event.task, now)
        elif event.event_type is EventType.departure_of_scheduler:
            event.task.end_scheduler_service_time = now
            add_to_best_server(event.task, now)
            next_task = get_next_scheduler_task(now)
            if next_task is None:
                system.scheduler.set_idle()
            else:
                next_task.start_scheduler_service_time = now
                add_to_right_time_place(Event(EventType.departure_of_scheduler,
                                              now + system.scheduler.get_next_service_time(), event.task))
        elif event.event_type is EventType.departure_of_core:
            event.task.end_core_service_time = now
            statistical_data.leave_task(event.task)
            if event.server.queue_length() == 0:
                event.core.set_idle()
            else:
                new_task = event.server.pop_of_queue(now)
                new_task.start_core_service_time = now
                add_to_right_time_place(Event(EventType.departure_of_core, now + event.core.get_next_service_time()
                                              , new_task, event.server, event.core))
        if not warm_up_passed and statistical_data.number_of_task_simulated == number_of_warm_up_task:
            statistical_data.reset(system, now)
            warm_up_passed = True
            start_main_simulation_time = now
        if warm_up_passed:
            statistical_data.update_queue_length(system, now, start_main_simulation_time)
            AccuracyChecker.check(statistical_data)
        if statistical_data.number_of_task_simulated >= max_number_of_tasks:
            Report.add_report_simulation_not_finished(statistical_data, max_task_number, now - start_main_simulation_time, system, now)
            break
        if AccuracyChecker.is_enough():
            Report.add_report_simulation_finished_successfully(statistical_data, task_generator.get_next_task().number, now - start_main_simulation_time, system, now)
            break
    return FEL
class Controller:
    def __init__(self):
        self.colorChangedEvent = Event()
        self.gestureEvent = Event()
        self.colorChangedEvent.append(self.onColorChanged)
        self.gestureEvent.append(self.onGestureRecognized)
        self.mainWindowRefresh = None
        if systemIsWindows:
            global resolution
            self.camera = cv2.VideoCapture(default_camera)
            height = self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
            width = self.camera.get(cv2.CAP_PROP_FRAME_WIDTH)
            resolution = (width, height)
        else:
            self.camera = PiCamera(resolution=resolution, framerate=framerate)
            self.rawCapture = PiRGBArray(self.camera, size=resolution)
            time.sleep(0.1)
            self.Bluetoothplayer = Bluetoothplayer()

        self.HandRecognizer = HandRecognizer()
        self.GestureRecognizer = GestureRecognizer(resolution,
                                                   self.gestureEvent)
        self.FrameDrawing = FrameDrawing()
        # UI-Elements:
        self.window = None
        self.colorPickerButton = None
        self.imageContainer = None
        self.initUI()

    def initUI(self):
        self.window = Tk()
        self.window.bind('<Escape>', lambda e: self.window.quit())

        self.colorPickerButton = Button(self.window,
                                        text="set color range",
                                        command=self.button_changeColorRange)
        self.colorPickerButton.pack()
        self.imageContainer = Label(self.window)
        self.imageContainer.pack()

    def displayFrame(self, frame):
        img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        imgTk = ImageTk.PhotoImage(image=img)
        self.imageContainer.imgtk = imgTk
        self.imageContainer.configure(image=imgTk)

    def _process_frame(self, frame):
        hand = self.HandRecognizer.getHand(frame)
        if hand is not None:
            self.FrameDrawing.drawHand(frame, hand)
            self.GestureRecognizer.addHandToGestureBuffer(hand)
            gesture = self.GestureRecognizer.getGesture()
            if gesture is not None and gesture.startpoint is not None and gesture.endpoint is not None:
                self.FrameDrawing.drawGesture(frame, gesture)
        else:
            self.FrameDrawing.putText(frame, "No hand detected")
            self.GestureRecognizer.clearBuffer()

    def getNextFrame(self):
        if systemIsWindows:
            _, frame = self.camera.read()
        else:
            self.camera.capture(self.rawCapture,
                                format="bgr",
                                use_video_port=True)
            frame = self.rawCapture.array
            self.rawCapture.truncate(0)
        return frame

    def process_frame_loop(self):
        frame = self.getNextFrame()

        if frame is not None:
            self._process_frame(frame)
            self.displayFrame(frame)
        else:
            message.showerror("Error", "No frame found")

        self.mainWindowRefresh = self.imageContainer.after_idle(
            self.process_frame_loop)

    def button_changeColorRange(self):
        ColorRangePicker(self.camera, self.colorChangedEvent)
        if self.mainWindowRefresh is not None:
            self.imageContainer.after_cancel(self.mainWindowRefresh)

    def onColorChanged(self, lowerColor, upperColor):
        self.HandRecognizer.filter.set_color_range(lowerColor, upperColor)
        self.process_frame_loop()

    def onGestureRecognized(self, gestureName):
        if not systemIsWindows:
            if gestureName == "Play" and not self.Bluetoothplayer.Playing:
                self.Bluetoothplayer.play()
            if gestureName == "Pause" and self.Bluetoothplayer.Playing:
                self.Bluetoothplayer.pause()
            if gestureName == "Previous":
                self.Bluetoothplayer.prevTrack()
            if gestureName == "Next":
                self.Bluetoothplayer.nextTrack()
        else:
            print(gestureName)

    def camera_is_available(self):
        image = self.getNextFrame()

        # If we do not get anything, probably no camera is connected
        if image is None:
            return False

        # Check for black image (program started twice)
        if self._is_mostly_black(image):
            return False

        return True

    @staticmethod
    def _is_mostly_black(frame):
        average_color_per_row = numpy.average(frame, axis=0)
        average_color = numpy.average(average_color_per_row, axis=0)
        if average_color[0] < LITTLE_COLOR and average_color[
                1] < LITTLE_COLOR and average_color[2] < LITTLE_COLOR:
            return True
        return False