コード例 #1
0
    def add(self, title='', path=None):
        # Adds a new bookmark as a dictionary item to the self.bookmarks
        # bookmark -- {'title':'Custom Title', 'path':'path/to/item'}
        if path == None:
            pass
        bookmark = {'title': title, 'path': path}

        # TODO
        # Check if there is an already existing bookmark with the same path

        # Assert that bookmark.path is an existing file or directory
        if not os.path.exists(bookmark['path']):
            dialogs.alert('Invalid Bookmark')
            pass

        # Append this bookmark to self.bookmarks
        self.bookmarks.append(bookmark)

        # Update save file
        self.update_file()

        # Reload the table view
        # self.tableview.reload()

        # Show HUD confirmation
        dialogs.hud_alert('Created bookmark for ' +
                          self.get_path(self.count() - 1))
コード例 #2
0
ファイル: the_bible.py プロジェクト: lmjs0417/The-Bible-App
def search_to_clipboard(sender):
    tbl = table
    all = tbl.data_source.items
    string = ''.join(pairs[x[0]] + str(x) + '\n\n' for x in all)
    clipboard.set(matches.text + '\n\n' + string)
    sound.play_effect('rpg:BookFlip2')
    dialogs.alert('It is coppied')
コード例 #3
0
ファイル: ConnectionWindow.py プロジェクト: glushko311/emma
    def validate_mysql(self):
        if not self.glade.get_widget("tb_name").get_text():
            dialogs.alert("Please enter connection name!")
            return False

        # all is fine
        return True
コード例 #4
0
    def saveas(self):
        try:
            name = dialogs.input_alert('Game title').strip()
        except KeyboardInterrupt:
            return

        if name == '':
            dialogs.alert('The name cannot be empty.',
                          '',
                          'OK',
                          hide_cancel_button=True)
            return

        hash = sha512(name.encode('utf-8')).hexdigest()
        records = GameConfig.get_all_records()
        if hash in records.values():
            dialogs.alert(f'Record \'{name}\' already exists.',
                          '',
                          hide_cancel_button=True)
            return

        with open(f'{DIRNAME}/_index', 'a', encoding='utf-8') as f:
            f.write(f'{hash}={name}\n')

        self.save(f'{DIRNAME}/{hash}')
コード例 #5
0
	def person_save_action(self, sender, update=False):
		"""
		Adds a new person to the listsource and creates a new MS Person object.
		Also saves the Group list to a pickle file.
		"""
		view = sender.superview
		name, data1, data2 = self.get_person_values(view)
		# Check name is unique. This is essential because of the way I have
		# had to implement the deleting of a list item from the object list.
		self.unique_name(name, 'people')
		# check name_textfield contains a value
		if name:
			# Create a new Person object and add it to the people list
			# of the selected group
			new_person = simple_module.Person(name, data1, data2)
			# Check to see if this is a new person or an updated person
			if update is True:
				self.selected_group_obj(self.selected_group_row).replace_person(
					self.selected_accessory_row, new_person)
			else:
				# Add item to the listsource
				self.people_listsource.items.append({
					'title': name,
					'accessory_type': 'detail_button'})
				self.selected_group_obj(self.selected_group_row).add_person(new_person)
			self.save_file('ios_persistance.pkl', self.groups_list)
			view.close()
		else:
			# If name field has been left blank open dialog box.
			dialogs.alert('Please enter a unique name')
コード例 #6
0
ファイル: post.py プロジェクト: zcherries/tumtum
    def post_reblog_original(self) -> None:
        client = self.get_client()
        post = self.get_post_from_post_id()
        tags = post.get('tags')
        reblog_key = self.get_reblog_key(post)
        comment = dialogs.text_dialog(title='Enter comment:', )
        state = dialogs.list_dialog(
            title='Reblog state:',
            items=constants.POST_STATES,
        )

        for blog in constants.BLOGS:
            response = client.reblog(
                blog,
                id=self.post_id,
                reblog_key=reblog_key,
                comment=comment,
                tags=tags,
                state=state,
            )
            if not response.get('id'):
                dialogs.alert(title='Error', message=pformat(response))

        print(
            'Reblogged to all blogs:',
            pformat(constants.BLOGS),
        )
コード例 #7
0
ファイル: objc_browser.py プロジェクト: wilt00/objc_tools
def class_objects(cla='', alloc=True):
        functions = []
        initializers = []
        py_methods = []
        try:
            c = ObjCClass(cla)
        except ValueError:
            dialogs.alert(cla + ' is not a known class')
        try:
            initializers = dir(c)
        except:
            return None
        if alloc:
            num_methods = c_uint(0)
            method_list_ptr = class_copyMethodList(c.ptr, byref(num_methods))
            for i in range(num_methods.value):
                selector = method_getName(method_list_ptr[i])
                sel_name = sel_getName(selector)
                if not isinstance(sel_name, str):
                    sel_name = sel_name.decode('ascii')
                py_method_name = sel_name.replace(':', "_")
                if '.' not in py_method_name:
                    py_methods.append(py_method_name)
            free(method_list_ptr)
        functions = [x for x in py_methods if x not in initializers]
        return [['Initializers', initializers], ['Methods', functions]]
コード例 #8
0
ファイル: post.py プロジェクト: zcherries/tumtum
    def post_reblog(self) -> Dict[str, Any]:
        client = self.get_client()
        post_info = self.get_download_and_post_data()
        blog_captions = post_info.get('blog_captions')
        blogs = [caption['blog'] for caption in blog_captions]

        for caption in blog_captions:
            tags = helpers.split_list(post_info.get('tags'))
            random_state = secrets.choice(constants.POST_STATES)
            blog = caption.get('blog')

            response = client.reblog(
                blog,
                id=post_info.get('post_id'),
                reblog_key=post_info.get('reblog_key'),
                comment=caption.get('caption'),
                tags=tags,
                attach_reblog_tree=post_info.get('keep_tree'),
                state=random_state,
            )
            if not response.get('id'):
                dialogs.alert(title='Error', message=pformat(response))

        print(
            f'Reblogged to {len(blogs)} blog(s):',
            pformat(blogs),
        )
        return post_info
コード例 #9
0
    def validate_mysql(self):
        if not self.glade.get_widget('tb_name').get_text():
            dialogs.alert('Please enter connection name!')
            return False

        #all is fine
        return True
コード例 #10
0
def search_to_file(sender):
    tbl = table
    all = tbl.data_source.items
    string = "".join(pairs[x[0]] + str(x) + "\n\n" for x in all)
    with open("Notes/" + "search: " + search_field.text + web_search_field.text + ".txt", "a") as outfile:
        outfile.write(matches.text + "\n\n" + string)
    dialogs.alert("It is written")
コード例 #11
0
	def group_save_action(self, sender, update=False):
		"""
		Adds a new group to the listsource and creates a new
		simple_module Group object.
		Also saves the Group list to a pickle file.
		"""
		view = sender.superview
		name, data1, data2 = self.get_group_values(view)
		# check name is unique. This is essential because of the way i have
		# had to implement the deleting of a list item from the object list.
		self.unique_name(name, 'group')
		# check name_textfield contains a value
		if name:
			# Create a new Group object
			new_group = simple_module.Group(name, data1, data2)
			# Check to see if this is a new person or an updated group
			if update is True:
				# If it's updated replace existing group with new one.
				self.groups_list[self.selected_accessory_row] = new_group
			else:
				# Add item to the listsource
				self.groups_listsource.items.append({
					'title': name,
					'accessory_type': 'detail_disclosure_button'})
				# create a new Group object and add it to the group object list
				self.groups_list.append(
					simple_module.Group(name, data1, data2)
					)
			self.save_file('ios_persistance.pkl', self.groups_list)
			view.close()
		else:
			dialogs.alert('Please enter a unique name')
コード例 #12
0
def main():

    selection = dialogs.alert('Type', '', 'Encrypt', 'Decrypt')
    if selection == 1:
        i = dialogs.alert('Image', '', 'Take Photo', 'Select from Photos')
        if i == 1:
            im = photos.capture_image()
        else:
            im = photos.pick_image()

        im.thumbnail(
            (430, 430)) if im.size[0] > 430 or im.size[1] > 430 else None

        # im, im_arr = load_image("Test.img")
        im_arr = im.load()
        x_size, y_size = im.size
        basic_encrypt_scramble(im_arr, x_size, y_size)
        two_key_encryption(im_arr, x_size, y_size, 123, 4574574)
        im.show()
        save_image(input("Name (example.png):"), im)

    else:
        i = dialogs.alert('Image', '', 'Load Image', 'Select from Photos')
        if i == 1:
            im = Image.open(input("Name (example.png): "))
        else:
            im = photos.pick_image()
        n, d = (int(num) for num in input("(n, d) = ").split(","))
        im_arr = im.load()
        x_size, y_size = im.size

        two_key_decryption(im_arr, x_size, y_size, 123, 4574574)
        basic_decrypt_unscramble(im_arr, x_size, y_size, n, d)
        im.show()
        save_image(input("Name (example.png): "), im)
コード例 #13
0
    def button_tapped(self, sender):
        self.bbimg.monolize(self.i)
        self.bbimg.transpalent()
        self.bbimg.copy()
        ok = ui.Button(title='OK')

        dialogs.alert('Copied!', '', 'OK', hide_cancel_button=True)
        self.close()
コード例 #14
0
ファイル: ConnectionWindow.py プロジェクト: fastflo/emma
 def validate_mysql(self):
     """
     Validate MySQL settings
     :return: bool
     """
     if not self.glade.get_widget('tb_name').get_text():
         dialogs.alert('Please enter connection name!')
         return False
     return True
コード例 #15
0
 def validate_mysql(self):
     """
     Validate MySQL settings
     :return: bool
     """
     if not self.glade.get_widget('tb_name').get_text():
         dialogs.alert('Please enter connection name!')
         return False
     return True
コード例 #16
0
def search_to_file(sender):
    tbl = table
    all = tbl.data_source.items
    string = ''.join(pairs[x[0]] + str(x) + '\n\n' for x in all)
    with open(
            'Notes/' + 'search: ' + search_field.text + web_search_field.text +
            '.txt', 'a') as outfile:
        outfile.write(matches.text + '\n\n' + string)
    dialogs.alert('It is written')
コード例 #17
0
def getGPS():
	if location.is_authorized():
		location.start_updates()
		sleep(1)
		loc=location.get_location()
		dialogs.alert(title='Location updated', message=f'[{loc["longitude"]:.3f},{loc["latitude"]:.3f}]\n or enter manually',button1='Got It', hide_cancel_button=True)
		return [loc['longitude'], loc['latitude']]
	else:
		dialogs.alert(title='Cannot get GPS', message='You have to enable it from setting/privacy or enter manually',button1='Got It', hide_cancel_button=True)
		return HOMEGPS
コード例 #18
0
ファイル: Noti.py プロジェクト: whustedt/Noti
def pause_or_continue(sender):
    '''UI: Pause/Weiter'''
    if PlannedNoti.check_if_pause_data_is_available():
       PlannedNoti.load_paused_data()
       dialogs.alert(title='Zwischenstand geladen\nWeiter gehts!', button1='Okay', hide_cancel_button=True)
       print(get_startchoice_text())
    else:
        PlannedNoti.pause()
        dialogs.alert(title='Zwischenstand gesichert', button1='Okay', hide_cancel_button=True)
    sender.superview.close()
コード例 #19
0
ファイル: objc_browser_nav.py プロジェクト: scj643/objc_tools
 def __init__(self, cla=''):
     self.class_name = cla
     self.obs = []
     try:
         c = ObjCClass(self.class_name)
     except ValueError:
         dialogs.alert(self.class_name + ' is not a known class')
     try:
         self.obs.append(['Class',dir(c.alloc())])
     except:
         pass
コード例 #20
0
def alert(message):
    """Zobrazi varovný dialog s textem a tlacitkem OK.

    Arguments:
        message (str): Varovna zprava.
    """

    dialogs.alert('Chybné údaje',
                  message,
                  button1='OK',
                  hide_cancel_button=True)
コード例 #21
0
 def __init__(self, cla=''):
     self.class_name = cla
     self.obs = []
     try:
         c = ObjCClass(self.class_name)
     except ValueError:
         dialogs.alert(self.class_name + ' is not a known class')
     try:
         self.obs.append(['Class', dir(c.alloc())])
     except:
         pass
    def tableview_did_select(self, tableview, section, row):
        # Called when a row IS selected.
        print('printing...did select')

        handleKeys = self.data.keys()
        handleKeySection = self.data.keys()[section]
        handleAvatarURL = self.data[self.data.keys()[section]][1]
        handleRelevantTweets = self.data[self.data.keys()[section]][0]
        handleRowTweet = self.data[self.data.keys()[section]][0][row]

        dialogs.alert(str(self.data[self.data.keys()[section]][0][row]))
コード例 #23
0
def button_startgps(sender):
    location.start_updates()

    if location.is_authorized():
        location.start_updates()
        dialogs.hud_alert('GPS Started', 'success', 1)
    else:
        dialogs.alert(
            'App not authorized to use GPS. Enable GPS in system preferences.',
            'Plz fix',
            'Oh rats... gonna fix that now',
            hide_cancel_button=True)
コード例 #24
0
	def snippetselectaction(self, snippet):
		selection = dialogs.alert(title='Action', message='Please select your action', button1='Copy to clipboard', button2='Create new file', button3='Show/Edit Snippet contents')
		if selection == 1:
			clipboard.set(snippet[2])
		elif selection == 2:
			title = dialogs.input_alert(title='Filename Entry', message='Please enter a title for your new file, to insert in a folder foldername\filename.py')
			self.make_file(filename=title, contents=snippet[2])
		elif selection == 3:
			dialogs.alert(title='Message',message='Press\nDone - to save content changes \nX - to cancel and not save', button1='Ok', hide_cancel_button=True)
			contents = dialogs.text_dialog(title=snippet[1], text=snippet[2])
			if not contents == None:
				dbmanager().edit_snippet(contents = contents, title=snippet[1], snippetid=snippet[0])
				self.updatesnippetslistview()
コード例 #25
0
ファイル: Image Effects.py プロジェクト: hherde/PythonistaGit
def main():
	effect = dialogs.alert('Select Effect', '', 'Sketch', 'Emboss', 'Color Tiles')
	i = dialogs.alert('Image', '', 'Demo Image', 'Select from Photos')
	if i == 1:
		img = Image.open('test:Lenna')
	else:
		img = photos.pick_image()
	if effect == 1:
		sketch(img).show()
	elif effect == 2:
		emboss(img).show()
	else:
		color_tiles(img).show()
	print('Tip: You can tap and hold the image to save it to your photo library.')
コード例 #26
0
ファイル: Image Effects.py プロジェクト: miwagner1/Pythonista
def main():
	effect = dialogs.alert('Select Effect', '', 'Sketch', 'Emboss', 'Color Tiles')
	i = dialogs.alert('Image', '', 'Demo Image', 'Select from Photos')
	if i == 1:
		img = Image.open('test:Lenna')
	else:
		img = photos.pick_image()
	if effect == 1:
		sketch(img).show()
	elif effect == 2:
		emboss(img).show()
	else:
		color_tiles(img).show()
	print 'Tip: You can tap and hold the image to save it to your photo library.'
コード例 #27
0
def button_pressed_confirm(sender):
    '@type sender:ui.button'
    if len(category.selected_rows) == 0:
        alert("Please select a category")
        return

    # selecte_row: The section and row of the first selected row (as a 2-tuple).
    category_name = category.data_source.items[category.selected_row[1]]

    if agent_name.text == '':
        alert("Please enter an agent name.")
        return

    write_record(sender, transfer_date.date, agent_name.text,
                 price_amount.text, category_name)
    reload_records(records)
コード例 #28
0
def load_thoughts(sender):
    with open("Notes/" + thoughts_file, "r", encoding="utf-8") as infile:
        selection = dialogs.alert("Import {}".format(infile.name), "Are you sure?", "Yes", "No")
        if selection == 1:
            thoughts.text = infile.read()
        elif selection == 2:
            None
コード例 #29
0
def clear_bookmarks(sendr):
    selection = dialogs.alert('Delete Bookmarks', 'Are you sure?', 'Yes', 'No')
    print(selection)
    if selection == 1:
        book_marks.segments = ['']
    elif selection == 2:
        None
コード例 #30
0
def clear_bookmarks(sendr):
    selection = dialogs.alert("Delete Bookmarks", "Are you sure?", "Yes", "No")
    print(selection)
    if selection == 1:
        book_marks.segments = [""]
    elif selection == 2:
        None
コード例 #31
0
def decode():
    i = dialogs.alert('Image', '', 'Load Image', 'Select from Photos')
    if i == 1:
        im = Image.open(input("Name (example.png): "))
    else:
        im = photos.pick_image()

    data = ''
    imgdata = iter(im.getdata())

    while (True):
        pixels = [
            value for value in imgdata.__next__()[:3] +
            imgdata.__next__()[:3] + imgdata.__next__()[:3]
        ]
        # string of binary data
        binstr = ''

        for i in pixels[:8]:
            if (i % 2 == 0):
                binstr += '0'
            else:
                binstr += '1'

        data += chr(int(binstr, 2))
        if (pixels[-1] % 2 != 0):
            return data
コード例 #32
0
    def touch_ended(self, touch):
        # this method is called, when user releases a finger from the screen

        # if start button is pressed, goto game scene
        if self.start_button.frame.contains_point(touch.location):
            config.pressed_home = False
            config.game_over = False
            config.score = 0
            config.blob_hit = 0
            config.squareman_hit = 0
            self.present_modal_scene(LevelsListScene())

        # if help button is pressed, goto game scene
        if self.help_button.frame.contains_point(touch.location):
            self.present_modal_scene(HelpScene())

        # if credits button is pressed, goto game scene
        if self.credits_button.frame.contains_point(touch.location):
            self.present_modal_scene(CreditsScene())

        # if setting button is pressed, goto game scene
        if self.settings_button.frame.contains_point(touch.location):
            self.present_modal_scene(SettingScene())

        # if bonus button is pressed, goto game scene
        if self.bonus_button.frame.contains_point(touch.location):
            locked = dialogs.alert(
                title="Temporarily Locked",
                message=
                "This feature will be locked until the next update where all levels will be added.",
                button1="OK",
                hide_cancel_button=True)
コード例 #33
0
def fill_placeholders(action_in):
  # Find placeholders
  known_placeholders = set()
  placeholders = []
  fields = []
  for placeholder_match in re.finditer(u"«(.+?)»", action_in):
    placeholder = placeholder_match.group(1)
    if placeholder not in known_placeholders:
      known_placeholders.add(placeholder)
      placeholders.append(placeholder)
      fields.append({'type': 'text', 'title': placeholder, 'key': placeholder})

  action_out = action_in

  # Substitute the placeholders
  if len(placeholders) == 0:
    if dialogs.alert(u"No template placeholders were found.", u"""
If your project text has placeholders (that look like «this»), this script will prompt for values you'd like to substitute for them.
""", u"Continue") != 1:
      return

  else:
#    print fields
    values = dialogs.form_dialog(title='', fields=fields, sections=None)
#    print values
    if values:
      for key in values:
        action_out = re.sub(u"«" + key + u"»", values[key], action_out)
    else:
      return None

  return action_out
コード例 #34
0
	def unique_name(self, name, origin):
		"""
		Checks to see if supplied name is already used in origin list.
		If it is an alert dialog box is displayed.
		
		This is required as the method of deleting objects when a list item
		is deleted only works if all the list titles are unique.
		"""
		if origin == 'people':
			object_list = self.groups_list[self.selected_group_row].get_people()
		elif origin == 'group':
			object_list = self.groups_list
			
		for object in object_list:
			if name == object.get_name():
				dialogs.alert('Please use a unique name')
コード例 #35
0
 def touch_ended(self, touch):
     # this method is called, when user releases a finger from the screen
     
     # if start button is pressed, goto game scene
     if self.start_button.frame.contains_point(touch.location):
         config.pressed_home = False
         config.game_over = False
         config.score = 0
         config.blob_hit = 0
         config.squareman_hit = 0
         self.present_modal_scene(LevelsListScene())
         
     # if help button is pressed, goto game scene
     if self.help_button.frame.contains_point(touch.location):
         self.present_modal_scene(HelpScene())
     
     # if credits button is pressed, goto game scene
     if self.credits_button.frame.contains_point(touch.location):
         self.present_modal_scene(CreditsScene())
     
     # if setting button is pressed, goto game scene
     if self.settings_button.frame.contains_point(touch.location):
         self.present_modal_scene(SettingScene())
     
     # if bonus button is pressed, goto game scene
     if self.bonus_button.frame.contains_point(touch.location):
         locked = dialogs.alert(title = "Temporarily Locked",
                                message = "This feature will be locked until the next update where all levels will be added.",
                                button1 = "OK",
                                hide_cancel_button = True)
コード例 #36
0
def main():
    selection = dialogs.alert('Type', '', 'Encode', 'Decode')

    if (selection == 1):
        encode()

    else:
        print("Decoded word:\n\n" + decode())
コード例 #37
0
def load_thoughts(sender):
    with open('Notes/' + thoughts_file, 'r', encoding='utf-8') as infile:
        selection = dialogs.alert('Import {}'.format(infile.name),
                                  'Are you sure?', 'Yes', 'No')
        if selection == 1:
            thoughts.text = infile.read()
        elif selection == 2:
            None
コード例 #38
0
ファイル: Compile Tasks.py プロジェクト: cclauss/Pythonista-4
def main():
    if not appex.is_running_extension():
        with open(db) as tasks:
            for task in tasks:
                task = urllib.quote(task)
                webbrowser.open(due % task)
                time.sleep(10)
                while TESTER.paused:
                    time.sleep(2)
        open(db, 'w').close()  # Erase file
    else:
        shared = appex.get_input()
        if shared: tasks = get_tasks(shared)
        with open(db, 'a') as dbfile:
            dbfile.writelines(tasks)
        #for task in tasks:
        #dialogs.share_text(task)
    dialogs.alert('Done!', '', 'Ok', hide_cancel_button=True)
コード例 #39
0
ファイル: ConnectionWindow.py プロジェクト: glushko311/emma
    def on_test_button_clicked(self, *args):
        if self.cmb_connection_type.get_active() == 0:
            if not self.validate_mysql():
                return
            import _mysql

            data = {"connect_timeout": 6}
            widget_map = {"password": "******"}
            for n in ["host", "user", "password", "port"]:
                if n == "port":
                    port = self.glade.get_widget("tb_port").get_text()
                    if not port:
                        port = "3306"
                    data[widget_map.get(n, n)] = int(port)
                else:
                    data[widget_map.get(n, n)] = self.glade.get_widget("tb_%s" % n).get_text()
            try:
                handle = _mysql.connect(**data)
            except _mysql.DatabaseError as err:
                dialogs.alert(
                    "could not connect to host <b>%s</b> with user <b>%s</b> and password <b>%s</b>:\n<i>%s</i>"
                    % (data["host"], data["user"], data["passwd"], sys.exc_value)
                )
                return
            dialogs.alert(
                "successfully connected to host <b>%s</b> with user <b>%s</b>!" % (data["host"], data["user"])
            )
            handle.close()
        else:
            dialogs.alert("Nothing to test")
コード例 #40
0
ファイル: ConnectionWindow.py プロジェクト: fastflo/emma
 def on_test_button_clicked(self, *_):
     """
     :param _: []
     :return: None
     """
     if self.cmb_connection_type.get_active() == 0:
         if not self.validate_mysql():
             return
         import _mysql
         data = {
             "connect_timeout": 6
         }
         widget_map = {
             "password": "******"
         }
         for n in ["host", "user", "password", "port"]:
             if n == 'port':
                 port = self.glade.get_widget('tb_port').get_text()
                 if not port:
                     port = '3306'
                 data[widget_map.get(n, n)] = int(port)
             else:
                 data[widget_map.get(n, n)] = self.glade.get_widget("tb_%s" % n).get_text()
         try:
             handle = _mysql.connect(**data)
         except _mysql.DatabaseError as err:
             print "_mysql.DatabaseError:", err.message
             dialogs.alert(
                 "could not connect to host <b>%s</b> with user <b>%s</b> "
                 "and password <b>%s</b>:\n<i>%s</i>\nMySQL error message:\n%s" % (
                     data["host"],
                     data["user"],
                     data["passwd"],
                     sys.exc_value,
                     err.message
                 )
             )
             return
         dialogs.alert(
             "successfully connected to host <b>%s</b> with user <b>%s</b>!" % (
                 data["host"],
                 data["user"]
             )
         )
         handle.close()
     else:
         dialogs.alert('Nothing to test')
コード例 #41
0
ファイル: QueryTab.py プロジェクト: glushko311/emma
    def __init__(self, emma):
        """
        @param emma: Emma
        """
        super(QueryTab, self).__init__()
        self.xml = gtk.glade.XML(os.path.join(emma.glade_path, "querytab.glade"), "first_query")
        self.xml.signal_autoconnect(self)

        self.tab_label.set_text("Query")
        self.tab_label_icon.set_from_file(os.path.join(icons_path, "page_code.png"))

        self.emma = emma

        self.save_result = self.xml.get_widget("save_result")
        self.save_result_sql = self.xml.get_widget("save_result_sql")
        self.local_search = self.xml.get_widget("local_search_button")
        self.remove_order = self.xml.get_widget("remove_order")

        self.label = self.xml.get_widget("query_label")

        self.add_record = self.xml.get_widget("add_record_tool")
        self.delete_record = self.xml.get_widget("delete_record_tool")

        self.query_bottom_label = self.xml.get_widget("query_bottom_label")
        self.query_db_label = self.xml.get_widget("query_db_label")

        self.textview = self.xml.get_widget("query_text")

        self.query_text_sw = self.xml.get_widget("query_text_sw")
        self.apply_record = self.xml.get_widget("apply_record_tool")
        self.ui = self.xml.get_widget("first_query")
        self.toolbar = self.xml.get_widget("inner_query_toolbar")
        self.toolbar.set_style(gtk.TOOLBAR_ICONS)

        self.scrolledwindow6 = self.xml.get_widget("scrolledwindow6")
        self.treeview = QueryTabTreeView(emma)
        self.scrolledwindow6.add(self.treeview)
        self.treeview.show()

        self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)

        self.treeview.connect("cursor_changed", self.on_query_view_cursor_changed)
        # todo: move to keymap
        self.treeview.connect("key_press_event", self.on_query_view_key_press_event)
        self.treeview.connect("button_press_event", self.on_query_view_button_press_event)

        self.execution_timer_running = False
        self.execution_timer_interval = 0
        self.editable = False

        self.sort_timer_running = False
        self.sort_timer_execute = 0

        self.query_encoding_menu = None

        self.filled_fields = []

        # replace textview with gtksourcevice
        try:
            org_tv = self.textview
            manager = gtksourceview2.language_manager_get_default()
            language = manager.get_language("sql")

            sb = gtksourceview2.Buffer()
            sb.set_highlight_syntax(True)
            sb.set_language(language)
            sv = self.textview = gtksourceview2.View(sb)

            self.query_text_sw.remove(org_tv)
            self.query_text_sw.add(sv)
            sv.show()

            sv.set_show_line_numbers(True)
            sv.set_show_line_marks(True)
            sv.set_tab_width(4)
            sv.set_auto_indent(True)
            sv.set_insert_spaces_instead_of_tabs(False)
            sv.set_show_right_margin(True)
            sv.set_smart_home_end(True)
            sv.set_right_margin_position(80)

            # sv config
            # for pt, pn, pd in (
            #     (bool, "show_line_numbers", True),
            #     #(bool, "show_line_markers", False),
            #     #(int, "tabs_width", 4),
            #     (bool, "auto_indent", True),
            #     (bool, "insert_spaces_instead_of_tabs", False),
            #     #(bool, "show_margin", True),
            #     #(int, "margin", 80),
            #     (bool, "smart_home_end", True)
            # ):
            #
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sv, "set_%s" % pn)
            #     method(v)
            # sb config
            # for pt, pn, pd in (
            #     (bool, "check_brackets", True),
            #     (bool, "highlight", True),
            #     (int, "max_undo_levels", 15)
            # ):
            #     cn = "sourceview.%s" % pn
            #     try:
            #         v = self.emma.config[cn]
            #         if pt == bool:
            #             v = v == "1" or v.lower() == "true" or v.lower() == "yes"
            #         else:
            #             v = pt(v)
            #     except:
            #         v = pd
            #     method = getattr(sb, "set_%s" % pn)
            #     method(v)
        except:
            dialogs.alert(traceback.format_exc())

        self.current_host = None
        self.current_db = None
        self.model = None
        self.last_source = None
        self.result_info = None
        self.append_iter = None
        self.last_path = None
        self.encoding = None
        if hasattr(self, "query"):
            self.textview.get_buffer().set_text(self.query)
        self.last_auto_name = None

        #
        #   INIT Query tab actions
        #

        self.remember_order_action = QueryTabRememberOrder(self, emma)
        self.remove_order_action = QueryTabRemoveOrder(self, emma)
        self.set_result_font_action = QueryTabSetResultFont(self, emma)
        self.local_search_action = QueryTabLocalSearch(self, emma)
        self.save_result_sql_action = QueryTabSaveResultSql(self, emma)
        self.save_result_csv_action = QueryTabSaveResultCsv(self, emma)
        self.manage_row_action = QueryTabManageRow(self, emma)

        #
        #
        #

        self.emma.key_map.connect("key-release", self.key_release)
        self.init_from_config()
コード例 #42
0
ファイル: mlbplayista.py プロジェクト: HyShai/MLBPlayista

if __name__ == '__main__':
	try:
		if not live_player_is_installed():
			raise Exception('Please install Live Player')
		config = get_config()
		listings = get_listings(config)
		gamelist = sort_listings(config, listings)
		game = select_game(gamelist)
		items = [{
				'teamcode': k,
				'title': TEAMCODES[k][1]} for k in [game['hometeam'], game['awayteam']]]
		if game['national']:
			items.append({'teamcode': '0', 'title': 'National'})
		elif game['plus']:
			items.append({'teamcode': '+', 'title': 'MLB Plus'})
		team = dialogs.list_dialog(
			title='Select team broadcast',
			items=items)
		if not team:
			raise Exception('No broadcast selected')
		teamcode = team['teamcode']
		event_id = game['event_id']
		get_media(config=config, listings=listings, teamcode=teamcode,event_id_param=event_id)
		if config.get('debug'):
			sys.exit()
		serve_json_url()
	except Exception as e:
		dialogs.alert('Error: ' + str(e))
コード例 #43
0
def clear_thoughts(sender):
    selection = dialogs.alert("Clear Thoughts", "Are you sure?", "Yes", "No")
    if selection == 1:
        thoughts.text = ""
    elif selection == 2:
        None
コード例 #44
0
 def textview_did_end_editing(self, textview):
     with open("Notes/" + thoughts_file, "w", encoding="utf-8") as infile:
         infile.write(tv.text)
     dialogs.alert("updated")