Пример #1
0
    def submit_form(self):
        # Insert inputs to DB

        if (not self.ids.cost.text) or (not self.ids.noun.text) or (not self.ids.verb.text):
            popup = Popup(title='Input Error',
                content=Label(text='Please enter all fields'),
                size_hint=(None, None), size=(350, 350))

            popup.open()

        elif not (self.ids.cost.text.isdigit()):
            popup = Popup(title='Input Error',
                content=Label(text='Please enter an interger for cost'),
                size_hint=(None, None), size=(350, 350))

            self.ids.cost.text = ''

            popup.open()

        else:
            verb = self.ids.verb.text
            noun = self.ids.noun.text
            cost = self.ids.cost.text
            create_mistake(self.eid, False, verb, noun, cost)

            # Clear input field
            self.ids.verb.text = "Did"
            self.ids.noun.text = ''
            self.ids.cost.text = ''

            self.display_mistakes()
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def show_save(self):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title="Save file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(path, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def save(self, path, filename):
        with open(os.path.join(path, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()
Пример #3
0
    def _perform_do_pull(self, instance, remotes, *args):
        '''Try to perform a pull
        '''
        remote = remotes[0]
        remote_repo = self.repo.remotes[remote]
        progress = GitRemoteProgress()

        status = Popup(title='Git pull progress',
                       content=progress.label,
                       size_hint=(None, None),
                       size=(500, 200))
        status.open()

        @ignore_proj_watcher
        def pull(*args):
            '''Do a pull in a separated thread
            '''
            try:
                remote_repo.pull(progress=progress)

                def set_progress_done(*args):
                    progress.label.text = 'Completed!'

                Clock.schedule_once(set_progress_done, 1)
                progress.stop()
                show_message('Git remote pull completed!', 5)
            except GitCommandError as e:
                progress.label.text = 'Failed to pull!\n' + str(e)
            get_designer().close_popup()

        progress.start()
        threading.Thread(target=pull).start()
Пример #4
0
    def open_statistics(self):
        """Utworzenie i wyświetlenie okienka zawierającego najlepszy i kilka ostatnich wyników z danego ćwiczenia"""
        from stats import ScoresPopupContent

        st = Popup(title=u"{t} - Wyniki".format(t=self.name), content=ScoresPopupContent(table_name=self.table_name), size_hint_x=0.8)
        st.open()
        st.content.close_bt.bind(on_release=st.dismiss)
Пример #5
0
class MessageBox(EnergyGameApp):
    def __init__(self, parent, titleheader="Title", message="Message", options={"OK": ""}, size=(400, 400)):

        def popup_callback(instance):
            "callback for button press"
            self.retvalue = instance.text
            self.popup.dismiss()

        self.parent = parent
        self.retvalue = None
        self.titleheader = titleheader
        self.message = message
        self.options = options
        self.size = size
        box = GridLayout(orientation='vertical', cols=1)
        box.add_widget(Label(text=self.message, font_size=16))
        b_list = []
        buttonbox = BoxLayout(orientation='horizontal')
        for b in self.options:
            b_list.append(Button(text=b, size_hint=(1,.35), font_size=20))
            b_list[-1].bind(on_press=popup_callback)
            buttonbox.add_widget(b_list[-1])
        box.add_widget(buttonbox)
        self.popup = Popup(title=titleheader, content=box, size_hint=(None, None), size=self.size)
        self.popup.open()
        self.popup.bind(on_dismiss=self.OnClose)

    def OnClose(self, event):
        self.popup.unbind(on_dismiss=self.OnClose)
        self.popup.dismiss()
        if self.retvalue and self.options[self.retvalue] != "":
            command = "self.parent."+self.options[self.retvalue]
            exec command
Пример #6
0
    def do_add(self, *args):
        '''Git select files from a list to add
        '''
        d = get_designer()
        if d.popup:
            return False
        files = self.repo.untracked_files
        if not files:
            show_alert('Git Add', 'All files are already indexed by Git')
            return

        # create the popup
        fake_setting = FakeSettingList()
        fake_setting.allow_custom = False
        fake_setting.items = files
        fake_setting.desc = 'Select files to add to Git index'

        content = SettingListContent(setting=fake_setting)
        popup_width = min(0.95 * Window.width, 500)
        popup_height = min(0.95 * Window.height, 500)
        popup = Popup(
            content=content, title='Git - Add files', size_hint=(None, None),
            size=(popup_width, popup_height), auto_dismiss=False)

        content.bind(on_apply=self._perform_do_add,
                     on_cancel=d.close_popup)

        content.show_items()
        d.popup = popup
        popup.open()
Пример #7
0
    def do_branches(self, *args):
        '''Shows a list of git branches and allow to change the current one
        '''
        d = get_designer()
        if d.popup:
            return False
        branches = []
        for b in self.repo.heads:
            branches.append(b.name)

        # create the popup
        fake_setting = FakeSettingList()
        fake_setting.allow_custom = True
        fake_setting.items = branches
        fake_setting.desc = 'Checkout to the selected branch. \n' \
                'You can type a name to create a new branch'
        fake_setting.group = 'git_branch'

        content = SettingListContent(setting=fake_setting)
        popup_width = min(0.95 * Window.width, 500)
        popup_height = min(0.95 * Window.height, 500)
        popup = Popup(
            content=content, title='Git - Branches', size_hint=(None, None),
            size=(popup_width, popup_height), auto_dismiss=False)

        content.bind(on_apply=self._perform_do_branches,
                     on_cancel=d.close_popup)

        content.selected_items = [self.repo.active_branch.name]
        content.show_items()
        d.popup = popup
        popup.open()
Пример #8
0
    def confirm_print(self):
        layout0 = BoxLayout(orientation='vertical')
        layout1 = BoxLayout(orientation='horizontal')
        label = Label(
            text='You want to print {} copies?'.format(self.prints),
            font_size=30)
        button0 = Button(
            text='Just do it!',
            font_size=30,
            background_color=(0, 1, 0, 1))
        button1 = Button(
            text='No',
            font_size=30,
            background_color=(1, 0, 0, 1))
        layout1.add_widget(button1)
        layout1.add_widget(button0)
        layout0.add_widget(label)
        layout0.add_widget(layout1)

        popup = Popup(
            title='Are you sure?',
            content=layout0,
            size_hint=(.5, .5),
            auto_dismiss=False)

        button0.bind(on_release=partial(
            self.handle_print_touch, popup))

        button1.bind(on_release=popup.dismiss)
        popup.open()
Пример #9
0
 def on_touch_down(self, touch):
   if not self.collide_point(touch.x, touch.y):
     return
   popup = Popup(title='Edit variable',
     content=VariableSelector(self),
     size_hint=(None, None), size=(400, 400))
   popup.open()
Пример #10
0
    def changeScreen(self, screen):
        # back button
        print screen
        print self.currentScreen
        if(screen != '' and screen != 'back' and screen != 'setting'):
            self.currentScreen = screen
        elif(screen == 'back'):
            screen = self.currentScreen

        if(screen == 'receptor'):
            #Check data input
            Receptors = Variable.parsepdb.Receptors
            Ligands = Variable.parsepdb.Ligands
            if(len(Receptors) == 0 or len(Ligands) == 0):
                popup = Popup(title='Warning!',
                content=Label(text='Please insert your data to two \ncolumn Receptors and Ligands before \nrunning this simulation'),
                size_hint=(None, None), size=(300, 200))
                popup.open()
                return

        if(screen == 'load'):
            self.get_screen(screen).setupView()
        elif(screen == 'receptor'):
            self.get_screen(screen).setupView()
        elif (screen == 'running'):
            self.get_screen(screen).setupView()
        elif (screen == 'configuration'):
            self.get_screen(screen).setupView()

        self.current = screen
Пример #11
0
    def do_email(self, popup, address, filename, widget):
        thread = SenderThread(address, filename)
        thread.daemon = True
        thread.start()
        popup.dismiss()

        layout = BoxLayout(orientation='vertical')
        label = Label(
            text='Just sent this image to:\n\n{}'.format(address),
            font_size=30)
        button = Button(
            text='Awesome!',
            font_size=30,
            background_color=(0, 1, 0, 1))
        layout.add_widget(label)
        layout.add_widget(button)

        popup = Popup(
            title='Just thought you should know...',
            content=layout,
            size_hint=(.5, .5))

        button.bind(on_release=popup.dismiss)
        from kivy.core.window import Window

        Window.release_all_keyboards()
        self.reset_email_textinput()
        popup.open()
Пример #12
0
        def viewGames(self):
            sview = ScrollView(size_hint=(.9, .8), pos_hint={'center_x':.5, 'center_y':.5})
            layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
            # Make sure the height is such that there is something to scroll.
            layout.bind(minimum_height=layout.setter('height'))
            # Run sql query to get all available games
            availableGames = retrieve("SELECT * FROM Games")
            
            if availableGames == "":
                popup = Popup(title='No Games', content=Label(text='There are currently no available games'), size_hint=(None, None), size=(400, 100))
                popup.open()
            elif availableGames == 0:
                popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(None, None), size=(400, 100))
                popup.open()
            else:
                for tpl in availableGames:
                    uid, name, location, creator, status = tpl
                    print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n"
                    print name
                    print "\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n"
                    btn = Button(id=name, text=name, size_hint_y=None, height=200)
                    btn.bind(on_press=self.seeInfo)
                    layout.add_widget(btn)

            sview.add_widget(layout)
            self.add_widget(sview)
Пример #13
0
        def login_but(self):

                # gets the data from the text inputs on the login page
                uname = self.ids['uname_input']
                pword = self.ids['pass_input']

                # make sure that the values are not null
                if len(uname.text) > 0:
                        if len(pword.text) > 0:
                                popup = Popup(title='', content=Label(text='Loading . . .'), size_hint=(.9, .3), size=(800, 800))
                                popup.open()
                                query = retrieve("SELECT * FROM users WHERE username = \"%s\" AND password = \"%s\"" % (uname.text, pword.text))
                                popup.dismiss()
                                if query == 0:
                                        popup = Popup(title='Connection', content=Label(text='Could not connect to the database'), size_hint=(.9, .3), size=(800, 800))
                                        popup.open()
                                elif len(query) < 1:
                                        popup = Popup(title='Invalid Credentials', content=Label(text='Username or Password is Incorrect'), size_hint=(.9, .3), size=(800, 800))
                                        popup.open()
                                else:
                                        user.uid, user.firstname, user.lastname, user.username, user.password, user.game_id, user.bt_ID, user.status, user.target = query[0]
                                        bt_ID = myBTA.getAddress()
                                        results = create("UPDATE users SET bt_ID = '%s' WHERE uid = '%s'" % (bt_ID, user.uid))
                                        uname.text = ""
                                        pword.text = ""
                                        sm.current = "Home"
                        else:
                                popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Password'), size_hint=(.9, .3), size=(800, 800))
                                popup.open()
                else:
                        popup = Popup(title='Invalid Credentials', content=Label(text='Please Enter a Username'), size_hint=(.9, .3), size=(800, 800))
                        popup.open()
Пример #14
0
class Add_debris_select(BoxLayout):
    debris_id = ObjectProperty(None)
    get_debris_id = ObjectProperty(None)
    debris_type = ObjectProperty(None)
    get_debris_type = ObjectProperty(None)
    debris_weight = ObjectProperty(None)
    get_debris_weight = ObjectProperty(None)
    debris_lat = ObjectProperty(None)
    get_debris_lat = ObjectProperty(None)
    debris_long = ObjectProperty(None)
    get_debris_long = ObjectProperty(None)
    add_debris_to_db = ObjectProperty(None) 

    def __init__(self,**kwargs):
        super(Add_debris_select,self).__init__(**kwargs)
        
    def on_back(self):
        self.parent.parent.transition.direction = 'left'
        self.parent.parent.current = 'display_database'
        
    def on_dismiss(self, arg):
        pass

    def not_full_info(self,event):
        self.popup = Popup(title= "Information",
        content = Info_Pop(),
        size_hint=(None, None), size=(self.width/2, self.height/2))
        self.popup.bind(on_dismiss = self.on_dismiss)
        self.popup.open() 
Пример #15
0
 def posterror(self, message, dt):
     print(message)
     self.switchscreen(self.startmenu)
     errorpopup = Popup(title='Error',
                   content=Label(text=message),
                        size_hint=(None, None), size=(600,200))
     errorpopup.open()
Пример #16
0
    def yes_callback(self):
        print('The button Yes is being pressed' + self.notary_file)

        json = getMetaData(self.notary_file_no_path,self.file_owner,self.file_created_dt,self.file_created_by)

        print('Meta Json Test: ' + str(json))
        import notary_client
        try :
            result = notary_app.notary_obj.notarize_file(str(self.notary_file), json)
        except notary_client.NotaryException as e:
           print("Code %s " % e.error_code)
           print(e.message)

        try :
            notary_app.notary_obj.upload_file_encrypted(str(self.notary_file))
        except notary_client.NotaryException as e:
           print("Code %s " % e.error_code)
           print(e.message)

        popup = Popup(title='Confirmation of Upload',
                      content=Label(text='Congrats. Your document notariztion and upload are successfully.'),
                      size_hint=(None, None),
                      size=(400, 200))
        popup.open()

        notary_app.sm.current = 'viewclaims'
Пример #17
0
    def search_start(self, instance):

        """
        Function to start the retrieval of possible meanings from the inserted chunk.
        Check first if the label is empty and then if the chuck is already present in the DB
        :param instance:
        :return:
        """

        if self.ti_chunk.text == '':
            # if chunk is empty alert user
            popup = Popup(title='Alert!!', content=Label(text="Empty chunk inserted, retry!"),
                          size_hint=(0.5, 0.3), font_size='38sp')
            popup.open()
            return

        rows = self.db.existchunk_ud(userid=self.app.root.userID,
                                     senderid=self.app.root.senderID, chunk=self.ti_chunk.text)
        if len(rows) > 0:
            # if chunk is already present in the UD table
            popup = Popup(title='Alert!!',
                          content=Label(text="Chunk already present!\nYou can modify it pressing on the edit button!"),
                          size_hint=(0.5, 0.3), font_size='38sp')
            popup.open()
        else:
            # add popup with the chosen text which will start the thread
            p = AddPopup(self.ti_chunk.text)
            p.bind(on_dismiss=self.callback_add)
            p.open()
Пример #18
0
class VariableDescriptions(Widget):

    def tab_info(self):
        self.pbuilder = self.parent.parent
        self.description_tab = TabbedPanel()
        particle_info = TabbedPanelHeader(text = 'Particle')
        behavior_info = TabbedPanelHeader(text = 'Behavior')
        color_info = TabbedPanelHeader(text = 'Color')
        particle_info.font_size = self.size[0]*.28
        behavior_info.font_size = self.size[0]*.28
        color_info.font_size = self.size[0]*.28
        particle_info.content = RstDocument(source="param_descriptions/ParticleTab.rst")
        behavior_info.content = RstDocument(source="param_descriptions/BehaviorTab.rst")
        color_info.content = RstDocument(source="param_descriptions/ColorTab.rst")
        particle_info.scroll_distance = 2
        particle_info.scroll_timeout = 500
        behavior_info.scroll_distance = 2
        behavior_info.scroll_timeout = 500
        color_info.scroll_distance = 2
        color_info.scroll_timeout = 500
        self.description_tab.default_tab = particle_info
        self.description_tab.tab_width = self.size[0]*4.36
        self.description_tab.tab_height = self.size[1]*.7
        self.description_tab.add_widget(particle_info)
        self.description_tab.add_widget(behavior_info)
        self.description_tab.add_widget(color_info)
        self.description_popup = Popup(title="Variable Descriptions", content = self.description_tab, size_hint = (.8,.8), on_open=self._popup_opened, on_dismiss=self._popup_dismissed)
        self.description_popup.open()

    def _popup_opened(self, instance):
        self.pbuilder.demo_particle.pause()

    def _popup_dismissed(self, instance):
        self.pbuilder.demo_particle.resume()
Пример #19
0
 def weather(self, obj):
     weather = getWeather()
     popup = Popup(title='Test popup',
                   content=Label(text=weather),
                   size_hint=(None, None),
                   size=(400, 400))
     popup.open()
Пример #20
0
	def save_data(self): 
		num_of_exit_ppl=0;num_of_steps=0;centre=''     
		if len(self.ids.num_of_steps.text)!=0:
			try:
				num_of_steps=float(self.ids.num_of_steps.text)            
			except ValueError:
				num_of_steps=""
				error_popup=Popup(title='Error',content=Label(text="Only numeric values allowed for number of exit people. Your input is dismissed.\nReturn to previous menu and return again.")\
					,size_hint=(.75,.75),auto_dismiss=True)
				error_popup.open()
				Clock.schedule_interval(error_popup.dismiss, 3) 
		if len(self.ids.num_of_exit_ppl.text)!=0:
			try:
				num_of_exit_ppl= float(self.ids.num_of_exit_ppl.text)
			except ValueError:
				num_of_exit_ppl=""
				error_popup=Popup(title='Error',content=Label(text="Only numeric values allowed for number of steps. Your input is dismissed.\nReturn to previous menu and return again.")\
					,size_hint=(.75,.75),auto_dismiss=True)
				error_popup.open()
				Clock.schedule_interval(error_popup.dismiss, 3)
		mins=float(self.ids.stopwatch.text[:2])
		secs= float(self.ids.stopwatch.text[3:5])
		milli_secs=float(re.findall(r'](\w+)\[', self.ids.stopwatch.text)[0])
		time_to_exit=(mins*60+secs+0.001*milli_secs) #check this conversion
		if len(self.ids.centre.text[0]) !=0:
			centre=self.ids.centre.text[0].lower()
		exp_date_time=datetime.now().strftime('%d-%m-%y %H:%M:%S')
		exp_data.update_exp_data(num_of_exit_ppl,num_of_steps,time_to_exit,exp_date_time[:8]
			,exp_date_time[9:],centre)
Пример #21
0
    def load_particle(self,name='templates/thelight.pex'):
        progress_dialog = Popup(title="Loading...", content=Label(text="Please wait while the particle file is being loaded."), size_hint=(.5,.5))
        progress_dialog.open()

        pbuilder = self.parent.parent
        pl = pbuilder.params_layout
        pw = pbuilder.particle_window

        if not pl.tabs_loaded:
            # if the default panel is loaded, we need to create tabs
            pl.create_tabs()
        else:
            # if not, then the tabs are already there, but we do need to stop and remove the particle
            pbuilder.demo_particle.stop(clear = True)
            pw.remove_widget(pbuilder.demo_particle)

        new_particle = kivyparticle.ParticleSystem(name)
        new_particle.pos = pw.center_x, pw.center_y
        pbuilder.demo_particle = new_particle
        pw.add_widget(pbuilder.demo_particle)
        pbuilder.demo_particle.start()
        pbuilder.active_filename = os.path.basename(name)

        pl.particle_tabs.tab_list[0].content.get_values_from_particle()
        pl.particle_tabs.tab_list[1].content.get_values_from_particle()
        pl.particle_tabs.tab_list[2].content.get_values_from_particle()
        pl.open_first_tab()

        progress_dialog.dismiss()
Пример #22
0
	def readme_pop(self):
		""" Readme """

		popup = Popup(title='README')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text= "Copyright (C) 2015 Revathy Narayanan\n" +
					  "The TimeTracker is a Python application \n that will keep"+
					  " track of time spent\n in day-to-day activities.\n\n"+
"The Application will have features \n"+
"* Start/Stop watch \n * Log Task\n * Add Comments\n"+
"* Generate & View Timesheet\n * Mail Timesheet\n\n "+
"The code is licensed under MIT License(MIT).\n "+
"Please see the file license in this distribution\n for license terms in the link below :\n"+
"https://github.com/rev20/Time-Tracker/blob/master/LICENSE \n\n"+
"Following is the link for the repository: \n"+
"https://github.com/rev20/Time-Tracker/")

		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)
Пример #23
0
	def timesheet_pop(self):
		"""Popup to display the Timesheet"""

		popup = Popup(title='Timesheet')
		b=BoxLayout(orientation='vertical')
		s = ScrollView()
		global tslabel
		tslabel=Label(size_hint_y=None,line_height=1.5,valign="top",
					  text="|_ID_|______DATE______|___TIME_SPENT____|_____TASK_________|")
		tslabel.bind(texture_size=tslabel.setter('size'))
		btn1=Button(text='CLOSE',size_hint=(1,.06))
		s.add_widget(tslabel)
		b.add_widget(s)
		b.add_widget(btn1)
		popup.content=b
		popup.open()
		btn1.bind(on_press=popup.dismiss)

		con=lite.connect('TimeTracker.db')
		with con:
				cur=con.cursor()
				cur.execute("SELECT ID, TASK_DATE, TIME, TASK FROM Timesheet")
				rows = cur.fetchall()
				for row in rows:
				  tslabel.text=tslabel.text+"\n   "
				  tslabel.text+=str(row[0]).center(4)+"      "+str(row[1])
				  tslabel.text+="  "+str(row[2]).center(34)+"  "+str(row[3])
		if con:
				con.close()
Пример #24
0
def PopupAudit(audit_obj, key):
    def on_close(*args):
        def _on_close(*args):
            Window.rotation = 0
        Clock.schedule_once(_on_close, .25)

    assert isinstance(audit_obj, AuditResult) or audit_obj is None
    if audit_obj is None:
        text = "No audit attribute found for %s" % key
    else:
        text = str(audit_obj)
    btnclose = Button(text='Continue', size_hint_y=None, height='50sp')
    content = BoxLayout(orientation='vertical')
##    lbl = TextInput(text=text, font_size='12sp', auto_indent=True,
##            readonly=True, disabled=True,
##            font_name='fonts'+os.sep+'DroidSansMono.ttf')
    lbl = ScrollableText(text=text)
    content.add_widget(lbl)
    content.add_widget(btnclose)
    p = Popup(title='Audit of "%s"' % key, content=content,
                #size=('300dp', '300dp'),
                size_hint=(.95, .75))
    btnclose.bind(on_release=p.dismiss)
    p.bind(on_open=lbl.go_top)
    # See if this is a pretty long audit, so we will display long ways
    if max([len(a) for a in text.split('\n')]) > 30:
        p.bind(on_dismiss=on_close) and None
        p.size_hint = (.95, .95)
        Window.rotation = 90
    p.open()
Пример #25
0
class NewImage():
    def __init__(self, callback):
        self.title = "New Image: "
        self.callback = callback
        self.content = NewDialog(ok=self._ok, cancel=self._dismiss)
        self._popup = Popup(title=self.title, content=self.content, pos_hint={'center': 1, 'top': 1},
                            size_hint=(0.3, 0.3))

    def open(self):
        self._popup.open()

    def _ok(self, wtext, htext):
        Window.release_all_keyboards()
        try:
            w = int(wtext)
            h = int(htext)
        except:
            PopupMessage("Notification", "Width and height should be greater than zero")
            return
        if w == 0 or h == 0:
            PopupMessage("Notification", "Width and height should be greater than zero")
            return
        self.callback((w, h))
        self._popup.dismiss()

    def _dismiss(self):
        Window.release_all_keyboards()
        self._popup.dismiss()
Пример #26
0
class ChooseOptionPopup:
    m_dictOptionCallback = None
    
    def __init__(self, title, listOptionCallback):
        self.m_dictOptionCallback = {}
        
        layout = BoxLayout(orientation="vertical")
        
        for option,callback in listOptionCallback:
            if callback != None:
                self.m_dictOptionCallback[option] = callback
                btn = Button(text=option, size_hint=(1, 0.1))
                btn.bind(on_release = self.choice)
                layout.add_widget(btn)
            else:
                layout.add_widget(Label(text=option, size_hint=(1, 0.1)))
        
        self.popup = Popup(title=title,content=layout,size_hint=(0.5, min(0.1 + len(listOptionCallback) * 0.1, 1.0)))
        self.popup.open()
        
    def choice(self, instance):
        self.dismiss_popup()
        (self.m_dictOptionCallback[instance.text])()
        
    def dismiss_popup(self):
        self.popup.dismiss()
Пример #27
0
def PopupOk(text, title='', btn_text='Continue', input=None, callback=None):
    btnclose = Button(text=btn_text, size_hint_y=None, height='50sp')
    content = BoxLayout(orientation='vertical')
    p = Popup(title=title, content=content, size=('300dp', '300dp'),
                size_hint=(None, None), pos_hint={'top':.95})
    content.add_widget(Label(text=text))
    if input is not None:
        assert callback is not None
        ti = TextInput(height='50sp', font_size='30sp', input_type=input,
                        multiline=False, size_hint_y = None, focus=True)
        content.add_widget(ti)
        def _callback(*args):
            try:
                ti.hide_keyboard()
            except AttributeError:
                # On a real computer, not the phone
                pass
            if ti.text == '':
                callback(None)
            else:
                callback(ti.text)
        p.bind(on_dismiss=_callback)
        p.is_visable = True

    content.add_widget(btnclose)

    btnclose.bind(on_release=p.dismiss)
    p.open()
    if input is not None:
        while not p.is_visable:
            EventLoop.idle()
        return ti.text
Пример #28
0
	def mail_pop(self):
		"""Popup with features to mail timesheet """

		f=FloatLayout()
		global popup2
		popup2 = Popup(title='Mail Timesheet',content=f,
		size_hint=(1.0, 0.6), size=(400, 400))
		g=GridLayout(cols=1,row_force_default=True,
					 row_default_height=40,pos_hint={'center_x':.5})
		global msg
		msg=Label(text="ENTER AN EMAIL ID")
		global mail_id
		mail_id=TextInput(write_tab=False)
		g.add_widget(msg)
		g.add_widget(mail_id)
		btn1=Button(text='MAIL',size_hint=(0.2,0.1),
					pos=(popup2.width-350,popup2.height-250) )
		btn1.bind(on_press=(MyApp.mail_timesheet))
		btn2=Button(text='CLOSE',size_hint=(0.2,0.1),
					pos=(popup2.width-50,popup2.height-250))
		f.add_widget(btn1)
		f.add_widget(btn2)
		f.add_widget(g)
		popup2.open()
		btn2.bind(on_press=popup2.dismiss)
Пример #29
0
    def openinfo(self, *args):
        """
        Display element info into pop-up
        """

        boxpop = BoxLayout(orientation='vertical')

        description = Description()
        description.text = self.main.tip_info

        boxpop.add_widget(TitreDescription())
        boxpop.add_widget(description)

        usage = Usage()
        usage.text = self.main.apl_info

        boxpop.add_widget(TitreUsage())
        boxpop.add_widget(usage)
       
        popup = Popup(
            title=self.main.nametext,
            content=boxpop,
            separator_color=get_color_from_hex('42bd3bff'),
            title_size = 20,
            size_hint=(None, None),
            size=(640, 280))
        popup.open()
Пример #30
0
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    
    #def erro_popup():
		# we have to create Error_POP up with "Ok" button, when Ok button 
		# will b pressend Error_popup will be dismissed 
		   
    def dismiss_popup(self):
		
        # dismissing the popup created for Load Dialog
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        
        # created the POPUP for load Dialog
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path,filename):
    	
        self.text_input.text = read_pdf(filename[0])
        self.dismiss_popup()
Пример #31
0
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    text_input2 = ObjectProperty(None)
    text_input3 = ObjectProperty(None)

    def __init__(self):
        super(self.__class__, self).__init__()
        self.isLoaded = False
        self.loaded_file = FILETYPE.UNKNOWN
        self.h = ''
        self.rsaModule = RSA()

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file",
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        if filename[0][-4:] == ".wav":
            self.h = HeaderBuilderWAV()
            self.loaded_file = FILETYPE.WAV
        elif filename[0][-4:] == ".bmp":
            self.h = HeaderBuilderBMP()
            self.loaded_file = FILETYPE.BMP
        else:
            raise ValueError('Not known extension of file')
        self.h.readHeader(os.path.join(path, filename[0]))
        self.text_input.text = str(self.h.header)
        self.dismiss_popup()
        self.isLoaded = True

    def cos(self):
        self.dismiss_popup()

    def display_wav_fft(self, samples, sample_rate, num_channels, fignum):
        #time vector
        n = len(samples)
        k = np.arange(n)
        T = float(n) / sample_rate
        freq = k / T
        freq = freq[range(n / 2)]

        fig, ax = plt.subplots(num_channels, 1)

        for i in range(0, num_channels):
            plt.figure(fignum)

            #calculate fft and normalize results
            if num_channels is 1:
                y = np.fft.fft(samples) / n
                y = y[range(n / 2)]
                plt.plot(freq, abs(y))
                plt.title('Channel {} FFT'.format(i + 1))
                plt.xlabel('Freq (Hz)')
            else:
                y = np.fft.fft(samples[:, i]) / n
                y = y[range(n / 2)]
                ax[i].plot(freq, abs(y))
                ax[i].set_title('Channel {} FFT'.format(i + 1))
                ax[i].set_xlabel('Freq (Hz)')

    def display_bmp_fft(self, samples):
        plt.figure(1)
        fft = fftpack.fft2(samples)
        plt.imshow(np.abs(np.fft.fftshift(fft)), interpolation='nearest')
        plt.show()

    def fourier_transform(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()

            #return Button(text='Hello World')
        else:
            if self.loaded_file is FILETYPE.WAV:
                sample_rate = self.h.header.get_property("SampleRate")
                num_channels = self.h.header.get_property("NumChannels")
                self.display_wav_fft(self.h.data[0:1000], sample_rate,
                                     num_channels, 1)
                plt.show()
            elif self.loaded_file is FILETYPE.BMP:
                self.display_bmp_fft(self.h.data)
                #rsaModule = RSA()
                #enc = rsaModule.encrypt(self.h.data)
                #dec = rsaModule.decrypt(enc)
                #if (self.h.data==dec).all:
                #    print "good"
                #else:
                #    print "bad"

    def encrypt(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        if self.loaded_file is FILETYPE.WAV:
            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="Only BMP files are supported!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        elif self.loaded_file is FILETYPE.BMP:
            file = open(self.h.filename, "rb")
            image = file.read()
            file.close()

            header = image[:54]
            data = image[54:84]
            enc = self.rsaModule.encrypt(
                np.transpose(np.fromstring(data, dtype=np.uint8)))
            dec = self.rsaModule.decrypt(enc)
            print(np.fromstring(data, dtype=np.uint8)[0:10])
            print(dec[0:10])
            print(len(dec))
            print(len(data))
            print([ord(c) for c in data[0:10]])
            print(dec[0:10])
            file = open("example2.bmp", "wb")
            for i in range(len(dec)):
                if dec[i] > 255:
                    print('RSA error')
                    self.moduleRSA = RSA()
                    return

            d = [int(v) for v in dec]
            d2 = [chr(v) for v in d]
            print(d2)
            file.write(header.join(d2))
            file.close()
            print("--------------------------------------")

    def decrypt(self):
        if not self.isLoaded:

            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="File not Loaded!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        if self.loaded_file is FILETYPE.WAV:
            content = ErrorDialog(load=self.cos, cancel=self.dismiss_popup)
            self._popup = Popup(title="Only BMP files are supported!",
                                content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        elif self.loaded_file is FILETYPE.BMP:
            file = open(self.h.filename, "rb")
            image = file.read()
            file.close()
            header = image[:54]
            data = image[54:]
            print(np.fromstring(data, dtype=np.uint8)[0:10])
Пример #32
0
class LampiApp(App):
    _updatingUI = False
    _hue = NumericProperty()
    _saturation = NumericProperty()
    _brightness = NumericProperty()
    lamp_is_on = BooleanProperty()
    just_turned_on = True

    def _get_hue(self):
        return self._hue

    def _set_hue(self, value):
        self._hue = value

    def _get_saturation(self):
        return self._saturation

    def _set_saturation(self, value):
        self._saturation = value

    def _get_brightness(self):
        return self._brightness

    def _set_brightness(self, value):
        self._brightness = value

    hue = AliasProperty(_get_hue, _set_hue, bind=['_hue'])
    saturation = AliasProperty(_get_saturation, _set_saturation,
                               bind=['_saturation'])
    brightness = AliasProperty(_get_brightness, _set_brightness,
                               bind=['_brightness'])
    gpio17_pressed = BooleanProperty(False)

    def on_start(self):
        self._publish_clock = None
        self.mqtt = Client(client_id=MQTT_CLIENT_ID, protocol=MQTT_VERSION)
        self.mqtt.on_connect = self.on_connect
        self.mqtt.connect(MQTT_BROKER_HOST, port=MQTT_BROKER_PORT,
                          keepalive=MQTT_BROKER_KEEP_ALIVE_SECS)
        self.mqtt.will_set('lamp/connection/lamp_ui/state', "0", qos=2, retain=True)
        self.mqtt.publish('lamp/connection/lamp_ui/state', "1", qos=2, retain=True)
        self.mqtt.loop_start()
        self.set_up_GPIO_and_IP_popup()

    def on_hue(self, instance, value):
        if self._updatingUI:
            return
        if self._publish_clock is None:
            self._publish_clock = Clock.schedule_once(
                lambda dt: self._update_leds(), 0.01)

    def on_saturation(self, instance, value):
        if self._updatingUI:
            return
        if self._publish_clock is None:
            self._publish_clock = Clock.schedule_once(
                lambda dt: self._update_leds(), 0.01)

    def on_brightness(self, instance, value):
        if self._updatingUI:
            return
        if self._publish_clock is None:
            self._publish_clock = Clock.schedule_once(
                lambda dt: self._update_leds(), 0.01)

    def on_lamp_is_on(self, instance, value):
        if self._updatingUI:
            return
        if self._publish_clock is None:
            self._publish_clock = Clock.schedule_once(
                lambda dt: self._update_leds(), 0.01)

    def on_connect(self, client, userdata, flags, rc):
        self.mqtt.subscribe(TOPIC_LAMP_CHANGE_NOTIFICATION)
        self.mqtt.message_callback_add(TOPIC_LAMP_CHANGE_NOTIFICATION,
                                       self.receive_new_lamp_state)

    def receive_new_lamp_state(self, client, userdata, message):
        new_state = json.loads(message.payload)
        Clock.schedule_once(lambda dt: self._update_ui(new_state), 0.01)

    def _update_ui(self, new_state):
        self._updatingUI = True
        try:
            if 'client' in new_state:
                if new_state['client'] == 'lamp_ui' and not self.just_turned_on:
                    return
            if 'color' in new_state:
                self.hue = new_state['color']['h']
                self.saturation = new_state['color']['s']
            if 'brightness' in new_state:
                self.brightness = new_state['brightness']
            if 'on' in new_state:
                self.lamp_is_on = new_state['on']
        finally:
            self._updatingUI = False

    def _update_leds(self):
        msg = {'color': {'h': self._hue, 's': self._saturation},
               'brightness': self._brightness,
               'on': self.lamp_is_on,
               'client': 'lamp_ui'}
        self.mqtt.publish(TOPIC_SET_LAMP_CONFIG, json.dumps(msg), qos = 1)
        self._publish_clock = None

    def set_up_GPIO_and_IP_popup(self):
        self.pi = pigpio.pi()
        self.pi.set_mode(17, pigpio.INPUT)
        self.pi.set_pull_up_down(17, pigpio.PUD_UP)
        Clock.schedule_interval(self._poll_GPIO, 0.05)
        self.popup = Popup(title='IP Addresses',
                           content=Label(text='IP ADDRESS WILL GO HERE'),
                           size_hint=(1, 1), auto_dismiss=False)
        self.popup.bind(on_open=self.update_popup_ip_address)

    def update_popup_ip_address(self, instance):
        interface = "wlan0"
        ipaddr = lampi_util.get_ip_address(interface)
        instance.content.text = "{}: {}".format(interface, ipaddr)

    def on_gpio17_pressed(self, instance, value):
        if value:
            self.popup.open()
        else:
            self.popup.dismiss()

    def _poll_GPIO(self, dt):
        # GPIO17 is the rightmost button when looking front of LAMPI
        self.gpio17_pressed = not self.pi.read(17)
 def check_online(self):
     popup = Popup(title='Check Online',
                   content=Label(text='Coming soon!'),
                   size_hint=(None, None),
                   size=(400, 400))
     popup.open()
Пример #34
0
class SeedClassification(GridLayout):
    """

    """
    classification_model = ObjectProperty()
    loaded_image = ObjectProperty()
    input_vector = ListProperty()
    status = StringProperty('Status: No model selected!')

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load_model(self):
        content = LoadDialog(load=self.load_model,
                             cancel=self.dismiss_popup,
                             default_path=os.getcwd(),
                             filters=["*.json"]
                             )
        self._popup = Popup(title="Load model file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def show_load_image(self):
        if self.classification_model is None:
            self.status = "Please import your classification model before \
                classify the image."
            return

        content = LoadDialog(load=self.load_image,
                             cancel=self.dismiss_popup,
                             default_path=os.getcwd(),
                             filters=["*.jpg", "*.jpeg", "*.bmp", "*.png"]
                             )
        self._popup = Popup(title="Load image file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load_model(self, path, filename):
        with open(os.path.join(path, filename[0]), 'r') as file_object:
            config_file = json.load(file_object)
            self.classification_model = config_file['data']
            self.status = f"model file {os.path.split(filename[0])[1]}" + \
                " loaded.\nYou can use to classify image now."
            print(self.classification_model)
            self.dismiss_popup()

    def load_image(self, path, filename):
        image = ImageRecognition(os.path.join(path, filename[0]))
        width, height, texture_data = image.getTextureData()
        texture = Texture.create(size=(width, height))
        texture.blit_buffer(texture_data, colorfmt='bgr', bufferfmt='ubyte')
        self.loaded_image = texture
        width, height = image.getWidthHeight()
        self.predict([width, height, None])
        self.dismiss_popup()

    def calculate_class_probabilities(self):
        """
        Calculate the class probability for input sample.
        Combine probability of each feature
        """
        probabilities = {}
        for class_model in self.classification_model:
            classValue = class_model['class_id']
            classModels = class_model['features']
            print(classValue, " ", classModels)
            probabilities[classValue] = 1
            for i in range(len(classModels)):
                (mean, stdev) = (classModels[i]['mean'],
                                 classModels[i]['stdev'])
                x = self.input_vector[i]
                # print(f"{x}, {mean}, {stdev}")
                probabilities[classValue] *= self.calculate_pdf(x, mean, stdev)
        return probabilities

    def calculate_pdf(self, x, mean, stdev):
        x_minus_mean = float(x) - float(mean)
        """Calculate probability using gaussian density function"""
        if stdev == 0.0:
            if x == mean:
                return 1.0
            else:
                return 0.0
        exponent = math.exp(-(math.pow(x_minus_mean, 2) /
                            (2 * math.pow(float(stdev), 2))))
        return 1 / (math.sqrt(2 * math.pi) * stdev) * exponent

    def predict(self, inputVector):
        """
        Compare probability for each class.
        Return the class label which has max probability.
        """

        self.input_vector = inputVector
        probabilities = self.calculate_class_probabilities()
        (bestLabel, bestProb) = (None, -1)
        for (classValue, probability) in probabilities. items():
            if bestLabel is None or probability > bestProb:
                bestProb = probability
                bestLabel = classValue
        self.status = f"Object width: {inputVector[1]}" + \
            f", Object height: {inputVector[0]} \n" + \
            f"Image classified as {bestLabel} " + \
            f"with probability = {bestProb}"

    pass
class FirmwareUpdateView(BaseConfigView):
    progress_gauge = ObjectProperty(None)
    _settings = None

    def __init__(self, **kwargs):
        Builder.load_file(FIRMWARE_UPDATE_VIEW_KV)
        super(FirmwareUpdateView, self).__init__(**kwargs)
        self._settings = kwargs.get('settings', None)
        self.register_event_type('on_config_updated')
        self.ids.fw_progress.ids.add_gauge.text = ''

    def on_config_updated(self, rcpCfg):
        pass

    def check_online(self):
        popup = Popup(title='Check Online',
                      content=Label(text='Coming soon!'),
                      size_hint=(None, None),
                      size=(400, 400))
        popup.open()

    def prompt_manual_restart(self):
        popup = None

        def _on_ok(*args):
            popup.dismiss()
            self._restart_json_serial()

        popup = okPopup(
            'Operation Complete',
            '1. Unplug RaceCapture from USB\n2. Wait 3 seconds\n3. Re-connect USB',
            _on_ok)

    def prompt_manual_bootloader_mode(self, instance):
        self._popup.dismiss()
        popup = None

        def _on_answer(inst, answer):
            popup.dismiss()
            if answer == True:
                self._start_update_fw(instance)
            else:
                self._restart_json_serial()
        popup = confirmPopup('Enable Bootloader Mode',
                             '1. Disconnect 12v power\n2. Unplug RaceCapture from USB\n' \
                             '3. Wait 3 seconds\n4. While holding front panel button, re-connect USB',
                             _on_answer)

    def set_firmware_file_path(self, path):
        self._settings.userPrefs.set_pref('preferences', 'firmware_dir', path)

    def get_firmware_file_path(self):
        return self._settings.userPrefs.get_pref('preferences', 'firmware_dir')

    def select_file(self):
        if platform == 'win':
            ok_cb = self.prompt_manual_bootloader_mode
        else:
            ok_cb = self._start_update_fw
        user_path = self.get_firmware_file_path()
        print("the user path " + str(user_path))
        content = LoadDialog(ok=ok_cb,
                             cancel=self.dismiss_popup,
                             filters=['*' + '.ihex'],
                             user_path=user_path)
        self._popup = Popup(title="Load file",
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def _update_progress_gauge(self, percent):
        self.ids.fw_progress.value = int(percent)

    def _teardown_json_serial(self):
        Logger.info(
            'FirmwareUpdateView: Disabling RaceCapture Communcications')
        # It's ok if this fails, in the event of no device being present,
        # we just need to disable the com port
        self.rc_api.disable_autorecover()
        try:
            #Windows workaround (because windows sucks at enumerating
            #USB in a timely fashion)
            if not platform == 'win':
                self.rc_api.resetDevice(True, RESET_DELAY)
            self.rc_api.shutdown_comms()
        except:
            pass
        sleep(5)

    def _restart_json_serial(self):
        Logger.info(
            'FirmwareUpdateView: Re-enabling RaceCapture Communications')
        self.rc_api.enable_autorecover()
        self.rc_api.run_auto_detect()

    def _update_thread(self, instance):
        try:
            selection = instance.selection
            filename = selection[0] if len(selection) else None
            if filename:
                #Even though we stopped the RX thread, this is OK
                #since it doesn't return a value
                try:
                    self.ids.fw_progress.title = "Processing"
                    self._teardown_json_serial()
                except:
                    import sys, traceback
                    print "Exception in user code:"
                    print '-' * 60
                    traceback.print_exc(file=sys.stdout)
                    print '-' * 60
                    pass

                self.ids.fw_progress.title = "Progress"

                #Get our firmware updater class and register the
                #callback that will update the progress gauge
                fu = fw_update.FwUpdater(logger=Logger)
                fu.register_progress_callback(self._update_progress_gauge)

                retries = 5
                port = None
                while retries > 0 and not port:
                    #Find our bootloader
                    port = fu.scan_for_device()

                    if not port:
                        retries -= 1
                        sleep(2)

                if not port:
                    self.ids.fw_progress.title = ""
                    raise Exception("Unable to locate bootloader")

                #Go on our jolly way
                fu.update_firmware(filename, port)
                self.ids.fw_progress.title = "Restarting"

                #Windows workaround
                if platform == 'win':
                    self.prompt_manual_restart()
                #Sleep for a few seconds since we need to let USB re-enumerate
                sleep(3)
            else:
                alertPopup('Error Loading', 'No firmware file selected')
        except Exception as detail:
            alertPopup('Error Loading',
                       'Failed to Load Firmware:\n\n' + str(detail))

        self._restart_json_serial()
        self.ids.fw_progress.value = ''
        self.ids.fw_progress.title = ""

    def _start_update_fw(self, instance):
        self._popup.dismiss()
        self.set_firmware_file_path(instance.path)
        print('path: ' + str(self.get_firmware_file_path()))
        #The comma is necessary since we need to pass in a sequence of args
        t = Thread(target=self._update_thread, args=(instance, ))
        t.daemon = True
        t.start()

    def dismiss_popup(self, *args):
        self._popup.dismiss()
Пример #36
0
    def showWindowsPackPopup(self):

        print("showWindowsPackPopup....")
        box = BoxLayout(orientation="vertical", spacing=1)

        self.infoBtn = Button(text='Cancel', size_hint=(1, 0.5))
        PictureInternal(injectWidget=box, accessAssets="logo")
        if platform == 'win':
            box.add_widget(
                Label(
                    size_hint=(1, 0.5),
                    text=
                    'Make android APK final application package with PROJECT_NAME data folder. \n You will need to have docker installed on your computer.'
                ))
        elif platform == 'linux':
            box.add_widget(
                Label(
                    size_hint=(1, 0.5),
                    text=
                    'Make android APK final application package with PROJECT_NAME data folder. \n You will need to have docker installed on your computer.'
                ))
        else:
            box.add_widget(
                Label(
                    size_hint=(1, 0.5),
                    text=
                    'Make android APK final application package with PROJECT_NAME data folder. \n You will need to have docker installed on your computer. Not tested env !'
                ))

        _local1 = '[b]Relative path:[b] ' + self.engineConfig.currentProjectName
        box.add_widget(Label(size_hint=(1, 0.2), markup=True, text=_local1))
        _local0 = '[b]Package Execute File destination path:[b] ' + self.engineConfig.currentProjectPath + '/Package/'
        box.add_widget(Label(size_hint=(1, 0.2), markup=True, text=_local0))

        self.makeWinPackBtn = Button(markup=True,
                                     size_hint=(1, 0.5),
                                     text='[b]Make Package[b]')

        self.testLog = "test log"
        self.LOGS = TextInput(
            text='',
            foreground_color=(0, 1, 0, 1),
            background_color=self.engineConfig.getThemeBackgroundColor())

        self.debugLogTextLabel = Label(
            markup=True,
            text=
            "Building final execute package in progress ... Editor will be freezed until packaging works. You can go to VisualCode terminal to see logs."
        )
        box.add_widget(self.debugLogTextLabel)
        box.add_widget(self.LOGS)

        box.add_widget(self.makeWinPackBtn)
        box.add_widget(self.infoBtn)

        _local = 'CrossK ' + self.engineConfig.getVersion()
        popup = Popup(title=_local, content=box, auto_dismiss=False)

        self.infoBtn.bind(on_press=popup.dismiss)

        if platform == 'win':
            self.makeWinPackBtn.bind(on_press=lambda a: self.runInNewThread())
        elif platform == 'linux' or True:
            self.makeWinPackBtn.bind(on_press=lambda a: self.runInNewThread())
            # self.makeWinPackBtn.bind(on_press=lambda a:self.makeLinuxPack())
            # self.makeWinPackBtn.bind(on_press=partial(self.makeLinuxPack))

        popup.open()
Пример #37
0
class ChecklistWidget(ScrollView):
    screen_manager = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(ChecklistWidget, self).__init__(*args, **kwargs)
        Window.bind(on_keyboard=self.on_back_btn)
        self.checklist_layout = GridLayout(cols=1)
        self.checklist_layout.size_hint_y = None
        self.checklist_layout.id = 'checklist'
        self.checklist_layout.bind(
            minimum_height=self.checklist_layout.setter('height'))
        self.title = ''
        self.submit_button = Button()
        self.filewidget = FileWidget()
        self.confirmation_popup = Popup()
        self.data = None
        self.question_list = []
        self.response_list = []
        self.rect = Rectangle()
        self.checklist_menu_layout = GridLayout(cols=1)
        self.file_select_popup = Popup()
        self.set_background(self.checklist_menu_layout)
        self.do_get_checklists()

    def set_background(self, layout):
        """
		Sets a solid color as a background.

		:param layout: The layout for whichever part of the screen should be set.
		"""
        layout.bind(size=self._update_rect, pos=self._update_rect)

        with layout.canvas.before:
            Color(0, 0, 0, 1)
            self.rect = Rectangle(size=layout.size, pos=layout.pos)

    def _update_rect(self, instance, value):
        """
		Ensures that the canvas fits to the screen should the layout ever change.
		"""
        self.rect.pos = instance.pos
        self.rect.size = instance.size

    def do_get_checklists(self):
        """
		Creates the base screen for the checklist manager.
		It includes previously loaded checklists as well as a button for new checklists.
		"""
        self.clear_widgets()
        self.checklist_menu_layout.clear_widgets()
        titles = []
        new_json_button = Button(text='Load New Checklist', size_hint_y=None)
        new_json_button.bind(on_release=lambda x: self.do_popup_file_select())
        self.checklist_menu_layout.add_widget(new_json_button)
        for dirname, dirnames, _ in os.walk('/sdcard/operator/checklists/'):
            for subdirname in dirnames:
                loc = os.path.join(dirname, subdirname)
                name = loc.split("/")
                titles.append(name[len(name) - 1])
        for title in titles:
            button_to_checklist = Button(text=title, size_hint_y=None)
            button_to_checklist.bind(
                on_release=functools.partial(self.do_open_checklist, title))
            self.checklist_menu_layout.add_widget(button_to_checklist)
        self.add_widget(self.checklist_menu_layout)

    def do_popup_file_select(self):
        """
		Prompts the user to navigate to the .JSON file
		"""
        self.filewidget = FileWidget()
        box = BoxLayout(orientation='vertical')
        box_int = BoxLayout(orientation='horizontal', size_hint=(1, .2))
        close_button = Button(text='Load')
        close_button.bind(
            on_release=lambda x: self.do_add_checklist_location())
        dismiss_button = Button(text='Cancel')
        dismiss_button.bind(
            on_release=lambda x: self.file_select_popup.dismiss())
        box.clear_widgets()
        box_int.add_widget(close_button)
        box_int.add_widget(dismiss_button)
        box.add_widget(self.filewidget)
        box.add_widget(box_int)
        self.file_select_popup = Popup(title='Choose File',
                                       content=box,
                                       size_hint=(None, None),
                                       size=(800, 1000),
                                       auto_dismiss=False)
        self.file_select_popup.open()

    def do_load_true_path(self, path, filename):
        """
		Does a series of a checks to make sure the file that is trying to be loaded is valid.

		:param str path: The directory of the file.
		:param list filename: The name of the file.
		:return: The path to the validated JSON file. If the path is deemed invalid, None is returned.
		:rtype: str
		"""
        full_path = os.path.join(path, filename[0])
        if not os.path.isfile(full_path):
            toast("Not a valid file!", True)
            return
        if not os.access(full_path, (os.R_OK | os.W_OK)):
            toast("No permission, please move file", True)
            return
        if not full_path.endswith('.json'):
            toast("Not a JSON file!", True)
            return
        with open(full_path) as f:
            path_list = str(f).split("'")
            true_path = path_list[1]
        if not os.path.exists(true_path):
            toast("Not a valid path!", True)
        return true_path

    def do_add_checklist_location(self):
        """
		Creates the subdirectory for the checklist.
		"""
        path = self.do_load_true_path(self.filewidget.path,
                                      self.filewidget.filename)
        if not isinstance(path, str):
            return
        with open(path) as p:
            self.data = json.load(p)
        title = self.data.get('title', DEFAULT_CHECKLIST_NAME)
        d = os.path.join('/sdcard/operator/checklists/', title)
        if not os.path.exists(d):
            os.makedirs(d)
        open(os.path.join(d, title + '_template.json'), 'a')
        shutil.copyfile(path, os.path.join(d, title + '_template.json'))
        self.do_get_checklists()
        self.file_select_popup.dismiss()

    def do_open_checklist(self, title, event):
        """
		Opens the checklist, depending on the request from the user in the base menu.

		:param str title: The title of the checklist, according to the title field in the .JSON file.
		"""
        toast("Loading...", True)
        self.clear_widgets()
        self.title = title
        json_path = self.get_recent_json(title)
        if json_path:
            self.gen_checklist(json_path)

    def get_recent_json(self, title):
        """
		Load the most recent .JSON file in the subdirectory.

		:param str title: The title of the checklist, according to the title field in the .JSON file.
		"""
        newest = max(glob.iglob(
            os.path.join('/sdcard/operator/checklists', title,
                         '*.[Jj][Ss][Oo][Nn]')),
                     key=os.path.getctime)
        return newest

    def on_back_btn(self, window, key, *args):
        """
		Saves when back button is called.
		"""
        if key == 27:
            self.submit_button.trigger_action(duration=0)

    def _get_checklist_widget_check(self, question, i):
        multiple_responses = BoxLayout(orientation='vertical',
                                       id='Response ' + i,
                                       size_hint_y=None,
                                       height=(len(question.answer) * 70),
                                       spacing=20)
        for key, value in question.answer.items():
            response = BoxLayout(orientation='horizontal',
                                 id='sub Response ' + i)
            response.add_widget(Label(text=key, id=key))
            if key.lower().startswith('other'):
                widget = TextInput(id=key, size_hint_x=.8)
                if isinstance(value, (str, unicode)):
                    widget.text = value
            else:
                widget = CheckBox(id=key)
                widget.active = value
            response.add_widget(widget)
            multiple_responses.add_widget(response)
        return multiple_responses

    def _get_checklist_widget_response_check(self, widget):
        results = {}
        for child in widget.walk(restrict=True):
            if isinstance(child, TextInput):
                value = child.text
            elif isinstance(child, CheckBox):
                value = child.active
            else:
                continue
            results[child.id] = value
        return results

    def _get_checklist_widget_date(self, question, i):
        date_widget = BoxLayout(orientation='horizontal',
                                id='Response ' + i,
                                size_hint_y=None)
        month_spinner = Spinner(id='Month Response ' + i,
                                text=question.answer[0],
                                values=MONTHS)
        day_spinner = Spinner(
            id='Day Response ' + i,
            text=question.answer[1],
            values=["{0:02}".format(j) for j in range(1, 32)])
        year_spinner = Spinner(
            id='Year Response ' + i,
            text=question.answer[2],
            values=["{0:04}".format(j) for j in range(2100, 1900, -1)])
        date_widget.add_widget(month_spinner)
        date_widget.add_widget(day_spinner)
        date_widget.add_widget(year_spinner)
        return date_widget

    def _get_checklist_widget_response_date(self, widget):
        for child in widget.children:
            if 'Month' in child.id:
                month = child.text
            elif 'Day' in child.id:
                day = child.text
            elif 'Year' in child.id:
                year = child.text
        return (month, day, year)

    def _get_checklist_widget_num(self, question, i):
        float_widget = FloatInput(hint_text=question.question,
                                  id='Response ' + i,
                                  size_hint_y=None)
        float_widget.text = str(question.answer)
        return float_widget

    def _get_checklist_widget_response_num(self, widget):
        return float(widget.text)

    def _get_checklist_widget_text(self, question, i):
        text_widget = TextInput(hint_text=question.question,
                                id='Response ' + i,
                                size_hint_y=None)
        text_widget.text = question.answer
        return text_widget

    def _get_checklist_widget_response_text(self, widget):
        return widget.text

    def _get_checklist_widget_yes_no(self, question, i):
        yes_no_widget = BoxLayout(orientation='vertical',
                                  id='Response ' + i,
                                  size_hint_y=None)
        yes_response = BoxLayout(orientation='horizontal',
                                 id='sub Response' + i)
        yes_response.add_widget(Label(text='Yes', id='Response ' + i))
        yes_checkbox = CheckBox(id='Yes Response ' + i, group='yes_no' + i)
        yes_response.add_widget(yes_checkbox)
        no_response = BoxLayout(orientation='horizontal',
                                id='sub Response' + i)
        no_response.add_widget(Label(text='No', id='Response ' + i))
        no_checkbox = CheckBox(id='No Response ' + i, group='yes_no' + i)
        no_response.add_widget(no_checkbox)
        if question.answer:
            yes_checkbox.active = True
        else:
            no_checkbox.active = True
        yes_no_widget.add_widget(yes_response)
        yes_no_widget.add_widget(no_response)
        return yes_no_widget

    def _get_checklist_widget_response_yes_no(self, widget):
        for child in widget.children:
            for child2 in child.children:
                if isinstance(child2, CheckBox):
                    if 'Yes' in child2.id:
                        return bool(child2.active)
                    else:
                        return not bool(child2.active)

    def gen_checklist(self, json_path):
        """
		Generates the actual layout, based on the parsed .JSON

		:param str json_path: The path to the JSON checklist file to load.
		"""
        self.checklist_layout.clear_widgets()
        with open(json_path) as file_h:
            self.data = json.load(file_h)
        self.question_list = self.decode_json(self.data)
        self.response_list = []
        for i, question in enumerate(self.question_list):
            i = str(i)
            widget_handler = getattr(self,
                                     '_get_checklist_widget_' + question.type,
                                     None)
            if widget_handler:
                # Adds a Label for each question
                response = ChecklistResponse(
                    question=question,
                    label_widget=Label(text=question.question,
                                       id='Question ' + i,
                                       size_hint_y=None),
                    response_widget=widget_handler(question, i))
                self.checklist_layout.add_widget(response.label_widget)
                self.checklist_layout.add_widget(response.response_widget)
                self.response_list.append(response)
        clear_and_delete = BoxLayout(orientation='horizontal',
                                     id='clear_and_delete',
                                     size_hint_y=None)
        clear_button = Button(text='Clear', id='clear')
        delete_button = Button(text='Delete', id='delete')
        clear_button.bind(on_release=lambda x: self.do_confirm_action('clear'))
        delete_button.bind(
            on_release=lambda x: self.do_confirm_action('delete'))
        clear_and_delete.add_widget(clear_button)
        clear_and_delete.add_widget(delete_button)
        self.checklist_layout.add_widget(clear_and_delete)
        self.submit_button = Button(text='Save', id='submit', size_hint_y=None)
        self.submit_button.bind(on_release=self.do_store_data)
        self.checklist_layout.add_widget(self.submit_button)
        self.clear_widgets()
        self.set_background(self.checklist_layout)
        self.add_widget(self.checklist_layout)

    def do_store_data(self, event):
        """
		Reads each response and writes a .JSON file with questions and responses.
		"""
        store = []
        answer = None
        for response in self.response_list:
            question = response.question
            widget = response.response_widget
            widget_handler = getattr(
                self, '_get_checklist_widget_response_' + question.type, None)
            if widget_handler:
                answer = widget_handler(widget)
            store.append(
                ChecklistQuestion(question=question.question,
                                  type=question.type,
                                  answer=answer)._asdict())

        json_filename = time.strftime('%H:%M_%m-%d-%Y') + '.json'
        file_location = os.path.join('/sdcard/operator/checklists', self.title)
        if not os.path.exists(file_location):
            os.makedirs(file_location)
        store = dict(title=self.title, questions=store)
        with open(os.path.join(file_location, json_filename), 'w') as file_h:
            json.dump(store,
                      file_h,
                      sort_keys=True,
                      indent=2,
                      separators=(',', ': '))
        self.clear_widgets()
        self.do_get_checklists()

    def decode_json(self, json_data):
        """
		Parse through the .JSON input

		:param json_data: JSON file.
		:rtype: list
		:return: An list of three arrays containing strings
		"""
        questions = []
        for question in json_data.get('questions', []):
            if 'question' not in question:
                continue
            q_type = question.get('type', 'text')
            q_answer = question.get('answer')
            if q_answer is None:
                q_answer = {
                    'check': {},
                    'date': ('January', '01', '2015'),
                    'num': 0,
                    'text': '',
                    'yes_no': False
                }[q_type]
                if isinstance(q_answer, dict) and len(q_answer) == 0:
                    for opt in question.get('options', []):
                        q_answer[opt] = False
            questions.append(
                ChecklistQuestion(question=question['question'],
                                  type=q_type,
                                  answer=q_answer))
        return questions

    def do_confirm_action(self, method):
        """
		This function will generate a popup that prompts the user to confirm their decision.

		:param str method: String to indicate the type of action.
		:rtype: bool
		:return: Returns a boolean. If true, the action is confirmed.
		"""
        confirmation_box = BoxLayout(orientation='vertical')
        confirmation_box.add_widget(
            Label(text='Are you sure?\nThis action is permanent.'))
        affirm_and_neg = BoxLayout(orientation='horizontal', spacing=50)
        affirmative = Button(text='Yes')
        negative = Button(text='Cancel')
        if method == "clear":
            affirmative.bind(
                on_release=lambda x: self.do_set_response(True, "clear"))
            negative.bind(
                on_release=lambda x: self.do_set_response(False, "clear"))
        else:
            affirmative.bind(
                on_release=lambda x: self.do_set_response(True, "delete"))
            negative.bind(
                on_release=lambda x: self.do_set_response(False, "delete"))
        affirm_and_neg.add_widget(affirmative)
        affirm_and_neg.add_widget(negative)
        confirmation_box.add_widget(affirm_and_neg)
        self.confirmation_popup = Popup(title='Confirmation',
                                        content=confirmation_box,
                                        size_hint=(.7, None),
                                        size=(650, 500),
                                        auto_dismiss=False)
        self.confirmation_popup.open()

    def do_set_response(self, response, method):
        """
		Calls the appropriate method after being confirmed. If not confirmed, the popup is dismissed with no action taken.

		:param bool response: Boolean to confirm response.
		:param str method: String to confirm the type of action.
		"""
        if method == "clear" and response:
            self.do_clear_data()
        elif method == "delete" and response:
            self.do_delete_data()
        self.confirmation_popup.dismiss()

    def do_clear_data(self):
        """
		Clears all responses of the current checklist. This does not delete the checklist.
		"""
        for child in self.checklist_layout.walk():
            if isinstance(child, (TextInput, FloatInput)):
                child.text = ''
            elif isinstance(child, Spinner):
                if 'day' in child.id:
                    child.text = '01'
                elif 'month' in child.id:
                    child.text = 'January'
                elif 'year' in child.id:
                    child.text = '2015'
            elif isinstance(child, CheckBox):
                child.active = False

    def do_delete_data(self):
        """
		Deletes the desired checklist (the directory).
		"""
        shutil.rmtree('/sdcard/operator/checklists/' + self.title)
        self.clear_widgets()
        self.do_get_checklists()
Пример #38
0
def show_update_ingredient_popup():
    show = UpdateIngredientPopUp()
    popup_window = Popup(title="Update Ingredient", content=show)
    show.ids.cancel.bind(on_press=popup_window.dismiss)
    popup_window.open()
Пример #39
0
class SettingCSVReader(SettingPath):
    app_ref = ObjectProperty(None)
    data_viewer = DataViewer()

    def _create_popup(self, instance):
        # create popup layout
        content = BoxLayout(orientation='vertical', spacing=5)
        popup_width = min(0.95 * Window.width, dp(500))
        self.popup = popup = Popup(title=self.title,
                                   content=content,
                                   size_hint=(None, 0.9),
                                   width=popup_width)

        # create the filechooser
        initial_path = os.path.join(os.getcwd(), app_settings.flame_log_dir)
        self.textinput = textinput = FileChooserListView(
            path=initial_path,
            size_hint=(1, 1),
            dirselect=False,
            show_hidden=self.show_hidden,
            filters=['*.csv'])
        #textinput.bind(on_path=self._print_csv_data)

        # construct the content
        content.add_widget(textinput)
        content.add_widget(SettingSpacer())

        # 2 buttons are created for accept or cancel the current value
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = Button(text='Open')
        btn.bind(on_release=self._csv_data_popup)
        btnlayout.add_widget(btn)
        btn = Button(text='Close')
        btn.bind(on_release=self._dismiss)
        btnlayout.add_widget(btn)
        content.add_widget(btnlayout)

        # all done, open the popup !
        popup.open()

    def _csv_data_popup(self, instance):
        value = self.textinput.selection[0]

        if not value:
            return

        # read csv file
        with open(value, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            items = [row for row in reader]
            self.data_viewer.clear()
            for i, item in reversed(list(enumerate(items[0]))):
                self.data_viewer.insert(item + ':   ' + items[1][i])

        # create popup layout
        self.csv_content = BoxLayout(orientation='vertical', spacing=5)
        popup_width = min(0.95 * Window.width, dp(500))
        self.csv_popup = Popup(title=value,
                               content=self.csv_content,
                               size_hint=(None, 0.9),
                               width=popup_width)

        # construct the self.csv_content
        self.csv_content.add_widget(SettingSpacer())
        self.csv_content.add_widget(self.data_viewer)
        self.csv_content.add_widget(SettingSpacer())

        # 2 buttons are created for accept or cancel the current value
        btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
        btn = Button(text='Close')
        btn.bind(on_release=self._csv_dismiss)
        btnlayout.add_widget(btn)
        self.csv_content.add_widget(btnlayout)

        # all done, open the popup !
        self.csv_popup.open()

    def _csv_dismiss(self, instance):
        self.csv_popup.dismiss()
        self.csv_content.remove_widget(self.data_viewer)
Пример #40
0
    def showPopup(self):
        plateImage = self.ids['plate-image']
        plate0 = self.ids['plate0']
        plate1 = self.ids['plate1']
        plate2 = self.ids['plate2']
        plate3 = self.ids['plate3']
        plate4 = self.ids['plate4']
        plate5 = self.ids['plate5']
        plate6 = self.ids['plate6']
        plate7 = self.ids['plate7']
        layout = FloatLayout()

        popupLabel = Label(text="Error: Please click "
                           "\n\"Verify Image\" before "
                           "\nsubmitting photo!",
                           size_hint=(0.8, 1),
                           pos_hint={
                               'x': 0.1,
                               'y': 0
                           },
                           halign='center',
                           valign='middle',
                           text_size=self.size)
        popupButton = Button(text="X",
                             background_normal='',
                             background_color=(1, 0, 0, 1),
                             size_hint=(0.1, 0.05),
                             pos_hint={
                                 'x': 0.9,
                                 'y': 0.9
                             },
                             font_size=12)

        layout.add_widget(popupLabel)
        layout.add_widget(popupButton)

        popupWindow = Popup(
            title="ERROR: VERIFY IMAGE",
            # "ERROR 404 YOUR COMPUTER IS CORRUPTED INSTALL ANTIVIRUS IMMEDIATELY",
            content=layout,
            size_hint=(None, None),
            size=(250, 250))
        popupButton.bind(on_press=popupWindow.dismiss)

        if len(str(plateImage.source)) > 0:
            global plateNumber
            plateNumber = plate0.text + plate1.text + plate2.text + plate3.text + plate4.text + \
                          plate5.text + plate6.text + plate7.text
            print(plateNumber)
            if self.isNewPlate():
                self.parent.current = "third"
            else:
                self.parent.current = "fourth"
            self.replaceImage()


#            self.plateNumber =

        else:
            self.parent.current = "second"
            self.replaceImage()
            popupWindow.open()
Пример #41
0
class MainLayout(BoxLayout):
    player1 = True
    player2 = False
    bsound = SoundLoader.load("sound/fireEffect.ogg")

    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)

        Window.bind(on_joy_axis=self.on_joy_axis)
        Window.bind(on_joy_button_down=self.on_joy_button_down)

        self.ids.lb.text = "[color=0000ff]Player1[/color]"
        self.ids.resetgame.bind(on_press=self.reset)

        self.ids.click1.bind(on_press=self.on_press1)
        self.ids.click2.bind(on_press=self.on_press2)
        self.ids.click3.bind(on_press=self.on_press3)
        self.ids.click4.bind(on_press=self.on_press4)
        self.ids.click5.bind(on_press=self.on_press5)
        self.ids.click6.bind(on_press=self.on_press6)
        self.ids.click7.bind(on_press=self.on_press7)
        self.ids.click8.bind(on_press=self.on_press8)
        self.ids.click9.bind(on_press=self.on_press9)

    def on_press1(self, obj):

        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click1.text = "[color=0000ff]X[/color]"
            self.ids.click1.disabled = True
            lista.append("x")
            listd.append("x")
            listg.append("x")

        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click1.text = "[color=ff0000]O[/color]"
            self.ids.click1.disabled = True
            lista.append("o")
            listd.append("o")
            listg.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press2(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click2.text = "[color=0000ff]X[/color]"
            self.ids.click2.disabled = True
            lista.append("x")
            liste.append("x")

        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click2.text = "[color=ff0000]O[/color]"
            self.ids.click2.disabled = True
            lista.append("o")
            liste.append("o")

        Clock.schedule_once(self.winner, 0.1)

    def on_press3(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click3.text = "[color=0000ff]X[/color]"
            self.ids.click3.disabled = True
            lista.append("x")
            listf.append("x")
            listh.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click3.text = "[color=ff0000]O[/color]"
            self.ids.click3.disabled = True
            lista.append("o")
            listf.append("o")
            listh.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press4(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click4.text = "[color=0000ff]X[/color]"
            self.ids.click4.disabled = True
            listb.append("x")
            listd.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click4.text = "[color=ff0000]O[/color]"
            self.ids.click4.disabled = True
            listb.append("o")
            listd.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press5(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click5.text = "[color=0000ff]X[/color]"
            self.ids.click5.disabled = True
            listb.append("x")
            liste.append("x")
            listg.append("x")
            listh.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click5.text = "[color=ff0000]O[/color]"
            self.ids.click5.disabled = True
            listb.append("o")
            liste.append("o")
            listg.append("o")
            listh.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press6(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click6.text = "[color=0000ff]X[/color]"
            self.ids.click6.disabled = True
            listb.append("x")
            listf.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click6.text = "[color=ff0000]O[/color]"
            self.ids.click6.disabled = True
            listb.append("o")
            listf.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press7(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click7.text = "[color=0000ff]X[/color]"
            self.ids.click7.disabled = True
            listc.append("x")
            listd.append("x")
            listh.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click7.text = "[color=ff0000]O[/color]"
            self.ids.click7.disabled = True
            listc.append("o")
            listd.append("o")
            listh.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press8(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click8.text = "[color=0000ff]X[/color]"
            self.ids.click8.disabled = True
            listc.append("x")
            liste.append("x")

        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click8.text = "[color=ff0000]O[/color]"
            self.ids.click8.disabled = True
            listc.append("o")
            liste.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def on_press9(self, obj):
        self.bsound.play()
        if self.player1 == True:
            self.player1 = False
            self.player2 = True
            self.ids.lb.text = "[color=ff0000]Player2[/color]"
            self.ids.click9.text = "[color=0000ff]X[/color]"
            self.ids.click9.disabled = True
            listc.append("x")
            listf.append("x")
            listg.append("x")
        else:
            self.player2 = False
            self.player1 = True
            self.ids.lb.text = "[color=0000ff]Player1[/color]"
            self.ids.click9.text = "[color=ff0000]O[/color]"
            self.ids.click9.disabled = True
            listc.append("o")
            listf.append("o")
            listg.append("o")
        Clock.schedule_once(self.winner, 0.1)

    def reset(self, obj):
        lista.clear(), listb.clear(), listc.clear(), listd.clear(
        ), liste.clear(), listf.clear(), listg.clear(), listh.clear()
        pdata = ""
        self.ids.lb.text = "[color=0000ff]Player1[/color]"

        self.player1 = True
        self.player2 = False
        self.ids.click1.text = ""
        self.ids.click2.text = ""
        self.ids.click3.text = ""
        self.ids.click4.text = ""
        self.ids.click5.text = ""
        self.ids.click6.text = ""
        self.ids.click7.text = ""
        self.ids.click8.text = ""
        self.ids.click9.text = ""
        #enable

        self.ids.click1.disabled = False
        self.ids.click2.disabled = False
        self.ids.click3.disabled = False
        self.ids.click4.disabled = False
        self.ids.click5.disabled = False
        self.ids.click6.disabled = False
        self.ids.click7.disabled = False
        self.ids.click8.disabled = False
        self.ids.click9.disabled = False

        #set Background
        self.ids.click1.background_color = [0, 0, .8, .5]
        self.ids.click2.background_color = [0, 0, .8, .5]
        self.ids.click3.background_color = [0, 0, .8, .5]
        self.ids.click4.background_color = [0, 0, .8, .5]
        self.ids.click5.background_color = [0, 0, .8, .5]
        self.ids.click6.background_color = [0, 0, .8, .5]
        self.ids.click7.background_color = [0, 0, .8, .5]
        self.ids.click8.background_color = [0, 0, .8, .5]
        self.ids.click9.background_color = [0, 0, .8, .5]

    def on_joy_axis(self, win, stickid, axisid, value):
        print(stickid, axisid, value)

    def on_joy_button_down(self, win, stickid, buttonid):
        # player1
        if buttonid == 0 and self.player1 == True and self.ids.click1.disabled == False:
            self.on_press1(win)
        elif buttonid == 1 and self.player1 == True and self.ids.click2.disabled == False:

            self.on_press2(win)

        elif buttonid == 2 and self.player1 == True and self.ids.click3.disabled == False:

            self.on_press3(win)
        elif buttonid == 3 and self.player1 == True and self.ids.click4.disabled == False:
            self.on_press4(win)
        elif buttonid == 4 and self.player1 == True and self.ids.click5.disabled == False:
            self.on_press5(win)
        elif buttonid == 5 and self.player1 == True and self.ids.click6.disabled == False:

            self.on_press6(win)
        elif buttonid == 6 and self.player1 == True and self.ids.click7.disabled == False:

            self.on_press7(win)
        elif buttonid == 7 and self.player1 == True and self.ids.click8.disabled == False:

            self.on_press8(win)
        elif buttonid == 8 and self.player1 == True and self.ids.click9.disabled == False:

            self.on_press9(win)
        elif buttonid == 9:
            # self.on_press9(win)
            self.reset(win)
            justdismiss = False

        # player2
        elif buttonid == 10 and self.player2 == True and self.ids.click1.disabled == False:

            self.on_press1(win)

        elif buttonid == 11 and self.player2 == True and self.ids.click2.disabled == False:

            self.on_press2(win)
        elif buttonid == 12 and self.player2 == True and self.ids.click3.disabled == False:

            self.on_press3(win)
        elif buttonid == 13 and self.player2 == True and self.ids.click4.disabled == False:

            self.on_press4(win)
        elif buttonid == 14 and self.player2 == True and self.ids.click5.disabled == False:

            self.on_press5(win)
        elif buttonid == 15 and self.player2 == True and self.ids.click6.disabled == False:

            self.on_press6(win)
        elif buttonid == 16 and self.player2 == True and self.ids.click7.disabled == False:

            self.on_press7(win)
        elif buttonid == 17 and self.player2 == True and self.ids.click8.disabled == False:

            self.on_press8(win)
        elif buttonid == 18 and self.player2 == True and self.ids.click9.disabled == False:

            self.on_press9(win)
        elif buttonid == 19:
            self.reset(win)
        print(buttonid)

    def winner(self, obj):
        pdata = ""
        title = ""

        sound = SoundLoader.load("sound/Sax.ogg")
        box = BoxLayout(orientation="vertical")
        box.add_widget(
            Image(
                source='images/gamepad3.png',
                allow_stretch=False,
                keep_ratio=False,
            ))
        if lista == standx or listb == standx or listc == standx or listd == standx or liste == standx or listf == standx or listg == standx or listh == standx:
            pdata = "[color=00ff00]Game over[/color]: [color=0000ff] player 1 win[/color]"
            title = "Congratulations player1"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]
            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            Clock.unschedule(self.winner, .1)
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()

        elif lista == stando or listb == stando or listc == stando or listd == stando or liste == stando or listf == stando or listg == stando or listh == stando:
            pdata = "[color=00ff00]Game over[/color]:[color=ff0000] player 2 win[/color]"
            title = "Congratulations player2"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]

            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()

        elif self.ids.click1.disabled == True and self.ids.click2.disabled == True and self.ids.click3.disabled == True and self.ids.click4.disabled == True and self.ids.click5.disabled == True and self.ids.click6.disabled == True and self.ids.click7.disabled == True and self.ids.click8.disabled == True and self.ids.click9.disabled == True:

            pdata = "[color=00ff00]Game over[/color]: [color=f0ff00] Drwa [/color]"
            title = "No Winner"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]

            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()

        #print(pdata)
        #print(lista,listb,listc,listd,liste,listf,listg,listh)

    def keyspop(self):
        box = BoxLayout(orientation="vertical")
        # box.add_widget(Image(source='images/appic.png', allow_stretch=False, keep_ratio=False, ))
        keysdata = "[color=f000ff]F11[/color]: \n" \
                   "[color=00ff00]Rotate the Window through 0, 90, 180 and 270 degrees[/color]\n\n" \
                   "[color=f000ff]Shift + F11[/color]: \n" \
                   "[color=00ff00]Switches between portrait and landscape on desktops[/color]\n\n" \
                   "[color=f000ff]F12[/color]: \n[color=00ff00]Take a screenshot[/color]\n\n"
        lb1 = Label(text=keysdata, markup=True)
        lb1.font_name = "fonts/DroidSans-Bold.ttf"
        lb1.bold = True
        box.add_widget(lb1)
        content2 = box
        self.popup = Popup(title="Special Keys",
                           content=content2,
                           size_hint=(None, None),
                           size=(500, 300))

        self.popup.background = "images/im2.png"
        self.popup.title_size = 30

        self.popup.title_color = [1, 1, 0, 1]
        self.popup.title_font = "fonts/actionis.ttf"
        self.popup.open()

    def author(self):
        box = BoxLayout(orientation="vertical")
        box.add_widget(
            Image(
                source='images/author.jpg',
                allow_stretch=False,
                keep_ratio=False,
            ))
        data = "Author :[color=ffff00]Ahmed Mohmed[/color]\nVersion :[color=ffff00]1.0[/color]"
        lb2 = Label(text=data, markup=True, font_size=30)
        lb2.font_name = "fonts/DancingScript-Bold.ttf"
        box.add_widget(lb2)
        content3 = box
        title = "About Tic Tac Toc"

        popup = Popup(title="About Tic Tac Toc",
                      content=content3,
                      size_hint=(None, None),
                      size=(400, 400))
        # popup.background_color=[0,1,1,1]
        popup.background = "images/au.jpg"
        popup.title_size = 30
        popup.title_color = [1, 1, 0, 1]
        popup.title_font = "fonts/actionis.ttf"
        popup.open()

    def control(self):
        box = BoxLayout(orientation="vertical")
        box.add_widget(
            Image(
                source='images/gamepad.jpg',
                allow_stretch=False,
                keep_ratio=False,
            ))
        content3 = box

        popup = Popup(title="Controlling",
                      content=content3,
                      size_hint=(None, None),
                      size=(500, 500))
        # popup.background_color=[0,1,1,1]
        popup.background = "images/au.jpg"
        popup.title_size = 30
        popup.title_color = [1, 1, 0, 1]
        popup.title_font = "fonts/actionis.ttf"
        popup.open()
Пример #42
0
    def update(self, dt):
        # display image from cam in opencv window
        global counter, meme_counter, meme, alarm, lookaway, memescreen, alarm_sound, notif_sound, meme_threshold, lookaway_threshold
        ret, frame = self.capture.read()
        cv2.imshow("CV2 Image", frame)
        # convert it to texture
        buf1 = cv2.flip(frame, 0)
        buf = buf1.tostring()
        texture1 = Texture.create(size=(frame.shape[1], frame.shape[0]),
                                  colorfmt='bgr')
        texture1.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
        # display image from the texture
        self.img1.texture = texture1

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        # display meme
        if (meme):
            ## load meme here
            idx = random.randint(0, 4)
            meme_src = src_path + meme_dict[idx]
            box = BoxLayout(padding=10, orientation='vertical')
            subbox1 = BoxLayout(padding=10, size_hint=(1, 0.8))
            subbox2 = BoxLayout(padding=10, size_hint=(1, 0.2))

            subbox1.add_widget(Image(source=meme_src))
            dismiss_btn = Button(text='Back to work!')

            subbox2.add_widget(dismiss_btn)

            box.add_widget(subbox1)
            box.add_widget(subbox2)
            popup = Popup(title='MEME', content=box, size=(400, 400))

            dismiss_btn.bind(on_press=popup.dismiss)
            popup.open()

            # play sound. set to repeat on half the length.
            if (notif_sound):
                notif_sound.play()
            print("meme loaded!")
            meme = False
            meme_counter = meme_counter / 2

        # play alarm noise. repeat every half length
        if (alarm):
            print("WAKE UP!")
            if (alarm_sound):
                alarm_sound.play()
            alarm = False
            counter = counter / 2

        if (lookaway):
            counter += 1
            print("lookaway:", counter)

        ## find faces. find eyes and smiles within faces.
        for (x, y, w, h) in faces:
            roi_gray = gray[y:y + h, x:x + w]
            roi_color = frame[y:y + h, x:x + w]

            eyes = eye_cascade.detectMultiScale(roi_gray)
            eyes = list(eyes)

            smile = smile_cascade.detectMultiScale(roi_gray, 1.8, 8)
            smile = list(smile)

            if (len(eyes) == 2):
                for (ex, ey, ew, eh) in eyes:
                    #print("eyes")
                    cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh),
                                  (0, 255, 0), 2)
                counter = 0

            if (len(smile) >= 1):
                for (sx, sy, sw, sh) in smile:
                    cv2.rectangle(roi_color, (sx, sy), (sx + sw, sy + sh),
                                  (0, 0, 255), 2)
                meme_counter = 0
                meme = False

            else:
                if (len(eyes) > 1):
                    if (memescreen):
                        print("meme counter: ", meme_counter)
                        meme_counter += 1
                    #print(meme_counter)

        if (lookaway):
            if (counter > lookaway_threshold):
                alarm = True

        if (memescreen):
            if (meme_counter > meme_threshold):
                print("Loading meme... ")
                meme = True
Пример #43
0
    def load_parcel(self, parcel_id):
        # if parcel is already loaded in robot
        if parcel_id in [p['id'] for p in self.parcels]:
            print("parcel already loaded")
            return False

        # if parcel is not yet loaded
        with open(self.lockers_path) as f:
            self.lockers = json.load(f)['lockers']

        # get the first empty locker
        for locker in self.lockers:
            if locker["has_parcel"] == False:
                loader = LoadingPopup()
                locker["uuid"] = randint(100, 999)
                data = {
                    'id': parcel_id,
                    'robot_compartment': locker['id'],
                    'uuid': locker["uuid"]
                }
                self.req = requests.post(config.URL + '/api/parcel/load',
                                         headers=config.HEADERS,
                                         json=data)
                print(self.req)
                if (self.req.status_code == requests.codes.ok):
                    print('loaded')
                    loader.stop_t()
                    self.parcels.append({
                        'id': parcel_id,
                        'locker_id': locker['id']
                    })
                    locker['parcel_id'] = parcel_id
                    locker['has_parcel'] = True
                    self.write_to_store()
                    box = FloatLayout()
                    label = Label(
                        text="Load parcel into \n[size=55][color=ffb355]" +
                        ' ' * 6 + locker['id'].strip('L') + "[/color][/size]",
                        pos_hint={
                            'center_x': .5,
                            'center_y': .7
                        },
                        markup=True,
                        color=(0, 0, 0, 1))
                    btn = RoundedButton(text='Unlock',
                                        pos_hint={
                                            'center_x': 0.5,
                                            'center_y': 0.4
                                        },
                                        size_hint=(0.45, 0.2),
                                        color=(0, 0, 0, 1))
                    self.bindFn = lambda *args: self.do_load(locker, btn)
                    btn.bind(on_press=self.bindFn)
                    box.add_widget(label)
                    box.add_widget(btn)
                    popup = Popup(title="Parcel Registered!",
                                  content=box,
                                  auto_dismiss=False,
                                  size_hint=(None, None),
                                  size=(400, 400))
                    popup.open()
                    self.popups.append(popup)
                    return True
                else:
                    loader.stop_t()
                    raise ValueError(self.req.json())
                    return False
Пример #44
0
class SidebarWidget(BoxLayout):
    def __init__(self, ps, fpm, **kwargs):
        super().__init__(**kwargs)
        self.ps = ps
        self.fpm = fpm

    def init_input(self, filename):
        '''
        Parses file input to ensure that source data is correct

        Args:
            filename: name of input file ending with .txt

        Returns:
            output: parsed input file in the form of a string

            for example, "ACTGGTGACTGTAAG"
        '''
        input_data = []
        for i in range(2):
            reader = open(filename)
            for line in reader:
                line_arr = line.split(' ')
                for index, substring in enumerate(line_arr):
                    if index == 0:
                        continue
                    char_arr = list(substring)
                    if char_arr[len(char_arr) - 1] == '\n':
                        char_arr.pop()
                    input_data += char_arr
            break

        expression = re.compile('[acgt]*')
        output = ''
        for i in input_data:
            if (re.fullmatch(expression, i) != None):
                output += i

        return output

    def open_explorer(self):
        # create popup
        self.browser = FileChooserListView()
        self.browser.path = os.getcwd()
        self.popup = Popup(title='File Browser',
                           content=self.browser,
                           size_hint=(0.9, 0.9),
                           auto_dismiss=True)
        self.browser.bind(on_submit=self.choose_file)
        self.popup.open()

    def choose_file(self, useless1, filename, useless2):
        self.popup.dismiss()
        try:
            output = self.init_input(filename[0])
        except FileNotFoundError:
            Popup(title='Error',
                  content=Label(text='File was not found'),
                  size_hint=(0.9, 0.9),
                  auto_dismiss=True).open()
            return
        except IndexError:
            Popup(title='Error',
                  content=Label(text='File was not found'),
                  size_hint=(0.9, 0.9),
                  auto_dismiss=True).open()
            return

        self.ps.set_input_data(output)
        self.fpm.set_input_data(output)
Пример #45
0
class Notes(Screen):
    userId = StringProperty("")
    note_id = StringProperty("")

    def __init__(self, **kwargs):
        super(Notes, self).__init__()
        self.DB = Database()
        Menu.logout = self.logout
        Menu.update_user = self.update_user
        Menu.insert_note = self.insert_note
        Menu.goto_notes = self.goto_notes
        NotePage.update_note = self.update_note
        NotePage.popup = self.deletePopup

        Clock.schedule_interval(self.reminder, 10)

    def on_enter(self, *args):
        x = datetime.datetime.now()
        year = x.strftime("%y")
        self.userId = self.manager.userId
        self.ids.container.clear_widgets()
        con = sqlite3.connect(self.DB.DB_PATH)
        cursor = con.cursor()
        x = ("select * from Notes where UserId= " + str(self.userId) + "")
        cursor.execute(x)
        result = cursor.fetchall()
        for i in result:
            wid = NotePage()
            r2 = ' Subject: ' + i[2] + '\n' + ' Note: ' + i[
                3] + '\n' + ' Clock: ' + str(i[4]) + ":" + str(
                    i[5]) + '\n' + ' Date: ' + str(
                        i[6]) + "/" + str(i[7] + "/" + year)
            wid.note_id = str(i[0])
            wid.note = r2
            self.ids.container.add_widget(wid)

        con.close()

    def reminder(self, id):
        box = BoxLayout(orientation='vertical')
        now = datetime.datetime.now()
        day = now.strftime("%d")
        month = now.strftime("%m")
        hour = now.strftime("%H")
        minute = now.strftime("%M")
        con = sqlite3.connect(self.DB.DB_PATH)
        cursor = con.cursor()
        x3 = ("select * from Notes where Hour='" + hour + "' and Minute= '" +
              minute + "' and Day='" + day + "' and Month='" + month + "'")
        cursor.execute(x3)
        result = cursor.fetchall()
        for nots in result:
            subject = nots[2]
            note = nots[3]
            box.add_widget(Image(source="Images/reminder.png"))
            box.add_widget(
                Label(text="Subject: " + subject, bold=True, italic=True))
            box.add_widget(Label(text="Note: " + note, bold=True, italic=True))

            deleteButton = Button(text="Delete",
                                  id="element" + str(nots[0]),
                                  bold=True,
                                  italic=True)
            deleteButton.bind(on_release=partial(self.delete_note, nots[0]))
            box.add_widget(deleteButton)

            editButton = Button(text="PostPone", bold=True, italic=True)
            editButton.bind(on_press=partial(self.Postpone, nots[0]))
            box.add_widget(editButton)

            self.popUp = Popup(title='',
                               content=box,
                               size_hint=(None, None),
                               size=(400, 400),
                               auto_dismiss=False)

            self.popUp.open()

    def delete_note(self, id, instance):
        con = sqlite3.connect(self.DB.DB_PATH)
        cursor = con.cursor()
        s = "delete from Notes where NoteId='" + str(id) + "'"
        cursor.execute(s)
        con.commit()
        con.close()
        for child in self.ids.container.children:
            if str(child.note_id) == str(id):
                self.ids.container.remove_widget(child)
                self.popUp.dismiss()

    def delete_note_fromPopup(self, id, instance):
        con = sqlite3.connect(self.DB.DB_PATH)
        cursor = con.cursor()
        s = "delete from Notes where NoteId='" + id + "'"
        cursor.execute(s)
        con.commit()
        con.close()
        for child in self.ids.container.children:
            if child.note_id == id:
                self.ids.container.remove_widget(child)
                self.popup.dismiss()

    def deletePopup(self, id):
        box = BoxLayout(orientation='vertical', padding=(10))
        box.add_widget(Image(source="Images/question.png"))
        box.add_widget(
            Label(text="Are you sure you want to delete this note?",
                  bold=True,
                  italic=True))
        self.popup = Popup(title=" ",
                           content=box,
                           size_hint=(None, None),
                           size=(350, 350),
                           auto_dismiss=False)

        deleteButton = Button(text="YES", bold=True, italic=True)
        deleteButton.bind(on_press=partial(self.delete_note_fromPopup, id))
        box.add_widget(deleteButton)
        box.add_widget(
            Button(text="NO",
                   bold=True,
                   italic=True,
                   on_press=self.popup.dismiss))
        self.popup.open()

    def logout(self):
        self.manager.current = "login"

    def update_user(self, userId):
        UpdateUser.userId = self.manager.userId
        self.manager.current = "updateuser"

    def insert_note(self):
        self.manager.current = "insertnote"

    def update_note(self, note_id):
        self.goto_updatenote(note_id)

    def update_notePopup(self, note_id, instance):
        self.manager.current = "updatenote"
        self.popUp.dismiss()

    def goto_notes(self):
        self.manager.current = "notes"

    def goto_updatenote(self):
        pass

    def Postpone(self, id, instance):

        x = 5
        now = datetime.datetime.now()
        minute = now.strftime("%M")
        hour = now.strftime("%H")
        day = now.strftime("%d")
        month = now.strftime("%m")
        con = sqlite3.connect(self.DB.DB_PATH)
        cursor = con.cursor()
        minute = int(minute) + x
        TotalDays = calendar.monthrange(now.year, now.month)[1]

        if minute >= 60:
            eklenecek = minute - 60
            minute = 00 + eklenecek
            minute = ("{:02d}".format(minute))
            hour = int(hour) + 1
            if hour >= 24:
                hour = hour - 24
                hour = ("{:02d}".format(hour))
                day = int(day) + 1
                if day > TotalDays:
                    day = day - TotalDays
                    day = ("{:02d}".format(day))
                    month = int(month) + 1
                    if month > 12:
                        month = 1
                        month = ("{:02d}".format(month))

            x1 = (hour, minute, day, month)
            s3 = 'update Notes set '
            s4 = 'Hour="%s", Minute="%s",Day="%s",Month="%s"' % x1
            s5 = ' where NoteId=%s' % id
            cursor.execute(s3 + s4 + s5)
            con.commit()
            con.close()
            self.popUp.dismiss()
            self.on_enter(instance)
        else:
            minute = ("{:02d}".format(minute))
            s = 'update Notes set '
            s1 = ' Minute="%s"' % minute
            s2 = ' where NoteId=%s' % id
            cursor.execute(s + s1 + s2)
            con.commit()
            con.close()
            self.popUp.dismiss()
            self.on_enter(instance)
Пример #46
0
    def winner(self, obj):
        pdata = ""
        title = ""

        sound = SoundLoader.load("sound/Sax.ogg")
        box = BoxLayout(orientation="vertical")
        box.add_widget(
            Image(
                source='images/gamepad3.png',
                allow_stretch=False,
                keep_ratio=False,
            ))
        if lista == standx or listb == standx or listc == standx or listd == standx or liste == standx or listf == standx or listg == standx or listh == standx:
            pdata = "[color=00ff00]Game over[/color]: [color=0000ff] player 1 win[/color]"
            title = "Congratulations player1"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]
            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            Clock.unschedule(self.winner, .1)
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()

        elif lista == stando or listb == stando or listc == stando or listd == stando or liste == stando or listf == stando or listg == stando or listh == stando:
            pdata = "[color=00ff00]Game over[/color]:[color=ff0000] player 2 win[/color]"
            title = "Congratulations player2"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]

            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()

        elif self.ids.click1.disabled == True and self.ids.click2.disabled == True and self.ids.click3.disabled == True and self.ids.click4.disabled == True and self.ids.click5.disabled == True and self.ids.click6.disabled == True and self.ids.click7.disabled == True and self.ids.click8.disabled == True and self.ids.click9.disabled == True:

            pdata = "[color=00ff00]Game over[/color]: [color=f0ff00] Drwa [/color]"
            title = "No Winner"
            lb1 = Label(text=pdata, markup=True, font_size=25)
            lb1.font_name = "fonts/DroidSans-Bold.ttf"
            lb1.bold = True
            butt1 = Button(text="Play Again")
            box.add_widget(lb1)
            box.add_widget(butt1)
            content2 = box
            popup = Popup(title=title,
                          content=content2,
                          size_hint=(None, None),
                          size=(400, 400))

            popup.background = "images/au.jpg"
            popup.title_size = 30

            popup.title_color = [1, 1, 0, 1]
            popup.title_font = "fonts/actionis.ttf"
            butt1.background_color = [1, 1, 0, 1]

            butt1.bind(on_release=self.reset)
            butt1.bind(on_release=popup.dismiss)

            popup.open()
            anim = Animation(x=50) + Animation(size=(300, 300), duration=2.)
            anim.start(popup)

            sound.play()
            lista.clear(), listb.clear(), listc.clear(), listd.clear(
            ), liste.clear(), listf.clear(), listg.clear(), listh.clear()
Пример #47
0
def show_popup():
    show = P()
    popupWindow = Popup(title="Popup Window", content=show, size_hint=(None, None), size = (400, 400))

    popupWindow.open()
Пример #48
0
    def unlock_parcel(self, code):
        code = json.loads(code)
        uuid = code['uuid']
        with open(self.lockers_path) as f:
            self.lockers = json.load(f)['lockers']
        if uuid in [str(l['uuid']) for l in self.lockers]:
            for locker in self.lockers:
                print(locker)
                try:
                    if str(locker['uuid']) == uuid:
                        print('unlock', code)
                        loader = LoadingPopup()
                        req = requests.post(config.URL + '/api/parcel/unlock',
                                            headers=config.HEADERS,
                                            json=code)
                        print(req)
                        if (req.status_code == requests.codes.ok):
                            loader.stop_t()
                            # load successful unlock popup
                            box = FloatLayout()
                            label = Label(text="Open locker\n" + " " * 8 +
                                          "[size=65][color=ffb355]" +
                                          locker['id'].strip('L') +
                                          "[/color][/size]",
                                          pos_hint={
                                              'center_x': .5,
                                              'center_y': .7
                                          },
                                          markup=True,
                                          color=(0, 0, 0, 1))
                            btn = RoundedButton(text="Unlock",
                                                pos_hint={
                                                    'center_x': 0.5,
                                                    'center_y': 0.35
                                                },
                                                size_hint=(0.45, 0.2),
                                                color=(0, 0, 0, 1))
                            self.bindFn = lambda *args: self.do_unlock(
                                locker['id'], btn)
                            btn.bind(on_press=self.bindFn)
                            box.add_widget(label)
                            box.add_widget(btn)
                            popup = Popup(title="Locker unlocked!",
                                          content=box,
                                          auto_dismiss=False,
                                          size_hint=(None, None),
                                          size=(400, 400))

                            popup.open()
                            self.popups.append(popup)
                            return True
                        else:
                            return False

                except Exception as e:
                    popup = Popup(
                        title="Hiccup",
                        content=Label(text="There was a minor error:\n " +
                                      str(e),
                                      color=(0, 0, 0, 1),
                                      font_size=18,
                                      pos_hint={
                                          'center_x': .5,
                                          'center_y': .6
                                      }),
                        size_hint=(None, None),
                        size=(400, 400))
                    popup.open()

                    pass
        else:
            popup = Popup(title="Error",
                          content=Label(
                              text="""This robot doesn't have your parcel.
                        \nCheck your robot location again, or 
                        \ncall our helpline at 96959382.""",
                              font_size=18,
                              color=(0, 0, 0, 1),
                              pos_hint={
                                  'center_x': .5,
                                  'center_y': .6
                              }),
                          size_hint=(None, None),
                          size=(400, 400))
            popup.open()

            return False
Пример #49
0
class ConvertToDraft(Screen):

    container = None

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load_primers(self, title='Load file'):
        content = LoadDialog(load=self.load_primers, cancel=self.dismiss_popup)
        self._popup = Popup(title=title, content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def load_primers(
        self,
        path,
        filename,
    ):
        self.ids['filename_text_input_primers'].text = os.path.join(
            path, filename[0])
        self.dismiss_popup()

    def startConverting(self, *args):
        app = App.get_running_app()
        app.root.ids['menu_screen'].ids[
            'convert_to_draft_menu_button'].background_color = (0.15, 0.35,
                                                                0.54, 1)
        self.ids[
            'convert_to_draft_log'].text = 'Started converting to draft-primers...'
        t = threading.Thread(target=self.runAdding)
        t.start()

    def runAdding(self, *args):
        global global_image_names, available_images
        try:
            client = docker.from_env()
        except:
            print('ERROR (1)! Could not connect to docker VM')
            exit(1)
        inputFilePath = self.ids['filename_text_input_primers'].text
        inputDir = os.path.dirname(inputFilePath)
        inputFileName = os.path.basename(inputFilePath)
        drive = os.path.splitdrive(inputDir)
        if drive[0] != '':
            inputDir = '/' + drive[0].replace(':', '') + drive[1].replace(
                '\\', '/')
        mounts = [Mount(target='/input', source=inputDir, type='bind')]
        cmd = [
            'python3', '/NGS-PrimerPlex/convertToDraftFile.py', '-in',
            '/input/' + inputFileName, '-out',
            '/input/' + inputFileName[:inputFileName.rfind('.')] + '.draft.xls'
        ]
        for image_name, available_image in zip(global_image_names,
                                               available_images):
            # If image without reference is available, use it
            # Elif image with zipped hg19 available, use it
            if available_image:
                break
        try:
            self.container = client.containers.run(image_name,
                                                   ' '.join(cmd),
                                                   mounts=mounts,
                                                   detach=True,
                                                   entrypoint='')
        except:
            print('ERROR (2)! Could not run image:')
            print('Image name: aakechin/ngs-primerplex')
            print('Command: ' + ' '.join(cmd))
            print('Mounts: ' + ', '.join(map(str, mounts)))
            exit(2)
        for stat in self.container.stats():
            containerStats = json.loads(stat.decode('utf-8'))
            newLog = self.container.logs().decode('utf-8')
            if newLog != '':
                writtenLog = self.ids['convert_to_draft_log'].text
                if newLog != writtenLog:
                    logParts = newLog.split('\n')
                    newLogParts = []
                    for n, part in enumerate(logParts):
                        if '%' in part:
                            if n < len(logParts) - 1 and '%' not in logParts[
                                    n + 1]:
                                newLogParts.append(part)
                            elif n == len(logParts) - 1:
                                newLogParts.append(part)
                        else:
                            newLogParts.append(part)
                    self.ids['convert_to_draft_log'].text = '\n'.join(
                        newLogParts)
            if len(containerStats['pids_stats']) == 0:
                break
        app = App.get_running_app()
        app.root.ids['menu_screen'].ids[
            'convert_to_draft_menu_button'].background_color = (0.226, 0.527,
                                                                0.273, 1)
        self.container.remove()
Пример #50
0
class SLogin(BoxLayout):

    user_id = ObjectProperty(None)
    saveuser_id = ObjectProperty(None)
    pwd_id = ObjectProperty(None)
    loginbtn_id = ObjectProperty(None)
    closebtn_id = ObjectProperty(None)
    userConf = {}
    loginFlag = None
    accountIdList = []

    def __init__(self, paramDict, **kwargs):
        super(SLogin, self).__init__(**kwargs)

        self.paramDict = paramDict
        self.app = self.paramDict.get(CONSTS.S_APP)

        self.initial_data()

    def initial_data(self):
        filePath = os.path.join(os.path.dirname(__file__), "../conf/user.ini")
        self.userConf = sutil.getDictFromFile(filePath)
        account = self.userConf.get("ACCOUNT")
        password = self.userConf.get("PASSWORD")
        if account != None and account != "":
            self.user_id.text = account
            self.saveuser_id.active = True
            self.pwd_id.text = password

    def login(self):
        self.loginFlag = None
        useridTxt = self.user_id.text
        if useridTxt == "":
            self.app.showErrorView(True, CONSTS.ERR_USER_IS_SPACE)
            return

        if useridTxt.find("@") != -1:
            useridTxt = "1|" + useridTxt
        else:
            useridTxt = "2|" + useridTxt

        self.loginDict = {}
        self.loginDict["Host"] = self.userConf.get("DOWNLOAD_URL").strip()
        self.loginDict["Port"] = int(
            self.userConf.get("DOWNLOAD_PORT").strip())
        self.loginDict["User"] = useridTxt
        self.loginDict["Password"] = self.pwd_id.text
        self.loginDict["ProductId"] = int(
            self.userConf.get("PRODUCT_ID").strip())
        self.loginDict["UserType"] = int(
            self.userConf.get("USER_TYPE").strip())
        self.loginDict["LoginType"] = int(
            self.userConf.get("LOGIN_TYPE").strip())

        self.loginEvent()

    def loginEvent(self):
        contentLayout = BoxLayout()
        contentLayout.orientation = "vertical"
        contentLayout.size_hint = (1, 1)
        contentLabel = SLabel(text="登入中...", size_hint=(1, .8))
        contentLayout.add_widget(contentLabel)

        sysConfDict = self.app.confDict.get(CONSTS.SYS_CONF_DICT)

        self.result = None
        self.dl_popup = Popup(title=sysConfDict.get("MSG_TITLE"),
                              content=contentLayout,
                              size_hint=(None, None),
                              size=(160, 120),
                              auto_dismiss=False)
        self.dl_popup.title_font = CONSTS.FONT_NAME
        self.dl_popup.bind(on_open=self.login_open)
        Clock.schedule_once(self.loginStart)

    def loginStart(self, instance):
        self.dl_popup.open()
        threading.Thread(target=self.toolkitLogin).start()

    def toolkitLogin(self):
        self.result = abxtoolkit.get_accountid(self.loginDict)

    def login_check(self, dt):
        if self.result != None:
            self.dl_popup.dismiss()
            self.event.cancel()
            errCode = self.result.get("ErrCode")
            if errCode != 0:
                errDesc = self.result.get("ErrDesc")
                self.loginFlag = False
                self.app.showErrorView(False, errCode, errDesc)
            else:
                self.loginFlag = True
                self.accountIdList = self.result.get("AccountID_List")
                if self.accountIdList == None:
                    self.accountIdList = []
                self.saveUserConf()

    def login_open(self, instance):
        self.event = Clock.schedule_interval(self.login_check, .0005)

    def saveUserConf(self):
        filePath = os.path.join(os.path.dirname(__file__), "../conf/user.ini")
        userConf = sutil.getDictFromFile(filePath)
        if self.saveuser_id.active:
            userConf["ACCOUNT"] = self.user_id.text
            userConf["PASSWORD"] = self.pwd_id.text
        else:
            userConf["ACCOUNT"] = ""
            userConf["PASSWORD"] = ""
        with open(filePath, 'w', encoding='utf-8') as f:
            for key in userConf.keys():
                value = userConf.get(key)
                aStr = key + "=" + value + "\n"
                f.write(aStr)
Пример #51
0
class ExtractRegions(Screen):

    container = None

    def add_gene(self, *args):
        self.ids['genes_table'].rows += 1
        if round(self.ids['genes_table'].size_hint_y, 1) < 0.9:
            self.ids['genes_table'].size_hint_y += 0.1
            self.ids['genes_table_empty_label'].size_hint_y -= 0.1
        if self.ids['genes_table'].children[0].size[1] < 30:
            for textInput in self.ids['genes_table'].children:
                textInput.font_size -= 0.5
        self.ids['genes_table'].add_widget(
            TextInput(multiline=False, valign='top', padding=(5, 2, 0, 0)))
        self.ids['genes_table'].add_widget(
            TextInput(multiline=False, valign='top', padding=(5, 2, 0, 0)))
        self.ids['genes_table'].add_widget(
            TextInput(multiline=False, valign='top', padding=(5, 2, 0, 0)))

    def run_extraction(self, *args):
        global global_image_names, available_images
        app = App.get_running_app()
        self.ids[
            'log_text_input'].text = 'Starting extraction of genome regions...'
        app.root.ids['menu_screen'].ids[
            'extract_regions_menu_button'].background_color = (0.15, 0.35,
                                                               0.54, 1)
        rows = []
        # Reference directory
        refDir = self.ids['genbank_directory'].text
        if refDir == '<Chosen directory with GenBank-files>':
            refDir = '/NGS-PrimerPlex/hg19/'
        else:
            if not os.path.isdir(refDir):
                refDir = os.path.dirname(refDir)
            if refDir[-1] != os.path.sep:
                refDir += os.path.sep
        # Reference genome
        wgRefPath = self.ids['wgref_file'].text
        if wgRefPath == '<Chosen reference genome FASTA-file>':
            wgRefPath = '/NGS-PrimerPlex/hg19/ucsc.hg19.fasta'
        wgRefDir = os.path.dirname(wgRefPath)
        wgRefName = os.path.basename(wgRefPath)
        # Output file
        outputFilePath = self.ids['output_file'].text
        if outputFilePath == '<Chosen output-file>':
            self.ids['log_text_input'].text = 'ERROR! Choose file for output!'
            return (None)
        outputFileDir = os.path.dirname(outputFilePath)
        outputFileName = os.path.basename(outputFilePath)
        # Read input table
        for i, cell in enumerate(self.ids['genes_table'].children):
            if i >= len(self.ids['genes_table'].children) - 3:
                break
            elif i % 3 == 0:
                rows.append([])
            elif i % 3 == 2 and (cell.text == '' or cell.text == ' '):
                rows = rows[:-1]
            if len(rows) > 0:
                rows[-1] = [cell.text.strip()] + rows[-1]
        if len(rows) == 0:
            self.ids[
                'log_text_input'].text = 'ERROR! Fill table with target genes!'
            return (None)
        file = open(outputFilePath + '_input_genes.txt', 'w')
        for row in rows:
            file.write('\t'.join(row) + '\n')
        file.close()
        # Intron size
        intronSize = self.ids['intron_size_text_input'].text
        # Command
        cmd = [
            'python3', '/NGS-PrimerPlex/getGeneRegions.py', '-glf',
            '/output/' + outputFileName + '_input_genes.txt', '-rf',
            '/output/' + outputFileName, '-intron', intronSize
        ]
        # Mounts and adding info about reference
        mounts = []
        if refDir != '/NGS-PrimerPlex/hg19/':
            drive = os.path.splitdrive(refDir)
            if drive[0] != '':
                refDir = '/' + drive[0].replace(':', '') + drive[1].replace(
                    '\\', '/')
            mounts.append(Mount(target='/ref', source=refDir, type='bind'))
            cmd.extend(['-ref', '/ref'])
            for image_name, available_image in zip(global_image_names,
                                                   available_images):
                # If image without reference is available, use it
                # Elif image with zipped hg19 available, use it
                if available_image:
                    break
        else:
            cmd.extend(['-ref', refDir])
            # In this case we can use only image with unzipped hg19
            if available_images[2]:
                image_name = global_image_names[2]
            elif available_images[1]:
                self.ids[
                    'log_text_input'].text = 'ERROR! Prepare hg19 reference first!'
                return (None)
            else:
                self.ids[
                    'log_text_input'].text = 'ERROR! Download aakechin/ngs-primerplex:latest first'
                return (None)
        drive = os.path.splitdrive(outputFileDir)
        if drive[0] != '':
            outputFileDir = '/' + drive[0].replace(':', '') + drive[1].replace(
                '\\', '/')
        mounts.append(
            Mount(target='/output', source=outputFileDir, type='bind'))
        if wgRefPath != '/NGS-PrimerPlex/hg19/ucsc.hg19.fasta':
            drive = os.path.splitdrive(wgRefDir)
            if drive[0] != '':
                wgRefDir = '/' + drive[0].replace(':', '') + drive[1].replace(
                    '\\', '/')
            mounts.append(Mount(target='/wgref', source=wgRefDir, type='bind'))
            cmd.extend(['-wgref', '/wgref/' + wgRefName])
        else:
            cmd.extend(['-wgref', wgRefPath])

        if self.ids['noncoding_switch'].active:
            cmd.append('-noncoding')
        t = threading.Thread(target=self.run_docker,
                             args=(
                                 image_name,
                                 cmd,
                                 mounts,
                             ))
        t.start()
        app.root.ids['design_primers'].ids[
            'regions_file'].text = outputFilePath

    def run_docker(self, image_name, cmd, mounts):
        try:
            client = docker.from_env()
        except:
            print('ERROR (3)! Could not connect to docker VM')
            exit(3)
        try:
            self.container = client.containers.run(image_name,
                                                   ' '.join(cmd),
                                                   mounts=mounts,
                                                   detach=True,
                                                   entrypoint='')
        except:
            print('ERROR (4)! Could not run image:')
            print('Image name: ' + image_name)
            print('Command: ' + ' '.join(cmd))
            print('Mounts: ' + ', '.join(map(str, mounts)))
            exit(4)
        for stat in self.container.stats():
            containerStats = json.loads(stat.decode('utf-8'))
            newLog = self.container.logs().decode('utf-8')
            if newLog != '':
                writtenLog = self.ids['log_text_input'].text
                if newLog != writtenLog:
                    logParts = newLog.split('\n')
                    newLogParts = []
                    for n, part in enumerate(logParts):
                        if '%' in part:
                            if n < len(logParts) - 1 and '%' not in logParts[
                                    n + 1]:
                                newLogParts.append(part)
                            elif n == len(logParts) - 1:
                                newLogParts.append(part)
                        else:
                            newLogParts.append(part)
                    self.ids['log_text_input'].text = '\n'.join(newLogParts)
            if len(containerStats['pids_stats']) == 0:
                break
        # Change background of this step button on the main screen
        app = App.get_running_app()
        if 'NGS-PrimerPlex finished!' in self.container.logs().decode('utf-8'):
            app.root.ids['menu_screen'].ids[
                'extract_regions_menu_button'].background_color = (0.226,
                                                                   0.527,
                                                                   0.273, 1)
        else:
            app.root.ids['menu_screen'].ids[
                'extract_regions_menu_button'].background_color = (0.754, 0.02,
                                                                   0.226, 1)
        self.container.remove()

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self, title='Load file'):
        if title == 'Choose directory with GenBank-files':
            content = LoadDialog(load=self.loadRefDir,
                                 cancel=self.dismiss_popup)
        elif title == 'Choose FASTA-file with reference genome':
            content = LoadDialog(load=self.loadRefGenome,
                                 cancel=self.dismiss_popup)
        else:
            print('ERROR (5)! Unknown file to load with the following title:')
            print(title)
            exit(5)
        self._popup = Popup(title=title, content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def show_save(self, title='Output file'):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title=title, content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def loadRefDir(self, path, filename):
        self.ids['genbank_directory'].text = path
        self.dismiss_popup()

    def loadRefGenome(self, path, filename):
        self.ids['wgref_file'].text = os.path.join(path, filename[0])
        app = App.get_running_app()
        app.root.ids['design_primers'].ids['wgref_file'].text = os.path.join(
            path, filename[0])
        self.dismiss_popup()

    def save(self, path, filename):
        self.ids['output_file'].text = os.path.join(path, filename)
        self.dismiss_popup()
Пример #52
0
class MainApp(App):
    """Main app building class."""

    def on_pause(self):
        """On pause kivy."""
        return True

    def build(self):
        """Build."""
        self.icon = 'icon.png'
        try:
            req = requests.get('https://tolstoj48.pythonanywhere.com/appis/tymy/')
        except:
            self.pop_up_no_connection()
        else:
            self.pop_up()
            result = req.json()
            Cache.register('tymy', limit=1, timeout=20)
            key = "tymy_vysledky"
            instance = result
            Cache.append("tymy", key, instance)
            self.manager = ManagerScreen()
            self.url_req()
            return self.manager

    def url_req(self):
        """Requests the server api. Stores the data."""
        self.api_queries =  ['https://tolstoj48.pythonanywhere.com/appis/rozpisy/',
            'https://tolstoj48.pythonanywhere.com/appis/aktualni_rozpis/']
        self.response_matches_result = Cache.get("tymy", "tymy_vysledky")
        self.success_results_matches()
        self.response_schedules = UrlRequest(self.api_queries[0], 
            on_success=self.success_results_schedules, 
            on_error=self.pop_up_no_connection,ca_file=cfi.where(), 
            verify=True)
        self.response_recent = UrlRequest(self.api_queries[1], 
            on_success=self.success_results_next_matches, 
            on_error=self.pop_up_no_connection,
            ca_file=cfi.where(), verify=True)

    def pop_up(self, *args):
        """Popups when the data are downloaded."""
        self.popup = Popup(title='Sokol Stodůlky', size_hint=(0.5 , 0.5), 
            separator_height = 0)
        dism = Label(text="Aplikace stahuje data...", size_hint=(1,1), 
            valign="middle", halign="center")
        self.popup.bind(on_dismiss=self.check_result)
        self.popup.add_widget(dism)
        dism.text_size = (dism.parent.width * 2, dism.parent.height * 2)
        self.popup.open()

    def pop_up_no_connection(self, *args):
        """Popups when the device is without connection."""
        self.popup_no_conn = Popup(title='Nedostupné internetové připojení', 
            size_hint=(1 , 1))
        dism = BoxLayout(orientation="vertical")
        label = Popupnoconn_label(text = "Vypněte aplikaci, připojte se a znovu ji zapněte")
        #label.size = label.texture_size
        button = Popupnoconn_button(text="Vypnout aplikaci")
        dism.add_widget(label)
        dism.add_widget(button)
        button.bind(on_release=self.kill)
        self.popup_no_conn.add_widget(dism)
        self.popup_no_conn.bind(on_dismiss=self.check_result)
        self.popup_no_conn.open()

    def kill(self, *args):
        App.get_running_app().stop()

    def check_result(self, *args):
        return True

    def let_dismiss(self, *args):
        return False

    def success_results_matches(self):
        """Process the obtained data of the played matches."""
        self.popup.unbind(on_dismiss=self.check_result)
        self.popup.dismiss()
        data_matches = self.get_team_data(data_matches=self.response_matches_result, 
            team="", final="all", matches=True)
        for i in data_matches:
            self.fetch_match_detail(i, i["tym"])
    
    def success_results_schedules(self, req, result):
        """Process the obtained data of the scheduled matches."""
        data_schedules = self.get_team_data(data_matches=
            self.response_schedules.result, matches=False)
        data_schedule_choice = ["rozpis_a", "rozpis_b", "rozpis_c", 
        "rozpis_st_d", "rozpis_ml_d", "rozpis_st_z", "rozpis_ml_z_a", 
        "rozpis_ml_z_b", "rozpis_ml_z_c"]
        helper_variable = 0
        for data in data_schedules:
            self.fetch_team_schedules("".join(data), 
                data_schedule_choice[helper_variable])
            helper_variable += 1
        
    def success_results_next_matches(self, req, result):
        """Process the obtained data of the planned scheduled matches."""
        self.fetch_next_matches()

    def fetch_match_detail(self, data, tym):
        """Creates the screens for the display of the details of the 
        particular matches.
        """
        screen = Screen(name = data["souperi"] + " - " + data["vysledek"])
        layout = BoxLayout(orientation="vertical")
        screen.add_widget(layout)
        label = ScrollableLabel(text =
                "[b]Soupeři[/b]: " + data["souperi"] + "\n\n" + 
                "[b]Výsledek[/b]: " + data["vysledek"] + "\n\n" + 
                "[b]Kolo[/b]: " + data["kolo"] + "\n\n" + 
                "[b]Datum[/b]: " + data["datum"] + "\n\n" + 
                "[b]Sestava[/b]: " + data["sestava"] + "\n\n" +
                "[b]Náhradnící[/b]: " + data["nahradnici"] + "\n\n" + 
                "[b]Góly[/b]: " + data["goly"] + "\n\n" + 
                "[b]Komentář[/b]: " + data["koment"] + "\n\n", 
                size_hint=[1,5])
        button = Button(text = "Zpět na hlavní menu", size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, 
            "_first_screen_"))
        layout.add_widget(button)
        button = Button(text = "Zpět na přehled utkání " + tym + "u", 
            size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, tym))
        layout.add_widget(button)
        layout.add_widget(label)
        self.manager.add_widget(screen)

    def fetch_team_schedules(self, data, rozpis):
        """Creates the screens for the display of the details of the 
        particular team schedules.
        """
        screen = Screen(name = rozpis)
        layout = BoxLayout(orientation="vertical")
        screen.add_widget(layout)
        label = ScrollableLabel(text = data,
               size_hint=[1,5])
        button = Button(text = "Zpět na hlavní menu", size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, "_first_screen_"))
        layout.add_widget(button)
        button = Button(text = "Zpět na výběr rozpisů", size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, "rozpisy"))
        layout.add_widget(button)
        layout.add_widget(label)
        self.manager.add_widget(screen)

    def fetch_next_matches(self):
        """Creates the screen with information about scheduled matches 
        in the next 6 days. Uses data from the api connection to the 
        remote server. Then sends data to prepare_data_for_next_macthes()
        method and puts them in the text.
        """
        screen = Screen(name = "rozpisy_aktualni")
        layout = BoxLayout(orientation="vertical")
        screen.add_widget(layout)
        label = ScrollableLabel(text = str(self.prepare_data_for_next_macthes()),
            size_hint=[1,5])
        button = Button(text = "Zpět na hlavní menu", size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, "_first_screen_"))
        layout.add_widget(button)
        button = Button(text = "Zpět na přehled rozpisů", size_hint_y = 1)
        button.bind(on_release = partial(self.switch_screen, "rozpisy"))
        layout.add_widget(button)
        layout.add_widget(label)
        self.manager.add_widget(screen)

    def prepare_data_for_next_macthes(self):
        """Returns only data from request to the api to the 
        fetch_next_matches() method.
        """
        return "".join(self.response_recent.result[0])

    def get_team_data(self, data_matches="", team="", final="", matches=""):
        """Format the requested data to suitable list format for all the input 
        data,
        """
        if matches == True:
            a_team = []
            b_team = []
            c_team = []
            for i in data_matches:
                if i["tym"] == "A-tým":
                    a_team.append(i)
                elif i["tym"] == "B-tým":
                    b_team.append(i)
                else:
                    c_team.append(i)
            if team == "A-tým":
                return a_team
            elif team == "B-tým":
                return b_team
            elif team == "C-tým":
                return c_team
            if final == "all":
                return data_matches
        else:
            return data_matches

    def switch_screen(self, switch_to, *args, **kwargs):
        """Switches screens on screenmanager."""
        self.manager.current = switch_to
Пример #53
0
    class CalcolatriceApp(App):
        ##########################################################################
        loadfile = ObjectProperty(None)
        savefile = ObjectProperty(None)
        text_input = ObjectProperty(None)

        
        
        def build_mesh(self):
            from math import sin, cos, pi
            """ returns a Mesh of a rough circle. """
            vertices = []
            indices = []
            step = 10
            istep = (pi * 2) / float(step)
            for i in range(step):
                x = 300 + cos(istep * i) * 100
                y = 300 + sin(istep * i) * 100
                vertices.extend([x, y, 0, 0])
                indices.append(i)
            """
            Mesh:
                vertices: (x1, y1, s1, v1, x2, y2, s2, v2, x3, y3, s3, v3...)
                indices: (1, 2, 3...)
                texture: some_texture
                rgba: 1,1,1,1
                mode: some_mode
                """
            #ritorna una area colorata chiusa
            return Mesh(vertices=vertices, indices=indices, mode='triangle_fan')
            #return Mesh(vertices=vertices, indices=indices, mode='line_loop')

        def dismiss_popup(self):
            self._popup.dismiss()
    
        def show_load(self):
            content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
            self._popup = Popup(title="Carica File", content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
    
        def show_save(self):
            content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
            self._popup = Popup(title="Salva File", content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
    
        def load(self, path, filename):
            self.stringa=np.asmatrix(np.genfromtxt(os.path.join(path, filename[0]),delimiter=","))
            print(self.stringa)
            print(filename)
            self.vada=np.size(self.stringa,0)-1
            #print(self.vada)
            self.root.ids.nomArch.theTxt.text=filename[0]
            fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
            axes = fig.gca()
            from calcolatrice.stampafigura import disegna
            disegna(self,self.stringa)
            figure_wgt = self.root.ids['figure_wgt']  # MatplotFigure
            figure_wgt.figure = fig

            #with open(os.path.join(path, filename[0])) as stream:
                #self.text_input.text = stream.read()
            self.dismiss_popup()
    
        def save(self, path, filename):
            #with open(, 'w') as stream:
            nome=self.root.ids.nomArch.theTxt.text
            #print("dd"+nome+"dd")
            strada=os.getcwd()+"\\" + nome
            #print(os.getcwd())
            #print(os.path.join(path, filename[0]))
            #stream.write(self.stringa)
            #print(strada)
            np.savetxt(strada, self.stringa, delimiter=',', newline='\n')    
            self.dismiss_popup()
        def salvaauto(self,*args):
            if self.vada>0:
                nome=self.root.ids.nomArch.theTxt.text
                estensione=".csv"
                strada=os.getcwd()+"\\" + nome
                nomeTemp=nome
                if nome=="":
                    k=0
                    nomeTemp="ciccione"+"0"+str(k)+str(estensione)
                    strada=os.getcwd()+"\\"+nomeTemp
                    while os.path.isfile(strada)==True:
                        nomeTemp="ciccione"+"0"+str(k)+str(estensione)
                        strada=os.getcwd()+"\\"+nomeTemp
                        k=k+1
                #print(strada)
                np.savetxt(strada, self.stringa, delimiter=',', newline='\n')    
                self.root.ids.nomArch.theTxt.text=nomeTemp
        ##########################################################################
        title = "Disegnatore di Biancardi"
        #stringa= MatrixProperty()
        #Status=StringProperty()
        def UndoZZZZ(self,*args):
            if self.vada>0:
                self.vada=self.vada-1
                self.stringa=self.stringa[:-1,:]
                fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
                axes = fig.gca()
                figure_wgt = self.root.ids['figure_wgt']  # MatplotFigure
                figure_wgt.figure = fig
                from calcolatrice.stampafigura import disegna
                disegna(self,self.stringa)
                self.root.ids.risoluzione.text="figure inserite %d"%self.vada

            #self.stringa=np.matrix("42015.,3.,1.,48.,0.,0.,0.,0.,0.,0.,0.;4.,1.,0.,0.,0.,0.,6.,10.,6.,10.,0.;2.,-1.,0.,4.,0.,3.,0.,3.1415,0.,0.,0.")
        def Resetta(self,*args):
            if self.vada>0:
                self.stringa=self.iniziale
                #self.root.ids.schifo.text=print(self.stringa)
                #print(self.stringa)
                self.vada=0
                #self.root.ids.schifo.text=""
                self.root.ids.risoluzione.text="resettato"
                fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
                fig.clf()
                figure_wgt = self.root.ids['figure_wgt']  # MatplotFigure
                figure_wgt.figure = fig
                self.root.ids.risoluzione.text="figure inserite %d"%self.vada

        def SalvaDisegno(self,*args):
            if self.vada>0:
                #print(self.root.ids.figure_wgt.figure.figure)
                #print(self.root.ids.figure_wgt.figure.bbox.bounds)
                #print(self.root.ids.figure_wgt.figure.dpi)
                #self.root.ids.figure_wgt.figure.savefig(filename)
                nome=self.root.ids.nomArch.theTxt.text
                estensione=".png"
                strada=os.getcwd()+"\\" + nome
                nomeTemp=nome
                if nome=="":
                    k=0
                    nomeTemp="ciccione"+"0"+str(k)+estensione
                    strada=os.getcwd()+"\\"+nomeTemp
                    while os.path.isfile(strada)==True:
                        nomeTemp="ciccione"+"0"+str(k)+estensione
                        strada=os.getcwd()+"\\"+nomeTemp
                        k=k+1
                #print(strada)
                self.root.ids.nomArch.theTxt.text=nomeTemp
                self.root.ids.figure_wgt.export_to_png(self.root.ids.nomArch.theTxt.text)
                #from matplotlib.backends.backend_pdf import PdfPages
                #with PdfPages('multipage_pdf.pdf') as pdf:
                    #pdf.savefig(self.root.ids.figure_wgt.figure)
        def BottonePremutoNocciolo(self,*args):
            if self.vuoifareancheilnocciolo==0:
                self.vuoifareancheilnocciolo=1
                self.iniziale[0,2]=1
            elif self.vuoifareancheilnocciolo==1:
                self.vuoifareancheilnocciolo=0
                self.iniziale[0,2]=0
            print('The checkbox is active')
        def build(self):
            # Matplotlib stuff, figure and plot
            fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
            axes = fig.gca()
            #axes.set_xlim(0, 50)
            #axes.grid(True)
            #fig.clf()
            axes.axis("on")
            #axes.set_xlim(0, 50)
            #axes.set_aspect('equal')
            # Kivy stuff
            root = Builder.load_file("nuovaForma.kv")
            figure_wgt = root.ids['figure_wgt']  # MatplotFigure
            figure_wgt.figure = fig
            self.root=root
            self.root.ids.risoluzione.text="figure inserite %d"%self.vada
            return root
        def __init__(self, **kwargs):
            super(CalcolatriceApp, self).__init__(**kwargs)
            self.mmma=2
            self.mmmb=2
            self.vada=0
            self.scalatore=1000
            self.kk=3
            self.discretizzaarchicerchi=80
            self.vuoifareancheilnocciolo=1
            self.contorna=1
            self.vuota=np.matrix("0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.")
            self.iniziale=np.matrix("0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.")
            self.iniziale[0,0]=42015.
            self.iniziale[0,1]=self.kk
            self.iniziale[0,2]=self.vuoifareancheilnocciolo
            self.iniziale[0,3]=self.discretizzaarchicerchi
            self.iniziale[0,4]=self.contorna
            self.stringa=self.iniziale
            self.vada=0
            #print(self.stringa)
        def Internet(*args):
            """
            For documentation of the webbrowser module,
            see http://docs.python.org/library/webbrowser.html
            """
            import webbrowser
            new = 2 # open in a new tab, if possible
            # open a public URL, in this case, the webbrowser docs
            url = "https://www.facebook.com/francescoscodesection\n"
            webbrowser.open(url,new=new)
            # open an HTML file on my own (Windows) computer
            #url = "file://X:/MiscDev/language_links.html"
            #webbrowser.open(url,new=new)
        def Calcolalo(self,*args):
            #import os
            #os.chdir("C:\Users\Von Braun\Google Drive\mat2pylab\calcolatrice")
            noncidevonoessereaste=1
            from calcolatrice.misuras import guardasecisonoaste
            noncidevonoessereaste=guardasecisonoaste(self)
            if noncidevonoessereaste and 0:
                self.stringa[0,2]=0
                self.vuoifareancheilnocciolo=0
            if self.vada>0:
                import time
                b0=time.clock()
                self.salvaauto(self)
                fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
                axes = fig.gca()
                figure_wgt = self.root.ids['figure_wgt']  # MatplotFigure
                figure_wgt.figure = fig
                #print(self.root.ids.figure_wgt.figure)
                if self.root.ids.quantidiscreti.theTxt.text!="":
                    self.stringa[0,3]=int(self.root.ids.quantidiscreti.theTxt.text)
                from calcolatrice.principale import codicesezione
                self.root.ids.risoluzione.text=codicesezione(self)
                #filename=self.root.ids.nomArch.theTxt.text
                #mpl.draw()
                #self.print_figure(self, filename)
                b=time.clock()
                print("tempo",round(b-b0,4))
                #self.uscita="cacca"+"\n"
                #self.root.ids.risoluzione.text=self.uscita
            else:
                self.root.ids.risoluzione.text="figure inserite %d"%self.vada
        def CreaSalvataggio(self,*args):
            if args[1]==1:
                val2=0. if args[2]=="" else str(args[2])
                val3=0. if args[3]=="" else str(args[3])
                val4=0. if args[4]=="" else str(args[4])
                val5=0. if args[5]=="" else str(args[5])
                if val2+val3+val4+val5!=0:
                    #val="1 "+val2+" 0 "+val3+" "+val4+" "+val5
                    from calcolatrice.misuras import UnireMatriciCol
                    self.stringa=UnireMatriciCol(self.stringa,self.vuota)
                    self.vada=self.vada+1
                    self.stringa[self.vada,0]=1.
                    self.stringa[self.vada,1]=float(val2)
                    self.stringa[self.vada,3]=float(val3)
                    self.stringa[self.vada,4]=float(val4)
                    self.stringa[self.vada,5]=float(val5)
                #print("10000",val)
                #stringa=stringa+args[1]+" "+args[2]+" "+args[3]+" "+args[4]+";"
            if args[1]==2:
                val2=0. if args[2]=="" else float(args[2])
                val3=0. if args[3]=="" else float(args[3])
                val4=0. if args[4]=="" else float(args[4])
                val5=0. if args[5]=="" else float(args[5])
                val6=0. if args[6]=="" else float(args[6])
                val7=0. if args[7]=="" else float(args[7])
                if val2+val3+val4+val5+val6+val7!=0:
                    self.vada=self.vada+1
                    #val="2 "+val2+" 0 "+val3+" "+val4+" "+val5+" "+val6+" "+val7
                    from calcolatrice.misuras import UnireMatriciColNon
                    self.stringa=UnireMatriciColNon(self.stringa,self.vuota)
                    self.stringa[self.vada,0]=2.
                    self.stringa[self.vada,1]=float(val2)
                    self.stringa[self.vada,3]=float(val3)
                    self.stringa[self.vada,4]=float(val4)
                    self.stringa[self.vada,5]=float(val5)
                    self.stringa[self.vada,6]=float(val6)*np.pi/180
                    self.stringa[self.vada,7]=float(val7)*np.pi/180

                #print("20000",val)
                #stringa=stringa+args[1]+" "+args[2]+" "+args[3]+" "+args[4]+" "+args[5]+" "+args[6]+";"
            if args[1]==2.5:
                val2=0. if args[2]=="" else str(args[2])
                val3=0. if args[3]=="" else str(args[3])
                val4=0. if args[4]=="" else str(args[4])
                val5=0. if args[5]=="" else str(args[5])
                val6=0. if args[6]=="" else str(args[6])
                val7=0. if args[7]=="" else str(args[7])
                if val2+val3+val4+val5+val6+val7!=0:
                    self.vada=self.vada+1
                    #val="2 "+val2+" 0 "+val3+" "+val4+" "+val5+" "+val6+" "+val7
                    from calcolatrice.misuras import UnireMatriciColNon
                    self.stringa=UnireMatriciColNon(self.stringa,self.vuota)
                    self.stringa[self.vada,0]=2.5
                    self.stringa[self.vada,1]=float(val2)
                    self.stringa[self.vada,3]=float(val3)
                    self.stringa[self.vada,4]=float(val4)
                    self.stringa[self.vada,5]=float(val5)
                    self.stringa[self.vada,6]=float(val6)
                    self.stringa[self.vada,7]=float(val7)
            if args[1]=="":
                inter=0
            else:
                inter=int(args[1])
            if printa:
                print("inter",inter)
            if inter>=3:
                #print(*args)
                #print(args[0])
                #print(args[1])
                #print(args[2])
                #print(args[3])
                val1=0. if args[1]=="" else float(args[1])
                val2=0. if args[2]=="" else float(args[2])
                val3=0. if args[3]=="" else str(args[3])
                from calcolatrice.misuras import UnireMatriciCol,UnireMatriciRig
                self.vada=self.vada+1
                #val=val1 +" "+val2+" 0 "+val3
                from calcolatrice.misuras import StringaToMatrix
                val4=StringaToMatrix(val3)
                if np.size(val4)==2*val1:
                    print("ok")
                else:
                    val1=np.size(val4)
                    print("non sono giuste")
                    #self.root.ids.n
                val5=np.matrix("0. 0. 0.")
                val5[0,0]=float(val1)
                val5[0,1]=float(val2)
                #print(val4)
                val6=UnireMatriciRig(val5,val4)
                #self.stringa[self.vada,3]=float(val3)
                #print(val6,type(val6))
                from calcolatrice.misuras import UnireMatriciColNon
                self.stringa=UnireMatriciColNon(self.stringa,val6)
                #if printa:
            #print(self.stringa)
            #print("30000",val)
            #print("fine",self.stringa)
            #self.stringa=self.stringa+val+";"
            #print("finish  ",self.stxringa)
            fig = mpl.figure.Figure(figsize=(self.mmma, self.mmmb))
            axes = fig.gca()
            figure_wgt = self.root.ids['figure_wgt']  # MatplotFigure
            figure_wgt.figure = fig
            from calcolatrice.stampafigura import disegna
            disegna(self,self.stringa)
            self.root.ids.risoluzione.text="figure inserite %d"%self.vada
            #mpl.savefig("ciccio.png")

            #stampa=self.stringa
            #self.root.ids.schifo.text="booooooooh"
            #self.root.ids.schifo.text=print(stampa)
            #str.replace(stampa,";",";\n")
            #disegna(self,numero1,kk,discretizzaarchicerchi)
            return self
Пример #54
0
class DesignPrimers(Screen):

    container = None

    def start_design(self, *args):
        global global_image_names, available_images
        app = App.get_running_app()
        self.ids['design_primers_log'].text = 'Starting primer design...'
        app.root.ids['menu_screen'].ids[
            'design_primers_menu_button'].background_color = (0.15, 0.35, 0.54,
                                                              1)
        # Regions file
        regionsFilePath = self.ids['regions_file'].text
        if regionsFilePath == '<Choose file with target genome regions>':
            self.ids[
                'design_primers_log'].text = 'ERROR! Choose file with target genome regions!'
            return (None)
        regionsFileDir = os.path.dirname(regionsFilePath)
        regionsFileName = os.path.basename(regionsFilePath)
        # Draft primers
        draftFilePath = self.ids['draft_file'].text
        if draftFilePath == '<Choose file with draft list of primers>':
            draftFilePath = None
        else:
            draftFileDir = os.path.dirname(draftFilePath)
            draftFileName = os.path.basename(draftFilePath)
        # Internal primers
        primersFilePath = self.ids['primers_file'].text
        if primersFilePath == '<Choose file with designed internal primers>':
            primersFilePath = None
        else:
            primersFileDir = os.path.dirname(primersFilePath)
            primersFileName = os.path.basename(primersFilePath)
        # Reference genome
        wgRefPath = self.ids['wgref_file'].text
        if wgRefPath == '<Chosen reference genome FASTA-file or leave it as it is to use hg19>':
            wgRefPath = '/NGS-PrimerPlex/hg19/ucsc.hg19.fasta'
        # VCF-file with SNPs
        snpsFilePath = self.ids['snps_file'].text
        if snpsFilePath == '<To check for covering SNPs choose VCF-file with SNPs>':
            snpsFilePath = None
        else:
            snpsFileDir = os.path.dirname(snpsFilePath)
            snpsFileName = os.path.basename(snpsFilePath)
        wgRefDir = os.path.dirname(wgRefPath)
        wgRefName = os.path.basename(wgRefPath)
        # Embedded PCR
        embedded = self.ids['embedded_switch'].active
        # Skip uncovered
        skip = self.ids['skip_switch'].active
        # Non-target hybridization
        nontargets = self.ids['nontargets_switch'].active
        # Embedded PCR
        snps = self.ids['snps_switch'].active
        # Threads number
        threads = self.ids['threads_text_input'].text.strip()
        # Run name
        runName = self.ids['run_name_text_input'].text.strip()
        drive = os.path.splitdrive(regionsFileDir)
        if drive[0] != '':
            regionsFileDir = '/' + drive[0].replace(
                ':', '') + drive[1].replace('\\', '/')
        mounts = [Mount(target='/regions', source=regionsFileDir, type='bind')]
        cmd = [
            'python3', '/NGS-PrimerPlex/NGS_primerplex.py', '-regions',
            '/regions/' + regionsFileName, '-th', threads, '-run', runName
        ]
        if wgRefPath != '/NGS-PrimerPlex/hg19/ucsc.hg19.fasta':
            drive = os.path.splitdrive(wgRefDir)
            if drive[0] != '':
                wgRefDir = '/' + drive[0].replace(':', '') + drive[1].replace(
                    '\\', '/')
            mounts.append(Mount(target='/wgref', source=wgRefDir, type='bind'))
            cmd.extend(['-ref', '/wgref/' + wgRefName])
            for image_name, available_image in zip(global_image_names,
                                                   available_images):
                # If image without reference is available, use it
                # Elif image with zipped hg19 available, use it
                if available_image:
                    break
        else:
            cmd.extend(['-ref', wgRefPath])
            # In this case we can use only image with unzipped hg19
            if available_images[2]:
                image_name = global_image_names[2]
            elif available_images[1]:
                self.ids[
                    'design_primers_log'].text = 'ERROR! Prepare hg19 reference first!'
                return (None)
            else:
                self.ids[
                    'design_primers_log'].text = 'ERROR! Download aakechin/ngs-primerplex:latest first'
                return (None)
        if draftFilePath != None:
            drive = os.path.splitdrive(draftFileDir)
            if drive[0] != '':
                draftFileDir = '/' + drive[0].replace(
                    ':', '') + drive[1].replace('\\', '/')
            mounts.append(
                Mount(target='/draft', source=draftFileDir, type='bind'))
            cmd.extend(['-draft', '/draft/' + draftFileName])
        elif primersFilePath != None:
            drive = os.path.splitdrive(primersFileDir)
            if drive[0] != '':
                primersFileDir = '/' + drive[0].replace(
                    ':', '') + drive[1].replace('\\', '/')
            mounts.append(
                Mount(target='/primers', source=primersFileDir, type='bind'))
            cmd.extend(['-primers', '/primers/' + primersFileName])
        if snpsFilePath != None:
            drive = os.path.splitdrive(snpsFileDir)
            if drive[0] != '':
                snpsFileDir = '/' + drive[0].replace(
                    ':', '') + drive[1].replace('\\', '/')
            mounts.append(
                Mount(target='/snps', source=snpsFileDir, type='bind'))
            cmd.extend(['-dbsnp', '/snps/' + snpsFileName])
        if embedded:
            cmd.append('-embedded')
        if skip:
            cmd.append('-skip')
        if nontargets:
            cmd.append('-blast')
        if snps:
            cmd.append('-snps')
        cmd.append('-gui')
        if self.ids['left_adapter'].text.strip() != '':
            p = re.compile('([^ATGCatgc]+)')
            if len(p.findall(self.ids['left_adapter'].text.strip())) > 0:
                self.ids[
                    'design_primers_log'].text = 'ERROR! Incorrect sequence of the left adapter!'
                return (None)
            else:
                cmd.extend(['-ad1', self.ids['left_adapter'].text.strip()])
        if self.ids['right_adapter'].text.strip() != '':
            p = re.compile('([^ATGCatgc]+)')
            if len(p.findall(self.ids['right_adapter'].text.strip())) > 0:
                self.ids[
                    'design_primers_log'].text = 'ERROR! Incorrect sequence of the right adapter!'
                return (None)
            else:
                cmd.extend(['-ad2', self.ids['right_adapter'].text.strip()])
        # Values from settings
        for value in app.root.ids['settings'].ids.keys():
            if value != 'autoadjust':
                cmd.extend(
                    ['-' + value, app.root.ids['settings'].ids[value].text])
            elif app.root.ids['settings'].ids[value].active == True:
                cmd.append('-' + value)
        self.ids['primer_design_stop_button'].disabled = False
        self.ids['primer_design_start_button'].disabled = True
        t = threading.Thread(target=self.run_docker,
                             args=(
                                 image_name,
                                 cmd,
                                 mounts,
                             ))
        t.start()
        # Change file name in the next step
        outputFileName = ''.join([
            regionsFilePath[:-4], '_NGS_primerplex_', runName,
            '_primers_combination_1_info.xls'
        ])
        app.root.ids['add_adapters'].ids[
            'filename_text_input_primers'].text = outputFileName

    def run_docker(self, image_name, cmd, mounts):
        try:
            client = docker.from_env()
        except:
            print('ERROR (3)! Could not connect to docker VM')
            exit(3)
        try:
            self.container = client.containers.run(image_name,
                                                   ' '.join(cmd),
                                                   mounts=mounts,
                                                   detach=True,
                                                   entrypoint='')
        except:
            print('ERROR (4)! Could not run image:')
            print('Image name: ' + image_name)
            print('Command: ' + ' '.join(cmd))
            print('Mounts: ' + ', '.join(map(str, mounts)))
            exit(4)
        for stat in self.container.stats():
            containerStats = json.loads(stat.decode('utf-8'))
            newLog = self.container.logs().decode('utf-8')
            if newLog != '':
                writtenLog = self.ids['design_primers_log'].text
                if newLog != writtenLog:
                    logParts = newLog.split('\n')
                    newLogParts = []
                    for n, part in enumerate(logParts):
                        if '%' in part:
                            if n < len(logParts) - 1 and '%' not in logParts[
                                    n + 1]:
                                newLogParts.append(part)
                            elif n == len(logParts) - 1:
                                newLogParts.append(part)
                        elif part == '':
                            continue
                        else:
                            newLogParts.append(part)
                    self.ids['design_primers_log'].text = '\n'.join(
                        newLogParts)
            if len(containerStats['pids_stats']) == 0:
                break
        # Change background of this step button on the main screen
        app = App.get_running_app()
        if 'NGS-PrimerPlex finished!' in self.container.logs().decode('utf-8'):
            app.root.ids['menu_screen'].ids[
                'design_primers_menu_button'].background_color = (0.226, 0.527,
                                                                  0.273, 1)
        else:
            app.root.ids['menu_screen'].ids[
                'design_primers_menu_button'].background_color = (0.754, 0.02,
                                                                  0.226, 1)
        self.ids['primer_design_stop_button'].disabled = True
        self.ids['primer_design_start_button'].disabled = False
        self.container.remove()

    def stop_design(self):
        if self.container != None:
            t = threading.Thread(target=self.stop_docker)
            t.start()
        self.ids['primer_design_stop_button'].disabled = True
        self.ids['primer_design_start_button'].disabled = False
        self.ids['design_primers_log'].text += '\nSTOPPED'

    def stop_docker(self):
        self.container.stop()

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self, title='Load file'):
        app = App.get_running_app()
        if title == 'Choose file with target genome regions':
            content = LoadDialog(load=self.loadTargetRegions,
                                 cancel=self.dismiss_popup)
        elif title == 'Choose file with draft list of primers':
            content = LoadDialog(load=self.loadDraftPrimers,
                                 cancel=self.dismiss_popup)
        elif title == 'Choose file with designed internal primers':
            content = LoadDialog(load=self.loadIntPrimers,
                                 cancel=self.dismiss_popup)
        elif title == 'Choose FASTA-file with reference genome':
            content = LoadDialog(load=self.loadRefGenome,
                                 cancel=self.dismiss_popup)
        elif title == 'Choose VCF-file with SNPs':
            content = LoadDialog(load=self.loadSnpsFile,
                                 cancel=self.dismiss_popup)
        else:
            print('ERROR (6)! Unknown file to load with the following title:')
            print(title)
            exit(6)
        self._popup = Popup(title=title, content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def loadTargetRegions(self, path, filename):
        self.ids['regions_file'].text = os.path.join(path, filename[0])
        self.dismiss_popup()

    def loadDraftPrimers(self, path, filename):
        self.ids['draft_file'].text = os.path.join(path, filename[0])
        self.ids[
            'primers_file'].text = '<Choose file with designed internal primers>'
        self.dismiss_popup()

    def loadIntPrimers(self, path, filename):
        self.ids['primers_file'].text = os.path.join(path, filename[0])
        self.ids[
            'draft_file'].text = '<Choose file with draft list of primers>'
        self.ids['embedded_switch'].active = True
        self.dismiss_popup()

    def loadRefGenome(self, path, filename):
        self.ids['wgref_file'].text = os.path.join(path, filename[0])
        self.dismiss_popup()

    def loadSnpsFile(self, path, filename):
        self.ids['snps_file'].text = os.path.join(path, filename[0])
        self.ids['snps_switch'].active = True
        self.dismiss_popup()
Пример #55
0
def alertPopup(title, msg):
    popup = Popup(title=title,
                  content=Label(text=msg),
                  size_hint=(None, None),
                  size=(dp(600), dp(200)))
    popup.open()
Пример #56
0
 def send_file(self):
     _content = FileChoosDialog(load=self.filechoose_submit)
     _popup = Popup(title='file choose', content=_content)
     _content.window = _popup
     _popup.open()
Пример #57
0
class Unicode_TextInput(BoxLayout):

    txt_input = ObjectProperty(None)
    unicode_string = StringProperty('''Latin-1 supplement: éé çç ßß

List of major languages taken from Google Translate
____________________________________________________
Try changing the font to see if the font can render the glyphs you need in your
application. Scroll to see all languages in the list.

Basic Latin:    The quick brown fox jumps over the lazy old dog.
Albanian:       Kafe të shpejtë dhelpra hedhje mbi qen lazy vjetër.
الثعلب البني السريع يقفز فوق الكلب القديمة البطيئة.         :Arabic
Africans:       Die vinnige bruin jakkals spring oor die lui hond.
Armenian:       Արագ Brown Fox jumps ավելի ծույլ հին շունը.
Azerbaijani:    Tez qonur tülkü də tənbəl yaşlı it üzərində atlamalar.
Basque:         Azkar marroia fox alferrak txakur zaharra baino gehiago jauzi.
Belarusian:     Хуткі карычневы ліс пераскоквае праз гультаяваты стары сабака.
Bengali:        দ্রুত বাদামী শিয়াল অলস পুরানো কুকুর বেশি
Bulgarian:      Бързата кафява лисица скача над мързелив куче.
Chinese Simpl:  敏捷的棕色狐狸跳过懒惰的老狗。
Catalan:        La cigonya tocava el saxofon en el vell gos mandrós.
Croation:       Brzo smeđa lisica skoči preko lijen stari pas.
Czech:          Rychlá hnědá liška skáče přes líného starého psa.
Danish:         Den hurtige brune ræv hopper over den dovne gamle hund.
Dutch:          De snelle bruine vos springt over de luie oude hond.
Estonian:       Kiire pruun rebane hüppab üle laisa vana koer.
Filipino:       Ang mabilis na brown soro jumps sa ang tamad lumang aso.
Finnish:        Nopea ruskea kettu hyppää yli laiska vanha koira.
French:         Le renard brun rapide saute par dessus le chien paresseux vieux.
Galician:       A lixeira raposo marrón ataca o can preguiceiro de idade.
Gregorian:      სწრაფი ყავისფერი მელა jumps გამო ზარმაცი წლის ძაღლი.
German:         Der schnelle braune Fuchs springt über den faulen alten Hund.
Greek:          Η γρήγορη καφέ αλεπού πηδάει πάνω από το τεμπέλικο γέρικο σκυλί.
Gujrati:        આ ઝડપી ભુરો શિયાળ તે બેકાર જૂના કૂતરા પર કૂદકા.
Gurmukhi:       ਤੇਜ ਭੂਰੇ ਰੰਗ ਦੀ ਲੂੰਬੜੀ ਆਲਸੀ ਬੁੱਢੇ ਕੁੱਤੇ ਦੇ ਉਤੋਂ ਦੀ ਟੱਪਦੀ ਹੈ ।
Hiation Creole: Rapid mawon Rena a so sou chen an parese fin vye granmoun.
Hebrew:         השועל החום הזריז קופץ על הכלב הישן עצלן.
Hindi:          तेज भूरे रंग की लोमड़ी आलसी बूढ़े कुत्ते के उपर से कूदती है ॥
Hungarian:      A gyors barna róka átugorja a lusta vén kutya.
Icelandic:      The fljótur Brown refur stökk yfir latur gamall hundur.
Indonesian      Cepat rubah cokelat melompat atas anjing tua malas.
Irish:          An sionnach donn tapaidh jumps thar an madra leisciúil d\'aois.
Italian:        The quick brown fox salta sul cane pigro vecchio.
Japanese:       速い茶色のキツネは、のろまな古いイヌに飛びかかった。
Kannada:        ತ್ವರಿತ ಕಂದು ನರಿ ಆಲೂಗಡ್ಡೆ ಹಳೆಯ ಶ್ವಾನ ಮೇಲೆ ಜಿಗಿತಗಳು.
Korean:         무궁화 게으른 옛 피었습니다.
Latin:          Vivamus adipiscing orci et rutrum tincidunt super vetus canis.
Latvian:        Ātra brūna lapsa lec pāri slinkam vecs suns.
Lithuanian:     Greita ruda lapė šokinėja per tingus senas šuo.
Macedonian:     Брзата кафена лисица скокови над мрзливи стариот пес.
Malay:          Fox coklat cepat melompat atas anjing lama malas.
Maltese:        Il-volpi kannella malajr jumps fuq il-kelb qodma għażżien.
Norweigian:     Den raske brune reven hopper over den late gamle hunden.
Persian:        روباه قهوه ای سریع روی سگ تنبل قدیمی میپرد.
Polish:         Szybki brązowy lis przeskoczył nad leniwym psem życia.
Portugese:      A ligeira raposa marrom ataca o cão preguiçoso de idade.
Romanian:       Rapidă maro vulpea sare peste cainele lenes vechi.
Russioan:       Быстрый коричневый лис перепрыгивает через ленивый старый пес.
Serniam:        Брза смеђа лисица прескаче лењог пса старог.
Slovak:         Rýchla hnedá líška skáče cez lenivého starého psa.
Slovenian:      Kožuščku hudobnega nad leni starega psa.
Spanish:        La cigüeña tocaba el saxofón en el viejo perro perezoso.
Swahili:        Haraka brown fox anaruka juu ya mbwa wavivu zamani.
Swedish:        Den snabba bruna räven hoppar över den lata gammal hund.
Tamil:          விரைவான பிரவுன் ஃபாக்ஸ் சோம்பேறி பழைய நாய் மீது தொடரப்படுகிறது
Telugu:         శీఘ్ర బ్రౌన్ ఫాక్స్ సోమరితనం పాత కుక్క కంటే హెచ్చుతగ్గుల.
Thai:           สีน้ำตาลอย่างรวดเร็วจิ้งจอกกระโดดมากกว่าสุนัขเก่าที่ขี้เกียจ
Turkish:        Hızlı kahverengi tilki tembel köpeğin üstünden atlar.
Ukranian:       Швидкий коричневий лис перестрибує через лінивий старий пес.
Urdu:           فوری بھوری لومڑی سست بوڑھے کتے پر کودتا.
Vietnamese:     Các con cáo nâu nhanh chóng nhảy qua con chó lười biếng cũ.
Welsh:          Mae\'r cyflym frown llwynog neidio dros y ci hen ddiog.
Yiddish:        דער גיך ברוין פוקס דזשאַמפּס איבער די פויל אַלט הונט.''')

    def dismiss_popup(self):
        self._popup.dismiss()

    def load(self, _path, _fname):
        self.txt_input.font_name = _fname[0]
        _f_name = _fname[0][_fname[0].rfind(os.sep) + 1:]
        self.spnr_fnt.text = _f_name[:_f_name.rfind('.')]
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="load file", content=content,
            size_hint=(0.9, 0.9))
        self._popup.open()
class RootWidget(FloatLayout):
    # Create an instance of the InpaintingControl class that will 
    # take care of all functionalities related to inpainting
    inpaintingControl = InpaintingControl()
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    
    # 
    # All the methods below are called by widgets of viscomp.kv
    #

    # Switch the GUI's current mode
    def next_mode(self):
        # change the mode of the inpainting class
        self.inpaintingControl.nextMode()
        # update the variable holding the current mode's descriptive text
        self.modeText = self.currentModeMsg()
        # update the variable holding the current image's descriptive text
        self.imageText = self.currentImageMsg()
        # display the current image in the imview widget
        self.display_current_image()
                
    # Switch the GUI's current image
    def next_image(self):
        # change the current image of the inpainting class
        self.inpaintingControl.nextImage()        
        # update the variable holding the current mode's descriptive text
        self.imageText = self.currentImageMsg()        
        # display the current image in the imview widget
        self.display_current_image()        

#########################################
## PLACE YOUR CODE BETWEEN THESE LINES ##
#########################################
    def run_algorithm(self):
        ok, msg = self.inpaintingControl.runAlgorithm(self.ids.imviewer)
        if not ok:
            # if the method returned an error, display a popup
            # with an error message
            self.show_error_popup(self.currentModeMsg(), msg)
        else:
            # if there were no errors, display the current image
            # we do this to ensure that if the currently-displayed
            # image is an output image of the algorithm, the image is
            # updated with the algorithm's results
            self.display_current_image()

        return
#########################################
        

    # Run the algorithm associate with the GUI's current mode for ONE iteration
    def step_algorithm(self):
        # the algorithm is executed by calling the method of
        # the InpaintingControl class
        ok, msg = self.inpaintingControl.runAlgorithm(self.ids.imviewer, maxIterations=1)
        if not ok:
            # if the method returned an error, display a popup
            # with an error message
            self.show_error_popup(self.currentModeMsg(), msg)
        else:
            # if there were no errors, display the current image
            # we do this to ensure that if the currently-displayed 
            # image is an output image of the algorithm, the image is 
            # updated with the algorithm's results
            self.display_current_image()

        return


    # These methods simply call the associated routine of the 
    # inpaintingControl class to get the descriptive strings to be
    # displayed by the GUI's various buttons
    def currentModeMsg(self):
        return self.inpaintingControl.currentModeMsg()
    def currentImageMsg(self):
        return self.inpaintingControl.currentImageMsg()
    def currentFileActionMsg(self):
        return self.inpaintingControl.currentFileActionMsg()

    # Method to update the image displayed by the imviewer widget
    def display_current_image(self):
        # first we get the OpenCV image associated with the GUI's 
        # current image
        currentOpenCVImage = self.inpaintingControl.imageData()
        # we also get the name of the image 
        currentOpenCVImageName = self.inpaintingControl.imageName()
        # then we call the imviewer's display routine to display it
        self.ids.imviewer.display_opencv_image(im=currentOpenCVImage, name=currentOpenCVImageName)

    # Method to display a small popup window showing an error message
    # The method expects a title for the popup as well as a message
    def show_error_popup(self, title, message):
        try:
            content = Label(text=message)
            self._popup = Popup(title=title, content=content,
                                size_hint=(0.9, None))
            self._popup.open()
        except Exception as e:
            Logger.exception('VisComp: Error %s' %message)

    # Method to close a popup that is currently shown on screen
    def dismiss_error_popup(self):
        self._popup.dismiss()

    show_vectors_callback = ObjectProperty(None)
    show_intensities_callback = ObjectProperty(None)

    # Routine to display the widgets for controlling the debug display
    def show_debug(self):
        content = DebugDialog(
            patch_radius_callback=self.inpaintingControl.setPatchRadius,
            show_patch_callback=self.inpaintingControl.debug.setShowPatch,
            show_vectors_callback=self.inpaintingControl.debug.setShowVectors,
            max_iterations_callback=self.inpaintingControl.setMaxIterations,
            verbose_callback=self.inpaintingControl.debug.setVerbose,
            show_intensities_callback=
                self.inpaintingControl.debug.setShowIntensities,
            patch_radius = self.inpaintingControl.patchRadius(),
            max_iterations = self.inpaintingControl.maxIterations(),
            show_patch = self.inpaintingControl.debug.showPatch(),
            show_vectors = self.inpaintingControl.debug.showVectors(),
            verbose = self.inpaintingControl.debug.verbose(),
            show_intensities = self.inpaintingControl.debug.showIntensities())
        self._debug = Popup(title="Debug Display Control", content=content, auto_dismiss=True, size_hint=(0.9, 0.9))
        self._debug.open()
        #print self._debug.ids.container.children[0].ids.show_vectors.active
        
    # Routine to display the dialog box for selecting an image file for
    # opening/writing
    def show_dialog(self):
        if self.inpaintingControl.isInputImage():
            content = LoadDialog(load=self.load, cancel=self.dismiss_error_popup)
            self._popup = Popup(title="Open Image", content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()
        elif self.inpaintingControl.isOutputImage():
            content = SaveDialog(save=self.save, cancel=self.dismiss_error_popup)
            self._popup = Popup(title="Save Image", content=content,
                                size_hint=(0.9, 0.9))
            self._popup.open()

    # Lower-level routines for loading and saving an image
    def _loadsave(self, filename, func, s):
        if len(filename)<=0:
            return
        
        ok, msg = func(filename)
        if not ok:
            title = 'Error %s Image'%s
            self.show_error_popup(title, msg)
        else:
            self.display_current_image()
        self.dismiss_error_popup()
    def load(self, path, filenameList):
        s = 'Opening'
        if filenameList is not None:
            self._loadsave(filenameList[0], self.inpaintingControl.load, s)

    def save(self, path, filename):
        s = 'Saving'
        if filename is not None:
            self._loadsave(filename, self.inpaintingControl.save, s)
Пример #59
0
class ModifyPathDialog(BoxLayout):
    """ Popup allowing user to modify a file path.

    This popup contains a text input field showing the current path, which can
    be modified by the user. Alternatively, the user can click the folder icon
    to open up a file browser to select a new file/dir using that method

    """
    setupGUI_dir = os.path.dirname(os.path.abspath(__file__))
    # var to store the current path (string)
    currentPath = StringProperty()

    # function to attach to the done button
    doneFunc = ObjectProperty(None)

    def updateCurrentPath(self, path, selection):
        """ Callback function to update the current path in the popup

        Parameters
        ----------
        path : string
            full path of parent directory of file(s) that were selected
        selection : list
            list of files that were selected from within `path` directory

        """
        # if a file was selected, return full path to the file
        if len(selection) > 0:
            self.currentPath = join(path, selection[0])
        # if it was a dir instead, just return the path to the dir
        else:
            self.currentPath = path

        # close the parent popup
        self._popup.dismiss()

    def launchFileBrowser(self, path='~/', fileFilter=[]):
        """ Launch pop-up file browser for selecting files

        Generic function to present a popup window with a file browser.
        Customizable by specifying the callback functions to attach to buttons
        in browser

        Parameters
        ----------
        path : string
            full path to starting directory of the file browser
        fileFilter : list
            list of file types to isolate in the file browser; e.g ['*.txt']

        """
        # check to make sure the current path points to a real location
        if os.path.exists(self.currentPath):
            startingPath = self.currentPath
        else:
            startingPath = '~/'

        # method to pop open a file browser
        content = LoadFileDialog(loadFunc=self.updateCurrentPath,
                                 cancelFunc=self.cancelFileChooser,
                                 path=startingPath,
                                 fileFilter=fileFilter)
        self._popup = Popup(title="Select",
                            content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def cancelFileChooser(self):
        """ Close the popup file browser """
        self._popup.dismiss()
Пример #60
0
class Setting(Screen, GridLayout, BoxLayout):
    newDevControl = 1
    portsCount = 0 #Should be Plug-And-Play Value
    
    def __init__(self, **kwargs):
        super(Setting, self).__init__(**kwargs)
    
    
    def addPorts(self):
        
        self.box = BoxLayout(orientation = 'vertical', padding = (5))

        global newDevControl       
        if(self.newDevControl):
            self.myLabel = Label(text = 'Enter Number Of Ports On New Device', font_size='25sp')
            self.box.add_widget(self.myLabel)
        else:
            self.myLabel = Label(text = 'Number Must Be An Integer Value', font_size='25sp')
            self.box.add_widget(self.myLabel)

        self.popup = Popup(title = 'Add New Device',
                           title_size = (35), title_align = 'center',
                           content = self.box, size = (25,25), auto_dismiss=True)
        
        self.uInput = TextInput(text='', multiline=False, font_size='25sp')
        self.box.add_widget(self.uInput)

        self.okBtn = Button(text='Update', on_press = self.getUser, font_size='20sp', on_release=self.popup.dismiss)
        self.box.add_widget(self.okBtn)

        self.cancelBtn = Button(text='Cancel', font_size='20sp', on_press=self.popup.dismiss)
        self.box.add_widget(self.cancelBtn)
   
        self.popup.open()

   
   
    def getUser(self, arg1):
        if(self.uInput.text.isdigit()):
            global newDevControl, portsCount
            
            # Make sure add them as numbers and not as strings
            self.old = int(self.portsCount)
            self.new = int(self.uInput.text)
            self.new += self.old

            self.portsCount = str(self.new)
            self.newDevControl = 1
            
            curs.execute("UPDATE PORTS SET Amount='" + self.portsCount + "'")
            conn.commit()
  
            print("User Entered: {}".format(self.uInput.text))
            
        else:
            global newDeviceControl
            self.newDevControl = 0
            print("Wrong value!")
            return self.addPorts()

        
    def getPorts(self):

        global portsCount
        for row in curs.execute("SELECT * FROM Ports"):
		self.portsCount = row[0]                       

        ##############################################################
        # Taylor, here is where I need to get your Plug And Play value
        # so I can substract it from the total ports count.
        # This is how I will be able to show the ports available
        #
        # e.g.: self.portsCount -= plugAnPlaCount      
        #############################################################
        
        self.box = BoxLayout(orientation = 'vertical', padding = (5))
        self.myLabel = Label(text = ("There are " + str(self.portsCount) + " Ports Available!"), font_size='25sp')
        self.box.add_widget(self.myLabel)
        #self.box.add_widget(Label(text = ("There are " + str(self.portsCount) + " Ports Available!"), font_size='25sp'))

        self.popup = Popup(title = 'Open Ports',
                        title_size = (35), title_align = 'center',
                        content = self.box, size = (25,25), auto_dismiss=True)
        
        self.popButton = Button(text='OK', font_size='20sp', on_press=self.popup.dismiss)
        self.box.add_widget(self.popButton)
        
        self.popup.open()


        ############################################################
        # IF PORTS >= 2048. AKA SOMAXCONN has been reached,        #
        # Call the script that updates this ammount.               #
        # Maybe Create another instance of the servere?            #
        # If SOMAXCONN is updated, I may need to reboot the system #
        # Maybe Create a warning pop up telling the user what is   #
        # about to happen so that they dont think they crashed the #
        # GUI by adding that new devicew                           #
        ############################################################
            
        
        print("{} Ports".format(self.portsCount))