Esempio n. 1
0
	def next(self,*largs):
		
		Clock.unschedule(self.next)
		
		if(self.screenManager.current == 'page1'):
			next = 'page2'
			page = self.page2
		else:
			next = 'page1'
			page = self.page1
			
		self.index += 1
		if self.index == len(self.photos):
			self.index = 0
		page.source = self.photos[self.index]
		page.background.scale = 1.0		
		self.screenManager.transition = self.transitions[random.randint(0, len(self.transitions) -1)]
		self.screenManager.current = next
		
		anim = Animation(
			scale=page.background.scale*1.3, 
			duration=15.0
		)
		
		Clock.schedule_once(self.next, 10)
		
		anim.start(page.background)
Esempio n. 2
0
 def my_screen(self):
     self.ws = WeatherScreen()
     self._image_path = os.path.join(graphics_dir, "na.png")
     self.ws.change_image(self._image_path, self._image_path)
     self._weather_updater()
     Clock.schedule_interval(self._weather_updater, 300)
     return self.ws
Esempio n. 3
0
File: main.py Progetto: mansxu/2048
	def move_topdown(self, top, from_keyboard=False):
		r = range(self.dim - 1, -1, -1) if top else range(self.dim)
		grid = self.grid
		moved = False

		for ix in range(self.dim):
			# get all the cube for the current line
			cubes = []
			for iy in r:
				cube = grid[ix][iy]
				if cube:
					cubes.append(cube)

			# combine them
			self.combine(cubes)

			# update the grid
			for iy in r:
				cube = cubes.pop(0) if cubes else None
				if grid[ix][iy] != cube:
					moved = True
				grid[ix][iy] = cube
				if not cube:
					continue
				pos = self.index_to_pos(ix, iy)
				if cube.pos != pos:
					cube.move_to(pos)

		if from_keyboard:
			return moved
		elif not self.check_end() and moved:
			Clock.schedule_once(self.spawn_number, .20)
Esempio n. 4
0
    def __init__(self, **kwargs):
        super(MainView, self).__init__(**kwargs)

        data_items = []
        data_items.append(DataItem())
        data_items.append(DataItem())
        data_items.append(DataItem())

        list_item_args_converter = lambda row_index, obj: {'text': obj.name,
                                                           'size_hint_y': None,
                                                           'height': 25}

        self.list_adapter = \
                ListAdapter(data=data_items,
                            args_converter=list_item_args_converter,
                            selection_mode='single',
                            propagate_selection_to_data=False,
                            allow_empty_selection=False,
                            cls=ListItemButton)

        self.list_view = ListView(adapter=self.list_adapter)

        self.add_widget(self.list_view)

        self.toggle = 'adding'

        Clock.schedule_interval(self.update_list_data, 1)
Esempio n. 5
0
def send_osc_go_on_signal(*args):
    osc_address = osc_go_address

    #send the gate on signal (ie the rising edge of the gate signal)
    send_osc_message(osc_address, [1.0])
    #queue up the gate off signal (ie the falling edge)
    Clock.schedule_once(send_osc_go_off_signal, _osc_go_delay)
Esempio n. 6
0
    def __init__(self, **kwargs):
        # Make sure opengl context exists
        EventLoop.ensure_window()

        self.canvas = RenderContext(use_parent_projection=True,
                                    use_parent_modelview=True)

        with self.canvas:
            self.fbo = Fbo(size=self.size)

        with self.fbo.before:
            PushMatrix()
        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            self._background_color = Color(*self.background_color)
            self.fbo_rectangle = Rectangle(size=self.size)
        with self.fbo.after:
            PopMatrix()

        super(EffectWidget, self).__init__(**kwargs)

        Clock.schedule_interval(self._update_glsl, 0)

        self.bind(size=self.refresh_fbo_setup,
                  effects=self.refresh_fbo_setup,
                  background_color=self._refresh_background_color)

        self.refresh_fbo_setup()
        self._refresh_background_color()  # In case thi was changed in kwargs
Esempio n. 7
0
 def __init__(self, cache_dir='cache', **kwargs):
     from kivy.base import EventLoop
     EventLoop.ensure_window()
     CACHE['directory'] = cache_dir
     self._invalid_scale = True
     self._tiles = []
     self._tiles_bg = []
     self._tilemap = {}
     self._layers = []
     self._default_marker_layer = None
     self._need_redraw_all = False
     self._transform_lock = False
     self.trigger_update(True)
     self.canvas = Canvas()
     self._scatter = MapViewScatter()
     self.add_widget(self._scatter)
     with self._scatter.canvas:
         self.canvas_map = Canvas()
         self.canvas_layers = Canvas()
     with self.canvas:
         self.canvas_layers_out = Canvas()
     self._scale_target_anim = False
     self._scale_target = 1.
     self._touch_count = 0
     Clock.schedule_interval(self._animate_color, 1 / 60.)
     self.lat = kwargs.get("lat", self.lat)
     self.lon = kwargs.get("lon", self.lon)
     super(MapView, self).__init__(**kwargs)
Esempio n. 8
0
	def build(self):
		self.service = None
		self.start_service()
		global RootApp
		RootApp = self

		# NavigationDrawer
		self.navigationdrawer = NavDrawer()

		# SidePanel
		side_panel = SidePanel()
		self.navigationdrawer.add_widget(side_panel)

		# MainPanel
		self.main_panel = MainPanel()

		# color picker
		self.color_selector = ColorSelector()

		# size selector
		self.size_selector = SizeSelector()

		self.navigationdrawer.anim_type = 'slide_above_simple'
		self.navigationdrawer.add_widget(self.main_panel)

		osc.init()
		oscid = osc.listen(port=3002)
		osc.bind(oscid, self.reCallback, '/date')
		Clock.schedule_interval(lambda *x: osc.readQueue(oscid), 0)

		return self.navigationdrawer
Esempio n. 9
0
File: main.py Progetto: diess/2048
    def move_leftright(self, right):
        r = range(3, -1, -1) if right else range(4)
        grid = self.grid
        moved = False

        for iy in range(4):
            # get all the cube for the current line
            cubes = []
            for ix in r:
                cube = grid[ix][iy]
                if cube:
                    cubes.append(cube)

            # combine them
            self.combine(cubes)

            # update the grid
            for ix in r:
                cube = cubes.pop(0) if cubes else None
                if grid[ix][iy] != cube:
                    moved = True
                grid[ix][iy] = cube
                if not cube:
                    continue
                pos = self.index_to_pos(ix, iy)
                if cube.pos != pos:
                    cube.move_to(pos)

        if not self.check_end() and moved:
            Clock.schedule_once(self.spawn_number, tempo)
Esempio n. 10
0
    def on_touch_down(self, touch):
        if self._touch:
            return super(ScrollView, self).on_touch_down(touch)
        if not self.collide_point(*touch.pos):
            return
        # support scrolling !
        if self._viewport and 'button' in touch.profile and \
                touch.button.startswith('scroll'):
            # distance available to move, if no distance, do nothing
            vp = self._viewport
            if vp.height > self.height:
                # let's say we want to move over 40 pixels each scroll
                d = (vp.height - self.height)
                d = self.scroll_distance / float(d)
                if touch.button == 'scrollup':
                    syd = self.scroll_y - d
                elif touch.button == 'scrolldown':
                    syd = self.scroll_y + d
                self.scroll_y = min(max(syd, 0), 1)
                return True

        self._touch = touch
        uid = self._get_uid()
        touch.grab(self)
        touch.ud[uid] = {
            'mode': 'unknown',
            'sx': self.scroll_x,
            'sy': self.scroll_y,
            'dt': None,
            'time': touch.time_start}
        Clock.schedule_once(self._change_touch_mode, self.scroll_timeout/1000.)
        return True
Esempio n. 11
0
    def _setup_default_tab(self):
        if self._default_tab in self.tab_list:
            return
        content = self._default_tab.content
        _tabs = self._tab_strip
        cls = self.default_tab_cls

        if not issubclass(cls, TabbedPanelHeader):
            raise TabbedPanelException('`default_tab_class` should be\
                subclassed from `TabbedPanelHeader`')

        # no need to instanciate if class is TabbedPanelHeader
        if cls != TabbedPanelHeader:
            self._current_tab = self._original_tab = self._default_tab = cls()

        default_tab = self.default_tab
        if self._original_tab == self.default_tab:
            default_tab.text = self.default_tab_text

        default_tab.height = self.tab_height
        default_tab.group = '__tab%r__' % _tabs.uid
        default_tab.state = 'down'
        default_tab.width = self.tab_width if self.tab_width else 100
        default_tab.content = content

        tl = self.tab_list
        if default_tab not in tl:
            _tabs.add_widget(default_tab, len(tl))

        if default_tab.content:
            self.clear_widgets()
            self.add_widget(self.default_tab.content)
        else:
            Clock.schedule_once(self._load_default_tab_content)
        self._current_tab = default_tab
Esempio n. 12
0
    def setupView(self):
        # Check gromacs version
        self.checkGromacVersion()

        #Check if folder is exits
        call('mkdir '+self.dataController.getdata('path '), shell=True)
        call('mkdir '+self.dataController.getdata('path ')+'/run', shell=True)
        call('mkdir '+self.dataController.getdata('path ')+'/output', shell=True)
        call('mkdir '+self.dataController.getdata('path ')+'/output/receptor', shell=True)
        call('mkdir '+self.dataController.getdata('path ')+'/output/ligand', shell=True)
        call('mkdir '+self.dataController.getdata('path ')+'/analyse', shell=True)
        
        runfolders = check_output('ls '+self.dataController.getdata('path ')+'/run/', shell = True).splitlines()
        if len(runfolders) > 0:
            popup = RemoveDialog()
            popup.open()
        else:
            call('rm -r '+self.dataController.getdata('path ')+'/run/*', shell=True)
            call('rm -r '+self.dataController.getdata('path ')+'/output/ligand/*', shell=True)
            call('rm -r '+self.dataController.getdata('path ')+'/output/receptor/*', shell=True)
            self.thread = Process(target= self.gromacsRun.main)
            self.thread.start()

        #Check log
        repeat_times = int(self.dataController.getdata('repeat_times '))
        self.progressUnit = 1000/(4.5 + repeat_times)/len(Variable.parsepdb.Ligands)
        self.progressPoint = 0
        self.dataController.setdata('status', '')
        Clock.schedule_interval(self.check_log, 5)
        Clock.schedule_interval(self.spin_progress, 0.05)
        # Clock.schedule_interval(self.pymol_log, 300)

        #close pymol
        self.pymol.cmd.window('hide')
Esempio n. 13
0
 def __init__(self, **kwargs):
     self.slides = []
     super(Slides, self).__init__(**kwargs)
     Window.bind(on_keyboard=self.on_keyboard)
     Clock.schedule_interval(self.increase_time, 1 / 30.0)
     Clock.schedule_once(self.init, 0)
     self.add_widget(SlidesForeground(slides=self))
Esempio n. 14
0
 def on_leave(self):
     Clock.unschedule(self.update)
     self.player1.score = 0
     self.player2.score = 0
     for c in self.pongfloat.children:
         if isinstance(c, WinLabel):
             self.pongfloat.remove_widget(c)
Esempio n. 15
0
 def delete_clock(self, touch, *args):
     # TODO: Fix touch_up passing through when popup dismissed.
     try:
         Clock.unschedule(touch.ud['event'])
     except KeyError:
         Logger.exception(
             'Application: Touch up passed through and unscheduled clock event could not be unscheduled. A bug...')
Esempio n. 16
0
    def on_enter(self):
        anim = Animation(
            opacity=1.0, duration=2.0)

#        anim &= Animation(size=[self.menu_text.size[0]+4, self.menu_text[1]+4], duration=.2)
        anim.start(self.story_text1)
        Clock.schedule_once(self.show_text2, 2.0)
Esempio n. 17
0
 def __init__(self):
     android.accelerometer_enable(True)
     Clock.schedule_interval(self.detect_motion, 0.1)
     self.last = None
     self.history = deque()
     self.shake_callback = None
     self.enabled = True
Esempio n. 18
0
 def _sign_tx(self, tx, password, on_success, on_failure):
     try:
         self.wallet.sign_transaction(tx, password)
     except InvalidPassword:
         Clock.schedule_once(lambda dt: on_failure(_("Invalid PIN")))
         return
     Clock.schedule_once(lambda dt: on_success(tx))
Esempio n. 19
0
 def __init__(self, **kwargs):
     self.register_event_type('on_subprocess_done')
     super(KivyConsole, self).__init__(**kwargs)
     # initialisations
     self.txtinput_command_line_refocus = False
     self.txtinput_run_command_refocus = False
     self.win = None
     self.scheduled = False
     self.command_history = []
     self.command_history_pos = 0
     self.command_status = 'closed'
     if sys.version_info >= (3, 0):
         self.cur_dir = os.getcwd()
     else:
         self.cur_dir = os.getcwdu()
     self.stdout = std_in_out(self, 'stdout')
     self.stdin = std_in_out(self, 'stdin')
     # self.stderror = stderror(self)
     # delayed initialisation
     Clock.schedule_once(self._initialize)
     self_change_txtcache = self._change_txtcache
     _trig = Clock.create_trigger(self_change_txtcache)
     self.bind(textcache=_trig)
     self._hostname = 'unknown'
     try:
         if hasattr(os, 'uname'):
             self._hostname = os.uname()[1]
         else:
             self._hostname = os.environ.get('COMPUTERNAME', 'unknown')
     except Exception:
         pass
     self._username = os.environ.get('USER', '')
     if not self._username:
         self._username = os.environ.get('USERNAME', 'unknown')
Esempio n. 20
0
    def build(self):

        self.settings_cls = SettingsWithSidebar

        game = PlanetGame(do_rotation=False,do_translation=False)
        # Settings come in as unicode!
        sunmass = float(App.get_running_app().config.get('planetapp','defaultsunmass'))
        game.sunmass = sunmass
        game.gravity = float(App.get_running_app().config.get('planetapp','gravity'))
        game.planetmass = float(App.get_running_app().config.get('planetapp','planetmass'))
        game.resetmass = float(App.get_running_app().config.get('planetapp','resetmass'))

        game.add_planet(True, (100,100), (0,0), sunmass, 10, (1,1,1))
        
        Clock.schedule_interval(game.update, 1.0 / 120.0)

        self.root = PlanetGameLayout()
        self.root.add_widget(game)
        

        b = Button(text="Reset",size_hint=(.3,.05),pos_hint={'x':.7,'y':0})
        b.bind(on_press=self.root.clear_planets)
        self.root.add_widget(b)
        b2 = SettingsButton(text="Settings",size_hint=(.3,.05),pos_hint={'x':.4,'y':0})
        self.root.add_widget(b2)

        b3 = Button(text="Next",size_hint=(.3,.05),pos_hint={'x':.1,'y':0})
        b3.bind(on_press=self.root.next_trajectory)
        self.root.add_widget(b3)
        self.root.reset_game()
Esempio n. 21
0
    def __init__(self, **kwargs):
        # initialize variables
        self._clipboard = Clipboard
        self.info_bubble = None
        self.qrscanner = None
        self.nfcscanner = None
        self.tabs = None
        self.is_exit = False

        super(ElectrumWindow, self).__init__(**kwargs)

        title = _('Electrum App')
        self.electrum_config = config = kwargs.get('config', None)
        self.language = config.get('language', 'en')
        self.network = network = kwargs.get('network', None)
        self.plugins = kwargs.get('plugins', [])

        self.gui_object = kwargs.get('gui_object', None)

        #self.config = self.gui_object.config
        self.contacts = Contacts(self.electrum_config)
        self.invoices = InvoiceStore(self.electrum_config)

        # create triggers so as to minimize updation a max of 2 times a sec
        self._trigger_update_wallet =\
            Clock.create_trigger(self.update_wallet, .5)
        self._trigger_update_status =\
            Clock.create_trigger(self.update_status, .5)
        self._trigger_notify_transactions = \
            Clock.create_trigger(self.notify_transactions, 5)
Esempio n. 22
0
 def __init__(self, **kwargs):
     super(TheCatWidget, self).__init__(**kwargs)
     Clock.schedule_interval(self.Update, 1.0 / 60.0)
     
     self._StateMachine = statemachine.StateMachine(self)
     self._StateMachine.SetState(statemachine.StateCatWander())
     self._CatPettingCounter = 0
Esempio n. 23
0
    def __init__(self, **kwargs):
        super(Graph, self).__init__(**kwargs)

        self._mesh = Mesh(mode='lines')
        self._mesh_rect = Mesh(mode='line_strip')
        val = 0.25
        self.canvas.add(Color(1 * val, 1 * val, 1 * val))
        self.canvas.add(self._mesh)
        self.canvas.add(Color(1, 1, 1))
        self.canvas.add(self._mesh_rect)
        mesh = self._mesh_rect
        mesh.vertices = [0] * (5 * 4)
        mesh.indices = [k for k in xrange(5)]

        self._plot_area = StencilView()
        self.add_widget(self._plot_area)

        self._trigger = Clock.create_trigger(self._redraw_all)
        self._trigger_size = Clock.create_trigger(self._redraw_size)

        self.bind(center=self._trigger_size, padding=self._trigger_size,
                  font_size=self._trigger_size, plots=self._trigger_size,
                  x_grid=self._trigger_size, y_grid=self._trigger_size,
                  draw_border=self._trigger_size)
        self.bind(xmin=self._trigger, xmax=self._trigger,
                  xlog=self._trigger, x_ticks_major=self._trigger,
                  x_ticks_minor=self._trigger,
                  xlabel=self._trigger, x_grid_label=self._trigger,
                  ymin=self._trigger, ymax=self._trigger,
                  ylog=self._trigger, y_ticks_major=self._trigger,
                  y_ticks_minor=self._trigger,
                  ylabel=self._trigger, y_grid_label=self._trigger)
        self._trigger()
Esempio n. 24
0
    def render_boggle_game_screen(self):
        logging.info("Rendering game screen.")

        self.clear_widgets()

        def handle_swipe_callback(self):
            # TODO: add in swipes or keyboard for user to input words.
            pass

        self.solve_boggle.set_board(self.num_columns, self.num_rows, None)
        logging.info("Solve Boggle created.")
        self.render_boggle_layout("", handle_swipe_callback, self.grid)
        logging.info("About to loop through buttons.")
        for i, button in enumerate(self.buttons):
            if i not in self.ignore:
                button.text = "[size=%s]%s[/size]" % (int(self.font), self.solve_boggle.boggle.boggle_array[i].upper())
            else:
                button.text = ""

        timer = Label(text="%s" % self.game_time, size_hint=(1, 1.0/self.num_rows), font_size=self.font)

        def timer_callback(dt):
            timer.text = str(int(timer.text) -1)
            if int(timer.text) == 0:
                self.render_boggle_solution_screen()

        Clock.schedule_interval(timer_callback, 1)

        self.add_widget(self.grid)
        self.add_widget(timer)

        # TODO: make this part of a function for a timer callback so it doesn't take time away from displaying the screen.
        self.words = self.solve_boggle.solve(ignore_indexes=self.ignore)
        logging.info("Got words.")
Esempio n. 25
0
 def build(self):
   """Initializes the user interface and starts timed events."""
   #TODO: Reorganize and consolidate; make necessary helper functions
   self.title = 'Open Lighting Architecture'
   self.ui_queue = Queue()
   self.layout = BoxLayout(orientation='vertical')
   self.selected_universe_service = UniverseSelectedService()
   self.ola_listener = OLAListener(self.ui_queue,
                                   self.create_select_server,
                                   self.create_ola_client,
                                   self.start_ola,
                                   self.stop_ola)
   #Screen creation and layout placing
   self.screen_tabs = ScreenTabs()
   self.monitor_screen = MonitorScreen(self.ola_listener,
                                       self.selected_universe_service,
                                       name='DMX Monitor')
   self.console_screen = ConsoleScreen(self.ola_listener,
                                       self.selected_universe_service,
                                       name='DMX Console')
   self.devsets = MainScreen(self.ola_listener,
                             self.selected_universe_service,
                             name='Device Settings')
   self.screen_tabs.ids.monitor_screen.add_widget(self.monitor_screen)
   self.screen_tabs.ids.console_screen.add_widget(self.console_screen)
   self.screen_tabs.ids.settings_screen.add_widget(self.devsets)
   self.layout.add_widget(self.screen_tabs)
   Clock.schedule_interval(lambda dt: self.display_tasks(),
                           self.EVENT_POLL_INTERVAL)
   Clock.schedule_interval(self._update_clock, 1 / 60.)
   return self.layout
Esempio n. 26
0
 def _on_click(self, sid):
     if sid == 'msgbox':
         XMessage(text='It could be your Ad', title='XMessage demo')
     elif sid == 'error':
         XError(text='Don`t panic! Its just the XError demo.')
     elif sid == 'confirm':
         XConfirmation(text='Do you see a confirmation?',
                       on_dismiss=self._callback)
     elif sid == 'progress':
         self._o_popup = XProgress(title='PopupProgress demo',
                                   text='Processing...', max=200)
         Clock.schedule_once(self._progress_test, .1)
     elif sid == 'input':
         XTextInput(title='Edit text', text='I\'m a text',
                    on_dismiss=self._callback)
     elif sid == 'notes':
         XNotes(title='Edit notes', on_dismiss=self._callback_notes,
                lines=['Text', 'Too many text...', 'Yet another row.'])
     elif sid == 'slider':
         self._o_popup = XSlider(
             min=.4, max=.9, value=.5, size_hint=(.6, .5),
             title_template='Slider test, Value: %0.2f',
             buttons=['Horizontal', 'Vertical', 'Close'],
             on_change=self._slider_value, on_dismiss=self._slider_click)
     elif sid == 'login':
         XAuthorization(
             on_dismiss=self._callback, login='******',
             required_fields={'login': '******', 'password': '******'},
             password='******')
Esempio n. 27
0
 def __init__(self, **kwargs):
     super(KYRScreenManager, self).__init__(**kwargs)
     self.loadAssets()
     self.room1 = KYRScreen(name='room1',
                            bg = 'assets/art/room1.png',
                            music = self.overworld,
                            startLocations = dict(top = (512, 96),
                                                  bottom = (512, 416),
                                                  left = (928, 256),
                                                  right = (96, 256)
                             )) # inverse directions, based on direction you enter from
     self.room2 = KYRScreen(name='room2',
                            bg = 'assets/art/room2.png',
                            startLocations = dict(top = (512, 96),
                                                  bottom = (512, 416),
                                                  left = (928, 256),
                                                  right = (96, 256)
                             ))
     
     #self.add_widget(room1)
     #self.add_widget(room2)
     self.buildLocationEvent()
     self.transition=WipeTransition()
     
     self.switch_to(self.room1)
     self.room1.isCurrent = True    
     
     Clock.schedule_interval(self.updatePlayerLocation, 0.5)
Esempio n. 28
0
    def add_term_widget(self, cfg):
        layout = TermBoxLayout()

        ti = TabbedPanelHeader()
        ti.text = ' '.join([str(len(self.root_widget.term_panel.tab_list) + 1), 'Terminal'])
        ti.content = layout
        ti.size_hint = (1,1)

        self.root_widget.term_panel.add_widget(ti)

        session = create_session(cfg, self.create_terminal(cfg))

        term_widget = TermTextInput(session)
        term_widget.size_hint = (1, 1)
        term_widget.pos_hint = {'center_y':.5, 'center_x':.5}

        layout.add_widget(term_widget)
        layout.term_widget = term_widget

        ti.term_widget = term_widget
        ti.session = session

        ti.session.term_widget = term_widget
        ti.session.terminal.term_widget = term_widget

        Clock.unschedule(self.root_widget.term_panel._load_default_tab_content)
        self.switch_to_tab(ti)

        conn_str = cfg.get_conn_str()

        if conn_str in self.conn_history:
            self.conn_history.remove(conn_str)

        self.conn_history.insert(0, conn_str)
Esempio n. 29
0
    def __init__(self, **kwargs):
        kwargs.setdefault('filename', None)
        kwargs.setdefault('eos', 'stop')
        kwargs.setdefault('async', True)
        kwargs.setdefault('autoplay', False)

        super(VideoBase, self).__init__()

        self._wantplay = False
        self._buffer = None
        self._filename = None
        self._texture = None
        self._volume = 1.
        self._state = ''

        self._autoplay = kwargs.get('autoplay')
        self._async = kwargs.get('async')
        self.eos = kwargs.get('eos')
        if self.eos == 'pause':
            Logger.warning("'pause' is deprecated. Use 'stop' instead.")
            self.eos = 'stop'
        self.filename = kwargs.get('filename')

        Clock.schedule_interval(self._update, 1 / 30.)

        if self._autoplay:
            self.play()
Esempio n. 30
0
    def on_scroll_start(self, touch, check_children=True):
        if check_children:
            touch.push()
            touch.apply_transform_2d(self.to_local)
            if self.dispatch_children('on_scroll_start', touch):
                touch.pop()
                return True
            touch.pop()

        if not self.collide_point(*touch.pos):
            touch.ud[self._get_uid('svavoid')] = True
            return
        if self.disabled:
            return True
        if self._touch or (not (self.do_scroll_x or self.do_scroll_y)):
            return self.simulate_touch_down(touch)

        # handle mouse scrolling, only if the viewport size is bigger than the
        # scrollview size, and if the user allowed to do it
        vp = self._viewport
        if not vp:
            return True
        scroll_type = self.scroll_type
        ud = touch.ud
        scroll_bar = 'bars' in scroll_type

        # check if touch is in bar_x(horizontal) or bar_y(vertical)
        width_scrollable = vp.width > self.width
        height_scrollable = vp.height > self.height

        d = {
            'bottom': touch.y - self.y - self.bar_margin,
            'top': self.top - touch.y - self.bar_margin,
            'left': touch.x - self.x - self.bar_margin,
            'right': self.right - touch.x - self.bar_margin
        }

        ud['in_bar_x'] = (scroll_bar and width_scrollable
                          and (0 <= d[self.bar_pos_x] <= self.bar_width))
        ud['in_bar_y'] = (scroll_bar and height_scrollable
                          and (0 <= d[self.bar_pos_y] <= self.bar_width))

        if vp and 'button' in touch.profile and \
                touch.button.startswith('scroll'):
            btn = touch.button
            m = self.scroll_wheel_distance
            e = None

            if ((btn == 'scrolldown' and self.scroll_y >= 1)
                    or (btn == 'scrollup' and self.scroll_y <= 0)
                    or (btn == 'scrollleft' and self.scroll_x >= 1)
                    or (btn == 'scrollright' and self.scroll_x <= 0)):
                return False

            if (self.effect_x and self.do_scroll_y and height_scrollable
                    and btn in ('scrolldown', 'scrollup')):
                e = self.effect_x if ud['in_bar_x'] else self.effect_y

            elif (self.effect_y and self.do_scroll_x and width_scrollable
                  and btn in ('scrollleft', 'scrollright')):
                e = self.effect_y if ud['in_bar_y'] else self.effect_x

            if e:
                if btn in ('scrolldown', 'scrollleft'):
                    if self.smooth_scroll_end:
                        e.velocity -= m * self.smooth_scroll_end
                    else:
                        e.value = max(e.value - m, e.min)
                        e.velocity = 0
                elif btn in ('scrollup', 'scrollright'):
                    if self.smooth_scroll_end:
                        e.velocity += m * self.smooth_scroll_end
                    else:
                        e.value = min(e.value + m, e.max)
                        e.velocity = 0
                touch.ud[self._get_uid('svavoid')] = True
                e.trigger_velocity_update()
            return True

        in_bar = ud['in_bar_x'] or ud['in_bar_y']
        if scroll_type == ['bars'] and not in_bar:
            return self.simulate_touch_down(touch)

        if in_bar:
            if (ud['in_bar_y'] and not self._touch_in_handle(
                    self._handle_y_pos, self._handle_y_size, touch)):
                self.scroll_y = (touch.y - self.y) / self.height
            elif (ud['in_bar_x'] and not self._touch_in_handle(
                    self._handle_x_pos, self._handle_x_size, touch)):
                self.scroll_x = (touch.x - self.x) / self.width

        # no mouse scrolling, so the user is going to drag the scrollview with
        # this touch.
        self._touch = touch
        uid = self._get_uid()

        ud[uid] = {
            'mode': 'unknown',
            'dx': 0,
            'dy': 0,
            'user_stopped': in_bar,
            'frames': Clock.frames,
            'time': touch.time_start
        }

        if self.do_scroll_x and self.effect_x and not ud['in_bar_x']:
            self._effect_x_start_width = self.width
            self.effect_x.start(touch.x)
            self._scroll_x_mouse = self.scroll_x
        if self.do_scroll_y and self.effect_y and not ud['in_bar_y']:
            self._effect_y_start_height = self.height
            self.effect_y.start(touch.y)
            self._scroll_y_mouse = self.scroll_y

        if not in_bar:
            Clock.schedule_once(self._change_touch_mode,
                                self.scroll_timeout / 1000.)
        return True
Esempio n. 31
0
 def on_pre_enter(self):
     global fps, enemy_fps, score
     score = 0
     Clock.schedule_interval(self.update, 1.0 / fps)
     Clock.schedule_interval(self.enemy_update, 1.0 / enemy_fps)
Esempio n. 32
0
 def __init__(self, **kwargs):
     self._trigger_update_tab_bar = \
         Clock.schedule_once(self._update_tab_bar, 0)
     super().__init__(**kwargs)
Esempio n. 33
0
 def __init__(self, **kwargs):
     # enables access to properties and methods to its parent class
     super(CloudLayout, self).__init__(**kwargs)
     # starts a clock the spawns a cloud every 2 seconds
     Clock.schedule_interval(self.spawn_cloud, 2.)
Esempio n. 34
0
    def __init__(self, **kwargs):
        # access methods and properties of the parent class
        super(PopCount, self).__init__(**kwargs)
        global popCount, missCount, missesAllowed, bestPopCount

        # every 50 pops, 10 more misses are allowed. When these lives are added this variable because True to prevent
        # the game from adding more lives since a clock checks if the pig popped 50 balloons 60fps and would continue
        # adding lives until another balloon is popped.
        self.added_lives = False
        # the pop icon y position is located roughly 8% down from the top of the screen
        self.pop_position_y = Window.height - Window.height * .0846
        # the pop icon height is 7% of screen height
        self.popHeight = Window.height * 0.07
        # ensure the balloon image keeps its original width:height ratio
        self.popWidth = self.popHeight * 97 / 103
        # place the icon slightly to the right of the the left side of the screen
        self.pop_position_x = self.popWidth / 2

        # sets the width of the pop count text box proportional to the its icon's width, which is proportional to the
        # device size
        self.pop_label_width = 350 * self.popWidth / 54.5836
        # create a Label object with pre-set attributes
        self.pop_label = Label(
            # the label is located to the right of the pop icon with a 40% margin. It has the same y pos as the icon.
            pos=(self.pop_position_x + self.popWidth * 1.4,
                 self.pop_position_y),
            # the text this label says is the pop count
            text=str(popCount),
            # set the text box to the size of the calculated label width and the height the same height as the icon.
            size=(self.pop_label_width, self.popHeight),
            # the size of the text is the same as the line above. These two lines create the text box.
            text_size=(self.pop_label_width, self.popHeight),
            # since the game is written in a FloatLayout kivy likes to know if the object should be position between
            # 0-100% from the right size of the screen, this is the size hint. Since we know the exact x position,
            # that is already proportional to device size pass in None.
            size_hint_x=None,
            # 23sp size of the text in the testing environment. This text size is proportional to the height of
            # of the screen.
            font_size=str(23 * self.popWidth / 54.5836) + "sp",
            # sets the font to a pixelated arcade font located in this projects directory
            font_name="PressStart2P.ttf",
            # align text to the left of the text area horizontally
            halign='left',
            # align text to the center of the text area vertically
            valign='center')

        # spawns the miss icon left of the label with a 20% margin
        self.miss_position_x = self.pop_position_x + self.pop_label_width * 1.2
        # sets the y position of the miss icon to the same as the pop label y
        self.miss_position_y = self.pop_position_y
        # sets the miss icon width to the same value as the pop width
        self.missWidth = self.popWidth
        # sets the miss icon height to the same value as the pop height
        self.missHeight = self.popHeight

        # creates a label with pre-set attributes
        self.misses_label = Label(
            # the label is located to the right of the pop label with a 40% margin. It has the same y pos as the icon.
            pos=(self.miss_position_x + self.missWidth * 1.4,
                 self.miss_position_y),
            # concatenates the miss count with a "/" and the miss allowed
            text=str(missCount) + "/" + str(missesAllowed),
            # width and height of textbox set to the same value as the pop count text box.
            size=(self.pop_label_width, self.popHeight),
            # same as size of the label. Creates the textbox.
            text_size=(self.pop_label_width, self.popHeight),
            # since the game is written in a FloatLayout kivy likes to know if the object should be position between
            # 0-100% from the right size of the screen, this is the size hint. Since we know the exact x position,
            # that is already proportional to device size pass in None.
            size_hint_x=None,
            # 23sp size of the text in the testing environment. This text size is proportional to the height of
            # of the screen.
            font_size=str(23 * self.popWidth / 54.5836) + "sp",
            # sets the font to a pixelated arcade font located in this projects directory
            font_name="PressStart2P.ttf",
            # align text to the left of the text area horizontally
            halign='left',
            # align text to the center of the text area vertically
            valign='center')
        # creates the best pop count label
        self.best_label = Label(
            # located at the same x position at the pop icon and beneath the pop icon.
            pos=(self.pop_position_x, self.pop_position_y - self.popHeight),
            # displays the text Best: bestPopCount
            text=str("Best:" + str(bestPopCount)),
            # creates the textbox size as the same as the pop count label's textbox
            size=(self.pop_label_width, self.popHeight),
            # creates the textbox size as the same as the pop count label's textbox
            text_size=(self.pop_label_width, self.popHeight),
            # do not place the x position proportional to the device size since it is already hard-coded into an x
            # value
            size_hint_x=None,
            # set the font size to be smaller than the pop count label and make it proportional to the device size
            font_size=str(14 * self.popWidth / 54.5836) + "sp",
            # sets the font to a pixelated arcade font located in this projects directory
            font_name="PressStart2P.ttf",
            # align text to the left of the text area horizontally
            halign='left',
            # align text to the center of the text area vertically
            valign='center',
            # set the color of the font to white
            color=(1, 1, 1, 1))
        # add the labels and icons to the canvas
        self.add_widget(self.best_label)
        self.add_widget(self.pop_label)
        self.add_widget(self.misses_label)
        # start a clock to continuously update the text of the labels
        Clock.schedule_interval(self.update_text, 1 / 60.)
Esempio n. 35
0
 def on_leave(self):
     Clock.unschedule(self.update)
Esempio n. 36
0
 def on_pre_enter(self):
     Clock.schedule_interval(self.update, 1.0 / 60)
Esempio n. 37
0
	def __init__ ( self, **kwargs ):
		super ( Ostacolo, self ).__init__ ( **kwargs )

		self.offset = 0
		self.velocity_x = 2
		self.move_event = Clock.schedule_interval ( self.movimento, 0 ) #1.0 / 60.0 )
Esempio n. 38
0
 def on_stop(*l):
     if duration:
         Clock.schedule_once(self.hide, duration + .5)
Esempio n. 39
0
    def analyze_extra(self, mode, **kwargs):
        stones = {s.coords for s in self.stones}
        cn = self.current_node

        if mode == "stop":
            self.katrain.pondering = False
            for e in set(self.engines.values()):
                e.stop_pondering()
                e.terminate_queries()
            return

        engine = self.engines[cn.next_player]
        Clock.schedule_once(self.katrain.analysis_controls.hints.activate, 0)

        if mode == "ponder":
            cn.analyze(
                engine,
                ponder=True,
                priority=PRIORITY_EXTRA_ANALYSIS,
                region_of_interest=self.region_of_interest,
                time_limit=False,
            )
            return

        if mode == "extra":
            visits = cn.analysis_visits_requested + engine.config["max_visits"]
            self.katrain.controls.set_status(i18n._("extra analysis").format(visits=visits), STATUS_ANALYSIS)
            cn.analyze(
                engine,
                visits=visits,
                priority=PRIORITY_EXTRA_ANALYSIS,
                region_of_interest=self.region_of_interest,
                time_limit=False,
            )
            return

        if mode == "game":
            nodes = self.root.nodes_in_tree
            only_mistakes = kwargs.get("mistakes_only", False)
            threshold = self.katrain.config("trainer/eval_thresholds")[-4]
            if "visits" in kwargs:
                visits = kwargs["visits"]
            else:
                min_visits = min(node.analysis_visits_requested for node in nodes)
                visits = min_visits + engine.config["max_visits"]
            for node in nodes:
                max_point_loss = max(c.points_lost or 0 for c in [node] + node.children)
                if not only_mistakes or max_point_loss > threshold:
                    node.analyze(engine, visits=visits, priority=-1_000_000, time_limit=False, report_every=None)
            self.katrain.controls.set_status(i18n._("game re-analysis").format(visits=visits), STATUS_ANALYSIS)
            return

        elif mode == "sweep":
            board_size_x, board_size_y = self.board_size

            if cn.analysis_exists:
                policy_grid = (
                    var_to_grid(self.current_node.policy, size=(board_size_x, board_size_y))
                    if self.current_node.policy
                    else None
                )
                analyze_moves = sorted(
                    [
                        Move(coords=(x, y), player=cn.next_player)
                        for x in range(board_size_x)
                        for y in range(board_size_y)
                        if (policy_grid is None and (x, y) not in stones) or policy_grid[y][x] >= 0
                    ],
                    key=lambda mv: -policy_grid[mv.coords[1]][mv.coords[0]],
                )
            else:
                analyze_moves = [
                    Move(coords=(x, y), player=cn.next_player)
                    for x in range(board_size_x)
                    for y in range(board_size_y)
                    if (x, y) not in stones
                ]
            visits = engine.config["fast_visits"]
            self.katrain.controls.set_status(i18n._("sweep analysis").format(visits=visits), STATUS_ANALYSIS)
            priority = PRIORITY_SWEEP
        elif mode in ["equalize", "alternative", "local"]:
            if not cn.analysis_complete and mode != "local":
                self.katrain.controls.set_status(i18n._("wait-before-extra-analysis"), STATUS_INFO, self.current_node)
                return
            if mode == "alternative":  # also do a quick update on current candidates so it doesn't look too weird
                self.katrain.controls.set_status(i18n._("alternative analysis"), STATUS_ANALYSIS)
                cn.analyze(engine, priority=PRIORITY_ALTERNATIVES, time_limit=False, find_alternatives="alternative")
                visits = engine.config["fast_visits"]
            else:  # equalize
                visits = max(d["visits"] for d in cn.analysis["moves"].values())
                self.katrain.controls.set_status(i18n._("equalizing analysis").format(visits=visits), STATUS_ANALYSIS)
            priority = PRIORITY_EQUALIZE
            analyze_moves = [Move.from_gtp(gtp, player=cn.next_player) for gtp, _ in cn.analysis["moves"].items()]
        else:
            raise ValueError("Invalid analysis mode")

        for move in analyze_moves:
            if cn.analysis["moves"].get(move.gtp(), {"visits": 0})["visits"] < visits:
                cn.analyze(
                    engine, priority=priority, visits=visits, refine_move=move, time_limit=False
                )  # explicitly requested so take as long as you need
Esempio n. 40
0
 def close(self):
     self.text_input_popup.dismiss()
     Window.release_all_keyboards()
     Clock.schedule_once(self._schedule_validate, .2)
Esempio n. 41
0
def on_pre_enter(self):
    """
    This method adds image button to go back as well as it updates profile picture widget and so on.
    :param self: It is for handling class structure.
    :return:
    """

    # layout_menubar = self.ids["layout_menubar"]
    # layout_menubar.remove_widget(self.btn_logout)
    # layout_menubar.add_widget(image_button.add_button("data/img/ico_back.png",
    #                                                   "data/img/ico_back_select.png",
    #                                                   .075,
    #                                                   {"x": 0, "y": 0},
    #                                                   self.on_back
    #                                                   )
    #                           )

    try:
        self.check_connection.cancel()
    except:
        Clock.schedule_once(
            partial(check_connection.is_alive, self.ids["ico_connection"]))
        self.check_connection = Clock.schedule_interval(
            partial(check_connection.is_alive, self.ids["ico_connection"]),
            5.0)

    info_type = Cache.get("data", "type")
    self.ids["txt_type"].text = info_type.title() + " Statistics"

    info_select = Cache.get("data", "select")
    self.ids["txt_select"].text = info_select

    if info_type == "class":
        statistics = database_api.getStats(Cache.get("lect", "code"), None)
    else:
        statistics = database_api.getStats(Cache.get("lect", "code"),
                                           info_select)

    pyplot.figure(1)
    pyplot.bar(statistics.keys(), statistics.values(), color="blue")
    pyplot.xlabel("Y")
    pyplot.ylabel("X")
    pyplot.grid(True)
    pyplot.axes().set_aspect("equal")
    pyplot.tight_layout()
    self.ids["layout_graph_top_right"].add_widget(
        FigureCanvasKivyAgg(pyplot.gcf()))

    pyplot.figure(2)
    pyplot.plot(statistics.keys(), statistics.values(), color="green")
    pyplot.xlabel("Y")
    pyplot.ylabel("X")
    pyplot.grid(True)
    pyplot.axes().set_aspect("equal")
    pyplot.tight_layout()
    self.ids["layout_graph_bottom_right"].add_widget(
        FigureCanvasKivyAgg(pyplot.gcf()))

    pyplot.figure(3)
    pyplot.pie(statistics.values(),
               labels=statistics.keys()
               # explode=(0.1, 0, 0)
               )
    pyplot.grid(True)
    pyplot.axes().set_aspect("equal")
    pyplot.tight_layout()
    self.ids["layout_graph_bottom_left"].add_widget(
        FigureCanvasKivyAgg(pyplot.gcf()))

    self.ids["txt_analysis"].text = "TODO"
Esempio n. 42
0
 def __init__(self, **kwargs):
     super(SurveyQuestionYesNo, self).__init__(**kwargs)
     self.setup_no_answer_button()
     Clock.schedule_once(self.setup)
Esempio n. 43
0
 def show(self, pos, duration=0):
     Window.add_widget(self)
     # wait for the bubble to adjust it's size according to text then animate
     Clock.schedule_once(lambda dt: self._show(pos, duration))
Esempio n. 44
0
def show_error(message):
    chat_app.info_page.update_info(message)
    chat_app.screen_manager.current = "Info"
    Clock.schedule_once(sys.exit, 3)
Esempio n. 45
0
 def __init__(self, **kwargs):
     super(SurveyQuestionTextInput, self).__init__(**kwargs)
     Clock.schedule_once(self.setup)
Esempio n. 46
0
 def stop(self):
     print "Learning stop() called"
     self.reset()
     Clock.unschedule(self.checkTimeout)
Esempio n. 47
0
 def numpad_return_callback(self, value, is_return):
     if value is 0 and is_return:
         value = None
     if is_return:
         Clock.schedule_once(self._schedule_validate, .2)
     self.answer = value
Esempio n. 48
0
 def on_touch_up(self, touch):
     self.last_touch = Clock.get_time()
     self.checkIfModeIsCompleted()
Esempio n. 49
0
 def __init__(self, **kwargs):
     self._trigger_position_visible_slides = Clock.create_trigger(
         self._position_visible_slides, -1)
     super(Carousel, self).__init__(**kwargs)
     self._skip_slide = None
     self.touch_mode_change = False
Esempio n. 50
0
 def mostrar_popup(self):
     MDApp.get_running_app().popup_leituradados.open()
     Clock.schedule_once(self.pesquisar_cliente, 0.1)
Esempio n. 51
0
    def start(self):
        print "Learning start() called"
        self.add_shapes()

        self.last_touch = Clock.get_time()
        Clock.schedule_interval(self.checkTimeout, 5)
 def __init__(self, capture, fps, **kwargs):
     super(KivyCamera, self).__init__(**kwargs)
     self.capture = capture
     Clock.schedule_interval(self.update, 1.0 / fps)
Esempio n. 53
0
 def checkTimeout(self, dt=False):
     if abs(Clock.get_time() - self.last_touch) > TIMEOUT_DELAY:
         print "Timeout on mode 2, sending message to switch mode."
         self.controller.sendMessage("threshold_reached")
Esempio n. 54
0
 def on_exit(self):
     Clock.unschedule(self.new_day)
     self.stop()
Esempio n. 55
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     # Schedule remainder of init with delay to allow app to fully start.
     # This avoids error referencing App instance before it's ready.
     Clock.schedule_once(self.after_init)
Esempio n. 56
0
def alert_tracker_helper():
    alert_tracker()
    Clock.schedule_interval(alert_tracker_helper(), 5)
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.previous_tab = None
     self.widget_index = 0
     Window.bind(on_resize=self.on_resize)
     Clock.schedule_once(lambda x: self.on_resize(), 0)
Esempio n. 58
0
 def start(self):
     if not self.running:
         self.running = True
         self.start_time = datetime.now()
         Clock.schedule_interval(self.update, 0.1)
Esempio n. 59
0
 def displayMsg(self, msg):
     self.lblHd.font_size = 24
     self.lblHd.text = msg
     Clock.schedule_once(self.resetLabelHd, 4)
Esempio n. 60
-2
    def anim_reset(self, allow_anim):
        '''Reset an animation if available.

        .. versionadded:: 1.0.8

        :Parameters:
            `allow_anim`: bool
                Indicate whether the animation should restart playing or not.

        Usage::

            # start/reset animation
            image.anim_reset(True)

            # or stop the animation
            image.anim_reset(False)

        You can change the animation speed whilst it is playing::

            # Set to 20 FPS
            image.anim_delay = 1 / 20.

        '''
        # stop animation
        Clock.unschedule(self._anim)
        if allow_anim and self._anim_available:
            Clock.schedule_interval(self._anim, self.anim_delay)
            self._anim()