Пример #1
0
    def label_timeline(self, label):
        """Get timeline for a given label

        Parameters
        ----------
        label :

        Returns
        -------
        timeline : :class:`Timeline`
            Timeline made of all segments annotated with `label`

        """
        if label not in self.labels():
            return Timeline(uri=self.uri)

        if self._labelNeedsUpdate[label]:
            self._updateLabels()

            for l, hasChanged in self._labelNeedsUpdate.iteritems():
                if hasChanged:
                    self._labels[l] = Timeline(uri=self.uri)

            for segment, track, l in self.itertracks(label=True):
                if self._labelNeedsUpdate[l]:
                    self._labels[l].add(segment)

            self._labelNeedsUpdate = {l: False for l in self._labels}

        return self._labels[label].copy()
Пример #2
0
    def follow(self, target):
        current_time = time()

        user_following_tl = Timeline(self.client, following_key(self.user))
        user_following_tl.add(target, current_time)

        target_follower_tl = Timeline(self.client, follower_key(target))
        target_follower_tl.add(self.user, current_time)
Пример #3
0
    def test_free_frames_set(self):
        t = Timeline()
        self.assertEqual(set(), t.free_frames_set())

        t = Timeline(length=5)
        self.assertEqual(set(range(5)), t.free_frames_set())

        anim1 = Animation(np.ndarray((2, 1)))  # Anim with 2 frames
        se1 = ScoreSpaceElement(0, anim=anim1, window_start_frame=0)

        t.add_element(se1)  # Must reserve frames 0 and 1
        self.assertEqual(set(range(2, 5)), t.free_frames_set())
Пример #4
0
    def test_eq(self):
        t1 = Timeline(elements=[ScoreSpaceElement(0), ScoreSpaceElement(1)])
        t2 = Timeline(elements=[ScoreSpaceElement(0)])
        t3 = Timeline()
        t4 = Timeline(elements=[ScoreSpaceElement(0), ScoreSpaceElement(1)])
        t5 = Timeline(elements=[ScoreSpaceElement(1), ScoreSpaceElement(1)])

        self.assertEqual(t1, t4)
        self.assertNotEqual(t1, t2)
        self.assertNotEqual(t1, t3)
        self.assertNotEqual(t2, t3)
        self.assertNotEqual(t4, t5)
Пример #5
0
    def test_place(self):
        a1 = Animation(np.ndarray((2, 1)))

        scores = [
            [ScoreSpaceElement(0, 0, anim=a1), ScoreSpaceElement(3, 1, anim=a1), ScoreSpaceElement(5, 2, anim=a1), ScoreSpaceElement(6, 3, anim=a1)],
            [ScoreSpaceElement(1, 0, anim=a1), ScoreSpaceElement(2, 1, anim=a1), ScoreSpaceElement(4, 2, anim=a1), ScoreSpaceElement(5, 3, anim=a1)],
            [ScoreSpaceElement(4, 2, anim=a1), ScoreSpaceElement(6, 1, anim=a1), ScoreSpaceElement(10, 0, anim=a1)]
        ]

        timeline = Timeline(10)
        TimelinePlacer.layout_score_space_on_timeline(scores, timeline)
        desired_timeline = Timeline(length=10, elements=[ScoreSpaceElement(0, 0, anim=a1), ScoreSpaceElement(4, 2, anim=a1)])

        self.assertEqual(desired_timeline, timeline)
def timeline_json():
    headline = "Timeline Photo Headline"
    text = "this is the text"
    start_date = '2012,4,12'

    # find settings
    settings = Setting.query.order_by(desc(Setting.id)).all()
    if len(settings) > 0:
        setting = settings[0]
        headline = setting.headline
        text = setting.setting_text
        start_date = setting.start_date.replace("-", ",")

    # convert timeline's start date to datetime obj
    album_start_date = datetime.datetime.strptime(start_date, "%Y,%m,%d")

    # collect all photos
    tl = Timeline(headline, text, start_date)
    photos = Photo.query.filter(Photo.visibility == True).all()
    for photo in photos:
        dt = photo.start_date.replace("-", ",")

        # convert photo's start date to datetime obj
        photo_start_date = datetime.datetime.strptime(dt, "%Y,%m,%d")
        days_in_album = (photo_start_date - album_start_date).days + 1
        # get No.D after timeline's start date
        asset_caption = _("Day %(value)d", value=days_in_album)

        text = photo.photo_text + "<BR/><BR/><A href='%s'><i class='icon-zoom-in'></i>%s</A>" % (url_for("photos.show_html", filename=photo.filename), photo.filename)

        tl.add_date(startDate=dt, headline=photo.headline, asset_media=url_for("photos.show_thumb", filename=photo.filename), text=text, asset_caption=asset_caption)
    return tl.get_json()
Пример #7
0
    def handle_button_press(self, cr, rect, event_x, event_y):
        if self.is_expandable:
            if not self.in_animation:
                if self.has_expand:
                    text_width, text_height = self.shrink_button_width, self.shrink_button_height
                else:
                    text_width, text_height = self.expand_button_width, self.expand_button_height
                if is_in_rect((event_x, event_y),
                              (rect.width - (rect.width - self.label_wrap_width) / 2 - text_width,
                               rect.height - text_height,
                               text_width,
                               text_height)):

                    if self.has_expand:
                        start_position = self.expand_height
                        animation_distance = self.init_height - self.expand_height
                    else:
                        start_position = self.init_height
                        animation_distance = self.expand_height - self.init_height

                    self.in_animation = True

                    timeline = Timeline(self.animation_time, CURVE_SINE)
                    timeline.connect('update', lambda source, status:
                                     self.update(source,
                                                 status,
                                                 start_position,
                                                 animation_distance))
                    timeline.connect("completed", self.completed)
                    timeline.run()
        else:
            print "no expand button"
Пример #8
0
    def start_animation(self,
                        animation_time,
                        target_index=None,
                        direction="left"):
        if target_index is None:
            if self.active_index >= self.slider_numuber - 1:
                return False
                target_index = 0
            else:
                target_index = self.active_index + 1
        else:
            if target_index < self.active_index:
                direction = "right"

        if not self.in_animation:
            self.in_animation = True
            self.target_index = target_index

            self.timeline = Timeline(animation_time, CURVE_SINE)
            self.timeline.connect(
                "update", lambda source, status: self.update_animation(
                    source, status, direction))
            self.timeline.connect(
                "completed",
                lambda source: self.completed_animation(source, target_index))
            self.timeline.run()
        return True
Пример #9
0
    def test_reserve_frames(self):
        t = Timeline(length=7)
        self.assertEqual({0, 1, 2, 3, 4, 5, 6}, t.free_frames_set())
        self.assertEqual(False, t.full())

        t._reserve_frames(1, 2)
        self.assertEqual({0, 3, 4, 5, 6}, t.free_frames_set())

        with self.assertRaises(FramesAlreadyReservedError):
            t._reserve_frames(0, 2)

        t._reserve_frames(3, 3)
        self.assertEqual({0, 6}, t.free_frames_set())

        with self.assertRaises(FramesAlreadyReservedError):
            t._reserve_frames(3, 3)

        t._reserve_frames(0, 0)
        self.assertEqual({0, 6}, t.free_frames_set())

        t._reserve_frames(0, 1)
        self.assertEqual({6}, t.free_frames_set())
        self.assertEqual(False, t.full())

        t._reserve_frames(6, 1)
        self.assertEqual(set(), t.free_frames_set())
        self.assertEqual(True, t.full())
Пример #10
0
    def __init__(self, switchRadix, reconfig_penalty, timeline_params):

        self.switchRadix = switchRadix
        self.reconfig_penalty = reconfig_penalty
        self.switch_scheduler = Scheduler(switchRadix, reconfig_penalty)
        self.demand = Timeline(timeline_params)
        self.reconfig_delay = reconfig_penalty
        self.currConfig = None
Пример #11
0
def get_request_timeline(request):
    """Get a `Timeline` for request.

    This should ideally return the request.annotations['timeline'], creating it
    if necessary. However due to bug 623199 it instead using the adapter
    context for 'requests'. Once bug 623199 is fixed it will instead use the
    request annotations.

    :param request: A zope/launchpad request object.
    :return: A timeline.timeline.Timeline object for the request.
    """
    try:
        return webapp.adapter._local.request_timeline
    except AttributeError:
        return set_request_timeline(request, Timeline())
    # Disabled code path: bug 623199, ideally we would use this code path.
    return request.annotations.setdefault('timeline', Timeline())
Пример #12
0
 def graphicsView_reset(self):
     self.projects_list = db.get_projects()
     timeline = Timeline(self.projects_list)
     self.dates = timeline.generate_timeline()
     self.timeline_scene = self.create_scene()
     self.graphicsView.setScene(self.timeline_scene)
     self.projects = create_project_items(self.projects_list)
     self.show_projects()
     self.timeline_scene.itemClicked.connect(self.project_clicked)
Пример #13
0
Файл: tyrs.py Проект: Nic0/tyrs
def init_timelines():
    buffers = ('home', 'mentions', 'direct', 'search', 'user', 'favorite',
               'thread', 'user_retweet', 'list')
    timelines = {}
    for buff in buffers:
        timelines[buff] = Timeline(buff)
    container.add('timelines', timelines)
    container.add('buffers', buffers)
    completion = Completion()
    container.add('completion', completion)
Пример #14
0
    def test_construct(self):
        with self.assertRaises(ValueError):
            Timeline(length=-1)

        t = Timeline()
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 0)

        t = Timeline(length=5)
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 5)

        t = Timeline(elements=[])
        self.assertListEqual([], t.elements)
        self.assertEqual(t.length, 0)

        els = [ScoreSpaceElement(0), ScoreSpaceElement(1)]
        t = Timeline(elements=els)
        self.assertListEqual(els, t.elements)
 def clear(self):
     self.global_settings = {}
     PlateDesign.clear()
     #
     # TODO:
     #
     self.timeline = Timeline('TEST_STOCK')
     for matchstring, callbacks in self.subscribers.items():
         for callback in callbacks:
             callback(None)
Пример #16
0
def main():
    parser = CommandParser()
    try:
        command_list = parser.parse()
    except CommandParser.ParserException as e:
        sys.exit(e)

    router = Router(command_list)
    runner_class = router.get_runner()
    timeline = Timeline()
    runner_class(timeline).run(command_list)
Пример #17
0
    def test_daily(self):
        n_days = 10
        data = get_timed_data(n_days)

        timeline = Timeline(data)
        daily = timeline.split_daily()

        self.assertEqual(
            len(daily),
            n_days,
            msg='Testing with {} days should yield dictionary with {} items'.
            format(daily, daily))
Пример #18
0
    def OnInit(self):
        try:
            if self.options.record:
                # Connect to ROS master
                if not self.connect_to_ros():
                    raise Exception('recording requires connection to master')

                # Get filename to record to
                record_filename = time.strftime('%Y-%m-%d-%H-%M-%S.bag',
                                                time.localtime(time.time()))
                if self.options.name:
                    record_filename = self.options.name
                    if not record_filename.endswith('.bag'):
                        record_filename += '.bag'
                elif self.options.prefix:
                    prefix = self.options.prefix
                    if prefix.endswith('.bag'):
                        prefix = prefix[:-len('.bag')]
                    if prefix:
                        record_filename = '%s_%s' % (prefix, record_filename)

                rospy.loginfo('Recording to %s.' % record_filename)

            # Create main timeline frame
            self.frame = BaseFrame(None, 'rxbag', 'Timeline')
            self.frame.BackgroundColour = wx.WHITE
            self.frame.Bind(wx.EVT_CLOSE, lambda e: wx.Exit())

            scroll = wx.ScrolledWindow(self.frame, -1)
            scroll.BackgroundColour = wx.WHITE

            timeline = Timeline(scroll, -1)
            timeline.Size = (100, 100)

            self.frame.Show()
            self.SetTopWindow(self.frame)

            timeline.SetFocus()

            if self.options.record:
                timeline.record_bag(record_filename,
                                    all=self.options.all,
                                    topics=self.args,
                                    regex=self.options.regex,
                                    limit=self.options.limit)
            else:
                RxBagInitThread(self, timeline)

        except Exception, ex:
            print >> sys.stderr, 'Error initializing application:', ex
            #import traceback
            #traceback.print_exc()
            return False
Пример #19
0
    def graph_package_deps(self, p, pngname):
    
        tl = Timeline()
        
        def epoch(t): return t.toordinal() #float(t.strftime("%s"))
       
        def authColor(p): return hashColor(self.author(p))

        #depbar = "LightSkyBlue"
        #focalbar = "Yellow"
        reflbar = "PaleGoldenrod"
        

        vers_names = self.versions(p)

        # extend each version until the end of hte subsequent version
        for v,w in zip(vers_names[:-1], vers_names[1:]):     # Lost author for author color
            tl.span(p, epoch(self.dc[p][v]), epoch(self.dc[p][w]), p + ":" + v, v, authColor(p), None)
        vlast = vers_names[-1]
        tl.span(p, epoch(self.dc[p][vlast]), epoch(self.end_of_time), p + ":" + vlast, vlast, authColor(p), None)
    
        for dep in self.dependencies(p):
            for (ref,st,en) in self.dep_version_spans(p, dep):
                tl.span(dep, epoch(st), epoch(en), dep + "::" + ref, ref, reflbar, "bottom")
    
            depvers = self.dep_versions(p, dep)
            try:
                vn2 = self.versions(dep)
                for vv,ww in zip(vn2[:-1], vn2[1:]):
                    self.logwith( "deploop", vv,ww, self.dc[dep].keys())
                    tl.span(dep, epoch(self.dc[dep][vv]), epoch(self.dc[dep][ww]),
                            dep + ":" + vv, vv, authColor(dep), "top") 
                vvlast = vn2[-1]
                tl.span(dep, epoch(self.dc[dep][vvlast]), epoch(self.end_of_time),
                       dep + ":" + vvlast, vvlast, authColor(dep), "top") 
            except Exception, e:
                self.logwith("Exception processing dependency", dep, e)
            for vn in vers_names:
                if vn in depvers:
                    dep_ver = self.extractVersionLimiter(depvers[vn])
                    self.logwith( dep_ver)
                    destrec = tl.findByKey(dep + ":" + dep_ver)
                    srcrec = tl.findByKey(p + ":" + vn)
                    if len(destrec) > 0 and len(srcrec) > 0:
                        tl.connect(destrec[0], srcrec[0])
                        self.logwith( "version", vn, "of", p, "did link to dependency", dep, "version", dep_ver)
                    else:
                        self.logwith( "version", vn, "of", p, "***can't*** find dependency", \
                               dep, "version", dep_ver, "lendestrec=", len(destrec), "lensrcrec=", len(srcrec))
                else:
                    self.logwith(vn,"is not in",list(depvers))
                    self.logwith( "version", vn, "of", p, "did not update dependency on", dep)
Пример #20
0
    def test_process_and_get_timeline(self):
        p = AnimationRecognitionProcessor()
        p.process(self.data)
        timeline = p.get_timeline_with_placed_animations()

        desired_timeline = Timeline(
            length=5,
            elements=[
                ScoreSpaceElement(0, 0, self.lib_anim1),
                ScoreSpaceElement(4, 2, self.lib_anim2)
            ])

        self.assertEqual(desired_timeline, timeline)
Пример #21
0
    def graph_package_downstreams(self, p, pngname):
    
        tl = Timeline()
        
        def epoch(t): return t.toordinal() #float(t.strftime("%s"))
       
        def authColor(p): return hashColor(self.author(p))

        reflbar = "PaleGoldenrod"
        
        vers_names = self.versions(p)

        # Just show the first 20; the image gets too big otherwise
        for dep in list(self.reverse_dependencies(p))[:20]:
            for (ref,st,en) in self.dep_version_spans(dep, p):
                try:
                    vname = str(ref).strip()
                    if vname == "": vname = "*"
                except:
                    self.logwith("Could not correct version name ", ref)
                    vname = ref
                tl.span(dep, epoch(st), epoch(en), dep + "::" + ref, "-->" + vname, reflbar, "bottom", invisibleBar=True)
    
            depvers = self.dep_versions(dep, p)
            try:
                vn2 = self.versions(dep)
                for vv,ww in zip(vn2[:-1], vn2[1:]):
                    self.logwith( "deploop", vv,ww, self.dc[dep].keys())
                    tl.span(dep, epoch(self.dc[dep][vv]), epoch(self.dc[dep][ww]),
                            dep + ":" + vv, vv, authColor(dep), "top") 
                vvlast = vn2[-1]
                tl.span(dep, epoch(self.dc[dep][vvlast]), epoch(self.end_of_time),
                       dep + ":" + vvlast, vvlast, authColor(dep), "top") 
            except Exception, e:
                self.logwith("Exception processing dependency", dep, e)
            for vn in vers_names:
                if vn in depvers:
                    dep_ver = self.extractVersionLimiter(depvers[vn])
                    self.logwith( dep_ver)
                    destrec = tl.findByKey(dep + ":" + dep_ver)
                    srcrec = tl.findByKey(p + ":" + vn)
                    if len(destrec) > 0 and len(srcrec) > 0:
                        tl.connect(destrec[0], srcrec[0])
                        self.logwith( "version", vn, "of", p, "did link to dependency", dep, "version", dep_ver)
                    else:
                        self.logwith( "version", vn, "of", p, "***can't*** find dependency", \
                               dep, "version", dep_ver, "lendestrec=", len(destrec), "lensrcrec=", len(srcrec))
                else:
                    self.logwith(vn,"is not in",list(depvers))
                    self.logwith( "version", vn, "of", p, "did not update dependency on", dep)
Пример #22
0
def main():
    agent1 = Agent(1, (1, 1), name='agent1')
    agent2 = Agent(2, (2, 2), name='agent2')

    task1 = Task(3, (4, 3), name='task1')
    task2 = Task(5, (4, 5), name='task2')
    task3 = Task(10, (2, 4), name='task3')
    task4 = Task(4, (6, 4), name='task4')
    task5 = Task(12, (3, 4), name='task5')

    timeline = Timeline()

    t = 0
    agents = [agent1, agent2]
    tasks = [task1, task2, task3, task4, task5]
    # tasks = randomly_initialize_tasks(5)
    while tasks_are_available(tasks):
        # check for completion statuses
        for agent in agents:
            if t >= agent.getFinishTime():
                task = agent.getCurrTask()
                task.changeTaskCompletionStatus()  # mark task completed
                agent.changebusy(False)  # make agent free again

        for agent in agents:
            print(agent.getName(), 'is busy: ',
                  agent.getisBusy())  # check if agent is busy
            if agent.getisBusy() == False:
                nearest_task = find_nearest_unoccupied_task(
                    agent, tasks, agents)  # find nearest task
                nearest_task.changeTaskScheduleStatus(
                )  # change isTaskScheduled to True here
                agent.changebusy(True)  # agent is now busy
                (start_time, finish_time) = compute_start_and_finish_times(
                    agent, nearest_task, t)
                agent.updateAgentLocation(nearest_task.getloc())
                timeline.add_to_timeline(start_time, finish_time, agent,
                                         nearest_task)
                agent.setFinishTime(finish_time)
                agent.setCurrTask(nearest_task)
        t += .1
        print('time is ', t)

    print(timeline.sort_timeline())
    print(timeline.list_elements)
    # timeline.create_gant_chart()
    timeline.plot_path(agents)

    print('finished')
Пример #23
0
    def __init__(self, app=None, token=None, refresh_token=None, tokens=None):

        if tokens:
            token = tokens["access_token"]
            refresh_token = tokens["refresh_token"]

        self.app = app
        self.token = token
        self.refresh_token = refresh_token
        
        self.session = self.app.oauth.get_session(token=self.token)
        self.session.headers.update({'Content-Type': 'application/json'})

        self.timeline = Timeline(self)
        self.contacts = Contacts(self)
Пример #24
0
    def label_coverage(self, label):
        """

        Parameters
        ----------
        label :

        Returns
        -------

        """
        if label not in self.labels():
            return Timeline(uri=self.uri)

        return self.label_timeline(label).coverage()
Пример #25
0
    def __init__(self, file=None, verbose=False):
        # Create an empty workplace
        self.agents = []
        self.completed_tasks = []
        self.current_task = None
        self.tasks_todo = []
        self.time = 0
        self.timeline = Timeline()  # list of TimePoints
        self.coordination_times = {}
        self.Tperf = {}

        self.verbose = verbose

        if file:
            print("Reading from input file " + file + "...\n")
            self.parse_json(file, verbose)
Пример #26
0
    def setUp(self):
        self.client = Redis(decode_responses=True)
        self.client.flushdb()

        self.tl = Timeline(self.client, "blog::timeline")

        self.blogs = [
            {"id": "blog::100", "time": 1000},
            {"id": "blog::101", "time": 1500},
            {"id": "blog::102", "time": 1550},
            {"id": "blog::103", "time": 1700},
            {"id": "blog::104", "time": 1750},
            {"id": "blog::105", "time": 2500}
        ]

        self.reversed_blogs = list(reversed(self.blogs))
Пример #27
0
    def set_value(self, value):
        if (not self.in_animation) and value != self.value:
            self.start_value = self.value
            self.range = value - self.value
            times = int(abs(self.range)) * 10
            if times != 0:
                from timeline import Timeline, CURVE_SINE
                timeline = Timeline(times * 10, CURVE_SINE)
                timeline.connect("start", self.start_animation)
                timeline.connect("stop", self.stop_animation)
                timeline.connect("update", self.update_animation)
                timeline.run()
            else:
                self.value = value
                self.queue_draw()

        return False
Пример #28
0
    def start_animation(self, animation_time, index=None):
        # Update ticker with active index if option index is None.
        if index == None:
            if self.active_index >= self.image_number - 1:
                index = 0
            else:
                index = self.active_index + 1

        if not self.in_animiation:
            self.in_animiation = True
            self.target_index = index

            timeline = Timeline(animation_time, CURVE_SINE)
            timeline.connect('update', self.update_animation)
            timeline.connect("completed", lambda source: self.completed_animation(source, index))
            timeline.run()

        return True
Пример #29
0
    def __init__(self, address, port, username, ks, state):
        global KS, LOOP, USERNAME, TIMELINE, NODE, STATE
        global FOLLOWERS_CONS, REDIRECT_CONS

        TIMELINE = Timeline(username)
        USERNAME = username
        STATE = state
        KS = ks
        LOOP = asyncio.get_event_loop()
        self.address = address
        self.port = port
        self.id_generator = flake.generator(self.port)
        FOLLOWERS_CONS = {}
        REDIRECT_CONS = {}

        self.following_cons = {}
        self.listener = Listener(self.address, self.port)
        self.listener.daemon = True
        self.listener.start()
Пример #30
0
    def _updateLabels(self):

        # (re-)initialize changed label timeline
        for l, needsUpdate in self._labelNeedsUpdate.iteritems():
            if needsUpdate:
                self._labels[l] = Timeline(uri=self.uri)

        # fill changed label timeline
        for segment, track, l in self.itertracks(label=True):
            if self._labelNeedsUpdate[l]:
                self._labels[l].add(segment)

        self._labelNeedsUpdate = {l: False for l in self._labels}

        # remove "ghost" labels (i.e. label with empty timeline)
        labels = self._labels.keys()
        for l in labels:
            if not self._labels[l]:
                self._labels.pop(l)
                self._labelNeedsUpdate.pop(l)