def loginLime(): #window = dialogos.form_dialog(title='Phone Number', fields=[{'title':'Introduzca su numero de telefono de cuenta Lime con extension de pais (Ej: +34):\n','type':'number','value':'','key':'phone'}], sections=None) #phone = window['phone'] phone = dialogs.input_alert( 'Phome Number', 'Introduzca su numero de telefono de cuenta Lime con extension de pais (Ej: +34):', '+34', 'OK', hide_cancel_button=False) if not phone.startswith('+'): phone = '+' + phone #Miramos que tenga el + delante phone = phone.replace(' ', '') #Quitamos los espacios en blanco d = requests.get("https://web-production.lime.bike/api/rider/v1/login", data={"phone": phone}) #print(d.text) #window = dialogos.form_dialog(title='Lime Code', fields=[{'title':'Introduzca codigo recibido:','type':'number','value':'','key':'code'}], sections=None) #code = window['code'] code = dialogs.input_alert('Lime Code', 'Introduzca codigo recibido:', '', 'OK', hide_cancel_button=True) url = 'https://web-production.lime.bike/api/rider/v1/login' datos = {"login_code": code, "phone": phone} r = requests.post(url, data=datos) data = r.text print(data) with open(fil + '/data/cookie.dat', 'wb') as f: pickle.dump(r.cookies, f) h_lime = json.loads(data) with open(fil + '/data/token.dat', 'w') as f: f.write(h_lime['token'])
def main(): linkdump_url = 'http://*****:*****@localhost:9292' if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return url = appex.get_url() tags = dialogs.input_alert('Tags:', '') if not url: print('No input URL found.') return print(url) headers = { 'Content-Type': 'application/json', } data = '{' +\ '"url": "' + url + '",' +\ '"tags": "' + tags + '"' +\ '}' r = requests.post(linkdump_url + '/api/links', headers=headers, data=data) print(r.status_code)
def btn_type_tapped(sender): global btn_type, city_st, err try: city_st = dialogs.input_alert('Enter A City, ST:') if city_st: if not ',' in city_st: err = 'Formatting error' city_st = '' pass elif len(city_st.strip()) < 4: err = 'Unlikely city name.' city_st = '' pass else: btn_type = True v.close() pass else: err = 'Nothing Entered' if err: console.hud_alert(err, 'error') err = '' pass except KeyboardInterrupt: pass
def webopen(url=None): base_url = "safari-{0}" cburl = clipboard.get().encode() if not cburl.startswith("http"): cburl = dialogs.input_alert("URL?") url = base_url.format(cburl) if not url else base_url.format(url) webbrowser.open(url)
def findApp(Sender): returns = [] input = dialogs.input_alert('Input Keyword') for i in items: if i['title'].lower().find(input.lower()) != -1: returns += [i] table.data_source.items = returns
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}')
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 main(): if not appex.is_running_extension(): #print('Running in Pythonista app, using test data...\n') url = 'http://example.com' url = console.input_alert("Hello", "Enter URL", "http://inside.mines.edu/~tkaiser/golf.py") else: url = appex.get_url() if url: # TODO: Your own logic here... print('Input URL: %s' % (url, )) r = requests.get(url) text = r.text print(text) top = startdir() if len(text) > 0: # TODO: Your own logic here... # print('Input text: %s' % text) diddir = setdir(top) newfile = "" if diddir: newfile = dialogs.input_alert("File", "Create file:") if newfile is None: newfile = "" if len(newfile) > 0: file = open(newfile, "w") file.write(text) file.close() else: print('No input URL found.')
def create_dump(self, sender): txt = [] with open(input_alert('Make a hex dump of which file?'), 'rb') as f: while True: line = f.readline() if not line: break for byte in line: txt.append(byte) dump = [] offset = 1 while True: line = list(txt[offset - 1:offset + 7]) if not line: break hexes = [hex(num)[2:].zfill(2) for num in line] for i in range(0, len(line)): if not line[i] in range(32, 127): line[i] = 46 ascii_text = ''.join([chr(ch) for ch in line]) offset_string = hex(offset - 1)[2:].zfill(7) hex_string = ' '.join(hexes) dump.append( ('{}: {}{}|{}{}|'.format(offset_string, hex_string, ' ' * (27 - len(hex_string)), ascii_text, ' ' * (8 - len(ascii_text))))) offset += 8 self.dump = dump self['textview1'].text = '\n'.join(dump) self['offset'].text = '0000000' self['hexstring'].text = dump[0][12:35] self['asciistring'].text = dump[0][40:48]
def editpayload(payload): editing = True while editing: mainops = [{ 'title': 'Edit' }, { 'title': 'Add Webclip' }, { 'title': 'Add Wifi' }, { 'title': 'Serve' }, { 'title': 'Save' }] + payload.profile choice = dialogs.list_dialog('Profile', mainops) if choice == None: editing == False return payload if choice['title'] == 'Edit': payload.profile = dialogs.edit_list_dialog('Edit Profiles', payload.profile) if choice['title'] == 'Add Webclip': webclip(payload) if choice['title'] == 'Add Wifi': wifi(payload) if choice['title'] == 'Serve': cpload = mprofile.mkplist(payload) serve.run_server(cpload) if choice['title'] == 'Save': name = dialogs.input_alert('File name') name = name + '.mobileconfig' cpload = mprofile.mkplist(pload) cpload = mprofile.stripdict(cpload) plistlib.writePlist(cpload, name) return payload
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 addsnippet(self, sender, title=None, contents=None): if title == None: title = dialogs.input_alert(title='Title Entry', message='Please enter a title') if contents == None: contents = dialogs.text_dialog('Contents Entry') db = dbmanager() db.insert_snippet(title=title, contents=contents) self.updatesnippetslistview()
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 load_dump(self, sender): with open(input_alert('Load which hex dump?'), 'r') as f: self.dump = f.read().split('\n') self.dump.pop() self['textview1'].text = '\n'.join(self.dump) self['offset'].text = '0000000' self['hexstring'].text = self.dump[0][12:35] self['asciistring'].text = self.dump[0][40:48]
def view_files(sender): global thoughts_file file_select = dialogs.list_dialog("Select A File", ["New"] + os.listdir("Notes")) if file_select == "New": thoughts_file = dialogs.input_alert("Name your thoughts file") + ".txt" elif file_select == None: pass else: thoughts_file = file_select
def view_files(sender): global thoughts_file file_select = dialogs.list_dialog('Select A File', ['New'] + os.listdir('Notes')) if file_select == 'New': thoughts_file = dialogs.input_alert('Name your thoughts file') + '.txt' elif file_select == None: pass else: thoughts_file = file_select
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 do_view_playlist(sender): name = dialogs.input_alert(title="Playlist Name") if name and len(name) > 0: res = rsession.get("https://music.sarsoo.xyz/api/playlist", params={'name': name}, auth=auth) if 200 <= res.status_code < 300: clipboard.set(res.text) webbrowser.open('jayson:///view?clipboard=true') else: sender.superview['output_label'].text = f'Failed {res.status_code} {res.body}'
def do_view_tag(sender): tag_id = dialogs.input_alert(title="Tag ID") if tag_id and len(tag_id) > 0: res = rsession.get(f"https://music.sarsoo.xyz/api/tag/{tag_id}", auth=auth) if 200 <= res.status_code < 300: clipboard.set(res.text) webbrowser.open('jayson:///view?clipboard=true') else: sender.superview['output_label'].text = f'Failed {res.status_code} {res.body}'
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 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()
def do_run_playlist(sender): name = dialogs.input_alert(title="Playlist Name") if name and len(name) > 0: res = rsession.get("https://music.sarsoo.xyz/api/playlist/run", params={"name": name}, auth=auth) if 200 <= res.status_code < 300: output = 'Success' else: output = f'Failed {res.status_code} {res.body}' sender.superview['output_label'].text = output
def do_sort_playlist(sender): name = dialogs.input_alert(title="Playlist Name") if name and len(name) > 0: res = rsession.post("https://music.sarsoo.xyz/api/spotify/sort", json={"playlist_name": name}, auth=auth) if 200 <= res.status_code < 300: output = 'Success' else: output = f'Failed {res.status_code} {res.body}' sender.superview['output_label'].text = output
def search_diag(self, sender): keyword = dialogs.input_alert('Search keyword') search_index = list(self.app.index.values()) ret_dict = {} for each_cat in search_index: for key in each_cat.keys(): if keyword in key: ret_dict[key] = each_cat[key] if not ret_dict: print_msg('Not found!') return tools_table = AnimeTable(self.app, 'Search', ret_dict) self.app.nav_view.push_view(tools_table.view)
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 get_config(): myconfdir = os.path.join(os.environ['HOME'], mlbConstants.AUTHDIR) myconf = os.path.join(myconfdir, AUTHFILE) mydefaults = { 'video_player': DEFAULT_V_PLAYER, 'audio_player': DEFAULT_A_PLAYER, 'audio_follow': [], 'alt_audio_follow': [], 'video_follow': [], 'blackout': [], 'favorite': [], 'use_color': 0, 'adaptive_stream': 1, 'favorite_color': 'cyan', 'bg_color': 'xterm', 'show_player_command': 0, 'debug': 0, 'x_display': '', 'top_plays_player': '', 'use_librtmp': 1, 'use_nexdef': 0, 'condensed': 0, 'nexdef_url': 0, 'zdebug': 0, 'time_offset': '', 'postseason': 1, 'international': 1} config = MLBConfig(mydefaults) config.loads(myconf) if config.get('debug'): print 'Config: ' + repr(config.data) try: if not config.get('user'): config.set('user', dialogs.input_alert(title='Enter your MLB.tv username')) if not config.get('pass'): config.set('pass', dialogs.password_alert( title='Enter your MLB.tv password')) if not config.get('speed'): config.set('speed', dialogs.list_dialog( title='Select a speed (Kbps)', items=STREAM_SPEEDS)) except KeyboardInterrupt: pass for prop in ['user', 'pass', 'speed']: if not config.get(prop): raise Exception(prop + ' is required') return config
def main(): if not appex.is_running_extension(): print( 'Run this script from the share sheet extension in the Playgrounds app' ) return pg_path = appex.get_file_path() if not pg_path or not pg_path.endswith('.playgroundbook'): print('No Playground book found in share sheet input') return tmpdir = tempfile.gettempdir() pg_name = os.path.split(pg_path)[1] dest_path = os.path.join(tmpdir, pg_name) try: shutil.rmtree(dest_path) except IOError: pass shutil.copytree(pg_path, dest_path) chapters_path = os.path.join(dest_path, 'Contents/Chapters') chapter_names = os.listdir(chapters_path) chapter = dialogs.list_dialog('Chapter', chapter_names) if chapter is None: return try: page_title = dialogs.input_alert('New Page Title') except KeyboardInterrupt: return chapter_path = os.path.join(chapters_path, chapter) with open(os.path.join(chapter_path, 'Manifest.plist'), 'rb') as f: chapter_manifest = plistlib.readPlist(f) chapter_manifest['Pages'].append(page_title + '.playgroundpage') with open(os.path.join(chapter_path, 'Manifest.plist'), 'wb') as f: plistlib.dump(chapter_manifest, f) page_path = os.path.join(chapter_path, 'Pages/' + page_title + '.playgroundpage') os.mkdir(page_path) os.mkdir(os.path.join(page_path, 'Resources')) img = Image.open('test:Pythonista') img.save(os.path.join(page_path, 'Resources/Pythonista.png')) with open(os.path.join(page_path, 'Contents.swift'), 'w') as f: f.write(swift) manifest = manifest_tpl.replace('{{NAME}}', page_title) with open(os.path.join(page_path, 'Manifest.plist'), 'w') as f: f.write(manifest) console.open_in(dest_path) shutil.rmtree(dest_path)
def new_theme(sender): path = editor.get_path() dir = os.path.dirname(path) with open(dir + '/Sample.twitterrifictheme', 'rb') as f: data = plistlib.readPlist(f) themeName = dialogs.input_alert('Theme Name') if len(themeName) != 0: currentTabDir = TWITTERRIFIC_PATH % segmentedControl.segments[ segmentedControl.selected_index] writePath = currentTabDir + '/%s.twitterrifictheme' % themeName plistlib.writePlist(data, writePath) else: dialogs.alert('Invalid Name', button1='Ok', hide_cancel_button=True) loadTableView()
def button_record(sender): # code here global curloc, lastloc lastloc = curloc curloc = location.get_location() name = dialogs.input_alert("Enter Name", "Name:", "John Doe", hide_cancel_button=False) curloc = location.get_location() if curloc['horizontal_accuracy'] > 5: dialogs.hud_alert("Poor GPS accuracy", 'error', 1) count = 0 while count < 10 and curloc["horizontal_accuracy"] > 5: curloc = location.get_location() count += 1 dialogs.hud_alert('Location Recorded', 'success', 1) else: dialogs.hud_alert('Location Recorded', 'success', 1) form_url = 'https://docs.google.com/forms/d/e/1FAIpQLSeYmR_PSpxeeE1pJEP83Ui_eqz4OA6tqqx35cfPX1VL2mfd0g/formResponse' form_postbody = { 'entry.598678340': str(curloc['longitude']), 'entry.1352477612': str(curloc['latitude']), 'entry.1482071151': str(curloc['horizontal_accuracy']), 'entry.1391268977': urllib.parse.quote(str(name)), 'draftResponse': [], 'pageHistory': 0 } form_headers = { 'Referer': 'https://docs.google.com/forms/d/e/1FAIpQLSeYmR_PSpxeeE1pJEP83Ui_eqz4OA6tqqx35cfPX1VL2mfd0g/viewform' } try: val = requests.post(form_url, data=form_postbody, headers=form_headers) except: console.hud_alert('Error on upload', 'failure', 1)
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 editpayload(payload): editing = True while editing: mainops = [{'title':'Edit'},{'title':'Add Webclip'},{'title':'Add Wifi'},{'title':'Serve'},{'title':'Save'}]+payload.profile choice = dialogs.list_dialog('Profile',mainops) if choice == None: editing == False return payload if choice['title'] == 'Edit': payload.profile = dialogs.edit_list_dialog('Edit Profiles', payload.profile) if choice['title'] == 'Add Webclip': webclip(payload) if choice['title'] == 'Add Wifi': wifi(payload) if choice['title'] == 'Serve': cpload = profile.mkplist(payload) serve.run_server(cpload) if choice['title'] == 'Save': name = dialogs.input_alert('File name') name = name + '.mobileconfig' cpload = profile.mkplist(conf, pload) plistlib.writePlist(cpload, name) return
def search_itunes_api(app_name): params = {'term': term, 'entity': 'iPadSoftware'} return requests.get(ITUNES_API_URL, params=params).json()['results'] def retrieve_image(url): imageBytes = requests.get(url).content return Image.open(io.BytesIO(imageBytes)) def save_image_to_album(img): img.save(".tmp.png", "PNG") album = get_album() asset = photos.create_image_asset(".tmp.png") album.add_assets([asset]) # Prompt for the app to search for term = dialogs.input_alert("App Name", "Enter app to search for", "Spark Readdle") # Search for the app on iTunes results = search_itunes_api(term) # Sometimes we get multiple hits from the search, so prompt # the user to select the app they want if not results: dialogs.alert("No App Found") elif len(results) == 1: result = results[0] else: trackNames = [r['trackName'] for r in results] selectedTrack = dialogs.list_dialog("Select App", trackNames) result = [r for r in results if r['trackName'] == selectedTrack][0]
response = requests.post( url="https://life-timelines.herokuapp.com/log-emoji", data={ "name": self.name, "start": self.start, "end": self.end, "user": self.user, }) if response.status_code == 201: print(response.text) self.logged = True print(response.status_code) return self.logged if __name__ == "__main__": text = dialogs.input_alert("Gimme Emoji (separate by spaces)").split(" ") for word in text: a = Emoji(word) print(a.name) print(a.log()) sys.exit()
def input_alert_action(sender): print(dialogs.input_alert('input alert', 'test message'))
from shutil import copyfile import editor, dialogs src = editor.get_path() copyfile(src, dialogs.input_alert('New Name'))
print('\t错误:%s' % res.status_code) print('\t开始第 %s 次重试。' % retry) else: print('\t下载失败!') return False save_dir = './video' if not os.path.exists(save_dir): os.makedirs(save_dir) url = '' headers = {} if not appex.is_running_extension(): import clipboard url = dialogs.input_alert('请输入链接地址:') else: filepath = appex.get_attachments()[0] if '.har' == filepath[-4:]: import json with open(filepath, 'r') as f: #f=open(filepath,'r') #print('test') r = json.loads(f.readline())['log']['entries'][0]['request'] #print(r) f.close() url = r['url'] for h in r['headers']:
def change_player(self): self.player = dialogs.input_alert('Player:', '', self.player, 'Ok') self.player = self.player if self.player else 'Player' self.score_board.player_label.text = self.player self.score_board.load_highscore() self.board.load_state()
# coding: utf-8 # https://gist.github.com/b6c87590a06081175d8f import Image, photos, dialogs, sys 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:
from shutil import copyfile import editor,dialogs src = editor.get_path() copyfile(src,dialogs.input_alert('New Name'))