def tableview_did_select(self, tableview, section, row): # Called when a row was selected. sel = self.data_list.items[row] if sel: console.alert('Confirm action: \n%s' % sel, button1='Yes') self.view.close() self.callback(sel)
def push_pyui_to_wc(self): pyui_path, pyui_contents = self._get_pyui_contents_for_file() if not pyui_contents: console.alert("No PYUI file associated. Now say you're sorry.", button1="I'm sorry.", hide_cancel_button=True) else: self._push_file_to_wc(pyui_path, pyui_contents)
def run(self, input=''): shared_session = AVAudioSession.sharedInstance() category_set = shared_session.setCategory_error_(ns('AVAudioSessionCategoryPlayAndRecord'), None) settings = {ns('AVFormatIDKey'): ns(1633772320), ns('AVSampleRateKey'):ns(44100.00), ns('AVNumberOfChannelsKey'):ns(2)} tempfilenameparam = self.get_param_by_name('tempfilename') removetempfileparam = self.get_param_by_name('removetempfile') output_path = os.path.abspath(tempfilenameparam.value) out_url = NSURL.fileURLWithPath_(ns(output_path)) recorder = AVAudioRecorder.alloc().initWithURL_settings_error_(out_url, settings, None) started_recording = recorder.record() try: if started_recording: while True: console.alert(title='Recording started', message='close this alert to end recording...') except KeyboardInterrupt: recorder.stop() recorder.release() data = NSData.dataWithContentsOfURL_(out_url) retfilepath = output_path if removetempfileparam.value: os.remove(output_path) retfilepath = None return ElementValue(type=self.get_output_type(), value={'type':'m4a','filename':tempfilenameparam.value, 'audiodata':data, 'filepath':retfilepath}, objcCopy = True) self.status = 'complete'
def PythonistaTest(): '''A test of the module for iOS devices running Pythonista''' import console,photos,clipboard #Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) photos.save_image(im) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor = '#ededed') stitchImages(im, outim).show() console.hide_activity() outim.save('image.jpg') console.quicklook('image.jpg') mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image") if mode == 1: file = open('output.txt', 'w') file.write(out) file.close() console.open_in('output.txt') elif mode == 2: console.open_in('image.jpg') time.sleep(5) console.clear()
def load_folder(self): infos = list_folder(self.path) items = [] if self.path != '/': items.append({'title': '..', 'image': 'ionicons-arrow-up-c-32', 'up': True}) if not infos: import console console.alert('Error', 'Could not load folder. Please check if you entered the access token correctly.', 'OK', hide_cancel_button=True) self.status_label.hidden = True return for info in infos: path = info.get('path') name = os.path.split(path)[1] if name.startswith('.'): continue is_dir = info.get('is_dir', False) item = {'title': name, 'image': 'ionicons-folder-32' if is_dir else 'ionicons-ios7-download-outline-32', 'accessory_type': 'disclosure_indicator' if is_dir else 'none', 'is_dir': is_dir, 'path': info['path']} items.append(item) def c(o1, o2): u_cmp = -1 * cmp(o1.get('up', False), o2.get('up', False)) if u_cmp != 0: return u_cmp d_cmp = -1 * cmp(o1.get('is_dir', False), o2.get('is_dir', False)) if d_cmp == 0: return cmp(o1.get('path', '').lower(), o2.get('path', '').lower()) return d_cmp items.sort(cmp=c) self.tableview.data_source.items = items self.status_label.hidden = True self.name = self.path
def main(): console.alert('Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue') label = console.input_alert('Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue') if not label: return url = console.input_alert('Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue') if not url: return icon = photos.pick_image() if not icon: return console.show_activity('Preparing Configuration profile...') data_buffer = BytesIO() icon.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() unique_id = uuid.uuid4().urn[9:].upper() config = {'PayloadContent': [{'FullScreen': True, 'Icon': plistlib.Data(icon_data), 'IsRemovable': True, 'Label': label, 'PayloadDescription': 'Configures Web Clip', 'PayloadDisplayName': label, 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadType': 'com.apple.webClip.managed', 'PayloadUUID': unique_id, 'PayloadVersion': 1, 'Precomposed': True, 'URL': url}], 'PayloadDescription': label, 'PayloadDisplayName': label + ' (Shortcut)', 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1} console.hide_activity() run_server(config)
def run(self, input=''): np = self.get_param_by_name('VariableName') name = np.value or console.input_alert('Please enter Variable name') rv = self.get_param_by_name('fm:runtime_variables') if not name in rv.value: rv.value[name] = None if rv.value[name] == None: rv.value[name] = input.copyMe() rv.value[name].value = [] rv.value[name].value.append(input.copyValue()) #if not input.objcCopy: # rv.value[name] = copy.deepcopy(input) #else: # ev = ElementValue(input.type, input.value.copy(), input.isList, ) # rv.value[name] = ev else: if input.type == rv.value[name].type: if not isinstance(rv.value[name].value,list): #t = copy.deepcopy(rv.value[name].value) t = rv.value[name].copyValue() rv.value[name].value = [] rv.value[name].value.append(t) if isinstance(input,list): for i in input.copyValue(): rv.value[name].value.append(i) else: rv.value[name].value.append(input.copyValue()) else: console.alert('Error','Incorrect type to append to variable',button1='Ok',hide_cancel_button=True) self.status = 'complete'
def download_release(username, repo, unzip): formatdict = { "user": username, "repo": repo } page = urllib2.urlopen(releaselink % formatdict) data = json.load(StringIO(page.read())) page.close() if not data: console.alert("Error", "This repo has no releases", "Ok", hide_cancel_button=True) return elif "message" in data and data["message"] == "Not Found": console.alert("Error", "Repo not found", "Ok", hide_cancel_button=True) return else: vers = sorted([i["tag_name"] for i in data]) rview = release_view(vers) rview.present("sheet") rview.wait_modal() row = rview["rtable"].delegate.selrow if row is None: return lastrls = data[row] zipurl = lastrls["zipball_url"] page = urllib2.urlopen(zipurl) data = page.read() page.close() save_zip(data, lastrls["name"], unzip) console.hud_alert("Done!")
def main(): console.clear() print("---- Getting Started ----") # Collect / prepare text url, shorturl, title, desc = preptext() # Prompt with current content: post / edit / cancel preview = console.alert("Preview",desc+" - "+shorturl,"Post","Edit") if (preview == 2): ## Edit ### Prompt to edit remaining text (if any) desc = console.input_alert("Adjust Message","Edit to suit.",desc,"Post","OK") # Verify where to send messages target = console.alert("Where to?","Options:","All","Hipchat") # Distribute posts if (target == 1): post_twitter(desc,shorturl) post_slack_api(desc,shorturl) print "(6) Sending to all channels." else: print "(6) Sending just to Hipchat." # Use _api for direct posts and _app to load the local iOS app post_hipchat_api(desc,shorturl) #post_hipchat_app(desc,shorturl) #dropbox_write(desc,url,shorturl,title) # Display results in console print("\n---- All Finished! ----")
def run(self, input): try: if not photos.save_image(input.value): console.alert("didn't work") except error: console.alert('error: {}'.format(error)) self.status = 'complete'
def copy_url(input_url): '''Write a copy of the file at input_url to HOME/DESTINATION if the destination directory doesn't exist, it is created if the destination file already exists, the user can cancel or overwrite if it is a Python file, a comment line is added to log the origin''' basename, input_short, output_short, output_dir, output_path, is_Python = parse_into_paths(input_url) if not os.path.exists(output_dir): os.mkdir(output_dir) console.hud_alert('Created destination directory {}'.format(output_short)) if os.path.exists(output_path): try: console.alert('Duplicate file', '{} already exists in {}'.format(basename, output_short), 'Overwrite') # or Cancel except KeyboardInterrupt: return with contextlib.closing(urllib.urlopen(input_url)) as input: data = input.read() console.hud_alert('Got {} ({} chars) from {}'.format(basename, len(data), input_short)) with open(output_path, 'wb') as output: if is_Python: datetime = time.strftime('%a %d-%b-%Y %H:%M:%S', time.gmtime()) output.write('# Retrieved from {} on {}\n\n'.format(input_url, datetime)) output.write(data) console.hud_alert('Wrote {} to {}'.format(basename, output_short))
def configure(sender): sss_view = sender.superview.superview.superview if sss_view: sss_view.config_view.present("sheet") sss_view.config_view.wait_modal() tv = sender.superview.superview["contentContainer"].textview config = sss_view.config_view.config font_size = config.get_value("editor.font.size") gutter = config.get_value("editor.show.gutter") style = config.get_value("editor.style") margin = config.get_value("editor.print.margin") wrap = config.get_value("editor.line.wrap") soft_tab = config.get_value("editor.soft.tabs") tab_size = config.get_value("editor.tab.size") tv.evaluate_javascript("document.getElementById('editor').style.fontSize='%ipx'" % font_size) tv.evaluate_javascript("get_editor().getSession().setTabSize(%s);" % tab_size) tv.evaluate_javascript("get_editor().getSession().setUseSoftTabs(%s);" % soft_tab) tv.evaluate_javascript("get_editor().getSession().setUseWrapMode(%s);" % wrap) tv.evaluate_javascript("get_editor().getSession().setShowPrintMargin(%s);" % margin) tv.evaluate_javascript("get_editor().getSession().setShowInvisibles(%s);" % gutter) tv.evaluate_javascript("get_editor().getSession().setTheme(%s);" % style) else: console.alert("Configuration is only available through the Main View")
def run(self, input=""): verbParam = self.get_param_by_name("verb") paramsParam = self.get_param_by_name("params") if verbParam.value == "GET": if paramsParam.value == None: r = requests.get(input.value) else: r = requests.get(input.value, params=paramsParam.value) elif verbParam.value == "POST": if paramsParam.value == None: r = requests.post(input.value) else: r = requests.get(input.value, data=paramsParam.value) elif verbParam.value == "PUT": r = requests.put(input.value) elif verbParam.value == "DELETE": r = requests.delete(input.value) self.status = "complete" if r.status_code == 200: type = r.headers["content-type"].split("/")[0] value = Image.open(StringIO(r.content)) if type == "image" else r.text return ElementValue(type=type, value=value) else: console.alert(title="Error", message=r.status_code, button1="Ok", hide_cancel_button=True) return ElementValue(type=None, value=None)
def new_keymap(self): """creates a new keymap.""" try: keymapname = console.input_alert( "Create new Keymap", "Please enter the name of the new Keymap.", "", "Create" ) except KeyboardInterrupt: return if len(keymapname) == 0 or keymapname == MSG_NEW_KEYMAP: console.alert( "Please enter a name for the Keymap!", "", "Ok", hide_cancel_button=True ) return if keymapname in os.listdir(KEYMAPPATH): console.alert( "Error", "A Keymap with this name already exists!", "Ok", hide_cancel_button=True ) return keymap = Keymap(keymapname, {}) self.edit_keymap(keymap)
def commit(): token = get_token() fpath = editor.get_path() fname = os.path.basename(fpath) m = console.input_alert('Edit Description','Enter a new description:','') if m == '': m = None gist_id = get_gist_id() res = commit_or_create(gist_id,{fpath:editor.get_text()},token,m) try: id = res['id'] except KeyError: if gist_id: f = console.alert('Commit Failed', 'Do you have permission to commit? Would you like to fork?','Fork') if f == 1: res = fork(gist_id,token) try: id = res['id'] except KeyError: console.alert('Fork Error', 'There was a problem with the fork') else: set_gist_id(id) res = commit_or_create(id,{fpath:editor.get_text()},token,m) try: id = res['id'] except KeyError: console.alert('Commit Error', 'Commit still failed, maybe fork too') else: if gist_id is None: set_gist_id(id) print('success!')
def restore_youtubedl_backup(sender): if not os.path.isdir(backup_location) or not os.listdir(backup_location): console.alert('Nothing to do', 'No backups found to restore') else: folders = os.listdir(backup_location) folder = folders[len(folders)-1] shutil.move(backup_location+folder,youtubedl_location+youtubedl_dir) console.alert('Success','Successfully restored '+folder)
def error_dialog(title, message): '''A diaolog box for error messages.''' try: alert(title, message) except KeyboardInterrupt: pass webbrowser.open('drafts://') exit(message)
def set(): gist = get_gist_id(editor.get_path()) if gist == None: gist = '' gist = console.input_alert('Assign Gist ID','Enter the gist id for this file',gist) try: set_gist_id(editor.get_path(),gist) except InvalidGistIDError: console.alert('Invalid Gist ID', 'That does not appear to be a valid gist id')
def fileExplorerButtonPressed(_self, _cmd): path = console.input_alert('File Explorer') try: files = os.listdir(path) sfiles = "\n".join(files) console.alert(path, sfiles) except OSError: console.alert('Error', 'Path not found')
def save_bookmarks(sender): bookmarks_file = dialogs.input_alert("name") + ".txt" txt = book_marks.segments for x in txt: with open("Notes/" + bookmarks_file, "a", encoding="utf-8") as outfile: outfile.write(time_stamp + "\n" + str(x) + "\n") sound.play_effect("rpg:BookFlip2") console.alert("Saved to {}".format(bookmarks_file))
def error_dialog(title, message): """A diaolog box for error messages.""" try: alert(title, message) except KeyboardInterrupt: pass webbrowser.open("drafts://") exit(message)
def install_editolido(url, *args, **kwargs): """ Download and install editolido module, will overwrite if module already exists. Checks and display installed version. :param url: url to the editolido zip github release (required) :return: """ check_old_install() del args # otherwise PyCharm complains not used del kwargs # otherwise PyCharm complains not used if url: infos, zipball_url = infos_from_giturl(url), url if infos['version'] and auto_update_is_set(): infos, zipball_url = latest_release(url) else: infos, zipball_url = latest_release(url) try: if infos['tag']: download_package( zipball_url, '%s-%s' % (infos['name'], infos['tag']), get_install_dir(), name=infos['name'], ) else: logger.log('invalid url %s' % url) raise IOError except (IOError, OSError): logger.log('install failed') except requests.exceptions.RequestException: logger.error('install aborted') else: try: # noinspection PyUnresolvedReferences import editolido try: from importlib import reload except ImportError: # noinspection PyUnresolvedReferences from imp import reload reload(editolido) except ImportError: # pragma no cover console.alert( 'Module editolido manquant', "Assurez vous d'avoir une connexion internet et recommencez " "pour tenter un nouveau téléchargement", 'OK', hide_cancel_button=True, ) raise KeyboardInterrupt else: save_local_config(infos, module_name=infos['name']) if infos['version'] is None: console.hud_alert( 'editolido [%s] %s installé' % (infos['branch'], editolido.__version__)) else: console.hud_alert( 'module editolido %s installé' % editolido.__version__)
def fileManagerButtonPressed(_self, _cmd): path = console.input_alert('File Reader') try: file = open(path, 'r') console.alert(path, file.read()) file.close() #console.quicklook(path) except IOError: console.alert('Error', 'Path not found')
def manual_fire(sender): global system_armed if system_armed == True: choice = console.alert("WARNING! MANUAL FIRE MODE", "You are about to enter manual firing mode. Do you wish to proceed?", button1="YES") if choice == 1: v['manual_fire_button'].enabled = False hide_show_manual_fire(False) else: console.alert("System Is Not Armed!", "You must arm the system before you can enter manual firing mode.", button1="Okay", hide_cancel_button=True)
def check_params(self): if len(sys.argv) > 1: self.flow_passed_in = sys.argv[1] if self.flow_passed_in in self.flows: self.flowselectedcb(self.flow_passed_in, True) self.flow_passed_in = None else: console.alert("Error", self.flow_passed_in + " does not exist!", button1="Ok", hide_cancel_button=True) self.flow_passed_in = None
def main(): text = '' with codecs.open('LinkStack.txt', 'r', 'utf-8') as f: for line in f: text += CreateLink.main(line[:-1]) + '\n' clipboard.set(text) console.alert('Link Created!', '', 'OK', hide_cancel_button=True) with codecs.open('LinkStack.txt', 'w', 'utf-8') as f: f.write('')
def pull(): gist = get_gist_id(editor.get_path()) if gist is None: console.alert('Error', 'There is no gist id set for this file') else: fname = os.path.basename(editor.get_path()) newtxt = load(gist,fname) if newtxt is not None: editor.replace_text(0,len(editor.get_text()),newtxt)
def addMagnet(): magnetUrl = clipboard.get() # Not a complete syntax check lof the magnet URL - will need to improve for the future # Especially considering that this will be run in a shell on the remote-host if not (re.match("^magnet\:\?.*",magnetUrl)): console.alert("Not a magnet URL",magnetUrl,"OK",hide_cancel_button=True) exit() commands = [ "transmission-remote -n '"+transmissionRemoteUsername+":"+transmissionRemotePassword+"' --torrent-done-script /home/torrentbot/torrentbot/bin/remove-the-torrent.sh -a '"+magnetUrl+"'" ] executeSshCommand(commands)
def saveflow(self,sender): if self.flow_creation_view.data_source.title == '': console.alert(title='Error',message='Please enter a title',button1='Ok',hide_cancel_button=True) else: self.flow_manager.save_flow(self.flow_creation_view.data_source.title, self.selectedElements) console.alert(title='Success',message='Flow has been saved',button1='Ok',hide_cancel_button=True) self.get_flows() self.flow_view.data_source.flows = self.flows self.flow_view.reload_data()
def urlscheme_copy_repo_from_wc(self, path, b64_contents): tmp_zip_location = self.install_path + 'repo.zip' try: os.makedirs(os.path.join(os.path.expanduser('~/Documents'), path)) except OSError, e: if e.errno != errno.EEXIST: raise e console.alert('Overwriting existing directory', button1='Continue') shutil.rmtree(os.path.join(os.path.expanduser('~/Documents'), path))
def player_card_three_touch_up_inside(sender): # this function flips over the third card when it is touched. global player_total global player_total_two third_card = console.alert('Third Card', 'Would you like a third card?', 'Yes', 'No', hide_cancel_button=True) if third_card == 1: view['player_card_three_imageview'].image = ui.Image( 'card:' + str(player_card_three)) if player_total_one == 1: ace = console.alert('info', 'would you like 1 or 11', '1', '11', hide_cancel_button=True) if ace == 1: player_total = player_total + player_total_three view['player_total_label'].text = 'Player Total: ' + str( player_total) else: player_total = int(player_total) + 11 view['player_total_label'].text = 'Player Total: ' + str( player_total) else: player_total = player_total + player_total_three view['player_total_label'].text = 'Player Total: ' + str( player_total) else: pass
def onShareButton(sender): global AdventureFolder global mustSave if mustSave: id = console.alert( 'Warning', 'Un-saved modifications detected, do you want to save them?', 'Yes', 'No', hide_cancel_button=True) if id == 1: saveAdventure() mustSave = False make_zipfile("./" + AdventureFolder + ".thz", "./" + AdventureFolder + "/") console.open_in(AdventureFolder + ".thz")
def get_archiver(self, sender): length = int(self.info['length']) if len(list(Path(self.dl_path).iterdir())) == length + 2 and len( list(Path( self.dl_path).joinpath('thumbnails').iterdir())) == length: alert_title = '是否保存为压缩包?' else: alert_title = '本图库还没有下载完,是否保存为压缩包?' t = console.alert(alert_title, '', 'OK') if t: shutil.make_archive( os.path.join(os.path.expanduser('~/Documents'), os.path.split(self.dl_path)[1]), 'zip', self.dl_path) console.hud_alert('成功')
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return text = appex.get_text().strip('* \n') if not text: print('No text input found.') return s = get_session() row_translates = get_row_translates(s, text) all_t = "" for t in row_translates: all_t += "- " + t["value"] + "\n" first_translate = row_translates[0]["value"] answer = console.alert(text, '%s' % (all_t), 'Добавить в словарь', 'Отменить', hide_cancel_button=True) if (answer == 1): add_word(s, text, first_translate) console.alert("Слово добавлено", "", 'OK', hide_cancel_button=True)
def btnSideItemSave_Click(self): # # Perform Screen Validation Before Accepting Input. # hasEntryErrors = False if txtSideItemName.text == '': result = console.alert('Message...', 'Please Enter a Value for Item Name.', hide_cancel_button=True, button1='OK') hasEntryErrors = True if txtSidePricePerPack.text == '0' and not hasEntryErrors or txtSidePricePerPack.text == '' and not hasEntryErrors: result = console.alert('Message...', 'Please Enter a Value for Price Per Pack.', hide_cancel_button=True, button1='OK') hasEntryErrors = True if txtSideServingsPerPack.text == '0' and not hasEntryErrors or txtSideServingsPerPack.text == '' and not hasEntryErrors: result = console.alert('Message...', 'Please Enter a Value for Servings Per Pack.', hide_cancel_button=True, button1='OK') hasEntryErrors = True if txtSideServingsPerPerson.text == '0' and not hasEntryErrors or txtSideServingsPerPerson.text == '' and not hasEntryErrors: result = console.alert('Message...', 'Please Enter a Value for Servings Per Person.', hide_cancel_button=True, button1='OK') hasEntryErrors = True if not hasEntryErrors: # Side Items # Parameters: Item Name, Price/Pack, Servings/Pack, Servings/Person # populateEventInput() NewEvent.add_side_item(txtSideItemName.text, float(txtSidePricePerPack.text), int(txtSideServingsPerPack.text), int(txtSideServingsPerPerson.text)) pt_side_item.add_row([NewEvent.side_name, NewEvent.price_per_pack, NewEvent.servings_per_pack, NewEvent.servings_per_person, NewEvent.packs_needed, NewEvent.raw_cost]) NewEvent.hasSideItems = True lblSideItemCount.text = str(NewEvent.Side_Item_Count) # Close the view. vwCC_SideItem.close()
def quitter(sender): try: result = console.alert("Close", "", "Close File", "Quit") if result == 1: if sender.superview.superview is None: console.hud_alert("Close File") else: sender.superview.superview.on_close_file() elif result == 2: if sender.superview.superview.superview is None: sender.superview.superview.close() else: sender.superview.superview.superview.close() except KeyboardInterrupt as e: logger.warning("User cancled the input.")
def deleteCheatsheet(self, cheatsheet, post_action, confirm=True): but = 1 if confirm: but = console.alert( 'Are you sure?', 'Would you like to delete the cheatsheet, ' + cheatsheet.name, 'Ok') if but == 1: dbmanager = DBManager.DBManager() dbmanager.DocsetRemoved(cheatsheet.id) shutil.rmtree(cheatsheet.path) cheatsheet.status = 'online' if not post_action == None: post_action() cheatsheet.path = None
def reset_system_Act(self): if (console.alert( "初始化系统", '你确定要删除所有数据并重置系统吗?', '确定', '取消', hide_cancel_button=True) != 1): return self.app.activity_indicator.start() try: self.app.configService.Reset() self.app.trans_history = [] self.father.updateData() console.hud_alert('系统初始化成功!', 'success', 1.0) except Exception as e: console.hud_alert('系统初始化失败!', 'error', 1.0) finally: self.app.activity_indicator.stop()
def extra_b(sender): cc1 = sender.superview['textview1'].text try: Save1 = cc1[9] Save2 = cc1[10] Save4 = cc1[0:8] CC111 = cc1[:] except IndexError: console.alert('Error', 'Introduce un Bin valido') cc2 = sender.superview['textview2'].text Save1_2 = cc2[9] Save2_2 = cc2[10] CC222 = cc2[:] CCF1 = (((int(Save1) + int(Save1_2)) / 2) * 5) CCF2 = (((int(Save2) + int(Save2_2)) / 2) * 5) CCF = int(CCF1) + int(CCF2) X1 = 'xxxxxx' CCFG = str(Save4) + str(CCF) + str(X1) table = sender.superview['tableview1'].data_source.items table.append(CCFG)
def run(self, input=''): np = self.get_param_by_name('VariableName') name = np.value or console.input_alert('Please enter Variable name') rv = self.get_param_by_name('fm:runtime_variables') if not name in rv.value: rv.value[name] = None if rv.value[name] == None: rv.value[name] = input.copyMe() rv.value[name].value = [] rv.value[name].value.append(input.copyValue()) #if not input.objcCopy: # rv.value[name] = copy.deepcopy(input) #else: # ev = ElementValue(input.type, input.value.copy(), input.isList, ) # rv.value[name] = ev else: if input.type == rv.value[name].type: if not isinstance(rv.value[name].value, list): #t = copy.deepcopy(rv.value[name].value) t = rv.value[name].copyValue() rv.value[name].value = [] rv.value[name].value.append(t) if isinstance(input, list): for i in input.copyValue(): rv.value[name].value.append(i) else: rv.value[name].value.append(input.copyValue()) else: console.alert('Error', 'Incorrect type to append to variable', button1='Ok', hide_cancel_button=True) self.status = 'complete'
def deleteStackOverflow(self, stackoverflow, post_action, confirm=True): but = 1 if confirm: but = console.alert( 'Are you sure?', 'Would you like to delete the docset, ' + stackoverflow.name, 'Ok') if but == 1: dbmanager = DBManager.DBManager() dbmanager.DocsetRemoved(stackoverflow.id) shutil.rmtree(stackoverflow.path) stackoverflow.status = 'online' if not post_action == None: post_action() stackoverflow.path = None
def runflow(self,sender): try: self.flow_creation_view.reload() ret, message= self.flow_manager.run_flow(self.selectedElements,self.navigation_view, self.selectedFlowType) if ret: console.alert(title='Complete',message=message,button1='Ok',hide_cancel_button=True) else: console.alert(title='Error',message=message,button1='Ok',hide_cancel_button=True) except ValueError, e: console.alert(str(e))
def main(): console.clear() i = console.alert('Info', '画像の入力方法を選択して下さい。', 'Take Photo', 'Pick from Library') if i == 1: filename = take_photo() else: filename = pick_photo() if not filename: return console.show_image(filename) img = img_to_base64(filename) res_json = goog_cloud_vison(img) #print res_json imagebuffer = Image.open(filename) highlight_faces(imagebuffer, res_json['responses'][0]['faceAnnotations'])
def order_Act(self,sender): res=console.alert("排序规则","请选择排序关键字","收藏时间","名称","价格",hide_cancel_button=True)-1 keys=["收藏时间","名称","价格"] descs=["升序","降序"] if res == self.order_key: self.order_desc*=-1 self.order_desc+=1 else: self.order_key=res self.order_desc=0 self.orderBtn.title=keys[self.order_key]+": "+descs[self.order_desc] self.loadData()
def export_all_channels(sender): answer = console.alert( "Are you sure you want to export all accessible channels?", button1="Yes", button2="No", hide_cancel_button=True) if answer == 1: view = sender.superview answer = dce(view, 'exportall', '-f', view["format"].segments[view["format"].selected_index], '--dateformat u', '--media' if view["dlMedia"].value else '', save=True) log(sender, answer)
def main(): console.clear() i = console.alert('Info', '画像の入力方法を選択して下さい。', 'Take Photo', 'Pick from Library') if i == 1: filename = take_photo() else: filename = pick_photo() if not filename: return console.show_image(filename) img = img_to_base64(filename) res_json = goog_cloud_vison(img) #print res_json #print json.dumps(res_json, indent=2, sort_keys=True) print_description(res_json)
def select(): result = console.alert("", "Select", "Send", "Receive", 'Cancel', hide_cancel_button=True) if result == 1: files = file_picker()('Pick files', multiple=True, select_dirs=True, file_pattern=r'^.+$') if files: transfer.send(files) elif result == 2: transfer.receive(wait_interval)
def pasteDir(): '''Copy the directory in clipboard to the same directory as the current file ''' # get current directory location file = editor.get_path() dir = os.path.dirname(file) # get source directory from clipboard src = clipboard.get() # is it a valid source? if not os.path.exists(src): console.alert( 'Paste Error', 'Directory described in clipboard does not exist! Paste not possible.' + '\nClipboard content:\n\n' + src) return msg = re.match('.+(Pythonista3/Documents/)(.+)', src) if (msg == None) or (msg.group(2) == None): msg = 'clipboard content is not a valid pythonista3 sub-directory:\n' + src + '\npaste not possible.' console.alert('Paste Error', msg) return # get name of directory name = msg.group(2) name = name.split('/')[-1] # build destination name dst = dir + '/' + name # and a short version msg = re.match('.+(Pythonista3/Documents/)(.+)', dst).group(2) # if already exists then cancel if os.path.exists(dst): console.alert( 'Paste Error', 'Directory:\n' + msg + '\nalready exists! Paste not possible.') return # inform user and get confirmation ans = console.alert( 'Paste', '\nNB: YOU MUST SELECT A FILE IN THE DIRECTORY WHERE TO PASTE!' + '\n\nIs this the directory you want to create?\n\n' + msg, 'yes') # if yes, paste if ans == 1: shutil.copytree(src, dst) console.hud_alert('Done!', 'success', 0.5)
def copyDirPathToClipboard(): '''Copy current file directory to the clipboard ''' # get current location file = editor.get_path() dir = os.path.dirname(file) # inform user and get confirmation msg = re.match('.*Pythonista3/Documents/(.+)', dir).group(1) ans = console.alert( 'Copy', 'Copy this directory?\n' + msg + '\nNB: select a file to get its directory!', 'yes') # if yes, copy to clipboard if ans == 1: clipboard.set(dir) console.hud_alert('Done!', 'success', 0.5)
def removeHintButton(sender): global CurrentHint global Hint global CurrentHintID sound.play_effect('game:Error') result = console.alert("Delete Hint ?", "Do you confirm you want to delete this hint ?", "Yes", "No", hide_cancel_button=True) if result == 2: return Hint.pop(CurrentHintID) if CurrentHintID > len(Hint) - 1: CurrentHintID = len(Hint) - 1 CurrentHint = Hint[CurrentHintID] refreshEditorItems(True)
def copyDir(): '''Copy current file directory to the clipboard ''' # get current location file = editor.get_path() dir = os.path.dirname(file) # inform user and get confirmation msg = re.match('.*Pythonista3/Documents/(.+)', dir).group(1) ans = console.alert( 'Copy', '\nNB: YOU MUST SELECT A FILE IN THE DIRECTORY TO COPY!' + '\n\nIs this the directory you want to copy?\n\n' + msg, 'yes') # if yes, copy to clipboard if ans == 1: clipboard.set(dir) console.hud_alert('Done!', 'success', 0.5)
def main(): if appex.is_running_extension(): url = appex.get_url() if url == None: text = appex.get_text() url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0] else: text = clipboard.get().strip() url = [mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text)][0] if not "http" in url: url = "http://" try: url = console.input_alert("URL", "", url) except: return True console.hud_alert('URL: %s' % url) h = html2text.HTML2Text() try: r = requests.get(url=url, headers={ "User-agent": "Mozilla/5.0{0:06}".format( random.randrange(999999)) }) except Exception as e: raise (e.message) return True html_content = r.text.decode('utf-8') rendered_content = html2text.html2text(html_content) clipboard.set(rendered_content) launch_e = console.alert('Markdown copied to clipboard. Launch Evernote?', button1='Yes', button2='No', hide_cancel_button=True) if launch_e == 1: _eurl = "evernote://x-callback-url/new-note?type=clipboard&title=DRAFT&text=" app = UIApplication.sharedApplication() eurl = nsurl(_eurl) app.openURL_(eurl) appex.finish()
def process_imported_file(file_path): file_root, file_ext = os.path.splitext(file_path) if file_ext == '.zip': action = console.alert( 'Extract ZIP File', 'Extract contents to directory and remove ZIP file?', 'Yes', 'No', hide_cancel_button=True) if action == 1: with ZipFile(file_path, 'r') as zip_file: # Delete the directory we're about to expand into if it's present. if os.path.exists(file_root): shutil.rmtree(file_root) zip_file.extractall(file_root) # Delete the ZIP file os.remove(file_path)
def deleteDocset(self, docset, post_action, confirm=True): but = 1 if confirm: but = console.alert( 'Are you sure?', 'Would you like to delete the docset, ' + docset['name'] + '\n This may take a while.', 'Ok') if but == 1: p = os.path.join(self.docsetFolder, '_' + docset['name'].replace('/', '_'), '_' + docset['version'].replace('/', '_')) dbmanager = DBManager.DBManager() dbmanager.DocsetRemoved(docset['id']) shutil.rmtree(p) docset['status'] = 'online' docset['path'] = None if not post_action == None: post_action()
def main(): foo = editor.get_text() gist_url = first_url_from_comments(foo) try: filename, content = download_gist(gist_url) editor.replace_text(0,len(editor.get_text()),content) #else: #editor.make_new_file(filename, content) except InvalidGistURLError: console.alert('No Gist URL', 'The clipboard doesn\'t seem to contain a valid Gist URL.', 'OK') except MultipleFilesInGistError: console.alert('Multiple Files', 'This Gist contains multiple ' + 'Python files, which isn\'t currently supported.') except NoFilesInGistError: console.alert('No Python Files', 'This Gist contains no Python files.') except GistDownloadError: console.alert('Error', 'The Gist could not be downloaded.')
def main(): gist_url = clipboard.get() try: filename, content = download_gist(gist_url) if os.path.isfile(filename): i = console.alert('File exists', 'A file with the name ' + filename + ' already exists in your library.', 'Auto Rename') if i == 1: editor.make_new_file(filename, content) else: editor.make_new_file(filename, content) except InvalidGistURLError: console.alert('No Gist URL', 'The clipboard doesn\'t seem to contain a valid Gist URL.', 'OK') except MultipleFilesInGistError: console.alert('Multiple Files', 'This Gist contains multiple ' + 'Python files, which isn\'t currently supported.') except NoFilesInGistError: console.alert('No Python Files', 'This Gist contains no Python files.') except GistDownloadError: console.alert('Error', 'The Gist could not be downloaded.')
def onDeleteAdventureAction(sender): global AdventureFolder sound.play_effect('game:Error') result = console.alert( "Delete Adventure ?", "Do you confirm you want to delete this Adventure ?\nYou won't be able to recover it after this action !", "Yes", "No", hide_cancel_button=True) if result == 2: return print("deleting adventure : " + AdventureFolder) recurseDeleteFolder(AdventureFolder) launchTitleScreen()
def main(): filename = sys.argv[1] resp = console.alert('Alert!', 'Choose File Extension', filename + '.py', filename + '.pyui', hide_cancel_button=False) if resp == 1: ext = '.py' elif resp == 2: ext = '.pyui' text = clipboard.get() assert text, 'No text on the clipboard!' console.clear() print('Wait a Moment Please!') filename = save(filename, text, ext) console.set_font('Futura', 16) print('Done!\nFile Saved as:\n' + filename)
def copyFile(): '''Copy current file to the clipboard ''' # get current file file = editor.get_path() # get short version filepath, filename = os.path.split(file) # inform user and get confirmation ans = console.alert( 'Copy', '\n\nIs this the file you want to copy?\n\n' + filename, 'yes') # if yes, paste if ans == 1: # copy to clipboard clipboard.set(file) console.hud_alert('Done!', 'success', 0.5)
def end_button_action(self, sender): if self.saved != None: if not self.saved: b = console.alert('Projet non sauvé', "sauver d'abord?", 'oui', 'non', hide_cancel_button=True) if b == 1: self.save_button_action('auto') if ('from_launcher' in sys.argv) or ('Christian' not in str( ObjCClass('UIDevice').currentDevice().name()) ): # if from shortcut # launched by Launcher or by shortcut in Pam device # Back to home screen webbrowser.open('launcher://crash') self.close() VersionInStatusBar(version=False)