def move(self, target): assert C.is_valid_fen_loc(target) try: return self.piece.board.move(self.piece.fen_loc + target) except (ChessError, InvalidMove, LogicError) as e: dialogs.hud_alert('{}: {}'.format(e.__class__.__name__, e)) return False
def capture_screen(sender): v = bible with ui.ImageContext(v.width, v.height) as c: v.draw_snapshot() c.get_image().show() sound.play_effect('8ve:8ve-tap-kissy') dialogs.hud_alert('captured', duration=.1)
def choose_assets(): search = dialogs.input_alert('What is your album called?') albums = photos.get_albums() albums = list([a for a in albums if search in a.title]) albums = list([a for a in albums if get_album_ends(a)[0] is not None]) if len(albums) == 0: dialogs.hud_alert('No album found!', icon='error') return None album_names = [ { 'id': a.local_id, 'index': i, 'title': "{0} ({1})".format(a.title, get_album_dates(a)[0].strftime('%b %d, %Y')), #'image': get_asset_thumb(get_album_ends(a)[0]), 'accessory_type': 'checkmark' } for (i, a) in enumerate(albums) ] album = dialogs.list_dialog('Choose Album', album_names) if album is None: return None album_index = album['index'] assets = photos.pick_asset(albums[album_index], 'Choose Photos', True) return assets
def touch_ended(self, node, touch): if node == self: return for square in self.get_children_with_name('*'): #print(square.name) if isinstance(square, sk_BoardSquare) and touch in square: target_fen_loc = square.name save_fen_loc = node.fen_loc #node.move() is called on a different thread so it returns None!!! move_was_made = node.move( target_fen_loc) # always returns None!! #print('mwm 1', move_was_made) # fails!! move_was_made = node.fen_loc != save_fen_loc #print('mwm 2', move_was_made) if move_was_made: for piece in self.get_children_with_name('*'): # remove the killed sk_ChessPiece if (piece != node and isinstance(piece, sk_ChessPiece) and piece.fen_loc == node.fen_loc): if piece.piece.ptype == 'king': import dialogs dialogs.hud_alert('Game over man!') piece.remove_from_parent() #import dialogs #dialogs.hud_alert(str(type(self.view.superview))) self.view.superview.update_view(node.piece) node.position = square.position sound.play_effect('8ve:8ve-tap-professional') else: node.position = self.save_position sound.play_effect('8ve:8ve-beep-rejected') not_str = '' if move_was_made else 'not ' fmt = '{} at {} was {}moved to square {}\n' print(fmt.format(node.name, save_fen_loc, not_str, square.name))
def touch_ended(self, node, touch): if node == self: return for square in self.get_children_with_name('*'): #print(square.name) if isinstance(square, sk_BoardSquare) and touch in square: target_fen_loc = square.name save_fen_loc = node.fen_loc #node.move() is called on a different thread so it returns None!!! move_was_made = node.move(target_fen_loc) # always returns None!! #print('mwm 1', move_was_made) # fails!! move_was_made = node.fen_loc != save_fen_loc #print('mwm 2', move_was_made) if move_was_made: for piece in self.get_children_with_name('*'): # remove the killed sk_ChessPiece if (piece != node and isinstance(piece, sk_ChessPiece) and piece.fen_loc == node.fen_loc): if piece.piece.ptype == 'king': import dialogs dialogs.hud_alert('Game over man!') piece.remove_from_parent() #import dialogs #dialogs.hud_alert(str(type(self.view.superview))) self.view.superview.update_view(node.piece) node.position = square.position sound.play_effect('8ve:8ve-tap-professional') else: node.position = self.save_position sound.play_effect('8ve:8ve-beep-rejected') not_str = '' if move_was_made else 'not ' fmt = '{} at {} was {}moved to square {}\n' print(fmt.format(node.name, save_fen_loc, not_str, square.name))
def tableview_did_select(self, tableview, section): # Called when a row was selected. selected = self.selected_row[1] item = self.data_source.items[selected] clipboard.set(item) dialogs.hud_alert(item+' Copied') self.reload()
def _address_changed(self, sender): host = sender.text if self.remote_controller.is_reachable(host): self.remote_controller.set_host(host) self._defaults.setObject_forKey_(host, 'host') else: dialogs.hud_alert(f'{host} not reachable', icon='error')
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))
def reload_data(sender, response='Reloaded'): sender.superview['fwcontainer']['activity'].start() sender.enabled = False frameworks.fworks = get_frameworks() sender.superview['fwcontainer']['bundles'].reload() sender.superview['fwcontainer']['activity'].stop() dialogs.hud_alert('Reloaded') sender.enabled = True
def copy_records(): try: with io.open(DATA_FILE, 'r', encoding='utf-8') as f: clipboard.set(f.read()[:-1]) hud_alert("Records copied to clipboard.") except FileNotFoundError: logger.error( f"\"{DATA_FILE}\" does not exist yet, so data did not load.")
def api (url): root_view.network_status.start() try: return r.get(url,timeout=12).text except: hud_alert('网络连接失败','error',1) return False finally: root_view.network_status.stop()
def copyresult(sender): t1 = sender.superview['label1'].text t2 = sender.superview['label2'].text if t2: text = t2 + ' ' + t1 else: text = t1 clipboard.set(text) sound.play_effect('arcade:Coin_3') dialogs.hud_alert('Copied!')
def process(self, image_data): ui_image = ui.Image.from_data(nsdata_to_bytes(image_data)) self.imageview.image = ui_image overlay = ui.View() wim, him = ui_image.size ws, hs = self.imageview.frame.size if (ws / hs) < (wim / him): h = ws * him / wim overlay.frame = (0, (hs - h) / 2, ws, h) else: w = hs * wim / him overlay.frame = ((ws - w) / 2, 0, w, hs) self.imageview.add_subview(overlay) req = VNDetectRectanglesRequest.alloc().init().autorelease() #req.maximumObservations = 100 handler = VNImageRequestHandler.alloc().initWithData_options_( image_data, None).autorelease() success = handler.performRequests_error_([req], None) if success: results = req.results() if len(results) == 0: dialogs.hud_alert('Failed to find rectangle') return bbox = self.to_rect(req.results()[0].boundingBox()) bbox = ui.Rect(0, 0, 1, 1) recognized_matrix = self.recognize(image_data, bbox) ui_bbox = self.to_ui_rect(bbox) #imagecontext big_box = ui.View(frame=( ui_bbox[0] * overlay.width, ui_bbox[1] * overlay.height, ui_bbox[2] * overlay.width, ui_bbox[3] * overlay.height, )) overlay.add_subview(big_box) dim_x = big_box.width / 9 dim_y = big_box.height / 9 for col in range(9): for row in range(9): small_box = ui.Label(text=str(recognized_matrix[row][col]), text_color='red', border_color='red', border_width=1, frame=(col * dim_x, row * dim_y, dim_x, dim_y)) big_box.add_subview(small_box) self.copy_button.enabled = True self.share_button.enabled = True else: self.copy_button.enabled = False self.share_button.enabled = False dialogs.hud_alert('Failed to recognize anything')
def main(): title = dialogs.input_alert('Remind me in 5 minutes', 'Enter a title.', '', 'Remind me') r = reminders.Reminder() r.title = title due = datetime.now() + timedelta(minutes=5) r.due_date = due alarm = reminders.Alarm() alarm.date = due r.alarms = [alarm] r.save() dialogs.hud_alert('Reminder saved')
def restore(self, sender): txt = '\n'.join(self.dump) arr = [] for line in txt.split('\n'): hex_string = line[12:35] for byte in hex_string.split(' '): if byte: arr.append(int(byte, 16)) with open(input_alert('New file name?'), 'wb') as f: f.write(bytes(arr)) hud_alert('Restoration complete!', 'success')
def zip_notes(sender): if dialogs.alert('Create?', 'this will zip all notes', 'Yes', 'No') == 1: time_stamp = datetime.datetime.today().strftime('%m_%d_%Y_%H:%M:%S') zf = zipfile.ZipFile("Notes Backup {}.zip".format(time_stamp), "w") for dirname, subdirs, files in os.walk("Notes"): zf.write(dirname) for filename in files: zf.write(os.path.join(dirname, filename)) zf.close() dialogs.hud_alert('Notes Zipped!') else: dialogs.hud_alert('Not zipped', 'error')
def main(): if not keyboard.is_keyboard(): return text = keyboard.get_selected_text() if not text: dialogs.hud_alert('No text selected', 'error') return new_text = text.title() keyboard.insert_text(new_text)
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)
def main(): if not keyboard.is_keyboard(): return text = keyboard.get_selected_text() if not text: dialogs.hud_alert('No text selected', 'error') return newText = quote(text, safe=':/') keyboard.insert_text(newText)
def save(): """Save an attachment""" if appex.is_running_extension(): sFp = appex.get_file_path() if sFp: dialogs.hud_alert('Saving...') comps = __file__.split(os.sep) doc_path = os.sep.join(comps[:comps.index('Documents') + 1]) with open(sFp, 'rb') as f1: with open(doc_path + '/' + os.path.basename(sFp), 'wb') as f2: shutil.copyfileobj(f1, f2, length=512 * 1024) dialogs.hud_alert('Saved') appex.finish()
def main(): base_theme_name = get_current_theme_name() default_theme_path = get_theme_path(base_theme_name) with open(default_theme_path) as f: theme_json = f.read() edited_theme = dialogs.text_dialog('Edit Theme (%s)' % base_theme_name, theme_json, font=('Menlo', 14), autocorrection=False, spellchecking=False, autocapitalization=ui.AUTOCAPITALIZE_NONE, done_button_title='Apply') if not edited_theme: return user_theme_path = os.path.join(get_user_themes_path(), 'MyTheme.json') with open(user_theme_path, 'w') as f: f.write(edited_theme) set_theme('User:MyTheme') dialogs.hud_alert('Theme saved')
def main(): text = '万徳' if not text: dialogs.hud_alert('No text selected', 'error') return newText = quote(text, safe=':/') # todo: url = f'quicka2://?text={newText}' #url = f'quicka2://?text=aaa' shortcuts.open_url(url)
def completeReminder(): _title = sys.argv[1] if len(sys.argv) > 1 else None _list = sys.argv[2] if len(sys.argv) > 2 else None if _list: calendars = reminders.get_all_calendars() _list = [x for x in calendars if x.title == _list] _list_title = _list[0].title todo = reminders.get_reminders(completed=False, calendar=_list[0]) callback = 'twodo://x-callback-url/showList?name=%s' % quote( _list_title) else: todo = reminders.get_reminders(completed=False) callback = 'twodo://' if len(todo) == 0: return dialogs.hud_alert('You don\'t have any reminder left to do.') if _title: this = [x for x in todo if x.title == _title] if len(this) == 1: this = this[0] elif len(this) <= 0: return dialogs.hud_alert( 'You don\'t have any reminder matching these terms.') else: todomap = {x.title: x for x in this} this = dialogs.list_dialog('Multiple matches', todomap.keys()) if not this: return dialogs.hud_alert( 'You gotta pick the correct reminder.') else: this = todomap.get(this) else: todomap = {x.title: x for x in todo} this = dialogs.list_dialog('Multiple matches', todomap.keys()) if not this: return dialogs.hud_alert('You gotta pick the correct reminder.') else: this = todomap.get(this) this.completed = True this.save() webbrowser.open(callback)
def main(): if not keyboard.is_keyboard(): return text = keyboard.get_selected_text() if not text: dialogs.hud_alert('No text selected', 'error') return url = f'shortcuts://run-shortcut?name=テキストを連携&input={text}' newUrl = quote(url, safe=':/') webbrowser.open(newUrl)
def recognize(self, image_data): req = VNRecognizeTextRequest.alloc().init().autorelease() handler = VNImageRequestHandler.alloc().initWithData_options_( image_data, None ).autorelease() success = handler.performRequests_error_([req], None) if success: self.recognized_text = [ str(result.text()) for result in req.results() ] self.tableview.reload() else: dialogs.hud_alert('Failed to recognize anything')
def post_submission_request(self, blog: str) -> None: client = self.get_client() response = client.create_text(blog, title=submissions.REQUEST_TITLE, body=submissions.REQUEST_BODY, slug='submission-guidelines', format='html', state='queue', tags=[]) pprint(response) dialogs.hud_alert( message=f'Submissions requested: {blog}', icon='success', duration=2, )
def main(): if not appex.is_running_extension(): assets = choose_assets() if assets is None: return assets = process_assets(assets) if len(assets.deletable) > 0: photos.batch_delete(assets.deletable) dialogs.hud_alert("{0} photos updated".format(len(assets.new))) else: images = appex.get_attachments() print(images)
def menu_button_selected(self, title): if title in ['Dismiss', 'Continue']: pass elif title in ['Restart', 'New Game']: self._new_game() elif title == 'Board size': self.dismiss_modal_scene() action = lambda: self.present_modal_scene( MenuScene( title, '', ['3x3', '4x4', '5x5', 'Custom'] ) ) self.delay(0.1, action) elif title == 'Custom': try: size = int(dialogs.input_alert('Board size:', '', '4')) size = max(2, min(8, size)) self.board_size = size self.board.set_size(size) except ValueError: dialogs.hud_alert( 'Invalid input: Use a single integer', 'error', 2 ) return except KeyboardInterrupt: return elif title[0].isdigit(): size = int(title[0]) self.board_size = size self.board.set_size(size) elif 'player' in title: try: self.change_player() except KeyboardInterrupt: pass return elif title in ['Highscores']: self.dismiss_modal_scene() action = lambda: self.present_modal_scene( MenuScene(title, self.score_board.get_top_list(), []) ) self.delay(0.1, action) else: return self.dismiss_modal_scene()
def main(): if not keyboard.is_keyboard(): print('This script is meant to be run in the Pythonista keyboard.') return # (phrase, shortcut) all = keyboard.get_text_replacements() snippets = [s[0] for s in all if s[1] == '☻'] snippets.sort() if len(snippets) == 0: dialogs.hud_alert('No Text Replacements') return selected = dialogs.list_dialog('Text Replacements', snippets) if selected: keyboard.insert_text(selected)
def write_record(sender, transfer_date, agent_name, price_amount, category_name): '@type sender: ui.button' date_format = '%Y-%m-%d' formatted_data = ( f"{transfer_date:{date_format}}{SEPERATOR}" f"{agent_name.replace(SEPERATOR,'')}{SEPERATOR}" # Remove tabs f"{price_amount}{SEPERATOR}" f"{category_name}{NEW_LINE}") with io.open(DATA_FILE, 'a+', encoding='utf-8') as f: f.write(formatted_data) logger.info( f"\"{formatted_data[:-1]}\" appended to \"{DATA_FILE}\" file.") hud_alert(f"Added entry for {agent_name.replace(SEPERATOR, '')}.")
def main(): feed = feedparser.parse('http://nasa.gov/rss/dyn/lg_image_of_the_day.rss') latest = feed['entries'][0] title = latest['title'] description = latest['summary'] print '%s\n\n%s' % (title, description) links = latest['links'] image_url = None for link in links: if link.get('type').startswith('image'): image_url = link.get('href') if image_url: urllib.urlretrieve(image_url, 'ImageOfTheDay.jpg') img = Image.open('ImageOfTheDay.jpg') img.show() dialogs.alert('Save to Camera Roll?', title, 'Save') photos.save_image(img) dialogs.hud_alert('Image Saved')
def main(): assert any([x in url for x in ("youtube", "youtu.be")]), "{0} is not a YouTube URL!".format(url) assert ":" in ts, "timestamp must be written as (hh:)mm:ss" if ts.count(":") == 1: mins, secs = map(int, ts.split(":")) hrs = 0 elif ts.count(":") == 2: hrs, mins, secs = map(int, ts.split(":")) else: sys.stderr.write("Bad timestamp (too many ':')") sys.exit(0) seconds = hrs*(60**2) + mins*(60**1) + secs*(60**0) newurl = "{url}?t={seconds}".format(url=url, seconds=seconds) clipboard.set(newurl) dialogs.hud_alert("{0} copied to clipboard".format(newurl)) return newurl
def action_import(sender): """Import a new vocabulary file. This selects a file from the iOS file picker and replace the current vocabulary file with it. """ choice = console.alert('This will override your current data', button1='Okay') if choice: f = dialogs.pick_document(types=['public.text']) try: if f is not None: vocab.load_json_file(f) vocab.save_json_file() except json.JSONDecodeError: dialogs.hud_alert('Invalid JSON file.', icon='error') return if f is not None: dialogs.hud_alert('Import was successful.') lookup_view['table'].reload()
def main(): filename = editor.get_path() if not filename: dialogs.hud_alert('No file selected', 'error') return pyui_filename = os.path.splitext(filename)[0] + '.pyui' if not os.path.exists(pyui_filename): folder = os.path.split(filename)[0] files = os.listdir(folder) files = [f for f in files if f.endswith('.pyui')] if not files: dialogs.hud_alert('No pyui files found', 'error') return selected_pyui = dialogs.list_dialog('Select pyui file', files) if not selected_pyui: return pyui_filename = os.path.join(folder, selected_pyui) with open(pyui_filename, 'rb') as f: pyui = f.read() compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8') wrapped = '\n'.join(textwrap.wrap(compressed, 70)) code = """\ data = '''\\\n%s ''' import ui import bz2 from base64 import b64decode pyui = bz2.decompress(b64decode(data)) v = ui.load_view_str(pyui.decode('utf-8')) """ % (wrapped,) clipboard.set(code) dialogs.hud_alert('Code copied', 'success')
from objc_util import ObjCClass, UIApplication, CGSize, on_main_thread import sys import appex import dialogs import ui UIReferenceLibraryViewController = ObjCClass('UIReferenceLibraryViewController') @on_main_thread def main(): input = ' '.join(sys.argv[1:]) or dialogs.text_dialog() if input: referenceViewController = UIReferenceLibraryViewController.alloc().initWithTerm_(input) rootVC = UIApplication.sharedApplication().keyWindow().rootViewController() tabVC = rootVC.detailViewController() referenceViewController.setTitle_("Definition: '{}'".format(input)) referenceViewController.setPreferredContentSize_(CGSize(540, 540)) referenceViewController.setModalPresentationStyle_(2) #tabVC.addTabWithViewController_(referenceViewController) tabVC.presentViewController_animated_completion_(referenceViewController, True, None) if __name__ == '__main__': if not appex.is_running_extension(): main() else: dialogs.hud_alert('Script does not work in app extension', icon='error')
def tableview_did_select(self, tableview, section, row): tableview.selected_row = -1 clipboard.set(tableview.data_source.items[row]) dialogs.hud_alert('copied')
def quit_action(sender): msg = '{} is not yet implemented!!'.format(sender.title) dialogs.hud_alert(msg) print(msg)
def action_get_score(self, sender): dialogs.hud_alert('Score: {}'.format(self.game.ai_rateing))
images = [] number_of_images = int(dialogs.input_alert("# of images?")) assert 1 <= number_of_images <=36 i = 0 while i < number_of_images: images.append(photos.pick_image()) i += 1 widths, heights = zip(*(j.size for j in images)) total_width = sum(widths) max_height = max(heights) new_image = Image.new("RGB", (total_width, max_height)) x_offset = 0 for im in images: new_image.paste(im, (x_offset, 0)) x_offset += im.size[0] try: photos.save_image(new_image) dialogs.hud_alert("Saved!") new_image.show() except Exception: dialogs.hud_alert("could not save file!".title(), "error") sys.exit(0)
def tableview_height_for_section_row(self,tv,section,row): #heights=[random.randrange(11,72) for x in range(100)] dialogs.hud_alert(str(row)) return self.heights[row]