def execute(self): """Implements Action.execute.""" print('\n' + MSG_BYE) input(INPUT_EXIT) sys.exit()
def run(self, inverted=False): """Execute the flashcard. It will transition between this states: 1) Content shows the placeholder and will wait for an input to continue. 2) Content is shown and will wait for an input to continue. """ self.draw(show_placeholder=True, inverted=inverted) input() self.draw() input()
def _export_csv(self, subscribers, save_path): input('\n' + SPACE8 + MSG_CSV_DOWNLOAD) print('\n' + SPACE8 + MSG_EXPORT) exporter = ExportCsv() try: exporter.export(subscribers, save_path) except ExportCsvException as e: raise ActionException(SPACE12 + ERROR_CAPTION + str(e)) print(SPACE12 + MSG_DONE)
def _ocr_for_get_gzh_article_by_url_text(self, url): logger.debug( 'vcode appear, using _ocr_for_get_gzh_article_by_url_text') timestr = str(time.time()).replace('.', '') timever = timestr[0:13] + '.' + timestr[13:17] codeurl = 'http://mp.weixin.qq.com/mp/verifycode?cert=' + timever coder = self._session.get(codeurl) if hasattr(self, '_ocr'): result = self._ocr.create(coder.content, 2040) img_code = result['Result'] else: result = None im = readimg(coder.content) im.show() img_code = input("please input code: ") post_url = 'http://mp.weixin.qq.com/mp/verifycode' post_data = {'cert': timever, 'input': img_code} headers = { "User-Agent": self._agent[random.randint(0, len(self._agent) - 1)], 'Host': 'mp.weixin.qq.com', 'Referer': url } rr = self._session.post(post_url, post_data, headers=headers) print(rr.text) remsg = eval(rr.text) if remsg['ret'] != 0: logger.error('cannot jiefeng get_gzh_article because ' + remsg['errmsg']) print(remsg) raise WechatSogouVcodeException( 'cannot jiefeng get_gzh_article because ' + remsg['errmsg']) self._cache.set(config.cache_session_name, self._session) logger.debug('ocr ', remsg['errmsg']) return result
def _select_action(self): action_keys = self._action_titles.keys() print(ACTION_LIST_HEADER) for key in action_keys: print(SPACE4 + str(key) + '. ' + self._action_titles[key]) # Show input prompt until an actual action key is entered key = 0 i = 0 while (key not in action_keys): if (i > 0): print(SPACE8 + MSG_ACTIONS_AVAILABLE + ', '.join(str(num) for num in action_keys)) i += 1 try: key = (int(input('\n' + SPACE4 + INPUT_ACTION))) except ValueError: pass action = self._actions[key] try: action.execute() except ActionException as e: raise AppException(str(e))
def validate_profile_choice(dims): """ ensure proper options are chosen for selecting a single profile """ if dims[0] > 1: profile_choice = int( input( "Multiple profiles detected.\nplease choose which profile to use.\n" )) while profile_choice not in range(dims[0]): profile_choice = int( input("Incorrect selection.\nplease choose {}.\n".format( range(dims[0])))) else: profile_choice = 0 return profile_choice
def validate_calibration(prompt, name): """ ensures proper options are chosen for calibration """ while True: temp_value = input(prompt) try: float(temp_value) if temp_value > 0: return float(temp_value) else: print("invalid {}".format(name)) except: print("invalid {}".format(name))
def choose_display(): """ prompt user to choose scale bar display """ choices = ["d", "theta", "both"] temp_choice = "false" while temp_choice not in choices: temp_choice = input( "Please choose the scale to display.\nd, theta, both\n") if temp_choice not in choices: print("incorrect choice\n") return temp_choice
def _ask_confirmation(self): key = '' keys = [INPUT_YES, INPUT_NO] i = 0 while (key not in keys): if (i > 0): print(SPACE12 + MSG_ACTIONS_AVAILABLE + ', '.join(char for char in keys)) i += 1 key = input('\n' + SPACE8 + INPUT_YES_NO).upper() if (key == INPUT_YES): return True return False
def check_savepath(savepath): save_results = True if not os.path.exists(os.path.dirname(savepath)): try: os.makedirs(os.path.dirname(savepath)) except OSError as exc: if exc.errno != errno.EEXIST: raise # if file exists elif os.path.exists(savepath): # ask if user wants to rewrite rewrite = input( "The file '{}' already exists. Would you like to write over it? (y/n)" .format(os.path.relpath(savepath))) if rewrite == 'n': save_results = False return save_results
def provide_family(): """ prompt user and ensure proper selection of base Crystal family """ family = None while family is None: temp_choice = input( "Would you like to suggest a crystal family? yes or no\n") if temp_choice == "yes": family = temp_choice elif temp_choice == "no": family = temp_choice else: print("Invalid choice. Please choose yes or no\n") return family
def choose_peaks(peak_locs, display_type): """ prompt user to select which peaks to classify on """ d = peak_locs["d_spacing"] theta = peak_locs["2theta"] vec = peak_locs["vec"] if display_type == "d" or display_type == "both": print(d) if display_type == "theta" or display_type == "both": print(theta) maximum = min(len(d), len(theta)) print(maximum, len(d), len(theta)) raw_choices = input( "Choose which peaks you'd like to select separated by spaces.\n" ).split(" ") temp_choices = [] for choice in raw_choices: try: temp_index = int(choice) if temp_index > 0 and temp_index <= maximum and temp_index not in temp_choices: temp_choices.append(temp_index) else: print("index {} outside of available peaks".format(temp_index)) except: print("couldn't convert {} into an index".format(choice)) print(temp_choices) temp_locs = { "d_spacing": [d[i - 1] for i in temp_choices], "2theta": [theta[i - 1] for i in temp_choices], "vec": [vec[i - 1] for i in temp_choices] } return temp_locs
def _jiefeng(self): """对于出现验证码,识别验证码,解封 Args: ruokuai: 是否采用若快打码平台 Raises: WechatSogouVcodeException: 解封失败,可能验证码识别失败 """ logger.debug('vcode appear, using _jiefeng') codeurl = 'http://weixin.sogou.com/antispider/util/seccode.php?tc=' + str( time.time())[0:10] coder = self._session.get(codeurl) if hasattr(self, '_ocr'): result = self._ocr.create(coder.content, 3060) img_code = result['Result'] else: im = readimg(coder.content) im.show() img_code = input("please input code: ") post_url = 'http://weixin.sogou.com/antispider/thank.php' post_data = {'c': img_code, 'r': quote(self._vcode_url), 'v': 5} headers = { "User-Agent": self._agent[random.randint(0, len(self._agent) - 1)], 'Host': 'weixin.sogou.com', 'Referer': 'http://weixin.sogou.com/antispider/?from=%2f' + quote(self._vcode_url.replace('http://', '')) } rr = self._session.post(post_url, post_data, headers=headers) remsg = eval(rr.content) if remsg['code'] != 0: logger.error('cannot jiefeng because ' + remsg['msg']) raise WechatSogouVcodeException('cannot jiefeng because ' + remsg['msg']) self._cache.set(config.cache_session_name, self._session) print('ocr ', remsg['msg'])
def _authorize(self): print('\n' + MSG_AUTH) i = 0 manual_auth = False parse_success = False # Try to sign in APP_AUTHORIZE_RETRIES+1 times while (not parse_success): i += 1 if (i == APP_AUTHORIZE_RETRIES + 2): break if (i > 1): print('\n' + SPACE4 + MSG_AUTH_RETRY + '\n') login = input(SPACE4 + INPUT_USERNAME) secret = getpass.getpass(SPACE4 + INPUT_PASSWORD) # Try to get the verification code try: parse_success = self._client.authorize_terminal(login, secret) except ClientException as e: # Will have to auth manually manual_auth = True break except ClientAuthException as e: # Wrong creds? print('\n' + SPACE4 + str(e)) continue except ClientAuthPageException: # Can't parse the response page print ('\n' + SPACE4 + MSG_AUTH_PAGE_PARSE) manual_auth = True break browser_success = False manual_success = False # Will have to to sign-in via the AWeber page if (not parse_success) or (manual_auth): print('\n' + SPACE4 + MSG_AUTH_MANUAL) print(SPACE8 + self._client.auth_url) # Open the auth web page try: browser_success = self._client.authorize_browser() except ClientAuthException as e: raise AppException(SPACE4 + ERROR_CAPTION + str(e)) # Ask the user to input the verification code he got from the # web page above and try to authorize the app via the API. if (browser_success): i = 0 while (not manual_success): i += 1 if (i == APP_AUTHORIZE_RETRIES + 2): break if (i > 1): print('\n' + SPACE12 + MSG_AUTH_RETRY + '\n') code = input(SPACE8 + INPUT_CODE) try: manual_success = self._client.verify_code(code) except ClientException as e: print('\n' + SPACE12 + ERROR_CODE) if (manual_success): break if (not parse_success) and (not manual_success): raise AppException('\n' + ERROR_AUTH)
def label_road_network(input_shp, road_network_geojson, attributes, geojson_outf, rename_attributes = None): #####################append_city_names##################### # read links geojson ''' Generalized function of append_city_names: Allows user to specify which attributes to keep from the input shape file. Spatial join shape file with network, so that network file now has identifying labels - input_shp: type str, filepath for generalized shapefile for cities, neighborhoods, from any state - road_network_geojson: type str, filepath for input geoJSON network file - attributes: type str OR str array, selected attributes that will be joined - geojson_outf: type str, filepath for output file with identifying labels - rename_attributes: type str OR str array, either string or array of strings (should match attributes), can be used if user would like to rename the attributes to more user-friendly names Example: label_road_network('maryland_counties.shp','network.geojson','countyname00','new_network.geojson', 'CountyName') ''' links = gpd.GeoDataFrame.from_file(road_network_geojson) # read input shapefile shape = gpd.GeoDataFrame.from_file(input_shp) # if only one attribute if type(attributes) == str: attributes = [attributes] # check if column name in input_shp for x in attributes: if x not in shape.columns: raise ValueError("Column name {} is not in input_shp".format(x)) if len(attributes) != (len(rename_attributes)): raise ValueError("Number of attributes different from number of rename attributes.") rename_columns = {} for i in range(len(attributes)): rename_columns.update({attributes[i]:rename_attributes[i]}) shape = shape.rename(columns = rename_columns) # chedk if each attribute is already a property in the road network for x in rename_attributes: if x in links.columns: rejoin = input("Attribute '{}' already in the network geojson, do you want to redo join? (y/n)".format(x)) if rejoin: links = links.drop(x, 1) else: rename_attributes.remove(x) # if there are any files left to join if len(rename_attributes) == 0: print ("There are no new attributes to join") return None rename_attributes.append('geometry') shape = shape[rename_attributes] # spatial join links_w_city = sjoin(links, shape, 'left') links_w_city = links_w_city.reset_index().drop_duplicates(subset='index').set_index('index') links_w_city = links_w_city.drop('index_right',1) save_results = check_savepath(geojson_outf) if save_results: with open(geojson_outf, 'w') as f: f.write(links_w_city.to_json())
from __future__ import print_function from future.builtins.misc import input ISYname = "" ans = "" ISYIP = "" ISYUSER = "" ISYPWD = "" exswitch = "" while not ans in ('y', 'Y', 'n', 'N'): ans = input("Set up minimal example system?") if ans in ('y', 'Y'): go = "" while not go in ('y', 'Y'): ISYname = input("Name to use for the ISY hub (defaults to ISY): ") if ISYname == "": ISYname = "ISY" ISYIP = input("full URL to access ISY: ") if ISYIP.endswith('/'): ISYIP = ISYIP[0:-1] ISYUSER = input("ISY user name: ") ISYPWD = input("ISY password: "******"Example switch to use (ISY name): ") print("ISY Name: " + ISYname) print("IP: " + ISYIP) print("USER: "******"PASSWORD: "******"SWITCH: " + "[[" + exswitch + "]]") go = input("OK? (y/n)") with open('/home/pi/Consoleauth', "w") as f:
def get_next_response(self): return input()
from aweber_tools import App, AppException from future.builtins.misc import input try: app = App('config.cfg') app.run() except AppException as exception: print(str(exception)) input('\nPress any key to exit..')