class CalculatorApp(App):
    theme_cls = ThemeManager()
    theme_cls.theme_style = 'Dark'
    nav_drawer = ObjectProperty()
    
           
    def build(self):
        self.content_widgets = Content()
        return self.content_widgets

    def get_value(self, text):
        self.value = text
        calculator = ComplexCalculator()
       
        result,initial_expression = calculator.calculate(text)
        
        if(result == False):
           self.error_dialog()
        else:
            expression_show = ' '.join([str(elem) for elem in initial_expression ])   
            self.success_dialog(result,expression_show)
    

    def success_dialog(self,result,expression_show):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Expresion ingresada:  "+str(expression_show),
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Resultado:  "+str(result),
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        
    def error_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Error al ingresar la expresión",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="Error",
                               content=content,
                               size_hint=(.8, None),
                               height=100,
                               auto_dismiss=False)

        self.dialog.add_action_button("Cerrar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
Beispiel #2
0
def error_pop(matter):
	content = MDLabel(font_style='Body1',theme_text_color='Secondary',text=matter,size_hint_y=None,valign='top')
	content.bind(texture_size=content.setter('size'))
	dialog2 = MDDialog(title="Error",content=content,size_hint=(.8, None),height=dp(200),auto_dismiss=False)
	dialog2.add_action_button("Dismiss",action=lambda *x:dialog2.dismiss())
	dialog2.open()
#This PC\Lenovo K8 Plus\SanDisk SD card\Android\data\org.coursera.android\files\Download
Beispiel #3
0
class PopList(TwoLineListItem):
    def __init__(self,**kwargs):
        super(PopList,self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            print(str(self.text))
            content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="{}".format(self.secondary_text),
                          size_hint_y=None,
                          valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="{}".format(self.text),
                                   content=content,
                                   size_hint=(.9, None),
                                   height=dp(300),
                                   auto_dismiss=False)

            self.dialog.add_action_button("Dismiss",
                                          action=lambda *x: self.dialog.dismiss())
            self.dialog.open()

        super(PopList, self).on_touch_down(touch)
Beispiel #4
0
class RemoveButton(IRightBodyTouch, MDIconButton):
    name = StringProperty()

    def remove_anime_from_list(x, self, anime_to_remove):
        x.parent.parent.parent.remove_widget(x.parent.parent)
        if anime_to_remove in Global.ANIME_CONFIRM_LIST:
            Global.ANIME_CONFIRM_LIST.remove(anime_to_remove)

        self.dismiss()

    def on_release(self):
        anime_to_remove = self.parent.parent.text
        self.dialog3 = MDDialog(title='Are you sure you want to remove ' +
                                anime_to_remove +
                                ' anime from your watchlist?',
                                size_hint=(.8, None),
                                height=dp(150),
                                auto_dismiss=False)

        self.dialog3.add_action_button(
            "Actually....", action=lambda *x: self.dialog3.dismiss())
        self.dialog3.add_action_button(
            "Im Sure!",
            action=lambda *x: self.remove_anime_from_list(
                self.dialog3, anime_to_remove))
        self.dialog3.open()

        pass
Beispiel #5
0
def conf_pop(dis,but1,action1):
	content = MDLabel(font_style='Body1',theme_text_color='Secondary',text=dis,size_hint_y=None,valign='top')
	content.bind(texture_size=content.setter('size'))
	dialog0 = MDDialog(content=content,size_hint=(.8, None),height=dp(200),auto_dismiss=True)
	dialog0.add_action_button(but1,action= action1)
	dialog0.add_action_button("cancel",action=lambda *x: dialog0.dismiss())
	return dialog0
Beispiel #6
0
 def create_list_dialog(title, items, on_selected_item):
     """
     Creates a dialog from given title and list.
     items is a list of BaseListItem objects.
     """
     # select_list = PWSelectList(items=items, on_release=on_release)
     select_list = PWSelectList(items=items)
     select_list.bind(selected_item=on_selected_item)
     content = select_list
     dialog = MDDialog(title=title, content=content, size_hint=(.9, .9))
     # workaround for MDDialog container size (too small by default)
     dialog.ids.container.size_hint_y = 1
     # close the dialog as we select the element
     select_list.bind(
         selected_item=lambda instance, value: dialog.dismiss())
     dialog.add_action_button("Dismiss", action=lambda *x: dialog.dismiss())
     return dialog
Beispiel #7
0
class TelaVisualizarContato(Screen):
    cheaderwidget = ObjectProperty()
    contato = ObjectProperty()

    def __init__(self, contato_id, **kwargs):
        self.app = App.get_running_app()
        self.contato = ContatoModel[contato_id]

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

    def on_pre_enter(self, *args):
        toolbar = self.app.root.ids['toolbar']
        toolbar.title = s.perfil.capitalize()
        toolbar.left_action_items = [[
            'arrow-left',
            lambda x: self.app.root.switch_to(TELAS.LISTA_CONTATO)
        ]]
        toolbar.right_action_items = [[
            'delete', lambda x: self.delete_contact()
        ]]

    def delete_contact(self):
        content = MDLabel(
            text=
            "Tem certeza que quer excluir este contato?\nEsta ação não tem retorno.",
            font_style='Caption',
            size_hint_y=None,
            valign='center')
        self.dialog = MDDialog(title="Excluir Contato.",
                               content=content,
                               size_hint=(0.8, None),
                               height=dp(300),
                               auto_dismiss=True)
        self.dialog.add_action_button("Confirmar",
                                      action=lambda *x: self.confirm_delete())
        self.dialog.add_action_button("Cancelar",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def confirm_delete(self):
        self.dialog.dismiss()
        db(ContatoModel.id == self.contato.id).delete()
        self.app.root.switch_to(TELAS.LISTA_CONTATO)
Beispiel #8
0
class DisposalList(MDList):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.refresh_list()

    def refresh_list(self):
        #обновление списка задач
        try:
            res = GetResult('getDisposalList', {'readed': 0}, [
                'Number', 'Theme', 'ShortTask', 'Sender_id', 'Receiver_id',
                'Task', 'isExecute'
            ])

            for i in res:
                # текст задачи
                if i[2] != '':
                    disposal_text = i[2]
                else:
                    disposal_text = 'ПУСТО'
                # иконка выполнения
                if i[6] == '0':
                    icon_text = 'clock'
                else:
                    icon_text = 'calendar-check'

                # номер + тема задачи
                theme_text = (i[0] + ' ' + i[1])
                if len(theme_text) > 30:
                    theme_text = theme_text[:27] + '...'

                item = DisposalItem(text=theme_text,
                                    secondary_text=disposal_text,
                                    icon_text=icon_text,
                                    data=i)
                self.add_widget(item)
        except:
            #сообщение об ошибке
            content = MDLabel(font_style='Body1',
                              text='Не подключения, проверьте настройки!',
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="Внимание",
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200))

            self.dialog.add_action_button(
                "ОК", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()
Beispiel #9
0
 def create_dialog(title, body):
     """
     Creates a dialog from given title and body.
     Adds it to the dialogs track list.
     """
     content = MDLabel(font_style='Body1',
                       theme_text_color='Secondary',
                       text=body,
                       size_hint_y=None,
                       valign='top')
     content.bind(texture_size=content.setter('size'))
     dialog = MDDialog(title=title,
                       content=content,
                       size_hint=(.8, None),
                       height=dp(200),
                       auto_dismiss=False)
     dialog.add_action_button("Dismiss", action=lambda *x: dialog.dismiss())
     dialog.bind(on_dismiss=Controller.on_dialog_dismiss)
     Controller.dialogs.append(dialog)
     return dialog
Beispiel #10
0
class BodyScanApp(App):
	theme_cls = ThemeManager()
	nav_drawer = ObjectProperty()
	username = StringProperty("")
	rights = StringProperty("")

	def showAddUserdialog(self):
		content = AddUserContent()
		self.dialog = MDDialog(title="Add Friend/Coach",
								content=content,
								size_hint=(.8, None),
								height=dp(200),
								auto_dismiss=False)
		self.dialog.add_action_button("Dismiss",
										action=lambda
										*x: self.dialog.dismiss())
		self.dialog.open()

	def build(self):
		self.nav_drawer = BodyScanNavDrawer()
		self.theme_cls.primary_palette = "Blue"
		self.theme_cls.primary_hue = "500"
Beispiel #11
0
class QuoteButton(TwoLineListItem):
    def __init__(self, **kwargs):
        super(QuoteButton, self).__init__(**kwargs)

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            if touch.is_double_tap:
                print('doouble')
            else:
                content = MDLabel(font_style='Body1',
                                  theme_text_color='Secondary',
                                  text="{}".format(self.secondary_text),
                                  valign='top')

                content.bind(size=content.setter('text_size'))
                self.dialog = MDDialog(title="{}".format(self.text),
                                       content=content,
                                       size_hint=(.9, None),
                                       height=dp(200),
                                       auto_dismiss=False)

                self.dialog.add_action_button(
                    "Dismiss", action=lambda *x: self.dialog.dismiss())
                self.dialog.add_action_button("Share",
                                              action=lambda *x: self.share())
                self.dialog.open()
        super(QuoteButton, self).on_touch_down(touch)

    def share(self):
        print 'sharing'
        intent = Intent()
        intent.setAction(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_TEXT,
                        String('{}'.format(self.secondary_text)))
        intent.setType('text/plain')
        chooser = Intent.createChooser(intent, String('Share...'))
        PythonActivity.mActivity.startActivity(chooser)
Beispiel #12
0
class AddCommentButton(MDFloatingActionButton):

    def commit(self):
        if self.dialog.content.text.strip() != "":
            GetResult('SendComment', {'disposal_id': int(self.parent.parent.ids.number.text), 'comment': self.dialog.content.text.strip()}, [])
            self.dialog.dismiss()
            self.parent.parent.load_comments()

    def on_press(self):
        content = MDTextField()
        content.multiline = True
        content.hint_text = "Введите комментарий"
        content.focus = True
        self.dialog = MDDialog(title="Новый комментарий",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(400))

        self.dialog.add_action_button("Сохранить",
                                      action=lambda *x: self.commit())
        self.dialog.add_action_button("Отмена",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
Beispiel #13
0
class MyApp(App):
    theme_cls = ThemeManager()
    nav_drawer = ObjectProperty()

    def build(self):
        print('here we start')
        # self.theme_cls.theme_style = 'Dark'
        # self.show_example_dialog()
        # self.show_menu()
        return RootScreen()

    def test(self):
        print('here we go')

    def show_menu(self):
        self.nav_drawer = MyNavDrawer()
        self.nav_drawer.toggle()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                               "That's pretty awesome right!",
                          valign='top')

        content.bind(size=content.setter('text_size'))
        self.dialog = MDDialog(title="This is a pretty dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda
                                          *x: self.dialog.dismiss())
        self.dialog.open()
Beispiel #14
0
class CategoriesSearchTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Category()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 11
    _data = None
    search_result = dict()
    sql = ''

    def __init__(self, **kwargs):
        kwargs['size_hint_y'] = None
        super(CategoriesSearchTable, self).__init__(**kwargs)
        self.bind(minimum_height=self.setter('height'))
        self.pagination_next()
        self.call_load()

    def filter(self, name):
        self.sql = "SELECT * FROM categories WHERE name REGEXP '{}' ORDER BY name".format(
            name)
        s = self.data_object.execute(self.sql)
        name = dict()
        for val in s:
            name[val['name']] = val
        self.search_result = name
        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_category()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"

    def generate_pdf(self, dt):
        sorted_list = sorted(self.search_result)
        th = Thread(target=generate_pdf,
                    args=(sorted_list, self.search_result))
        th.start()

    def generate_excel_sheet(self, dt):
        id = list()
        name = list()

        # result = list(sup.execute('SELECT * FROM suppliers'))

        # print self.search_result.values()

        for v in self.search_result.values():
            id.append(int(v.get('id')))
            name.append(v.get('name'))

        data_dict = {
            # '1_ID': id,
            '2_Name': name,
        }

        # generate_excel(data_dict, excel_file_name="supplier_report4")

        th = Thread(
            target=generate_excel,
            args=(data_dict,
                  "ExcelReports\\categories_report\\categories_report_" +
                  str(datetime.today()).replace(" ", "_").replace(":", "_")))
        th.start()

    def make_excel(self):
        Clock.schedule_once(self.generate_excel_sheet)

    def make_report(self):
        Clock.schedule_once(self.generate_pdf)

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        # self.pages = list(self.data_object.get_categories())
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.search_result.get(key)['id'])
            name = str(self.search_result.get(key)['name'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=name))
            self.d.add_widget(option)

            super(CategoriesSearchTable, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, name):
        self.data_object.id = id
        self.data_object.name = name
        self.data_object.update_category()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        name = self.data_object.get_categories().get(id)['name']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        name_wid = DialogTextInput(name)

        b.add_widget(
            MDLabel(id='Name', text="Name", size_hint_x=None, width="90px"))
        b.add_widget(name_wid)

        self.dialog = MDDialog(title="Update Category",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save", action=lambda *x: self.save_edited_data(id, name_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()
Beispiel #15
0
class MainApp(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "Decentralize oil field"
    mnemonic = StringProperty()
    address = StringProperty()
    passphrase = StringProperty()
    repeat_passphrase = StringProperty()
    enabled_mnemonic = BooleanProperty(True)
    enabled_address = BooleanProperty(True)
    instagram_last_fetched = StringProperty()

    def __init__(self, **kwargs):
        super(MainApp, self).__init__(**kwargs)
        #Window.bind(on_close=self.on_stop)

    def stop(self, *largs):
        # Open the popup you want to open and declare callback if user pressed `Yes`
        # popup = ExitPopup(title=TEXT_ON_CLOSE_APPLICATION,
        #                   content=Button(text=TEXT_ON_CLOSE_APPLICATION_BUTTON_CLOSE),
        #                   size=(400, 400), size_hint=(None, None)
        #                   )
        # popup.bind(on_confirm=partial(self.close_app, *largs))
        # popup.open()
        return

    def build(self):
        self.main_widget = Builder.load_file(
            os.path.join(os.path.dirname(__file__), "./latest.kv"))
        self.theme_cls.theme_style = 'Dark'

        # self.theme_cls.theme_style = 'Dark'

        # self.main_widget.ids.text_field_error.bind(
        #     on_text_validate=self.set_error_message,
        #     on_focus=self.set_error_message)
        self.update_instagram_images_list()
        self.bottom_navigation_remove_mobile(self.main_widget)
        #__list = Factory.Lists()
        return self.main_widget

    def update_instagram_images_list(self):
        thumbnails = get_instagram_thumbnails()
        for image in thumbnails:

            item = TwoLineAvatarIconListItem(
                text=f"Top Liker [ {image['top_likers'][0]} ]",
                secondary_text=f"Total likes {image['likes']}")
            item.add_widget(ContactPhoto(source=image["disk_name"]))
            item.add_widget(MessageButton(id=image["id"]))
            self.main_widget.ids.scroll.add_widget(item)

            # new_widget = Factory.ThreeLineAvatarIconListItemCheckbox(
            #         text=f'id-{image["id"]}')
            # new_widget.add_widget(AvatarSampleWidget(source=image["disk_name"]))

        self.instagram_last_fetched = "Last Fetched from Instagram " + self.instagram_last(
        )
        return

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                          "That's pretty awesome right!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def loading_box(self):
        content = MDLabel(
            font_style='Body1',
            theme_text_color='Secondary',
            text=
            "Please wait while we are fetching your instagram, Hang tight!!!",
            size_hint_y=None,
            valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a long test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=True)

        # self.dialog.add_action_button("Dismiss",
        #                               action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        return

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon",
                    lambda x: x,
                    icon='clipboard-account')
        bs.add_item("Here's another!", lambda x: x, icon='nfc')
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook",
                    lambda x: x,
                    icon_src='./assets/facebook-box.png')
        bs.add_item("YouTube",
                    lambda x: x,
                    icon_src='./assets/youtube-play.png')
        bs.add_item("Twitter", lambda x: x, icon_src='./assets/twitter.png')
        bs.add_item("Da Cloud",
                    lambda x: x,
                    icon_src='./assets/cloud-upload.png')
        bs.add_item("Camera", lambda x: x, icon_src='./assets/camera.png')
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_close(self):
        print("Clicked on closing application")
        Window.close()
        return True

    def on_start(self):
        print(self.main_widget.ids.scr_mngr)
        if store.get("mnemonic"):
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_mnemonic)
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_save_mnemonic)
            #self.main_widget.ids.login_box.remove_widget(self.main_widget.ids.address)
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.repeat_passphrase)

            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.mnemonic)

            #self.main_widget.ids.login_box.add_widget(self.main_widget.ids.repeat_passphrase)
        else:
            self.main_widget.ids.login_box.remove_widget(
                self.main_widget.ids.button_login)

        return

    def on_instagram_login(self, username, password):
        try:
            instagram_object = instagram_login(username.text, password.text)
            #self.loading_box()
            #Snackbar(text="Please wait for sometime, lets us fetch your Insta Handle").show()

            max_id, posts = get_all_posts(instagram_object)

            Logger.info("Now fetching images from instagram")
            save_instagram(posts)
            # with open("instagram.data","wb") as f:
            #     pickle.dump(posts, f)
            store.put("instagram",
                      max_id=max_id,
                      time_zone=time.tzname,
                      last_fetch_utc=datetime.datetime.utcnow().timestamp(),
                      last_fetch_local=datetime.datetime.now(
                          datetime.timezone.utc).astimezone().isoformat())

        except Exception as e:
            Logger.error(e)
            Snackbar(
                text="Please check your instragram username and password again"
            ).show()
        return

    def instagram_last(self):
        try:
            data = store.get("instagram")
            print(f"Instagram data stored in local storage {data}")
            print(
                f"Instagram Last fectehd locally is {data['last_fetch_local']}"
            )

            result = datetime.datetime.fromtimestamp(
                data["last_fetch_utc"]).strftime("%d %B, %Y")
            print(f"Human readable last fecthed {result}")
            return result
        except Exception as e:
            print(f"Error in lest fecthed dtiem stamp UTC {e.__str__()}")
            return ""

    def on_show_mnemonic(self):
        """
        Show mnemonic after fetching it from local storage 
        """
        self.main_widget.ids.login_box.add_widget(
            self.main_widget.ids.mnemonic)

    def on_login(self, passphrase):
        encrypted = store.get("mnemonic")
        encrypted_mnemonic = encrypted["value"]
        salt = encrypted["salt"]

        scrypt_key, salt = generate_scrypt_key(passphrase.text,
                                               bytes.fromhex(salt))
        print(
            f"scrypt_key from password {scrypt_key.hex()} and salt is {salt.hex()}"
        )

        print(f"Encrypted Mnemonic is {encrypted_mnemonic}")

        try:
            result = aes_decrypt(scrypt_key, bytes.fromhex(encrypted_mnemonic))
        except Exception as e:
            print("Error ")
            print(e)
            Snackbar(text="Password entered is wrong").show()

        print(result)
        store.put("password", value=passphrase.text)
        return

    def on_save(self, passphrase, repeat_passphrase):
        if not self.mnemonic:
            Snackbar(text="PLease generate a New mnemonic").show()
            return
        if passphrase.text != repeat_passphrase.text or not passphrase.text:
            Snackbar(text="Passphrases must match").show()
            return

        if len(passphrase.text) < 8:
            Snackbar(
                text="Passphrases must be at least 8 characters long").show()
            return

        scrypt_key, salt = generate_scrypt_key(passphrase.text)
        encrypted_mnemonic = aes_encrypt(scrypt_key, self.mnemonic)

        store.put("mnemonic", value=encrypted_mnemonic.hex(), salt=salt.hex())
        store.put("address", value=self.address)
        return

    def generate_mnemonic(self):
        """
        Make an api request with the data to confirm the user registraion
        After succesful registration reset the form 
        """
        #TODO form validation with cerberus
        #TODO Check if macid is available from the host or not
        #TODO check if ip address

        r = requests.get(f"http://{store.get('GO_API')}/get_mnemonic")
        mnemonic = r.json()["data"]["mnemonic"]
        zeroth_private_key = r.json()["data"]["zeroth_private_key"]
        zeroth_public_key = r.json()["data"]["zeroth_public_key"]

        master_private_key = r.json()["data"]["master_private_key"]
        master_public_key = r.json()["data"]["master_public_key"]

        self.mnemonic = mnemonic
        self.address = hashlib.sha256(zeroth_public_key.encode()).hexdigest()
        return
Beispiel #16
0
class ImportSearchTable1(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Import()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None

    _filter_date = False
    _date_search = " AND date LIKE '%{}%' "
    _filter_status = False
    _status_search = " AND status LIKE '%{}%' "
    _filter_supplier_id = False
    _supplier_id_search = " AND supplier_id = {} "

    search_result = dict()

    def __init__(self, **kwargs):
        super(ImportSearchTable1, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def activate_date(self, state):
        if state == 'down':
            self._filter_date = True
        else:
            self._filter_date = False

    def activate_status(self, state):
        if state == 'down':
            self._filter_status = True
        else:
            self._filter_status = False

    def activate_supplier_id(self, state):
        if state == 'down':
            self._filter_supplier_id = True
        else:
            self._filter_supplier_id = False

    def filter(self, import_receipt_search_number, imports_search_date_label,
               import_supplier_search_id, import_search_status):
        self.sql = "SELECT * FROM imports WHERE receipt_number LIKE '%{}%' ".format(
            import_receipt_search_number)

        if self._filter_date:
            self.sql += self._date_search.format(imports_search_date_label)

        if self._filter_supplier_id:
            self.sql += self._supplier_id_search.format(
                import_supplier_search_id)

        if self._filter_status:
            self.sql += self._status_search.format(import_search_status)

        s = self.data_object.execute(self.sql)
        name = dict()
        for val in s:
            name[val['receipt_number']] = val
        self.search_result = name
        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_import()
            self.pagination_next(self.current)
        except KeyError:
            Snackbar(text=" Key Not Found ").show()
        except _mysql_exceptions.IntegrityError:
            Snackbar(
                text=
                "Cannot delete or update a parent row: a foreign key constraint fails"
            ).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        data_object = Supplier()
        data_dict = data_object.get_suppliers()
        for key in self._data:
            id = str(self.search_result.get(key)['id'])
            receipt_number = self.search_result.get(key)['receipt_number']
            date = str(self.search_result.get(key)['date'])
            supplier_id = str(
                data_dict.get(str(
                    self.search_result.get(key)['supplier_id']))['name'])
            status = str(self.search_result.get(key)['status'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=receipt_number))
            self.d.add_widget(DataLabel(text=date))
            self.d.add_widget(DataLabel(text=supplier_id))
            self.d.add_widget(DataLabel(text=status))
            self.d.add_widget(option)

            super(ImportSearchTable1, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, receipt_number, date, supplier_id, status):
        self.data_object.id = id
        self.data_object.receipt_number = receipt_number
        self.data_object.date = date
        self.data_object.supplier_id = supplier_id
        self.data_object.status = status
        self.data_object.update_import()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        receipt_ = self.data_object.get_imports().get(id)['receipt_number']
        dat = str(self.data_object.get_imports().get(id)['date'])
        supplier_ = str(self.data_object.get_imports().get(id)['supplier_id'])
        stat = str(self.data_object.get_imports().get(id)['status'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        receipt_number = DialogTextInput(receipt_)
        date = DialogTextInput(dat)
        supplier_id = DialogTextInput(supplier_)
        status = DialogTextInput(stat)

        b.add_widget(
            MDLabel(text="Receipt Number", size_hint_x=None, width="90px"))
        b.add_widget(receipt_number)
        b.add_widget(MDLabel(text="Date", size_hint_x=None, width="90px"))
        b.add_widget(date)
        b.add_widget(MDLabel(text="Suppler ID", size_hint_x=None,
                             width="90px"))
        b.add_widget(supplier_id)
        b.add_widget(
            MDLabel(id='date', text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button("Save",
                                      action=lambda *x: self.save_edited_data(
                                          id, receipt_number.text, date.text,
                                          supplier_id.text, status.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
Beispiel #17
0
class AudioEntry(OneLineAvatarIconListItem):
    #label = ObjectProperty(MDLabel(size_hint_x=None, width=35, font_style="Body1"))
    display_mode = StringProperty()

    def __init__(self, audio_file, **kwargs):
        super().__init__(**kwargs)
        self.audio_file = audio_file
        self.text = audio_file.name
        self.secondary_text = str(dict(self.audio_file.params)).replace(
            "{", "").replace("}", "")

        if audio_file.kivy_image:
            self.ids.avatar.texture = audio_file.kivy_image.texture

        self.menu_items = [
            dict(viewclass="MDMenuItem", text="Edit", on_release=self.edit),
            dict(viewclass="MDMenuItem",
                 text="Info",
                 on_release=self.info_dialog),
        ]

    def on_display_mode(self, *args):
        text = text_color = ""
        theme_text_color = "Hint"

        if self.display_mode == "bitrate":
            bitrate = self.audio_file.bitrate
            if bitrate < 150:
                text = self.audio_file.bitrate_str
                text_color = (1, 0.2, 0.2, 0.7)
                theme_text_color = "Custom"
            else:
                text = self.audio_file.bitrate_str

        elif self.display_mode == "date":
            text = str(self.audio_file.date)

        elif self.display_mode == "moods":
            text = str(self.audio_file.moods)

        elif self.display_mode == "images":
            text = f"{len(self.audio_file.images)} images"
            theme_text_color = "Hint"

        label = self.ids.label
        label.text = text
        label.theme_text_color = theme_text_color
        label.text_color = text_color if text_color else label.text_color

    def on_touch_up(self, touch):
        super().on_touch_up(touch)
        if self.collide_point(*touch.pos) and touch.grab_current is not None:
            if touch.device == "mouse" and touch.button == "right":
                MDDropdownMenu(items=self.menu_items,
                               width_mult=2).open(touch, touch=True)

    def edit(self):
        print("Editing")

    def info_dialog(self):
        content = MDList()
        label = MDLabel(font_style='Subhead',
                        theme_text_color='Secondary',
                        text="\n" + str(self.audio_file),
                        valign='center',
                        halign="center")
        label.bind(texture_size=label.setter('size'))

        image = SmartTile(allow_stretch=True,
                          keep_ratio=True,
                          box_color=[0, 0, 0, 0],
                          size_hint_y=None,
                          height=300)
        image._img_widget.texture = self.ids.avatar.texture

        content.add_widget(image)
        content.add_widget(label)

        self.dialog = MDDialog(title=self.audio_file.name,
                               content=content,
                               size_hint=(.8, 0.75),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
Beispiel #18
0
class KitchenSink(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "KivyMD Kitchen Sink"

    menu_items = [
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field_error.bind(
            on_text_validate=self.set_error_message,
            on_focus=self.set_error_message)
        self.bottom_navigation_remove_mobile(main_widget)
        return main_widget

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_example_snackbar(self, snack_type):
        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(
                text=
                "This is a very very very very very very very long snackbar!"
            ).show()

    def show_example_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="This is a dialog with a title and some text. "
                          "That's pretty awesome right!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def show_example_long_dialog(self):
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="Lorem ipsum dolor sit amet, consectetur "
                          "adipiscing elit, sed do eiusmod tempor "
                          "incididunt ut labore et dolore magna aliqua. "
                          "Ut enim ad minim veniam, quis nostrud "
                          "exercitation ullamco laboris nisi ut aliquip "
                          "ex ea commodo consequat. Duis aute irure "
                          "dolor in reprehenderit in voluptate velit "
                          "esse cillum dolore eu fugiat nulla pariatur. "
                          "Excepteur sint occaecat cupidatat non "
                          "proident, sunt in culpa qui officia deserunt "
                          "mollit anim id est laborum.",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="This is a long test dialog",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)

        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def get_time_picker_data(self, instance, time):
        self.root.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        self.time_dialog = MDTimePicker()
        self.time_dialog.bind(time=self.get_time_picker_data)
        if self.root.ids.time_picker_use_previous_time.active:
            try:
                self.time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        self.time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.root.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        if self.root.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon",
                    lambda x: x,
                    icon='clipboard-account')
        bs.add_item("Here's another!", lambda x: x, icon='nfc')
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook",
                    lambda x: x,
                    icon_src='./assets/facebook-box.png')
        bs.add_item("YouTube",
                    lambda x: x,
                    icon_src='./assets/youtube-play.png')
        bs.add_item("Twitter", lambda x: x, icon_src='./assets/twitter.png')
        bs.add_item("Da Cloud",
                    lambda x: x,
                    icon_src='./assets/cloud-upload.png')
        bs.add_item("Camera", lambda x: x, icon_src='./assets/camera.png')
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass
class ContentForAnimCard(BoxLayout):
    r = 0

    def name_it(self, i):
        if (self.r == 1):
            return
        self.r = 1
        self.ids.rate1.text = 'loading.......'
        k = threading.Thread(target=self.get_rate, args=(i, ))
        k.start()

    def get_rate(self, i):
        try:
            url = 'https://www.goldratetoday.com/gold-rate-' + i + '.php'
            with requests.Session() as s:
                r = s.post(url)
                k = r.content
                k = k.decode('utf-8')
            etree = html.fromstring(k)
            p = etree.xpath('/html/body/div[1]/div[2]/b/text()')
            self.ids.rate1.text = i + ' : ' + p[0]
            self.r = 0
        except Exception:
            self.ids.rate1.text = 'To get select a city and press get price'
            self.alert_dialog = MDDialog(
                title="WARNING!",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="no internet",
                events_callback=self.callback_for_menu_items,
            )
            self.r = 0
            self.alert_dialog.open()

    def callback_for_menu_items(self, *args):
        self.alert_dialog.dismiss()

    def pop(self):
        p = Popup(title='Garuda.inc',
                  title_color=[1, 0, 0, 1],
                  background='',
                  size_hint=[0.75, 0.6])
        b = BoxLayout(orientation='vertical')
        b.add_widget(Image(source='a1.jpg'))
        b1 = BoxLayout(orientation='vertical')
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(MDLabel(text='Developer : Datta', halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(MDLabel(text='Phone : 9182756561', halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(MDLabel(text='Whatsapp : 8008324644', halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(
            MDLabel(text='Email : [email protected]', halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b1.add_widget(
            MDLabel(text='Gold price : goldpricetoday.com', halign='left'))
        b1.add_widget(MDSeparator(height=dp(1)))
        b.add_widget(b1)
        p.add_widget(b)
        p.open()
Beispiel #20
0
class StatusTab(MDTab):
    app = ObjectProperty(None)
    irc_action = ObjectProperty(None)
    irc_action_send_btn = ObjectProperty(None)

    def __init__(self, **kw):
        super(StatusTab, self).__init__(**kw)
        self.app = App.get_running_app()
        Clock.schedule_once(self.__post_init__)

    def __post_init__(self, args):
        pass

    def update_irc_action_text(self, dt):
        self.irc_action.text = ''
        self.irc_action.on_focus()

    def send_action(self):
        Clock.schedule_once(self.update_irc_action_text)
        self.app.connection.sendLine(self.irc_action.text.strip('/'))
        self.msg_list.add_widget(
            MultiLineListItem(
                text="[b][color=1A237E]" +
                self.app.config.get('irc', 'nickname') + "[/color][/b] " +
                self.irc_action.text,
                font_style='Subhead',
            ))
        self.msg_list.parent.scroll_to(self.msg_list.children[0])
        Logger.info(
            "IRC: <%s> %s" %
            (self.app.config.get('irc', 'nickname'), self.irc_action.text))

    def on_irc_unknown(self, prefix, command, params):
        Logger.info("IRC UNKNOWN: <%s> %s %s" % (prefix, command, params))

    def on_noticed(self, user, channel, action):
        user = user.split('!')[0]
        if user == 'ChanServ':
            content = MDLabel(font_style='Body1',
                              theme_text_color='Secondary',
                              text=action,
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="Notice: {}".format(user),
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200),
                                   auto_dismiss=False)

            self.dialog.add_action_button(
                "Dismiss", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()
        else:
            self.msg_list.add_widget(
                MultiLineListItem(
                    text="[b][color=F44336]" + user + "[/color][/b] " + action,
                    font_style='Subhead',
                ))
            self.msg_list.parent.scroll_to(self.msg_list.children[0])
        Logger.info("IRC NOTICED: <%s> %s %s" % (user, channel, action))

    def nick_details(self, nick_list_item):
        self.app.connection.signedOn()
        nick_item_data = self.nick_data[nick_list_item.text]
        bs = MDListBottomSheet()
        bs.add_item("Whois ({})".format(nick_list_item.text), lambda x: x)
        bs.add_item(
            "{} ({}@{})".format(nick_item_data[7].split(' ')[1],
                                nick_item_data[3], nick_item_data[2]),
            lambda x: x)
        bs.add_item(
            "{} is connected via {}".format(nick_list_item.text,
                                            nick_item_data[4]), lambda x: x)
        bs.open()

    def __post_connection__(self, connection):
        connection.on_irc_unknown(self.on_irc_unknown)
        connection.on_noticed(self.on_noticed)

    def __post_joined__(self, connection):
        pass
Beispiel #21
0
class ContentForAnimCard(BoxLayout):
    r=0
    def name_it(self,i):
        if (self.r==1):
            return
        self.r=1
        self.ids.rate1.text='loading.......'
        k=threading.Thread(target=self.get_rate,args=(i,))
        k.start()
    
    def get_rate(self,i):
        if (i=='Select city'):
            self.alert_dialog = MDDialog(
                title="WARNING!",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="select a city and press button",
                events_callback=self.callback_for_menu_items,
            )
            self.r=0
            self.ids.rate1.text='To get select a city and press get price'
            self.alert_dialog.open()
            return
        
        try:
            url='https://www.goldratetoday.com/gold-rate-'+i+'.php'
            headers={
                'Sec-Fetch-Mode': 'navigate',
                'Sec-Fetch-User': '******',
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
            }
            with requests.Session() as s:
                r=s.post(url,headers=headers)
                k=r.content
                k=k.decode('utf-8')
            print(k)
            etree=html.fromstring(k)
            p=etree.xpath('/html/body/div[1]/div[2]/b/text()')
            self.ids.rate1.text=i+' : '+p[0]
            self.r=0
        except Exception as e:
            print(str(e))
            self.ids.rate1.text='To get select a city and press get price'
            self.alert_dialog = MDDialog(
                title="WARNING!",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="no internet",
                events_callback=self.callback_for_menu_items,
            )
            self.r=0
            self.alert_dialog.open()
    def callback_for_menu_items(self, *args):
        self.alert_dialog.dismiss()
    def pop(self):
        p=Popup(title='Garuda.inc',title_color=[1,0,0,1],background='',size_hint=[0.75,0.6])
        b=BoxLayout(orientation='vertical')
        b.add_widget(Image(source='a1.jpg'))
        b1=BoxLayout(orientation='vertical')
        b1.add_widget(MDSeparator(height= dp(1)))
        b1.add_widget(MDLabel(text='Developer : Datta',halign='left'))
        b1.add_widget(MDSeparator(height= dp(1)))
        b1.add_widget(MDLabel(text='Phone : 9182756561',halign='left'))
        b1.add_widget(MDSeparator(height= dp(1)))
        b1.add_widget(MDLabel(text='Whatsapp : 8008324644',halign='left'))
        b1.add_widget(MDSeparator(height= dp(1)))
        b1.add_widget(MDLabel(text='Email : [email protected]',halign='left'))
        b1.add_widget(MDSeparator(height= dp(1)))
        b1.add_widget(MDLabel(text='Gold price : goldpricetoday.com',halign='left'))
        b1.add_widget(MDSeparator(height= dp(1)))
        b.add_widget(b1)
        p.add_widget(b)
        p.open()
Beispiel #22
0
class NowalletApp(App):
    theme_cls = ThemeManager()
    theme_cls.theme_style = "Dark"
    theme_cls.primary_palette = "Grey"
    theme_cls.accent_palette = "LightGreen"

    units = StringProperty()
    currency = StringProperty()
    current_coin = StringProperty("0")
    current_fiat = StringProperty("0")
    current_fee = NumericProperty()
    current_utxo = ObjectProperty()

    def __init__(self):
        self.chain = nowallet.TBTC
        self.loop = asyncio.get_event_loop()
        self.is_amount_inputs_locked = False
        self.fiat_balance = False
        self.bech32 = False
        self.exchange_rates = None

        self.menu_items = [{
            "viewclass": "MDMenuItem",
            "text": "View YPUB"
        }, {
            "viewclass": "MDMenuItem",
            "text": "Lock with PIN"
        }, {
            "viewclass": "MDMenuItem",
            "text": "Manage UTXOs"
        }, {
            "viewclass": "MDMenuItem",
            "text": "Settings"
        }]
        self.utxo_menu_items = [{
            "viewclass": "MDMenuItem",
            "text": "View Private key"
        }, {
            "viewclass": "MDMenuItem",
            "text": "View Redeem script"
        }]
        super().__init__()

    def show_dialog(self, title, message, qrdata=None, cb=None):
        if qrdata:
            dialog_height = 300
            content = QRCodeWidget(data=qrdata,
                                   size=(dp(150), dp(150)),
                                   size_hint=(None, None))
        else:
            dialog_height = 200
            content = MDLabel(font_style='Body1',
                              theme_text_color='Secondary',
                              text=message,
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title=title,
                               content=content,
                               size_hint=(.8, None),
                               height=dp(dialog_height),
                               auto_dismiss=False)

        self.dialog.add_action_button(
            "Dismiss", action=cb if cb else lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def start_zbar(self):
        if platform != "android":
            return
        self.root.ids.sm.current = "zbar"
        self.root.ids.detector.start()

    def qrcode_handler(self, symbols):
        try:
            address, amount = nowallet.get_payable_from_BIP21URI(symbols[0])
        except ValueError as ve:
            self.show_dialog("Error", str(ve))
            return
        self.root.ids.address_input.text = address
        self.update_amounts(text=str(amount))
        self.root.ids.detector.stop()
        self.root.ids.sm.current = "main"

    def menu_button_handler(self, button):
        if self.root.ids.sm.current == "main":
            MDDropdownMenu(items=self.menu_items, width_mult=4).open(button)

    def menu_item_handler(self, text):
        # Main menu items
        if "PUB" in text:
            self.root.ids.sm.current = "ypub"
        elif "PIN" in text:
            self.root.ids.sm.current = "pin"
        elif "UTXO" in text:
            self.root.ids.sm.current = "utxo"
        elif "Settings" in text:
            self.open_settings()
        # UTXO menu items
        elif self.root.ids.sm.current == "utxo":
            addr = self.utxo.address(self.chain.netcode)
            key = self.wallet.search_for_key(addr)
            if "Private" in text:
                self.show_dialog("Private key", "", qrdata=key.wif())
            if "Redeem" in text:
                if self.bech32:
                    return
                script = b2h(key.p2wpkh_script())
                self.show_dialog("Redeem script", "", qrdata=script)

    def fee_button_handler(self):
        fee_input = self.root.ids.fee_input
        fee_button = self.root.ids.fee_button
        fee_input.disabled = not fee_input.disabled
        if not fee_input.disabled:
            fee_button.text = "Custom Fee"
        else:
            fee_button.text = "Normal Fee"
            fee_input.text = str(self.estimated_fee)
            self.current_fee = self.estimated_fee

    def fee_input_handler(self):
        text = self.root.ids.fee_input.text
        if text:
            self.current_fee = int(float(text))

    def set_address_error(self, addr):
        netcode = self.chain.netcode
        is_valid = addr.strip() and validate.is_address_valid(
            addr.strip(), ["address", "pay_to_script"], [netcode]) == netcode
        self.root.ids.address_input.error = not is_valid

    def set_amount_error(self, amount):
        _amount = Decimal(amount) if amount else Decimal("0")
        is_valid = _amount / self.unit_factor <= self.wallet.balance
        self.root.ids.spend_amount_input.error = not is_valid

    def do_spend(self, address, amount, fee_rate):
        self.spend_tuple = self.loop.run_until_complete(
            self.wallet.spend(address, amount, fee_rate, rbf=self.rbf))

    def send_button_handler(self):
        addr_input = self.root.ids.address_input
        address = addr_input.text.strip()
        amount_str = self.root.ids.spend_amount_input.text
        amount = Decimal(amount_str) / self.unit_factor

        if addr_input.error or not address:
            self.show_dialog("Error", "Invalid address.")
            return
        elif amount > self.wallet.balance:
            self.show_dialog("Error", "Insufficient funds.")
            return
        elif not amount:
            self.show_dialog("Error", "Amount cannot be zero.")
            return

        fee_rate_sat = int(Decimal(self.current_fee))
        fee_rate = nowallet.Wallet.satb_to_coinkb(fee_rate_sat)
        self.do_spend(address, amount, fee_rate)
        logging.info("Finished doing spend")

        txid, decimal_fee = self.spend_tuple[:2]

        message = "Added a miner fee of: {} {}".format(
            decimal_fee, self.chain.chain_1209k.upper())
        message += "\nTxID: {}...{}".format(txid[:13], txid[-13:])
        self.show_dialog("Transaction sent!", message)

    def check_new_history(self, dt):
        if self.wallet.new_history:
            self.update_screens()
            self.wallet.new_history = False

    @property
    def pub_char(self):
        if self.chain == nowallet.BTC:
            return "z" if self.bech32 else "y"
        elif self.chain == nowallet.TBTC:
            return "v" if self.bech32 else "u"

    def do_login(self):
        email = self.root.ids.email_field.text
        passphrase = self.root.ids.pass_field.text
        confirm = self.root.ids.confirm_field.text
        if not email or not passphrase or not confirm:
            self.show_dialog("Error", "All fields are required.")
            return
        if passphrase != confirm:
            self.show_dialog("Error", "Passwords did not match.")
            return
        self.bech32 = self.root.ids.bech32_checkbox.active
        self.menu_items[0]["text"] = "View {}PUB".format(self.pub_char.upper())

        self.root.ids.sm.current = "wait"
        try:
            self.do_login_tasks(email, passphrase)
        except (SocksConnectionError, ClientConnectorError):
            self.show_dialog(
                "Error",
                "Make sure Tor/Orbot is installed and running before using Nowallet.",
                cb=lambda x: sys.exit(1))
            return
        self.update_screens()
        self.root.ids.sm.current = "main"
        Clock.schedule_interval(self.check_new_history, 1)
        logging.info("Checking for new history.")
        self.do_listen_task()

    @engine. async
    def do_listen_task(self):
        yield Task(self.loop.run_until_complete,
                   self.wallet.listen_to_addresses())
        logging.info("Listening for new transactions.")

    @engine. async
    def do_login_tasks(self, email, passphrase):
        self.root.ids.wait_text.text = "Connecting.."

        server, port, proto = yield Task(self.loop.run_until_complete,
                                         nowallet.get_random_server(self.loop))
        connection = nowallet.Connection(self.loop, server, port, proto)
        yield Task(self.loop.run_until_complete, connection.do_connect())

        self.root.ids.wait_text.text = "Deriving Keys.."
        self.wallet = yield Task(nowallet.Wallet,
                                 email,
                                 passphrase,
                                 connection,
                                 self.loop,
                                 self.chain,
                                 bech32=self.bech32)

        self.root.ids.wait_text.text = "Fetching history.."
        yield Task(self.loop.run_until_complete,
                   self.wallet.discover_all_keys())

        self.root.ids.wait_text.text = "Fetching exchange rates.."
        self.exchange_rates = yield Task(
            self.loop.run_until_complete,
            fetch_exchange_rates(nowallet.BTC.chain_1209k))

        self.root.ids.wait_text.text = "Getting fee estimate.."
        coinkb_fee = yield Task(self.loop.run_until_complete,
                                self.wallet.get_fee_estimation())
        self.current_fee = self.estimated_fee = nowallet.Wallet.coinkb_to_satb(
            coinkb_fee)
        logging.info("Finished 'doing login tasks'")

    def update_screens(self):
        self.update_balance_screen()
        self.update_send_screen()
        self.update_recieve_screen()
        self.update_ypub_screen()
        self.update_utxo_screen()

    def toggle_balance_label(self):
        self.fiat_balance = not self.fiat_balance
        self.update_balance_screen()

    def balance_str(self, fiat=False):
        balance, units = None, None
        if not fiat:
            balance = self.unit_precision.format(self.wallet.balance *
                                                 self.unit_factor)
            units = self.units
        else:
            balance = "{:.2f}".format(self.wallet.balance * self.get_rate())
            units = self.currency
        return "{} {}".format(balance.rstrip("0").rstrip("."), units)

    def update_balance_screen(self):
        self.root.ids.balance_label.text = self.balance_str(
            fiat=self.fiat_balance)
        self.root.ids.recycleView.data_model.data = []

        for hist in self.wallet.get_tx_history():
            verb = "Sent" if hist.is_spend else "Recieved"
            hist_str = "{} {} {}".format(verb, hist.value * self.unit_factor,
                                         self.units)
            self.add_list_item(hist_str, hist)

    def update_utxo_screen(self):
        self.root.ids.utxoRecycleView.data_model.data = []
        for utxo in self.wallet.utxos:
            value = Decimal(str(utxo.coin_value / nowallet.Wallet.COIN))
            utxo_str = (self.unit_precision + " {}").format(
                value * self.unit_factor, self.units)
            self.add_utxo_list_item(utxo_str, utxo)

    def update_send_screen(self):
        self.root.ids.send_balance.text = \
            "Available balance:\n" + self.balance_str()
        self.root.ids.fee_input.text = str(self.current_fee)

    def update_recieve_screen(self):
        address = self.update_recieve_qrcode()
        encoding = "bech32" if self.wallet.bech32 else "P2SH"
        self.root.ids.addr_label.text = \
            "Current Address ({}):\n{}".format(encoding, address)

    def update_recieve_qrcode(self):
        address = self.wallet.get_address(self.wallet.get_next_unused_key(),
                                          addr=True)
        amount = Decimal(self.current_coin) / self.unit_factor
        self.root.ids.addr_qrcode.data = \
            "bitcoin:{}?amount={}".format(address, amount)
        return address

    def update_ypub_screen(self):
        ypub = self.wallet.ypub
        ypub = self.pub_char + ypub[1:]
        self.root.ids.ypub_label.text = "Extended Public Key (SegWit):\n" + ypub
        self.root.ids.ypub_qrcode.data = ypub

    def lock_UI(self, pin):
        if not pin:
            self.show_dialog("Error", "PIN field is empty.")
            return
        self.pin = pin
        self.root.ids.pin_back_button.disabled = True
        self.root.ids.lock_button.char = "unlock"

    def unlock_UI(self, attempt):
        if not attempt or attempt != self.pin:
            self.show_dialog("Error", "Bad PIN entered.")
            return
        self.root.ids.pin_back_button.disabled = False
        self.root.ids.lock_button.char = "lock"

    def update_pin_input(self, char):
        pin_input = self.root.ids.pin_input
        if char == "clear":
            pin_input.text = ""
        elif char == "lock":
            self.lock_UI(pin_input.text)
            pin_input.text = ""
        elif char == "unlock":
            self.unlock_UI(pin_input.text)
            pin_input.text = ""
        else:
            pin_input.text += char

    def update_unit(self):
        self.unit_factor = 1
        self.unit_precision = "{:.8f}"
        if self.units[0] == "m":
            self.unit_factor = 1000
            self.unit_precision = "{:.5f}"
        elif self.units[0] == "u":
            self.unit_factor = 1000000
            self.unit_precision = "{:.2f}"

        coin = Decimal(self.current_coin) / self.unit_factor
        fiat = Decimal(self.current_fiat) / self.unit_factor
        self.update_amount_fields(coin, fiat)

    def get_rate(self):
        rate = self.exchange_rates[self.price_api][self.currency] \
            if self.exchange_rates else 1
        return Decimal(str(rate))

    def update_amounts(self, text=None, type="coin"):
        if self.is_amount_inputs_locked:
            return
        amount = Decimal(text) if text else Decimal("0")
        rate = self.get_rate() / self.unit_factor
        new_amount = None
        if type == "coin":
            new_amount = amount * rate
            self.update_amount_fields(amount, new_amount)
        elif type == "fiat":
            new_amount = amount / rate
            self.update_amount_fields(new_amount, amount)
        self.update_recieve_qrcode()

    def update_amount_fields(self, coin, fiat):
        self.is_amount_inputs_locked = True
        _coin = self.unit_precision.format(coin)
        self.current_coin = _coin.rstrip("0").rstrip(".")
        _fiat = "{:.2f}".format(fiat)
        self.current_fiat = _fiat.rstrip("0").rstrip(".")
        self.is_amount_inputs_locked = False

    def build(self):
        self.icon = "icons/brain.png"
        self.use_kivy_settings = False
        self.rbf = self.config.get("nowallet", "rbf")
        self.units = self.config.get("nowallet", "units")
        self.update_unit()
        self.currency = self.config.get("nowallet", "currency")
        self.explorer = self.config.get("nowallet", "explorer")
        self.set_price_api(self.config.get("nowallet", "price_api"))

    def build_config(self, config):
        config.setdefaults(
            "nowallet", {
                "rbf": False,
                "units": self.chain.chain_1209k.upper(),
                "currency": "USD",
                "explorer": "blockcypher",
                "price_api": "BitcoinAverage"
            })
        Window.bind(on_keyboard=self.key_input)

    def build_settings(self, settings):
        coin = self.chain.chain_1209k.upper()
        settings.add_json_panel("Nowallet Settings",
                                self.config,
                                data=settings_json(coin))

    def on_config_change(self, config, section, key, value):
        if key == "rbf":
            self.rbf = value
        elif key == "units":
            self.units = value
            self.update_unit()
            self.update_amounts()
            self.update_balance_screen()
            self.update_send_screen()
            self.update_utxo_screen()
        elif key == "currency":
            self.currency = value
            self.update_amounts()
        elif key == "explorer":
            self.explorer = value
        elif key == "price_api":
            self.set_price_api(value)
            self.update_amounts()

    def set_price_api(self, val):
        if val == "BitcoinAverage":
            self.price_api = "btcav"
        elif val == "CryptoCompare":
            self.price_api = "ccomp"

    def key_input(self, window, key, scancode, codepoint, modifier):
        if key == 27:  # the back button / ESC
            return True  # override the default behaviour
        else:  # the key now does nothing
            return False

    def on_pause(self):
        return True

    def add_list_item(self, text, history):
        data = self.root.ids.recycleView.data_model.data
        icon = "check-circle" if history.height > 0 else "timer-sand"
        data.insert(
            0, {
                "text": text,
                "secondary_text": history.tx_obj.id(),
                "history": history,
                "icon": icon
            })

    def add_utxo_list_item(self, text, utxo):
        data = self.root.ids.utxoRecycleView.data_model.data
        data.insert(
            0, {
                "text": text,
                "secondary_text": utxo.as_dict()["tx_hash_hex"],
                "utxo": utxo
            })
Beispiel #23
0
class main(App):
    theme_cls = ThemeManager()
    title = "24 Game"
    Window.fullscreen = 'auto'

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        return main_widget

    def valid(self):
        global deck
        global List

        if (len(self.root.ids.playername.text) <= 10):
            self.root.ids.errorcode.opacity = 0
            self.root.ids._cardsleft.text = str(len(deck))
            (List, deck, drawncards) = draw4(deck)
            self.root.ids.gbr1.source = str(drawncards[0].FN)
            self.root.ids.gbr2.source = str(drawncards[1].FN)
            self.root.ids.gbr3.source = str(drawncards[2].FN)
            self.root.ids.gbr4.source = str(drawncards[3].FN)

            anim1 = Animation(x=50, y=400, t='linear', duration=1)
            anim2 = Animation(x=400, y=400, t='linear', duration=1)
            anim3 = Animation(x=750, y=400, t='linear', duration=1)
            anim4 = Animation(x=1100, y=400, t='linear', duration=1)
            anim1.start(self.root.ids.gbr1)
            anim2.start(self.root.ids.gbr2)
            anim3.start(self.root.ids.gbr3)
            anim4.start(self.root.ids.gbr4)

            reset1 = Animation(opacity=0)
            reset1.start(self.root.ids.title1)
            reset1.start(self.root.ids.title2)
            reset1.start(self.root.ids.title3)
            reset1.start(self.root.ids.title4)
            reset1.start(self.root.ids.title5)
            reset1.start(self.root.ids.title6)
            reset1.start(self.root.ids.title7)

            self.root.current = 'Screen2'
        else:
            self.root.ids.errorcode.opacity = 1

    def next(self):
        global List

        totalscore = 0
        (List, totalscore) = Listprocessf(List, totalscore)
        (List[0].E, totalscore) = kurung(List[0].E, totalscore)
        totalscore -= abs(24 - List[0].N)

        reset2 = Animation(x=-500, y=400, t='linear', duration=2)
        reset2.start(self.root.ids.gbr1)
        reset2.start(self.root.ids.gbr2)
        reset2.start(self.root.ids.gbr3)
        reset2.start(self.root.ids.gbr4)

        self.root.ids._hasil.text = str(List[0].E)
        self.root.ids._poin.text = str(totalscore)
        self.root.ids._cardsleft.text = str(len(deck))
        self.root.ids.totalpoin.text = str(
            int(self.root.ids.totalpoin.text) + int(self.root.ids._poin.text))

        animat = Animation(opacity=1, duration=1)
        animat.start(self.root.ids.label3)
        animat.start(self.root.ids.hasil)
        animat.start(self.root.ids.label4)
        animat.start(self.root.ids.poin)
        animat.start(self.root.ids.label5)
        animat.start(self.root.ids.totalpoin)

        self.root.current = 'Screen3'

    def nextdraw(self):
        global deck
        global List

        if (len(deck) > 0):
            (List, deck, drawncards) = draw4(deck)
            self.root.ids.gbr1.source = str(drawncards[0].FN)
            self.root.ids.gbr2.source = str(drawncards[1].FN)
            self.root.ids.gbr3.source = str(drawncards[2].FN)
            self.root.ids.gbr4.source = str(drawncards[3].FN)

            anim1 = Animation(x=50, y=400, t='linear', duration=1)
            anim2 = Animation(x=400, y=400, t='linear', duration=1)
            anim3 = Animation(x=750, y=400, t='linear', duration=1)
            anim4 = Animation(x=1100, y=400, t='linear', duration=1)
            anim1.start(self.root.ids.gbr1)
            anim2.start(self.root.ids.gbr2)
            anim3.start(self.root.ids.gbr3)
            anim4.start(self.root.ids.gbr4)

            reset3 = Animation(opacity=0)
            reset3.start(self.root.ids.label3)
            reset3.start(self.root.ids.hasil)
            reset3.start(self.root.ids.label4)
            reset3.start(self.root.ids.poin)
            reset3.start(self.root.ids.label5)
            reset3.start(self.root.ids.totalpoin)

            self.root.current = 'Screen2'
        else:
            content = MDLabel(font_style='Body1',
                              theme_text_color='Secondary',
                              text="There's no card left. The game is over!\n"
                              "Please start a new game or exit the game.",
                              size_hint_y=None,
                              valign='top')
            content.bind(texture_size=content.setter('size'))
            self.dialog = MDDialog(title="GAME OVER",
                                   content=content,
                                   size_hint=(.8, None),
                                   height=dp(200),
                                   auto_dismiss=False)

            self.dialog.add_action_button(
                "Dismiss", action=lambda *x: self.dialog.dismiss())
            self.dialog.open()

    def newgame(self):
        global deck

        deck = initiatedeck()

        reset4 = Animation(opacity=0)
        reset4.start(self.root.ids.label4)
        reset4.start(self.root.ids.hasil)
        reset4.start(self.root.ids.label4)
        reset4.start(self.root.ids.poin)
        reset4.start(self.root.ids.label5)
        reset4.start(self.root.ids.totalpoin)

        anima1 = Animation(opacity=1, duration=4)
        anima2 = Animation(opacity=1, duration=4.5)
        anima3 = Animation(opacity=1, duration=5)
        anima4 = Animation(opacity=1, duration=5.5)
        anima5 = Animation(opacity=1, duration=6)
        anima6 = Animation(opacity=1, duration=6.5)
        anima7 = Animation(opacity=1, duration=7)
        anima1.start(self.root.ids.title1)
        anima2.start(self.root.ids.title2)
        anima3.start(self.root.ids.title3)
        anima4.start(self.root.ids.title4)
        anima5.start(self.root.ids.title5)
        anima6.start(self.root.ids.title6)
        anima7.start(self.root.ids.title7)
Beispiel #24
0
    def salvar_transacao(self):  # todo

        # List of errors
        erros = []

        # Getting data of fields
        nome = self.ids.nome.text
        descricao = self.ids.descricao.text
        lancamento = self.ids.lancamento.text
        vencimento = self.ids.vencimento.text
        valor = Decimal(self.ids.valor.text).quantize(Decimal('1.00'),
                                                      rounding=ROUND_DOWN)
        parcelado = self.ids.parcelamento.active
        num_parcelas = int(self.ids.nparcelas.text)
        recorrente = self.ids.recorrente.active
        frequencia = self.ids.frequencia.text
        freq_qtd = self.ids.freq_qtd.text
        tipo_transacao = TIPO_TRANSACAO.RECEITA if self.ids.switch.active else TIPO_TRANSACAO.DESPESA
        tipo_pagamento = TIPO_PAGAMENTO.A_PRAZO if parcelado else TIPO_PAGAMENTO.A_VISTA
        contato = self.contato

        # Validating fields
        if nome in ['', ' ', None]:
            erros.append("O Campo 'nome' é obrigatório!")
        if lancamento in ['', ' ', None]:
            erros.append("O Campo 'data' é obrigatório!")
        else:
            try:
                lancamento = date(
                    *[int(f) for f in self.ids.lancamento.text.split('-')])
            except:
                erros.append(
                    "formato de data inválido para 'data'. \nClique no icone ao lado >>"
                )

        if vencimento in ['', ' ', None]:
            erros.append("O Campo 'validade' é obrigatório!")
        else:
            try:
                vencimento = date(
                    *[int(f) for f in self.ids.vencimento.text.split('-')])
            except:
                erros.append(
                    "Formato de data inválido para 'validade'.\nClique no icone ao lado >>"
                )

        try:
            diferenca = vencimento - lancamento
            if diferenca.days < 0:
                erros.append("A 'validade' não pode ser menor que a 'data'")
        except:
            pass

        if valor < 0:
            erros.append("O Campo 'valor' não pode ter valor negativo!")

        if recorrente and parcelado:
            erros.append(
                "A transação não pode ser parcelada e recorrente ao mesmo tempo.\n"
                "Marque apenas uma das opções.")

        if parcelado:
            if num_parcelas < 1:
                erros.append("O Campo 'parcela' não pode ser menor que 1!")
        else:
            num_parcelas = 1

        if not recorrente:
            frequencia = None
            freq_qtd = None
        else:
            if freq_qtd in ('', None) or int(freq_qtd) < 2:
                erros.append("O Campo 'nome' é obrigatório!\n"
                             "E não pode ser inferior a 2.")
        try:
            contato = ContatoModel[self.contato.id]
        except:
            pass

        # Showing dialog with errors found
        if erros:
            dialog = MDDialog(title='Errors', size_hint=(.9, .8))
            box = StackLayout(size_hint_y=None)
            for e in erros:
                box.add_widget(
                    MDLabel(text=e,
                            size_hint_y=None,
                            height='48dp',
                            font_size='18dp',
                            theme_text_color='Error'))

            dialog.content = box
            dialog.add_action_button('Close',
                                     action=lambda *x: dialog.dismiss())
            dialog.open()

        else:
            transacao_id = None

            parcel_value = (valor / num_parcelas).quantize(Decimal('1.00'),
                                                           rounding=ROUND_DOWN)
            excedent = (valor - (parcel_value * num_parcelas)).quantize(
                Decimal('1.00'), rounding=ROUND_DOWN)

            transacao_id = TransacaoModel.insert(
                nome=nome,
                descricao=descricao,
                valor=valor,
                lancamento=lancamento,
                tipo_transacao=tipo_transacao.name,
                parcelado=parcelado,
                tipo_pagamento=tipo_pagamento.name,
                recorrente=recorrente,
                frequencia=frequencia)
            db.commit()

            # Creating Parcels of the Ticket
            if not parcelado and not recorrente:
                ParcelaModel.insert(nome=nome,
                                    valor=valor,
                                    vencimento=vencimento,
                                    pago=False,
                                    transacao_id=transacao_id)
                db.commit()
            elif parcelado:
                for p in range(num_parcelas):
                    if p == num_parcelas - 1: parcel_value += excedent
                    nExpiration = vencimento + relativedelta(months=p)
                    ParcelaModel.insert(nome="{nome} {parcela}/{total}".format(
                        nome=nome, parcela=p + 1, total=num_parcelas),
                                        valor=parcel_value,
                                        vencimento=nExpiration,
                                        pago=False,
                                        transacao_id=transacao_id)
                    db.commit()
            elif recorrente:
                for req in range(int(freq_qtd)):
                    periodo = self.calcula_periodo(frequencia, req)
                    nExpiration = vencimento + periodo
                    ParcelaModel.insert(
                        nome="{nome} {mes}/{ano}".format(nome=nome,
                                                         mes=nExpiration.month,
                                                         ano=nExpiration.year),
                        valor=valor,
                        vencimento=nExpiration,
                        pago=False,
                        transacao_id=transacao_id)
                    db.commit()
            self.app.root.switch_to(TELAS.DETALHE_TRANSACAO,
                                    transacao_id=transacao_id)
Beispiel #25
0
class ImportSearchTable2(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = ImportDetail()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None

    search_result = data_object.get_import_details()

    _filter_import_id = False
    _filter_product_id = False
    _product_id_search = " AND product_id = {} "
    _filter_quantity = False
    _quantity_search = " AND quantity LIKE {} "
    _filter_unitprice = False
    _unitprice_search = " AND unitprice LIKE {} "

    def __init__(self, **kwargs):
        super(ImportSearchTable2, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()
        try:
            self.k_id = sorted([int(x) for x in self._data])[-1] + 1
            print self.parent
        except:
            print "Error"

    def activate_import_id(self, state):
        if state == 'down':
            self._filter_import_id = True
        else:
            self._filter_import_id = False
            self.search_result = self.data_object.get_import_details()
            self.pagination_next()

    def activate_product_id(self, state):
        if state == 'down':
            self._filter_product_id = True
        else:
            self._filter_product_id = False

    def activate_quantity(self, state):
        if state == 'down':
            self._filter_quantity = True
        else:
            self._filter_quantity = False

    def activate_unitprice(self, state):
        if state == 'down':
            self._filter_unitprice = True
        else:
            self._filter_unitprice = False

    def filter(self, import_import_search_id_text, import_product_search_id,
               import_search_quantity, import_search_unit_price):
        if self._filter_import_id:
            if import_import_search_id_text != '':
                self.sql = "SELECT * FROM import_details WHERE import_id = {} ".format(
                    import_import_search_id_text)
            else:
                self.sql = "SELECT * FROM import_details WHERE import_id LIKE '%%' "
            if self._filter_product_id and import_product_search_id != '':
                self.sql += self._product_id_search.format(
                    import_product_search_id)
            if self._filter_quantity and import_search_quantity != '':
                self.sql += self._quantity_search.format(
                    import_search_quantity)
            if self._filter_unitprice and import_search_unit_price != '':
                self.sql += self._unitprice_search.format(
                    import_search_unit_price)
            s = self.data_object.execute(self.sql)
            name = dict()
            for val in s:
                name[val['import_id']] = val
            self.search_result = name
        else:
            self.search_result = self.data_object.get_import_details()

        self.pagination_next()

    def delete_data(self, id):
        try:
            self.data_object.import_id = id
            self.data_object.delete_import_detail()
            self.pagination_next(self.current)
        except KeyError:
            Snackbar(text=" Key Not Found ").show()
        except _mysql_exceptions.IntegrityError:
            Snackbar(
                text=
                "Cannot delete or update a parent row: a foreign key constraint fails"
            ).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def calc_pages(self, pages, num_pages, num_page):
        pages_dict = dict()
        pages_lens = list()
        num = 0
        while num <= len(self.pages):
            pages_lens.append(num)
            num = num + self.offset
        pages_lens.append(len(self.pages))
        for num in range(0, num_pages):
            pages_dict[num + 1] = pages[pages_lens[num]:pages_lens[num + 1]]
        page_count = len(pages_dict.keys())
        return num_page, page_count, pages_dict[num_page]

    def pagination_next(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == page_count:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        self.pages = sorted(list(self.search_result))
        no_pages = int(math.ceil(len(self.pages) / float(self.offset)))
        try:
            self.current, page_count, self.page = self.calc_pages(
                self.pages, no_pages, self.current)
            self._data = self.page
            self.call_load()
            if self.current == 1:
                deactivate = True
            else:
                deactivate = False
        except:
            deactivate = True
            self.current = 1
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        import_data_object = Import()
        import_data_dict = import_data_object.get_imports()
        product_data_object = Product()
        product_data_dict = product_data_object.get_products()
        # print product_data_dict
        # print self._data
        for key in self._data:

            id = str(self.search_result.get(key)['id'])
            import_id = import_data_dict.get(
                str(self.search_result.get(key)
                    ['import_id']))['receipt_number']
            product_id = product_data_dict.get(
                str(self.search_result.get(key)['product_id']))['brandname']
            # print str(self.data_object.get_import_details().get(key)['product_id']) , "=>" , product_id
            quantity = str(self.search_result.get(key)['quantity'])
            unitprice = str(self.search_result.get(key)['unitprice'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=import_id))
            self.d.add_widget(DataLabel(text=product_id))
            self.d.add_widget(DataLabel(text=quantity))
            self.d.add_widget(DataLabel(text=unitprice))
            self.d.add_widget(option)

            super(ImportSearchTable2, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, import_id, product_id, quantity, unitprice):
        self.data_object.id = id
        self.data_object.import_id = import_id
        self.data_object.product_id = product_id
        self.data_object.quantity = quantity
        self.data_object.status = unitprice
        self.data_object.update_import_detail()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        import_id = str(
            self.data_object.get_import_details().get(id)['import_id'])
        product_id = str(
            self.data_object.get_import_details().get(id)['product_id'])
        quantity = str(
            self.data_object.get_import_details().get(id)['quantity'])
        unitprice = str(
            self.data_object.get_import_details().get(id)['unitprice'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        imp_id = DialogTextInput(import_id)
        prod_id = DialogTextInput(product_id)
        qty = DialogTextInput(quantity)
        uprice = DialogTextInput(unitprice)

        b.add_widget(
            MDLabel(id='destination',
                    text="Import ID",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(imp_id)
        b.add_widget(MDLabel(text="Product ID", size_hint_x=None,
                             width="90px"))
        b.add_widget(prod_id)
        b.add_widget(
            MDLabel(id='date', text="Quantity", size_hint_x=None,
                    width="90px"))
        b.add_widget(qty)
        b.add_widget(
            MDLabel(id='date',
                    text="Unit Price",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(uprice)

        self.dialog = MDDialog(title="Update Import",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, imp_id.text, prod_id.text, qty.text, uprice.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
class first_screen(Screen):
    theme_cls = ThemeManager()
    no = 1
    no1 = 1
    input_dialog = None
    com = 1
    intrest = 0.03
    term = 0
    today_date = time.strftime('%d-%m-%Y')

    def ok(self):
        try:
            self.ok1()
        except Exception:
            self.alert_dialog = MDDialog(
                title="WARNING!",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text="check inputs",
                events_callback=self.remove_pop,
            )
            self.alert_dialog.open()

    def remove_pop(self, *args):
        self.alert_dialog.dismiss()

    def ok1(self):
        #print(self.today_date,self.ids.date.text,self.ids.month.text,self.ids.year.text)
        if ((self.ids.date.text == '') | (self.ids.month.text == '') |
            (self.ids.year.text == '') | (self.ids.input.text == '')):
            return
        tm = intrest1.time1(self.today_date, self.ids.date.text,
                            self.ids.month.text, self.ids.year.text, 1)
        tm1 = intrest1.time1(self.today_date, self.ids.date.text,
                             self.ids.month.text, self.ids.year.text, 0)
        self.tm1 = [int(tm1) + 1, int(tm1), float(tm1)]
        self.ids.col5.text = str(self.tm1[1]) + ' months'
        self.ids.col4.text = str(self.tm1[0]) + ' months'
        dy = self.ids.date.text + '-' + self.ids.month.text + '-' + self.ids.year.text
        print(self.intrest)
        print(self.tm1[self.term])
        print(self.ids.sw.active)
        print(self.ids.input.text)
        #print(tm)
        if (self.ids.sw.active):
            total = intrest1.intrest(int(self.ids.input.text),
                                     self.tm1[self.term], self.intrest)
        else:
            total = intrest1.intrest1(int(self.ids.input.text),
                                      self.tm1[self.term], self.intrest)
        print(total)
        if (self.com != 1):
            self.l2.text = tm
            self.l4.text = str(total)
            self.k = intrest1.value()
            k = threading.Thread(target=network.do_all,
                                 args=(plyer.uniqueid.id, self.today_date, dy,
                                       self.ids.input.text, total,
                                       self.ids.sw.active, self.intrest,
                                       self.tm1[self.term]))
            k.start()
            return
        self.k = intrest1.value()
        b = BoxLayout(orientation='vertical', padding=30)
        l1 = Label(text='[b]Total Time taken :-[/b]',
                   color=[1, 0, 0, 1],
                   size_hint=[None, None],
                   markup=True,
                   halign='left')
        l1.bind(texture_size=l1.setter('size'))
        self.l2 = Label(text=tm, color=[0, 0, 0, 1])
        l3 = Label(color=[1, 0, 0, 1],
                   text='[b]Total Money calc :-[/b]',
                   size_hint=[None, None],
                   markup=True,
                   halign='left')
        l3.bind(texture_size=l3.setter('size'))
        self.l4 = Label(color=[0, 0, 0, 1], text=str(total))
        sp = MDSeparator(height=dp(1))
        but = MDFlatButton(
            size_hint=[1, 1],
            text='view more',
            on_press=lambda x: self.more_info(self.k, self.tm1[self.term]))
        b.add_widget(l1)
        b.add_widget(self.l2)
        b.add_widget(l3)
        b.add_widget(self.l4)
        b.add_widget(sp)
        b.add_widget(but)
        self.ids.result.remove_widget(self.ids.kr1)
        self.ids.result.add_widget(b)
        self.com = 0
        k = threading.Thread(target=network.do_all,
                             args=(plyer.uniqueid.id, self.today_date, dy,
                                   self.ids.input.text, total,
                                   self.ids.sw.active, self.intrest,
                                   self.tm1[self.term]))
        k.start()
        print('pressed ok')

    def change(self, no):
        if (self.no != no):
            self.clear_roll()
            self.cng_roll(no)
            self.no = no
        if (no == 3):
            self.show_example_dialog()

    def col(self, i):
        self.ok()
        if (i == 0):
            return [1, 0, 0, 1]
        else:
            return [0, 0, 0, 0.5]

    def clear_roll(self):
        #for clearing the canvas button and lighting
        if (self.no == 1):
            self.ids.gold.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.gold.canvas.after.add(
                Rectangle(pos=self.ids.gold.pos,
                          size=[self.ids.gold.width,
                                dp(2)]))
            self.ids.col1.color = [1, 1, 1, 0.5]
        elif (self.no == 2):
            self.ids.silver.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.silver.canvas.after.add(
                Rectangle(pos=self.ids.silver.pos,
                          size=[self.ids.silver.width,
                                dp(2)]))
            self.ids.col2.color = [1, 1, 1, 0.5]
        else:
            self.ids.other.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.other.canvas.after.add(
                Rectangle(pos=self.ids.other.pos,
                          size=[self.ids.other.width,
                                dp(2)]))
            self.ids.col3.color = [1, 1, 1, 0.5]

    def cng_roll(self, no):
        #for changing the roll
        if (no == 1):
            self.ids.gold.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.gold.canvas.after.add(
                Rectangle(pos=self.ids.gold.pos,
                          size=[self.ids.gold.width,
                                dp(2)]))
            self.ids.col1.color = [1, 1, 1, 1]
            self.intrest = 0.03
        elif (no == 2):
            self.ids.silver.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.silver.canvas.after.add(
                Rectangle(pos=self.ids.silver.pos,
                          size=[self.ids.silver.width,
                                dp(2)]))
            self.ids.col2.color = [1, 1, 1, 1]
            self.intrest = 0.04
        else:
            self.ids.other.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.other.canvas.after.add(
                Rectangle(pos=self.ids.other.pos,
                          size=[self.ids.other.width,
                                dp(2)]))
            self.ids.col3.color = [1, 1, 1, 1]

    def change1(self, no):
        # for canvas changing
        if (self.no1 != no):
            self.clear_roll1()
            self.cng_roll1(no)
            self.no1 = no

    def clear_roll1(self):
        #for clearing the canvas button and lighting
        if (self.no1 == 1):
            self.ids.term1.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.term1.canvas.after.add(
                Rectangle(pos=self.ids.term1.pos,
                          size=[self.ids.term1.width,
                                dp(2)]))
            self.ids.col4.color = [1, 1, 1, 0.5]
        elif (self.no1 == 2):
            self.ids.term2.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.term2.canvas.after.add(
                Rectangle(pos=self.ids.term2.pos,
                          size=[self.ids.term2.width,
                                dp(2)]))
            self.ids.col5.color = [1, 1, 1, 0.5]
        else:
            self.ids.term3.canvas.after.add(
                Color(rgba=self.theme_cls.primary_dark))
            self.ids.term3.canvas.after.add(
                Rectangle(pos=self.ids.term3.pos,
                          size=[self.ids.term3.width,
                                dp(2)]))
            self.ids.col6.color = [1, 1, 1, 0.5]

    def cng_roll1(self, no):
        #for changing the roll
        if (no == 1):
            self.ids.term1.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.term1.canvas.after.add(
                Rectangle(pos=self.ids.term1.pos,
                          size=[self.ids.term1.width,
                                dp(2)]))
            self.ids.col4.color = [1, 1, 1, 1]
            self.term = 0
        elif (no == 2):
            self.ids.term2.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.term2.canvas.after.add(
                Rectangle(pos=self.ids.term2.pos,
                          size=[self.ids.term2.width,
                                dp(2)]))
            self.ids.col5.color = [1, 1, 1, 1]
            self.term = 1
        else:
            self.ids.term3.canvas.after.add(
                Color(rgba=self.theme_cls.accent_color))
            self.ids.term3.canvas.after.add(
                Rectangle(pos=self.ids.term3.pos,
                          size=[self.ids.term3.width,
                                dp(2)]))
            self.ids.col6.color = [1, 1, 1, 1]
            self.term = 2
        print(self.term)

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.today_date = str(date_obj)
        tm = self.today_date.split('-')
        self.today_date = tm[2] + '-' + tm[1] + '-' + tm[0]
        self.ok()

    def show_date_picker(self):
        try:
            pd = self.previous_date
            MDDatePicker(self.set_previous_date, pd.year, pd.month,
                         pd.day).open()
        except Exception as e:
            MDDatePicker(self.set_previous_date).open()

    def show_example_dialog(self):
        def result(text_button, instance):
            k = (text_button, dir(instance), instance.text_field.text)
            try:
                self.intrest = float(instance.text_field.text) * 0.01
                self.ids.col3.text = "{0:0.2f}".format(self.intrest * 100)
                self.ok()
            except Exception:
                self.alert_dialog = MDDialog(
                    title="WARNING!",
                    size_hint=(0.8, 0.4),
                    text_button_ok="Ok",
                    text="check inputs",
                    events_callback=self.remove_pop,
                )
                self.alert_dialog.open()

        if not self.input_dialog:
            from kivymd.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(
                title="Change Intrest",
                hint_text="enter the intrest rate",
                size_hint=(0.8, 0.25),
                text_button_ok="Ok",
                events_callback=result,
            )
            self.input_dialog.text_field.input_type = 'number'
            self.input_dialog.text_field.text = str(self.intrest * 100)
        self.input_dialog.open()

    def more_info(self, x, t):
        k = GridLayout(rows=len(x) * 2 + 10,
                       size_hint_y=None,
                       spacing=60,
                       padding=30)
        k.bind(minimum_height=k.setter('height'))
        r = ScrollView(do_scroll_x=False)
        j = 0
        x1 = x[-1:][0]
        x.remove(x1)
        k.add_widget(
            Label(text=' [b]More Details[/b]',
                  size_hint=[1, 0.5],
                  markup=True,
                  color=[1, 0, 0, 1]))
        for i in x:
            sp = MDSeparator(height=dp(1))
            k.add_widget(sp)
            b = BoxLayout(padding=-50)
            l1 = Label(text=str(j * 6) + ' months', color=[1, 0, 0, 1])
            l2 = TextInput(text=str(i), size_hint=[1, None], readonly=True)
            b.add_widget(l1)
            b.add_widget(l2)
            k.add_widget(b)
            j += 1
        sp = MDSeparator(height=dp(1))
        k.add_widget(sp)
        b = BoxLayout(padding=-50)
        l1 = Label(text=str(t) + ' months', color=[1, 0, 0, 1])
        l2 = TextInput(text=str(x1), size_hint=[1, None], readonly=True)
        b.add_widget(l1)
        b.add_widget(l2)
        k.add_widget(b)
        x.append(x1)
        r.add_widget(k)
        g = BoxLayout(orientation='vertical')
        g.add_widget(r)
        g.add_widget(Label(text=' ', size_hint=[1, 0.5]))
        self.b = MDBottomSheet()
        self.b.gl_content.add_widget(g)
        Clock.schedule_once(self.resize_content_layout, 0)
        self.b.open()

    def resize_content_layout(self, *largs):
        self.b.gl_content.height = (self.b.height / 3) * 4

    def callback_for_menu_items(self, *args):
        print(args[0])
        self.k1.ids.h.text = args[0]
Beispiel #27
0
class mainapp(BoxLayout):
    def __init__(self, **kwargs):
        BoxLayout.__init__(self, **kwargs)
        self.orientation = "vertical"
        self.numpad = Builder.load_string(calc)
        self.add_widget(self.numpad)

        #Buttons
        self.out = self.numpad.ids['out']
        self.rout = self.numpad.ids['real_time_update']
        self.rout_2 = self.numpad.ids['real_time_update_2']
        self.delbutton = self.numpad.ids['cancel_but']
        self.equalbutton = self.numpad.ids['equal_but']
        self.differnbutton = self.numpad.ids['differentiate']
        self.integrabutton = self.numpad.ids['integrate']
        self.simplifybutton = self.numpad.ids['simplify']
        self.factorisebutton = self.numpad.ids['factorise']
        self.expandbutton = self.numpad.ids['expand']
        self.fractog = self.numpad.ids['fractog']
        self.solvebutton = self.numpad.ids['solve']

        #Binds
        self.delbutton.bind(on_release=self.delholdclr, on_press=self.delbut)
        self.equalbutton.bind(on_release=self.equal_call)
        self.differnbutton.bind(on_release=self.differentiate)
        self.integrabutton.bind(on_release=self.integral)
        self.simplifybutton.bind(on_release=self.simplify)
        self.factorisebutton.bind(on_release=self.factorise)
        self.expandbutton.bind(on_release=self.expand)
        self.out.bind(text=self.rout_update)
        self.rout_2.bind(text=self.rout_update)
        self.fractog.bind(active=self.rout_update)
        self.solvebutton.bind(on_release=self.solver)

        #Clock
        Clock.schedule_interval(self.outputloop, 0)

        # Coloring
        self.numpad.ids['arrow'].md_bg_color = (0.1, 0, 0, 0.1)

        for x in self.numpad.ids['basic_buts'].children:
            x.md_bg_color = (1, 0, 0, 0.2)

        for x in self.numpad.ids['functions_but'].children:
            x.md_bg_color = (0.1, 0, 0, 0.2)

        self.numpad.ids['inv'].md_bg_color = (0, 0.5, 0.5, 0.2)

        for x in self.numpad.ids['inv_tri'].children:
            x.md_bg_color = (0, 0.5, 0.5, 0.2)

        self.numpad.ids['back'].md_bg_color = (0.1, 0, 0, 0.2)

        # init() of matrix
        self.mat_init()

        # init() of limit
        self.limit_init()

        # extras
        self.pretex = '..'
        self.expr = 0

    def outputloop(self, dt):
        tex = self.out.text
        if tex == '':
            tex = '0'

        elif len(tex) > 1 and tex[:1] == '0':
            tex = tex[1:]
        self.out.text = tex

    def delbut(self, ins):
        tex = self.out.text
        tex = tex[:-1]
        self.out.text = tex
        Clock.schedule_once(self.clearall, 1)

    def clearall(self, ins):
        self.out.text = '0'

    def delholdclr(self, ins):
        Clock.unschedule(self.clearall)

    def equal_call(self, ins, out=None):
        if out == None:
            self.ou = self.out
        else:
            self.ou = out
        special_expr = False
        final_expr_str = self.out.text.replace('^', '**')
        try:
            expr = sympy.N(
                parse_expr(final_expr_str, transformations=transformations))
            try:
                expr = float(expr)
            except:
                pass

            if expr != expr.doit():
                self.out.text = str(expr.doit())
                spx = str(expr) + " = " + str(expr.doit())
                special_expr = 'Eq(' + str(expr) + ', ' + str(
                    expr.doit()) + ')'
                if sympy.sympify(special_expr) == True:
                    special_expr = False
                print("special expr", special_expr)
                self.out.text = str(expr.doit())
            self.expr = expr
        except Exception as e:
            print(e)
            expr = final_expr_str
        try:
            tex = str(eval(str(expr)))
        except:
            tex = expr
        if out == None:
            self.ou.text = str(tex).replace('**', '^')
        else:
            self.ou.text = str(tex)
            if special_expr:
                self.ou.text = special_expr
        self.out.text = self.out.text.replace('**', '^')

    def equalcall_old(self, ins, out=None):
        try:
            expr = N(
                parse_expr(self.out.text,
                           transformations=transformations,
                           evaluate=True))
            tex = str(expr)
            self.out.text = tex
        except:
            pass

    def rout_update(self, *args):
        exprg = self.expgen()
        if exprg != False:
            newtext = sympy.pretty(self.expgen())
            self.rout.text = newtext

    def differentiate(self, ins):
        try:
            expr = self.expgen()
            diff_expr = diff(expr, x)
            self.finaloutstr(diff_expr)

        except Exception as e:
            print(e)

    def integral(self, ins):
        try:
            expr = self.expgen()
            int_expr = integrate(expr, x)
            self.finaloutstr(int_expr)

        except Exception as e:
            print(e)

    def simplify(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = simplify(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def factorise(self, ins):
        try:
            expr = self.expgen()
            simplified_expr = sympy.factor(expr)
            self.finaloutstr(simplified_expr)

        except Exception as e:
            print(e)

    def expand(self, ins):
        try:
            expr = self.expgen()
            expand_expr = sympy.expand(expr)
            self.finaloutstr(expand_expr)

        except Exception as e:
            print(e)
            print(self.rout.text)

    def expgen(self):
        try:
            final_expr_str = self.out.text.replace('^', '**')
            if not self.fractog.active:
                expr = N(
                    parse_expr(final_expr_str,
                               transformations=transformations))
            else:
                expr = (parse_expr(final_expr_str,
                                   transformations=transformations))

            print("Generated Expr ", expr)
            return expr

        except Exception as e:
            print("Expression generated Error! \n", e)
            return False

    def finaloutstr(self, expr):
        tmps = str(expr)
        tmps.replace('**', '^').replace('(pi/180)', u'\u00b0')
        print(tmps)
        self.out.text = tmps
        self.equalcall(None)

    def solver(self, *args):
        try:
            expr = self.expgen()
            Logger.info(expr)
            eq = sympy.Eq(expr, 0, evaluate=False)
            finalcc = '\n\nExpression : \n' + sympy.pretty(eq)

            for symbol in list(expr.atoms(sympy.Symbol)):
                Logger.info(symbol)
                os.environ['dbg'] = '1'

                solved = sympy.solveset(eq, symbol)
                os.environ['dbg'] = '0'

                Logger.info(solved)
                solved_pretty = sympy.pretty(solved,
                                             use_unicode=True,
                                             num_columns=4000)
                top_content = '\n \n Solution for ' + str(symbol) + ':\n\n'
                finalc = (top_content + solved_pretty)
                try:
                    finalc.encode('utf-8')
                except:
                    pass
                finally:
                    print(finalc)
                print('creating button')
                finalcc += finalc
            self.make_dialog('Solve', finalcc)
            print('button created')

        except Exception as e:
            print(e)

    def make_dialog(self, title, finalc):
        content = Button(text=finalc,
                         padding=(0, 0),
                         font_name='Hack-Regular',
                         halign='left',
                         size_hint=(None, None),
                         color=[0, 0, 0, 1],
                         background_normal='./transparent.png',
                         background_down='./transparent.png')
        content.bind(size=lambda x, y: Logger.info(y))
        content.bind(
            texture_size=lambda obj, t: content.setter('size')(obj, t))
        bx = ScrollView(size_hint=(1, None),
                        size=(Window.width * 0.7, Window.height * 0.6))
        bx.add_widget(content)
        bx.bind(size=lambda obj, x: Logger.info(x))
        self.dialog = MDDialog(title=title, content=bx, size_hint=(0.8, 0.8))
        self.dialog.add_action_button('Dismiss',
                                      lambda *args: self.dialog.dismiss())
        self.dialog.open()

    ## MATRIX

    def mat_init(self):
        self.rows = self.numpad.ids['row']
        self.rows_2 = self.numpad.ids['row2']
        self.columns = self.numpad.ids['col']
        self.columns_2 = self.numpad.ids['col2']
        self.matrixgrid = self.numpad.ids['matrix_grid']
        self.matrixgrid2 = self.numpad.ids['matrix_grid_2']
        self.rrefbut = self.numpad.ids['rref']
        self.matrixmenu = self.numpad.ids['Matrix_menu']

        self.rrefbut.bind(on_release=self.rref_call)
        self.rows.bind(on_release=self.matup1)
        self.columns.bind(on_release=self.matup1)
        self.rows_2.bind(on_release=self.matup2)
        self.columns_2.bind(on_release=self.matup2)
        self.matupdate(1)
        self.matupdate(no=2)

        self.matrixgrid.bind(minimum_height=self.matrixgrid.setter('height'))
        self.matrixgrid2.bind(minimum_height=self.matrixgrid2.setter('height'))

        self.matrix1 = self.matrix2 = None

    def matup1(self, *args):
        self.matupdate(1)

    def matup2(self, *args):
        self.matupdate(no=2)

    def matupdate(self, no, *args):
        try:
            if no == 1:
                self.matrixgrid.cols = int(self.columns.text)
                self.matgridform(rows=int(self.rows.text),
                                 cols=int(self.columns.text),
                                 matgrid=self.matrixgrid)

            elif no == 2:
                self.matrixgrid2.cols = int(self.columns_2.text)
                self.matgridform(rows=int(self.rows_2.text),
                                 cols=int(self.columns_2.text),
                                 matgrid=self.matrixgrid2)

        except:
            pass

    def matgridform(self, rows, cols, matgrid):
        try:
            if len(matgrid.children) > rows * cols:
                for x in range((len(matgrid.children)) - rows * cols):
                    matgrid.remove_widget(matgrid.children[-1])

            else:
                for x in range(rows * cols - (len(matgrid.children))):
                    matgrid.add_widget(self.matblock())

        except Exception as e:
            print(e)

    def matblock(self):
        b = MDTextField(text='0', hint_text='0', padding_x=20)
        b.bind(text=self.checktext)

        return b

    def checktext(self, obj, text):
        if text == '':
            obj.text = '0'

        elif len(text) > 1 and text[:1] == '0':
            obj.text = text[1:]

    def make_matrix(self, cols, matgrid, mat):
        try:
            mat_list = []
            tmpl = []
            for x in matgrid.children:
                print(x.text)
                tmpl.append(
                    parse_expr(str(x.text), transformations=transformations))
            tmpl = tmpl[::-1]
            Logger.info(tmpl)
            try:
                mat_list = [
                    tmpl[i:i + cols] for i in xrange(0, len(tmpl), cols)
                ]
                print(mat_list)

            except:
                mat_list = [
                    tmpl[i:i + cols] for i in range(0, len(tmpl), cols)
                ]
                print(mat_list)

            mat = sympy.Matrix(mat_list)
            Logger.info(mat_list)
            print(mat_list)
            return mat

        except Exception as e:
            Logger.error(e)
            print(e)
            return False

    def rref_call(self, matno=1, *args):
        if matno == 2:
            matrix = self.matrix2
            matgrid = self.matrixgrid2
            cols = int(self.columns_2.text)

        else:
            matrix = self.matrix1
            matgrid = self.matrixgrid
            cols = int(self.columns.text)

        for x in matgrid.children:
            print(x.text)

        matrix = self.make_matrix(cols=cols, matgrid=matgrid, mat=matrix)
        print(matrix)
        if matrix == None or matrix == False:
            return

        rref = matrix.rref()[0]
        count = 0
        for x in matgrid.children:
            count -= 1
            x.text = str(rref[count])

        self.make_dialog(title='RREF',
                         finalc=sympy.pretty(sympy.Eq(matrix,
                                                      rref,
                                                      evaluate=False),
                                             use_unicode=True))

    ## LIMIT

    def limit_init(self):
        self.func = self.numpad.ids['f(x)']
        self.x0 = self.numpad.ids['X0']
        self.Sign = self.numpad.ids['sign']
        self.doit = self.numpad.ids['do_it']
Beispiel #28
0
class MainApp(App):
    theme_cls = ThemeManager()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.minimum_height = None
        self.ids = None
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_students = self.c.execute('SELECT * FROM STUDENTS')
        self.all_subjects = self.c.execute('SELECT * FROM SUBJECTS')
        self.get_courses = self.c.execute('SELECT * FROM COURSES')

    def database_creations(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        # creating student

        self.c.execute('''CREATE TABLE STUDENTS(
                        STUDENT_ID INT NOT NULL, 
                        STUDENT_NAME VARCHAR (250),
                        STUDENT_COURSE VARCHAR (250), 
                        STUDENT_CLASS_NAME VARCHAR (250),
                        PRIMARY KEY (STUDENT_ID));''')
        self.conn.commit()
        content = MDLabel(font_style='Body1',
                          theme_text_color='Secondary',
                          text="T"
                          "PERFECT TABLE CREATED!",
                          size_hint_y=None,
                          valign='top')
        content.bind(texture_size=content.setter('size'))
        self.dialog = MDDialog(title="SUCCESSFUL",
                               content=content,
                               size_hint=(.8, None),
                               height=dp(200),
                               auto_dismiss=False)
        self.dialog.add_action_button("Dismiss",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        print("committed")

    def get_student(self, value):

        sv = ScrollView()
        ml = MDList()
        sv.add_widget(ml)
        get_student = self.c.execute(
            'SELECT * FROM STUDENTS WHERE STUDENT_CLASS_NAME = ?', (value, ))
        for row in get_student:
            ml.add_widget(OneLineListItem(text=str(row[1])))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        r = GridLayout(cols=1, rows=1)
        r.add_widget(sv)
        p = Popup(title='STUDENTS',
                  size_hint=(.7, 0.7),
                  background_color=(0, 0, .9, .5),
                  auto_dismiss=True)
        p.add_widget(r)
        p.open()

    def list_course(self):
        box = BoxLayout()
        sv = ScrollView()
        ml = MDList()
        self.get_courses = self.c.execute('SELECT * FROM COURSES')

        for row in sorted(self.get_courses):
            ml.add_widget(OneLineListItem(text=str(row[1])))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.courses.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.courses.name)

    def subjects(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_subjects = self.c.execute('SELECT * FROM STUDENTS')
        sv = ScrollView()
        ml = MDList()
        for row in sorted(self.all_subjects):
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text="id: " + str(row[0]) + '\n'
                                  'under : ' + row[2]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.subjects.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.subjects.name)

    def teachers(self):
        sv = ScrollView()
        ml = MDList()
        rows = self.c.execute('SELECT * FROM TEACHERS')
        for row in sorted(rows):
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text="id: " + str(row[0]) + '\n'
                                  'under : ' + row[2]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        self.root.ids.teachers.add_widget(sv)
        self.root.ids.screen_manager.current = str(self.root.ids.teachers.name)

    def all_student(self):
        self.conn = sqlite3.connect('SCHOOL.db')
        self.c = self.conn.cursor()
        self.all_students = self.c.execute('SELECT * FROM STUDENTS')

        gris = GridLayout(
            rows=2,
            # row_default_height=(self.width - self.cols * self.spacing[0]) / self.cols,
            # row_force_default=True,
            # size_hint_y=None,
            # height=self.minimum_height,
            padding=(dp(1), dp(1)),
            spacing=dp(1))
        sv = ScrollView()
        ml = MDList()
        for row in self.all_students:
            ml.add_widget(
                ThreeLineListItem(text=str(row[1]),
                                  secondary_text=row[2] + '\n' + row[3]))
        sv.do_scroll_y = True
        sv.do_scroll_x = False
        sv.add_widget(ml)
        gris.add_widget(
            MDTextField(hint_text="Helper text on focus",
                        helper_text="This will disappear when you click off",
                        helper_text_mode="on_focus"))
        gris.add_widget(sv)
        self.root.ids.students.add_widget(gris)
        self.root.ids.screen_manager.current = str(self.root.ids.students.name)
Beispiel #29
0
class ExportTable1(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    export_object = Export()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 4
    _data = None
    data_in_page = None

    def __init__(self, **kwargs):
        super(ExportTable1, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def delete_data(self, id):
        try:
            self.export_object.id = id
            self.export_object.delete_export()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"
        except _mysql_exceptions.IntegrityError:
            Snackbar(text=str("You Cannot Delete This Record")).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.export_object.count_export()) / float(self.offset)))
        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = False
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.export_object.get_exports_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.data_in_page.get(key)['id'])
            date = str(self.data_in_page.get(key)['date'])
            status = self.data_in_page.get(key)['status']
            destination = self.data_in_page.get(key)['destination']

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=destination))
            self.d.add_widget(DataLabel(text=date))
            self.d.add_widget(DataLabel(text=status))
            self.d.add_widget(option)

            super(ExportTable1, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, destination, date, status):
        self.export_object.id = id
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        self.export_object.update_export()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        dest = self.data_in_page.get(id)['destination']
        dat = str(self.data_in_page.get(id)['date'])
        stat = self.data_in_page.get(id)['status']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        destination = DialogTextInput(dest)
        date = DialogTextInput(dat)
        status = DialogTextInput(stat)

        b.add_widget(
            MDLabel(id='destination',
                    text="Destination",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(destination)
        b.add_widget(MDLabel(text="Date", size_hint_x=None, width="90px"))
        b.add_widget(date)
        b.add_widget(
            MDLabel(id='date', text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(id, destination.text, date.
                                                    text, status.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def add_data(self, destination, date, status):
        self.export_object.destination = destination
        self.export_object.date = date
        self.export_object.status = status
        if destination != '' and date != '' and status != '':
            self.export_object.insert_export()
        else:
            Snackbar(text=" You Need To Fill All Fields ").show()
        self.call_load()
Beispiel #30
0
class SupplierTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Supplier()
    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 0
    offset = 11
    _data = None
    data_in_page = None

    def __init__(self, **kwargs):
        super(SupplierTable, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_supplier()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"
        except e:
            Snackbar(text=str(e)).show()

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.data_object.count_supplier()) / float(self.offset)))
        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_suppliers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = False
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_suppliers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        for key in self._data:
            id = str(self.data_in_page.get(key)['id'])
            name = str(self.data_in_page.get(key)['name'])
            address = str(self.data_in_page.get(key)['address'])
            contact = str(self.data_in_page.get(key)['contact'])

            if self.count % 2 == 1:
                self.d = DataWidget2(self.count,
                                     size_hint_y=None,
                                     height='40px')
            else:
                self.d = DataWidget(self.count,
                                    size_hint_y=None,
                                    height='40px')

            b = EditButton(self, id, text="edit")
            de = DeleteButton(self, self.d, id, text="delete")
            option = BoxLayout()

            option.add_widget(b)
            option.add_widget(de)

            self.d.add_widget(DataLabel(text=str(self.count)))
            self.d.add_widget(DataLabel(text=name))
            self.d.add_widget(DataLabel(text=address))
            self.d.add_widget(DataLabel(text=contact))
            self.d.add_widget(option)

            super(SupplierTable, self).add_widget(self.d)
            self.count += 1

    def save_edited_data(self, id, name, address, contact):
        self.data_object.id = id
        self.data_object.name = name
        self.data_object.address = address
        self.data_object.contact = contact
        self.data_object.update_supplier()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        name = self.data_in_page.get(id)['name']
        address = str(self.data_in_page.get(id)['address'])
        contact = self.data_in_page.get(id)['contact']
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        name_wid = DialogTextInput(name)
        address_wid = DialogTextInput(address)
        contact_wid = DialogTextInput(contact)

        b.add_widget(
            MDLabel(id='Name',
                    text="Destination",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(name_wid)
        b.add_widget(MDLabel(text="Address", size_hint_x=None, width="90px"))
        b.add_widget(address_wid)
        b.add_widget(
            MDLabel(id='Contact',
                    text="Status",
                    size_hint_x=None,
                    width="90px"))
        b.add_widget(contact_wid)

        self.dialog = MDDialog(title="This is a test dialog",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, name_wid.text, address_wid.text, contact_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()

    def add_data(self, name, address, contact):
        self.data_object.name = name
        self.data_object.address = address
        self.data_object.contact = contact
        if name != '' and address != '' and contact != '':
            self.data_object.insert_supplier()
        else:
            Snackbar(text=" You Need To Fill All Fields ").show()
        self.pagination_next()
        self.call_load()
class VouchersTable(GridLayout):
    count = NumericProperty(0)
    d = ObjectProperty(None)
    data_object = Voucher()

    # pagination
    pages = list()
    page = list()
    page_no = 0
    current = 1
    offset = 5
    _data = None
    data_in_page = None
    total = ObjectProperty(None)
    current_voucher = NumericProperty(0)
    voucher_details = ObjectProperty(None)

    def __init__(self, **kwargs):
        self.bind(minimum_height=self.setter('height'))
        super(VouchersTable, self).__init__(**kwargs)
        self.pagination_next()
        self.call_load()

    def reset_total(self):
        self.total.text = "[color='#000000'][b][size=40]0.0SDG[/size][/b][/color]"

    def delete_data(self, id):
        try:
            self.data_object.id = id
            self.data_object.delete_voucher()
            self.pagination_next(self.current)
        except KeyError:
            print "Key Not Found"

    def call_load(self):
        Clock.schedule_once(self.load_data)

    def pagination_next(self, page=1):
        self.current = int(page)
        no_pages = int(
            math.ceil(
                float(self.data_object.count_voucher()) / float(self.offset)))

        if self.current <= no_pages:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_vouchers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
        if self.current >= no_pages:
            deactivate = True
            self.current = no_pages
        else:
            deactivate = False
        return deactivate, str(self.current)

    def pagination_prev(self, page=1):
        self.current = int(page)
        if self.current > 0:
            offset = (self.current - 1) * self.offset
            self.data_in_page = self.data_object.get_vouchers_page(
                offset, self.offset)
            self.pages = list(self.data_in_page)
            self._data = self.pages
            self.call_load()
        else:
            deactivate = True
            self.current = 1
        if self.current == 1:
            deactivate = True
        else:
            deactivate = False
        return deactivate, str(self.current)

    def load_data(self, dt):
        self.clear_widgets()
        self.count = self.current * self.offset - self.offset + 1
        # categories_object = Category()
        # self.category_dict = categories_object.get_categories()
        self._data = []
        if self.data_in_page != None:
            self._data = sorted(list(self.data_in_page), reverse=True)
        # print self._data
        # print self.data_in_page
        if self._data != []:
            for key in self._data:
                id = str(self.data_in_page.get(key)['id'])
                date = str(self.data_in_page.get(key)['date'])
                submitted_by = str(self.data_in_page.get(key)['submitted_by'])
                status = str(self.data_in_page.get(key)['status'])

                if self.count % 2 == 1:
                    self.d = DataWidget2(self.count,
                                         size_hint_y=None,
                                         height='40px')
                else:
                    self.d = DataWidget(self.count,
                                        size_hint_y=None,
                                        height='40px')

                S = Voucher_selector(id,
                                     self.voucher_details,
                                     group='voucher',
                                     id="voucher_check_" + str(id))
                # de = DeleteButton(self, self.d, id, text="delete")
                # option = BoxLayout()
                # here I will add the checkbox
                # option.add_widget(S)
                # option.add_widget(de)

                self.d.add_widget(DataLabel(text=str(self.count)))
                self.d.add_widget(DataLabel(text=date))
                self.d.add_widget(DataLabel(text=submitted_by))
                self.d.add_widget(DataLabel(text=status))
                self.d.add_widget(S)

                super(VouchersTable, self).add_widget(self.d)
                self.count += 1

    def save_edited_data(self, id, brandname, genericname, quantityperunit,
                         unitprice, category_id, expiry_date, status):
        self.data_object.id = id
        self.data_object.brandname = brandname
        self.data_object.genericname = genericname
        self.data_object.quantityperunit = quantityperunit
        self.data_object.unitprice = unitprice
        self.data_object.category_id = category_id
        self.data_object.expiry_date = expiry_date
        self.data_object.status = status
        self.data_object.update_voucher()
        self.dialog.dismiss()
        self.pagination_next()

    def edit_data(self, id):
        brandname = str(self.data_in_page.get(id)['brandname'])
        genericname = str(self.data_in_page.get(id)['genericname'])
        quantityperunit = str(self.data_in_page.get(id)['quantityperunit'])
        unitprice = str(self.data_in_page.get(id)['unitprice'])
        category_id = str(self.data_in_page.get(id)['category_id'])
        expiry_date = str(self.data_in_page.get(id)['expiry_date'])
        status = str(self.data_in_page.get(id)['status'])
        b = GridLayout(size_hint=(None, None),
                       height='200px',
                       width="400px",
                       cols=2)
        brandname_wid = DialogTextInput(brandname)
        genericname_wid = DialogTextInput(genericname)
        quantityperunit_wid = DialogTextInput(quantityperunit)
        unitprice_wid = DialogTextInput(unitprice)
        category_id_wid = DialogTextInput(category_id)
        expiry_date_wid = DialogTextInput(expiry_date)
        status_wid = DialogTextInput(status)

        b.add_widget(MDLabel(text="Brand Name", size_hint_x=None,
                             width="90px"))
        b.add_widget(brandname_wid)
        b.add_widget(
            MDLabel(text="Generic Name", size_hint_x=None, width="90px"))
        b.add_widget(genericname_wid)
        b.add_widget(
            MDLabel(text="Quantity Per Unit", size_hint_x=None, width="90px"))
        b.add_widget(quantityperunit_wid)
        b.add_widget(MDLabel(text="Unit Price", size_hint_x=None,
                             width="90px"))
        b.add_widget(unitprice_wid)
        b.add_widget(
            MDLabel(text="Category ID", size_hint_x=None, width="90px"))
        b.add_widget(category_id_wid)
        b.add_widget(
            MDLabel(text="Expiry Date", size_hint_x=None, width="90px"))
        b.add_widget(expiry_date_wid)
        b.add_widget(MDLabel(text="Status", size_hint_x=None, width="90px"))
        b.add_widget(status_wid)

        self.dialog = MDDialog(title="Update Vocuher",
                               content=b,
                               size_hint=(None, None),
                               height="500px",
                               width="500px",
                               auto_dismiss=False)
        self.dialog.add_action_button(
            "Save",
            action=lambda *x: self.save_edited_data(
                id, brandname_wid.text, genericname_wid.text,
                quantityperunit_wid.text, unitprice_wid.text, category_id_wid.
                text, expiry_date_wid.text, status_wid.text))
        self.dialog.add_action_button("Cancel",
                                      action=lambda *x: self.dialog.dismiss())
        self.dialog.open()
        self.pagination_next()
        self.call_load()

    def add_new_voucher(self, date, submitted_by, status):
        self.data_object.date = date
        self.data_object.submitted_by = submitted_by
        self.data_object.status = status

        if date != '':
            if submitted_by != '' and status != '':
                self.data_object.insert_voucher()
                current_vouch = self.data_object.execute(
                    "SELECT id FROM vouchers ORDER BY id DESC LIMIT 1"
                )[0]['id']
                self.current_voucher = current_vouch
            else:
                Snackbar(text=" You Need To Fill All Fields ").show()
        else:
            Snackbar(text=" You Need To Add Barcode It's Important ").show()

        self.pagination_next()
        self.call_load()
Beispiel #32
0
class KitchenSink(App):
    theme_cls = ThemeManager()

    menu_items = [
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
        {"viewclass": "MDMenuItem", "text": "Example item"},
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        # self.theme_cls.theme_style = 'Dark'

        main_widget.ids.text_field.bind(on_text_validate=self.set_error_message, on_focus=self.set_error_message)
        return main_widget

    def show_example_snackbar(self, type):
        if type == "simple":
            Snackbar.make("This is a snackbar!")
        elif type == "button":
            Snackbar.make("This is a snackbar", button_text="with a button!", button_callback=lambda *args: 2)
        elif type == "verylong":
            Snackbar.make("This is a very very very very very very very long " "snackbar!", button_text="Hello world")

    def show_example_dialog(self):
        content = MDLabel(
            font_style="Body1",
            theme_text_color="Secondary",
            text="This is a dialog with a title and some text. That's pretty awesome right!",
            valign="top",
        )

        content.bind(size=content.setter("text_size"))
        self.dialog = MDDialog(
            title="This is a test dialog", content=content, size_hint=(0.8, None), height=dp(200), auto_dismiss=False
        )

        self.dialog.add_action_button("Dismiss", action=lambda *x: self.dialog.dismiss())
        self.dialog.open()

    def theme_swap(self):
        self.theme_cls.theme_style = "Dark" if self.theme_cls.theme_style == "Light" else "Light"

    def show_example_bottom_sheet(self):
        bs = MDListBottomSheet()
        bs.add_item("Here's an item with text only", lambda x: x)
        bs.add_item("Here's an item with an icon", lambda x: x, icon="md-cast")
        bs.add_item("Here's another!", lambda x: x, icon="md-nfc")
        bs.open()

    def show_example_grid_bottom_sheet(self):
        bs = MDGridBottomSheet()
        bs.add_item("Facebook", lambda x: x, icon_src="./assets/facebook-box.png")
        bs.add_item("YouTube", lambda x: x, icon_src="./assets/youtube-play.png")
        bs.add_item("Twitter", lambda x: x, icon_src="./assets/twitter.png")
        bs.add_item("Da Cloud", lambda x: x, icon_src="./assets/cloud-upload.png")
        bs.add_item("Camera", lambda x: x, icon_src="./assets/camera.png")
        bs.open()

    def set_error_message(self, *args):
        if len(self.root.ids.text_field.text) == 0:
            self.root.ids.text_field.error = True
            self.root.ids.text_field.error_message = "Some text is required"
        else:
            self.root.ids.text_field.error = False

    def on_pause(self):
        return True

    def on_stop(self):
        pass