def _reveal_code(self, code_breakers: List[CodeBreaker], final_code: Code) -> None: def clear_screen(): if os.name == 'nt': os.system('cls') else: os.system('clear') # reveal a random peg position for each breaker, make sure each reveal is a different position final_code_pegs: List[Peg] = final_code.get_pegs() indexes_random_able = list(range(len(final_code_pegs))) for code_breaker in code_breakers: print( messages.MASTERMIND_REVEAL_GUIDE.format( player_name=code_breaker.get_name())) prompt() index_of_indexes_random_able: int = random.randint( 0, len(indexes_random_able) - 1) random_index_to_reveal: int = indexes_random_able[ index_of_indexes_random_able] indexes_random_able.pop(index_of_indexes_random_able) revealed_peg: Peg = final_code_pegs[random_index_to_reveal] print( messages.MASTERMIND_REVEAL_PEG.format( position=random_index_to_reveal + 1, color=revealed_peg.value)) print(messages.MASTERMIND_CLEAR_SCREEN) prompt() clear_screen()
def main(): source = 'https://raw.githubusercontent.com/EnergizedProtection/block/master/basic/formats/hosts' backup_suffix = '.blocknsbackup' if os.getuid() != 0: pr('This program should run as root in order to edit system hosts file', 'BAD') exit(1) hosts = find_hosts_file() pr('Using hosts file: ' + hosts, 'DOT') if os.path.isfile(hosts + backup_suffix): pr('[Status %s]' % (Term.OKGREEN + Term.BOLD + 'APPLIED' + Term.ENDC), 'DOT') pr('Press [ENTER] to restore default hosts file', 'DOT') utils.prompt() shutil.move(hosts + backup_suffix, hosts) pr('Blocklist restored successfully, probably a restart is required!', 'GOOD') else: pr('Status: %s' % (Term.FAIL + Term.BOLD + 'NOT APPLIED' + Term.ENDC), 'DOT') pr('Press [ENTER] to download and install system DNS ad blocker', 'DOT') utils.prompt() shutil.copy(hosts, hosts + backup_suffix) pr('Fetching %s' % source, 'GOOD') data, tt = utils.download_blocklist(source) pr('%s bytes downloaded in %f seconds' % (len(data), tt), 'DOT') with open(hosts, 'w') as f: f.write(data) pr('Blocklist applied successfully, probably a restart is required!', 'GOOD')
def initConfUpdate(key): if (key in CONFIG.keys()): if (utils.prompt("{}: {} Change?".format(key, CONFIG[key]), False)): CONFIG[key] = input("{}: ".format(key)) else: if (utils.prompt("{}: <not set> Set?".format(key), True)): CONFIG[key] = input("{}: ".format(key))
def install_xcode(args, indent=0): echo("On Darwin, developer tools must be installed from Apple servers.", indent=indent, color=Fore.CYAN) echo("On the window that will open, click on \"Get Xcode\", if you want to", indent=indent, color=Fore.CYAN) echo("install the full Apple Development Environment (> 1Gb) or click ", indent=indent, color=Fore.CYAN) echo("on \"Install\" to only install command line tools required", indent=indent, color=Fore.CYAN) echo("by ikez.", indent=indent, color=Fore.CYAN) prompt("Press Return when ready and relaunch ikez when it will be done ! ", indent=indent, color=Fore.RED) exit_code = pretty_execute("Launching Apple developer tools installer", ['xcode-select', '--install'], args, indent=indent) sys.exit(1)
def install_brew(args, indent=0): echo("ikez use \"Homebrew\" (aka brew) package manager to install some", indent=indent, color=Fore.CYAN) echo("required frameworks (eg. libjpeg)", indent=indent, color=Fore.CYAN) echo("and programs (eg. git).", indent=indent, color=Fore.CYAN) echo("Homebrew home is http://brew.sh", indent=indent, color=Fore.CYAN) echo("You must install brew following instructions on the home page that will open.", indent=indent, color=Fore.CYAN) prompt("Press Return when ready and relaunch ikez when it will be done ! ", indent=indent, color=Fore.RED) exit_code = pretty_execute("Opening brew homepage", ['open', 'http://brew.sh'], args, indent=indent) sys.exit(1)
def main(): argvs = sys.argv if len(argvs) != 2: print('usage:\n delete_all_old_files.py <Slack Web API token>\n') exit() end_point = 'https://slack.com/api/' token = argvs[1] token = '?token=' + token # fetch files.list last_month_timestamp = (datetime.now() + timedelta(days=-30)).strftime('%s') files_list = utils.fetch_all_files(end_point + 'files.list' + token + '&ts_to=' + last_month_timestamp) # show your files for f in files_list: print(f['id'], f['url_private']) # files.delete print('------------------------------') print('{0} 件削除します。よろしいですか?'.format(len(files_list))) ans = utils.prompt() if ans == 'y' or ans == 'Y': for f in files_list: print(f['id'], f['url_private']) delete_status = utils.fetch(end_point + 'files.delete' + token + '&file=' + f['id']) print(delete_status) print('complete!!')
def enforcing_odoo_server_database_user(args, indent=0): """ Check supplied PostgreSQL user and password are valid """ echo("Enforcing appserver database user", indent=indent) if not args.password: args.password = args.username # test if user exists if postgresql.pg_user_exists(args.username, args=args, indent=indent + 1): # it exists ; is login password ok exit_code = pg_test_user_connection(args.username, args.password, args.host, args=args, indent=indent + 1) if exit_code: # No ! if args.force: exit_code = postgresql.pg_set_password(args.username, args.password, args, indent=indent + 1) elif not args.unattended: user_permission = (prompt( "User '%s' exists but with another password. Do you want to change his password with '%s' [Y/n] ? " % ( args.username, args.password, ), indent=indent + 1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if user_permission: exit_code = postgresql.pg_set_password(args.username, args.password, args, indent=indent + 2) else: echo( "ERROR: Wrong PostgreSQL password for user '%s'. Aborting Odoo installation." % args.username, indent=indent + 1, color=Fore.RED) echo( "Relaunch install --force or with valid PostgreSQL username and password or create one using 'ikez postgresql createuser' command.", indent=indent + 1, color=Fore.RED) return exit_code else: # User do not exists, create it exit_code = postgresql.pg_create_user(args.username, args.password, args=args, indent=indent + 1) return exit_code
def enforcing_odoo_server_database_user(args, indent=0): """ Check supplied PostgreSQL user and password are valid """ echo("Enforcing appserver database user", indent=indent) if not args.password: args.password = args.username # test if user exists if postgresql.pg_user_exists(args.username, args=args, indent=indent+1): # it exists ; is login password ok exit_code = pg_test_user_connection(args.username, args.password, args.host, args=args, indent=indent+1) if exit_code: # No ! if args.force: exit_code = postgresql.pg_set_password(args.username, args.password, args, indent=indent+1) elif not args.unattended: user_permission = (prompt("User '%s' exists but with another password. Do you want to change his password with '%s' [Y/n] ? " % (args.username, args.password,), indent=indent+1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if user_permission: exit_code = postgresql.pg_set_password(args.username, args.password, args, indent=indent+2) else: echo("ERROR: Wrong PostgreSQL password for user '%s'. Aborting Odoo installation." % args.username, indent=indent+1, color=Fore.RED) echo("Relaunch install --force or with valid PostgreSQL username and password or create one using 'ikez postgresql createuser' command.", indent=indent+1, color=Fore.RED) return exit_code else: # User do not exists, create it exit_code = postgresql.pg_create_user(args.username, args.password, args=args, indent=indent+1) return exit_code
def buy(): # echo current usd balance print "current usd balance: %s" % exchange.usd_balance() # echo ticker print "ticker: %s" % exchange.ticker() # prompt user for how many usd to exchange usd_to_receive = Decimal( utils.prompt("how much usd do you want to exchange?", "[0-9]+")) # subtract fee usd_to_exchange = usd_to_receive * (Decimal('1') / (Decimal('1') + config.commission)) btc_to_send, coin_cost = exchange.market_buy(usd_to_exchange) # log exchange print "market cost to buy coins: %s" % coin_cost print "revenue to sell coins: %s" % usd_to_receive print "profit not including account deposit fees: %s" % (usd_to_receive - coin_cost) ledger.log(usd_to_receive, btc_to_send, coin_cost) # send user btc # prompt user for btc address to send coins to user_addr = utils.prompt_for_addr( lambda s: exchange.send_btc(btc_to_send, s))
def main(): argvs = sys.argv if len(argvs) != 4: print( 'usage:\n delete_all_your_posts_in_direct_message.py <Slack Web API token> <Your Slack name> <Target user name>\n' ) exit() end_point = 'https://slack.com/api/' token, your_name, target_user_name = argvs[1:] token = '?token=' + token # fetch users.list users_list = utils.fetch(end_point + 'users.list' + token) your_id = [ member['id'] for member in users_list['members'] if member.get('name') == your_name ][0] target_user_id = [ member['id'] for member in users_list['members'] if member.get('name') == target_user_name ][0] print('your_id: ' + your_id) print('target_user_id: ' + target_user_id) # fetch im.list im_list = utils.fetch(end_point + 'im.list' + token) target_im_id = [ im['id'] for im in im_list['ims'] if im.get('user') == target_user_id ][0] print('target_im_id: ' + target_im_id) # fetch im.history im_history = utils.fetch_all_history(end_point + 'im.history' + token + '&channel=' + target_im_id + '&count=1000') your_posts_list = [ message for message in im_history if message.get('user') == your_id and message.get('subtype', '') == '' ] # show your posts for message in your_posts_list: print(message['text'].replace('\n', ''), message['ts']) # chat.delete print('------------------------------') print('{0} 件削除します。よろしいですか?'.format(len(your_posts_list))) ans = utils.prompt() if ans == 'y' or ans == 'Y': for message in your_posts_list: print(message['text'].replace('\n', ''), message['ts']) delete_status = utils.fetch(end_point + 'chat.delete' + token + '&ts=' + message['ts'] + '&channel=' + target_im_id) print(delete_status) print('complete!!')
def move(issue_key): """Transition issues""" jra = Jira.get_jira_service(); # Check for exception and ask user to configure issue = jra.get_issue(issue_key) possible_transitions = jra.get_transitions(issue) map(lambda x: click.echo(x['id']+" "+x['name']), possible_transitions) res = prompt("Please enter the id of transition: ", map(lambda x: x['id'], possible_transitions)) click.echo(jra.transition_issue(issue, res))
def main(): argvs = sys.argv if len(argvs) != 4: print( 'usage:\n delete_all_your_files_in_direct_message.py <Slack Web API token> <Your Slack name> <Target user name>\n' ) exit() end_point = 'https://slack.com/api/' token, your_name, target_user_name = argvs[1:] token = '?token=' + token # fetch users.list users_list = utils.fetch(end_point + 'users.list' + token) your_id = [ member['id'] for member in users_list['members'] if member.get('name') == your_name ][0] target_user_id = [ member['id'] for member in users_list['members'] if member.get('name') == target_user_name ][0] print('your_id: ' + your_id) print('target_user_id: ' + target_user_id) # fetch im.list im_list = utils.fetch(end_point + 'im.list' + token) target_im_id = [ im['id'] for im in im_list['ims'] if im.get('user') == target_user_id ][0] print('target_im_id: ' + target_im_id) # fetch files.list your_files_list = utils.fetch_all_files(end_point + 'files.list' + token + '&user='******'ims') ] # show your files for f in target_ims_your_files_list: print(f['id'], f['url_private']) # files.delete print('------------------------------') print('{0} 件削除します。よろしいですか?'.format(len(target_ims_your_files_list))) ans = utils.prompt() if ans == 'y' or ans == 'Y': for f in target_ims_your_files_list: print(f['id'], f['url_private']) delete_status = utils.fetch(end_point + 'files.delete' + token + '&file=' + f['id']) print(delete_status) print('complete!!')
def install_brew(args, indent=0): echo("ikez use \"Homebrew\" (aka brew) package manager to install some", indent=indent, color=Fore.CYAN) echo("required frameworks (eg. libjpeg)", indent=indent, color=Fore.CYAN) echo("and programs (eg. git).", indent=indent, color=Fore.CYAN) echo("Homebrew home is http://brew.sh", indent=indent, color=Fore.CYAN) echo( "You must install brew following instructions on the home page that will open.", indent=indent, color=Fore.CYAN) prompt("Press Return when ready and relaunch ikez when it will be done ! ", indent=indent, color=Fore.RED) exit_code = pretty_execute("Opening brew homepage", ['open', 'http://brew.sh'], args, indent=indent) sys.exit(1)
def deploy(release = True): '''Deploy site to the server''' if release: env.site_username = utils.prompt('site username: '******'site password: ') from static import server_types setup(release) if release: utils.install_environ(release) server = server_types[env.server_type] server.install(release) if release: utils.create_deploy() # call functions in after deploy hook for hook in utils.after_deploy_hook: hook() #.reboot() if not release: return server.result
def _select_game() -> Game: selection: str = prompt() selection_lower: str = selection.lower() if selection_lower == 'a': return Original2P() elif selection_lower == 'b': return Original1P() elif selection_lower == 'c': return Mastermind44() raise MasterMindException(messages.INVALID_SELECTION)
def setup(args): selections = [(('/scripts/msl-setup.sh', "MSL Dev PC"), "MSL Dev PC"), (('/scripts/ttb-setup.sh', "Turtlebot PC"), "Turtlebot PC")] selected = utils.showSelection("What do you want to setup?", selections) if (utils.prompt("Do you really want to start the {} setup?".format( selected[1]))): call(['sudo', DIR + selected[0]])
def _prompt_game_start(self) -> bool: """ prompt user to play the game or quit """ print(messages.PROMPT_PLAY_OR_QUIT) while True: action = prompt().lower() if action != 'p' and action != 'q': print(messages.INVALID_SELECTION) continue print() return action == 'p'
def scrape_all_jobs(self): """ Scrape for all Craigslist jobs and output into CSV files. In interactive mode, single-domain parsing is allowed. """ logger.debug("Scraping jobs") jobs_files = get_matching_csv_files(CLJobScraper.DOMAINS_ROOT_FILENAME) if not jobs_files : logger.debug("No files found with root filename %s", CLJobScraper.DOMAINS_ROOT_FILENAME) all_domains = [] for filename in jobs_files: with open(filename, "rb") as csv_file: csv_reader = csv.reader(csv_file) header = csv_reader.next() for row in csv_reader: city, domain = row all_domains.append(domain) if self.is_interactive: res = prompt("Scrape all domains?", ("y","N")) if res == "N": print_str = "" for i, domain in enumerate(all_domains, start=1): print_str += "{:<3}. {:<50}".format(i, domain) # 2 domains per line if not(i % 2): print(print_str) print_str = "" print("") res = prompt("What domain do you want to scrape?") try: all_domains = [all_domains[int(res)-1]] except (IndexError, ValueError): raise ValueError("Invalid number provided") for domain in all_domains: self.scrape_jobs(domain)
def clean_up(): rp = get_result_path() for file in sorted_nicely(glob('{}/{}'.format(rp, f))): bnf = basename(file) print_info(file, bnf) t = prompt('Delete? [y/n]', ['y', 'n']) if t == 'y': exec('rm -rf {}'.format(file)) elif t == 'n': print('Skip') else: assert (False) print('Done')
def install_wkhtmltopdf_darwin(args, indent=0): echo( "Installing wkhtmltopdf 0.12.1 (required by Odoo v8 and above to print QWeb reports)", indent=indent) echo( "On Darwin, wkhtmltopdf is installed using an interactive installer from wkhtmltopdf", indent=indent + 1, color=Fore.CYAN) echo("official web site: http://wkhtmltopdf.org", indent=indent + 1, color=Fore.CYAN) command = [ 'wget', 'http://downloads.sourceforge.net/project/wkhtmltopdf/archive/0.12.1/' 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg' ] if not os.path.exists('wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg'): exit_code = pretty_execute("Downloading wkhtmltopdf 0.12.1", command, args, indent=indent + 1) if exit_code: return exit_code prompt( "When you're ready, press Enter to launch wkhtmltopdf installer then relaunch" " ikez when it will be done ! ", indent=indent + 1, color=Fore.RED) exit_code = pretty_execute( "Launching 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg' installer", ['open', 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg'], args, indent=indent + 1) sys.exit(1)
def main(): source = 'https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling/hosts' hosts = 'c:\\Windows\\System32\\Drivers\\etc\\hosts' backup_suffix = '.blocknsbackup' if not os.path.isfile(hosts): print('[X] This version only supports Windows!') exit(3) admin_priv_check() print('[*] Using hosts file: ' + hosts) if os.path.isfile(hosts + backup_suffix): # Backup present print('[Status: APPLIED]') print('[*] Press [ENTER] to restore default hosts file') utils.prompt() shutil.move(hosts + backup_suffix, hosts) print( '[+] Blocklist restored successfully, probably a restart is required!' ) else: print('[Status: NOT APPLIED]') print( '[*] Press [ENTER] to download and install system DNS ad blocker') utils.prompt() shutil.copy(hosts, hosts + backup_suffix) print('[+] Fetching %s' % source) data, tt = utils.download_blocklist(source) print('[*] %s bytes downloaded in %f seconds' % (len(data), tt)) with open(hosts, 'wb') as f: f.write(data.encode('utf-8')) print( '[+] Blocklist applied successfully, probably a restart is required!' )
def _process_prompt_breaker_guessing(self, code_breaker: CodeBreaker, final_code: Code) -> AttemptFeedback: """ prompt breaker to input the code, then return the the feedback of his attempt """ attempt_code: Optional[Code] = None while attempt_code is None: attempt_input: str = prompt() try: attempt_code = Code.parse(attempt_input, self._game_rule) except CodeParsingException: print( MessageBankInterface.get_unparsable_token_mssg( self._game_rule.get_max_code_peg(), self._game_rule.allow_blank())) return code_breaker.make_a_guess(attempt_code, final_code)
def repos(args): selections = [('mslws', "MSL Workspace"), ('ttbws', "TurtleBot Workspace")] selected_ws = utils.showSelection( "Repos of which workspace do you want to change?", selections) if not checkConfig(selected_ws): return repoFolders = os.listdir( path.join(os.path.expanduser(CONFIG[selected_ws]), "src")) remoteRepos = OrderedDict() ghRepos = utils.getGithubRepos("CarpeNoctem") for repo in ghRepos: remoteRepos[repo["name"]] = repo localRepos = dict( filter(lambda x: x[1]['name'] in repoFolders, remoteRepos.items())) # show selection entries = OrderedDict( map(lambda x: (x[0], x[1]['name']), remoteRepos.items())) selected_repos = utils.showMultiSelection(u'GitHub Repositories', entries, selectedKeys=localRepos.keys()) print("=============== CHANGES ===============") remove = set(localRepos.keys()) - set(selected_repos) print("Remove:", list(remove)) add = set(selected_repos) - set(localRepos.keys()) print("Add:", list(add)) print("=======================================") if (len(remove) > 0 and not utils.prompt( "WARNING: Removed repos will be deleted! Continue?", False)): print("Aborting!") return for repo in remove: shutil.rmtree( path.join(os.path.expanduser(CONFIG[selected_ws]), "src/" + repo)) for repo in add: utils.cloneRepo( remoteRepos[repo]['ssh_url'], path.join(os.path.expanduser(CONFIG[selected_ws]), "src/" + repo))
def __prompt_final_code(game_rule: "GameRule") -> Code: """ prompt player to input the final code :param: game_rule: to check whether the final code follow the game rule :return: the final code object""" while True: try: print(messages.FINAL_CODE_ENTER) prompted_final_code_value: str = prompt() parsed_final_code_value: Code = Code.parse( prompted_final_code_value, game_rule) print(messages.FINAL_CODE_REENTER) prompted_final_code_value_reenter: str = prompt() if prompted_final_code_value != prompted_final_code_value_reenter: raise MasterMindException( messages.REENTER_CODE_VALUES_NOT_MATCH) print(messages.FINAL_CODE_STORED) return parsed_final_code_value except CodeParsingException: print( MessageBankInterface.get_unparsable_token_mssg( game_rule.get_max_code_peg(), game_rule.allow_blank())) except MasterMindException as e: print(e)
def install_xcode(args, indent=0): echo("On Darwin, developer tools must be installed from Apple servers.", indent=indent, color=Fore.CYAN) echo( "On the window that will open, click on \"Get Xcode\", if you want to", indent=indent, color=Fore.CYAN) echo("install the full Apple Development Environment (> 1Gb) or click ", indent=indent, color=Fore.CYAN) echo("on \"Install\" to only install command line tools required", indent=indent, color=Fore.CYAN) echo("by ikez.", indent=indent, color=Fore.CYAN) prompt("Press Return when ready and relaunch ikez when it will be done ! ", indent=indent, color=Fore.RED) exit_code = pretty_execute("Launching Apple developer tools installer", ['xcode-select', '--install'], args, indent=indent) sys.exit(1)
def install_wkhtmltopdf_darwin(args, indent=0): echo("Installing wkhtmltopdf 0.12.1 (required by Odoo v8 and above to print QWeb reports)", indent=indent) echo("On Darwin, wkhtmltopdf is installed using an interactive installer from wkhtmltopdf", indent=indent+1, color=Fore.CYAN) echo("official web site: http://wkhtmltopdf.org", indent=indent+1, color=Fore.CYAN) command = [ 'wget', 'http://downloads.sourceforge.net/project/wkhtmltopdf/archive/0.12.1/' 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg' ] if not os.path.exists('wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg'): exit_code = pretty_execute("Downloading wkhtmltopdf 0.12.1", command, args, indent=indent+1) if exit_code: return exit_code prompt("When you're ready, press Enter to launch wkhtmltopdf installer then relaunch" " ikez when it will be done ! ", indent=indent+1, color=Fore.RED) exit_code = pretty_execute("Launching 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg' installer", ['open', 'wkhtmltox-0.12.1_osx-cocoa-x86-64.pkg'], args, indent=indent+1) sys.exit(1)
def rename_task_monster(self): if not len(self.tasks): print("No tasks are currently recorded. Please add a task.") return if self.selected_task is None: print("No current task selected.") return if confirm_prompt("rename the task's monster (" + self.selected_task.monster + ")"): new_monster = prompt("Enter new monster name:") old_monster = self.selected_task.monster self.selected_task.monster = new_monster print("Successfully renamed " + old_monster + " to " + new_monster + ".") else: print("Operation aborted.")
def rename(): rp = get_result_path() for dirpath, dirs, files in walk('{}/{}'.format(rp, f)): for bfn in files: if target in bfn: continue dest_bfn = bfn.replace(source, target) t = prompt('Rename {} to {}? [y/n]'.format(bfn, dest_bfn), ['y', 'n']) if t == 'y': exec('mv {} {}'.format(join(dirpath, bfn), join(dirpath, dest_bfn))) elif t == 'n': print('Skip') else: assert (False) print('Done')
def init(args): print("Configure...") keys = ['mslws', 'ttbws'] for key in keys: initConfUpdate(key) print() print("New Config:") for key, value in CONFIG.items(): print("{}: '{}'".format(key, value)) print() if (utils.prompt("Save changes?", True)): saveConfig() print("Config saved.")
def main(): argvs = sys.argv if len(argvs) != 4: print('usage:\n delete_all_your_files_in_direct_message.py <Slack Web API token> <Your Slack name> <Target user name>\n') exit() end_point = 'https://slack.com/api/' token, your_name, target_user_name = argvs[1:] token = '?token=' + token # fetch users.list users_list = utils.fetch(end_point + 'users.list' + token) your_id = [member['id'] for member in users_list['members'] if member.get('name') == your_name][0] target_user_id = [member['id'] for member in users_list['members'] if member.get('name') == target_user_name][0] print('your_id: ' + your_id) print('target_user_id: ' + target_user_id) # fetch im.list im_list = utils.fetch(end_point + 'im.list' + token) target_im_id = [im['id'] for im in im_list['ims'] if im.get('user') == target_user_id][0] print('target_im_id: ' + target_im_id) # fetch files.list your_files_list = utils.fetch_all_files(end_point + 'files.list' + token + '&user='******'ims')] # show your files for f in target_ims_your_files_list: print(f['id'], f['url_private']) # files.delete print('------------------------------') print('{0} 件削除します。よろしいですか?'.format(len(target_ims_your_files_list))) ans = utils.prompt() if ans == 'y' or ans == 'Y': for f in target_ims_your_files_list: print(f['id'], f['url_private']) delete_status = utils.fetch(end_point + 'files.delete' + token + '&file=' + f['id']) print(delete_status) print('complete!!')
def main(): argvs = sys.argv if len(argvs) != 4: print('usage:\n delete_all_your_posts_in_direct_message.py <Slack Web API token> <Your Slack name> <Target user name>\n') exit() end_point = 'https://slack.com/api/' token, your_name, target_user_name = argvs[1:] token = '?token=' + token # fetch users.list users_list = utils.fetch(end_point + 'users.list' + token) your_id = [member['id'] for member in users_list['members'] if member.get('name') == your_name][0] target_user_id = [member['id'] for member in users_list['members'] if member.get('name') == target_user_name][0] print('your_id: ' + your_id) print('target_user_id: ' + target_user_id) # fetch im.list im_list = utils.fetch(end_point + 'im.list' + token) target_im_id = [im['id'] for im in im_list['ims'] if im.get('user') == target_user_id][0] print('target_im_id: ' + target_im_id) # fetch im.history im_history = utils.fetch_all_history(end_point + 'im.history' + token + '&channel=' + target_im_id + '&count=1000') your_posts_list = [message for message in im_history if message.get('user') == your_id and message.get('subtype', '') == ''] # show your posts for message in your_posts_list: print(message['text'].replace('\n', ''), message['ts']) # chat.delete print('------------------------------') print('{0} 件削除します。よろしいですか?'.format(len(your_posts_list))) ans = utils.prompt() if ans == 'y' or ans == 'Y': for message in your_posts_list: print(message['text'].replace('\n', ''), message['ts']) delete_status = utils.fetch(end_point + 'chat.delete' + token + '&ts=' + message['ts'] + '&channel=' + target_im_id) print(delete_status) print('complete!!')
def get_next_csv_filename(root_filename, last_index=0, is_interactive=False): """ Get the next CSV filename we should use to avoid overwriting. :param root_filename: Filename the CSV should start with :type root_filename: str :param last_index: Last filename index :type last_index: int :param is_interactive: Script can expect input from end user :type is_interactive: bool :returns: CSV filename :rtype: str """ if last_index == 0: file_index = "" else: file_index = last_index + 1 filename = "{}{}.csv".format(root_filename, file_index) filename_path = os.path.join(CSV_DIR, filename) if os.path.exists(filename_path): if last_index == 0 and is_interactive: # prompt before repeating an operation already done res = prompt(( "{} already exists, you may be repeating an intensive operation. " "Continue?").format(filename), ("y", "N")) if res == "N": ex_msg = "Avoiding operations that would regenerate {}".format( filename) logger.warning(ex_msg) raise IntensiveOpException(ex_msg) return get_next_csv_filename(root_filename, file_index or 1, is_interactive) else: return filename_path
def buy(): # echo current usd balance print "current usd balance: %s" % exchange.usd_balance() # echo ticker print "ticker: %s" % exchange.ticker() # prompt user for how many usd to exchange usd_to_receive = Decimal(utils.prompt("how much usd do you want to exchange?", "[0-9]+")) # subtract fee usd_to_exchange = usd_to_receive * (Decimal('1') / (Decimal('1') + config.commission)) btc_to_send, coin_cost = exchange.market_buy(usd_to_exchange) # log exchange print "market cost to buy coins: %s" % coin_cost print "revenue to sell coins: %s" % usd_to_receive print "profit not including account deposit fees: %s" % (usd_to_receive - coin_cost) ledger.log(usd_to_receive, btc_to_send, coin_cost) # send user btc # prompt user for btc address to send coins to user_addr = utils.prompt_for_addr(lambda s: exchange.send_btc(btc_to_send, s))
def get_next_csv_filename(root_filename, last_index=0, is_interactive=False): """ Get the next CSV filename we should use to avoid overwriting. :param root_filename: Filename the CSV should start with :type root_filename: str :param last_index: Last filename index :type last_index: int :param is_interactive: Script can expect input from end user :type is_interactive: bool :returns: CSV filename :rtype: str """ if last_index == 0: file_index = "" else: file_index = last_index + 1 filename = "{}{}.csv".format(root_filename, file_index) filename_path = os.path.join(CSV_DIR, filename) if os.path.exists(filename_path): if last_index == 0 and is_interactive: # prompt before repeating an operation already done res = prompt(("{} already exists, you may be repeating an intensive operation. " "Continue?").format(filename), ("y", "N")) if res == "N": ex_msg = "Avoiding operations that would regenerate {}".format(filename) logger.warning(ex_msg) raise IntensiveOpException(ex_msg) return get_next_csv_filename(root_filename, file_index or 1, is_interactive) else: return filename_path
def switchWifi(args): if len(args) < 1: print("Wi-Fi name missing, possible choices:", list(network.WIFIS)) return if args[0] not in network.WIFIS: print("Wrong Wi-Fi name! Possible choices:", network.WIFIS) return # get hostname hostname_file = open("/etc/hostname", "r") hostname = hostname_file.read().strip() if hostname in ROBOTS: (robot_type, robot_id) = ROBOTS[hostname] if utils.prompt( "WARNING: /etc/network/interfaces will be replaced! Continue?", False): network.update_interfaces(robot_type, robot_id, args[0]) else: print("Canceled by user.") else: print("You are not on a robot!")
def exp1(): """ Run baselines on real datasets. Take a while. """ dataset = prompt('Which dataset?') row_train = prompt('Train or test for row graphs? (1/0)') == '1' row_graphs = load_data(dataset, train=row_train).graphs col_train = prompt('Train or test for col graphs? (1/0)') == '1' col_graphs = load_data(dataset, train=col_train).graphs ds_metric = prompt('Which metric (ged|mcs)?', options=['ged', 'mcs']) algo = prompt('Which algorthm?') timeout_temp = prompt('Time limit in min? Empty for no limit') timeout = float(timeout_temp) * 60 if timeout_temp else None exec_turnoff_print() num_cpu = prompt_get_cpu() computer_name = prompt_get_computer_name() try: real_dataset_run_helper(computer_name, dataset, ds_metric, algo, row_graphs, col_graphs, num_cpu, timeout) except Exception as e: traceback.print_exc()
parser.add_argument("--data", help="Use post method to send the data(dict)", type=str) #{\"searchFor\":\"hi\",\"goButton\":\"go\"} parser.add_argument('--header', help='Add header', dest='add_header', nargs='?', const=True) parser.add_argument('--proxy', help='use prox(y|ies)', dest='proxy', action='store_false') args = parser.parse_args() if type(args.add_header) == bool: header = extractHeaders(prompt()) elif type(args.add_header) == str: header = extractHeaders(args.add_header) else: header = HEADER # 代理 if not args.proxy: config.PROXIES = {} if args.data: # 有额外的dict data 则是post url, GET, data, PATH = args.url, False, json.loads(args.data), False elif args.path: # 参数在path 一般是get url, GET, data, PATH = args.url, True, None, True else: # 不然则是get url, GET, data, PATH = args.url, True, None, False analyse(url, GET, data, PATH, header)
def real_dataset_run_helper(computer_name, dataset, ds_metric, algo, row_graphs, col_graphs, num_cpu, timeout): if ds_metric == 'ged': func = ged elif ds_metric == 'mcs': func = mcs # For MCS, since the solver can handle labeled and unlabeled graphs, but the compressed # encoding must be labeled (need to tell it to ignore labels or not). # TODO: this should go in some kind of config file specific for mcs if node_has_type_attrib(row_graphs[0]): labeled = True label_key = 'type' print('Has node type') else: labeled = False label_key = '' print('Does not have node type') else: raise RuntimeError('Unknown distance similarity metric {}'.format(ds_metric)) m = len(row_graphs) n = len(col_graphs) ds_mat = np.zeros((m, n)) time_mat = np.zeros((m, n)) outdir = '{}/{}'.format(get_result_path(), dataset) create_dir_if_not_exists(outdir + '/csv') create_dir_if_not_exists(outdir + '/{}'.format(ds_metric)) create_dir_if_not_exists(outdir + '/time') exsiting_csv = prompt('File path to exsiting csv files?') exsiting_entries = load_from_exsiting_csv(exsiting_csv, ds_metric, skip_eval=False) is_symmetric = prompt('Is the ds matrix symmetric? (1/0)', options=['0', '1']) == '1' if is_symmetric: assert (m == n) smart_needed = prompt('Is smart pair sorting needed? (1/0)', options=['0', '1']) == '1' csv_fn = '{}/csv/{}_{}_{}_{}_{}_{}cpus.csv'.format( outdir, ds_metric, dataset, algo, get_ts(), computer_name, num_cpu) file = open(csv_fn, 'w') print('Saving to {}'.format(csv_fn)) if ds_metric == 'ged': print_and_log('i,j,i_gid,j_gid,i_node,j_node,i_edge,j_edge,ged,lcnt,time(msec)', file) else: print_and_log( 'i,j,i_gid,j_gid,i_node,j_node,i_edge,j_edge,mcs,node_mapping,edge_mapping,time(msec)', file) # Multiprocessing. pool = mp.Pool(processes=num_cpu) # Submit to pool workers. results = {} pairs_to_run = get_all_pairs_to_run(row_graphs, col_graphs, smart_needed) for k, (i, j) in enumerate(pairs_to_run): g1, g2 = row_graphs[i], col_graphs[j] i_gid, j_gid = g1.graph['gid'], g2.graph['gid'] if (i_gid, j_gid) in exsiting_entries: continue if is_symmetric and (j_gid, i_gid) in exsiting_entries: continue if ds_metric == 'mcs': results[(i, j)] = pool.apply_async( func, args=(g1, g2, algo, labeled, label_key, True, True, timeout,)) else: results[(i, j)] = pool.apply_async( func, args=(g1, g2, algo, True, True, timeout,)) print_progress(k, m, n, 'submit: {} {} {} {} cpus;'. format(algo, dataset, computer_name, num_cpu)) # Retrieve results from pool workers or a loaded csv file (previous run). for k, (i, j) in enumerate(pairs_to_run): print_progress(k, m, n, 'work: {} {} {} {} {} cpus;'. format(ds_metric, algo, dataset, computer_name, num_cpu)) g1, g2 = row_graphs[i], col_graphs[j] i_gid, j_gid = g1.graph['gid'], g2.graph['gid'] if (i, j) not in results: lcnt, mcs_node_mapping, mcs_edge_mapping = None, None, None tmp = exsiting_entries.get((i_gid, j_gid)) if tmp: if ds_metric == 'ged': i_gid, j_gid, i_node, j_node, ds, lcnt, t = tmp else: i_gid, j_gid, i_node, j_node, ds, mcs_node_mapping, mcs_edge_mapping, t = tmp else: assert (is_symmetric) get_from = exsiting_entries[(j_gid, i_gid)] if ds_metric == 'ged': j_gid, i_gid, j_node, i_node, ds, lcnt, t = \ get_from else: j_gid, i_gid, j_node, i_node, ds, mcs_node_mapping, mcs_edge_mapping, t = \ get_from if ds_metric == 'ged': assert (lcnt is not None) assert (g1.graph['gid'] == i_gid) assert (g2.graph['gid'] == j_gid) assert (g1.number_of_nodes() == i_node) assert (g2.number_of_nodes() == j_node) s = form_ged_print_string(i, j, g1, g2, ds, lcnt, t) else: assert (mcs_node_mapping is not None and mcs_edge_mapping is not None) s = form_mcs_print_string( i, j, g1, g2, ds, mcs_node_mapping, mcs_edge_mapping, t) else: if ds_metric == 'ged': ds, lcnt, g1_a, g2_a, t = results[(i, j)].get() i_gid, j_gid, i_node, j_node = \ g1.graph['gid'], g2.graph['gid'], \ g1.number_of_nodes(), g2.number_of_nodes() assert (g1.number_of_nodes() == g1_a.number_of_nodes()) assert (g2.number_of_nodes() == g2_a.number_of_nodes()) exsiting_entries[(i_gid, j_gid)] = \ (i_gid, j_gid, i_node, j_node, ds, lcnt, t) s = form_ged_print_string(i, j, g1, g2, ds, lcnt, t) else: # MCS ds, mcs_node_mapping, mcs_edge_mapping, t = \ results[(i, j)].get() exsiting_entries[(i_gid, j_gid)] = \ (ds, mcs_node_mapping, mcs_edge_mapping, t) s = form_mcs_print_string( i, j, g1, g2, ds, mcs_node_mapping, mcs_edge_mapping, t) print_and_log(s, file) if ds_metric == 'mcs' and (i_gid, j_gid) in exsiting_entries: # Save memory, clear the mappings since they're saved to file. exsiting_entries[(i_gid, j_gid)] = list(exsiting_entries[(i_gid, j_gid)]) exsiting_entries[(i_gid, j_gid)][1] = {} exsiting_entries[(i_gid, j_gid)][2] = {} ds_mat[i][j] = ds time_mat[i][j] = t file.close() save_as_np(outdir, ds_metric, ds_mat, time_mat, get_ts(), dataset, row_graphs, col_graphs, algo, computer_name, num_cpu)
def q2(): dancing = prompt('what is the unicorn dancing on') if dancing == "what do you mean": print('you are good at this') return True return False
def q3(): name = prompt('what is megaman's real name') if name == "rock": print('you got all the questions right you are the megaman master') return True return False
def q1(): villian = prompt('who is the main villian of the megaman series') if villian == "dr.wily": print('you are correct') return True return False
if __name__ == "__main__": service = UserNamesHandler() your_ip = service.get_ip_address('eth0') if len(sys.argv) < 2 : print 'Usage : python telnet.py hostname port' sys.exit() name = raw_input("Your name: ") user_obj = UserData(name=name) host = sys.argv[1] port = settings.PORT client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.settimeout(2) # Connect Server try: client_socket.connect((host, port)) except Exception as e: print 'Unable to connect..',e sys.exit() print 'Connection Established..successfully..' prompt(user_obj) obj = ChatService() while 1: obj.chat(client_socket, user_obj)
def __repr__(self): return "ec2 | %s | %s" % (prompt(self.region), data(self.instance_id or 'all instances') )
def q1(): color = prompt('what is the color of the unicorn fur') if color == "i dont care": print('you are correct') return True return False
## IMPORT MODULES/PACKAGES from psychopy import event, visual import os import utils as ut ## SEED DATAFILES, QUERY CONDITION: subject_dir = os.path.join(os.getcwd(), 'data') [data, pnum, cnd] = ut.prompt() ## DEFINE PSYCHOPY ENVIRONMENT VARIABLES win = visual.Window(fullscr=True, units='pix', color=(1, 1, 1)) # IMAGES image = visual.ImageStim(win, size=(450, 450)) alt_img = visual.ImageStim(win, size=(450, 450)) imgs = [image, alt_img] # TEXT instructions = visual.TextStim(win, text='', font='High Tower Text', height=30, wrapWidth=800, color=(0, 0, 0)) correct = visual.TextStim(win, text='', font='High Tower Text', height=30, wrapWidth=800, color=(0, 0, 0)) incorrect = visual.TextStim(win,
def __repr__(self): return "lb | %s | %s" % (prompt(self.region), data(self.connected_to or 'Not connected') )
def __repr__(self): return "s3 | %s | %s" % (prompt(self.region), data(self.bucket or 'all instances') )
def prompt(self): return prompt('%s > ' % ( error('boto not configured') if not self._ready else self.context or error('context not set')) )
def install_virtualenv(args, indent=0): echo("Installing virtualenv", indent) if not System.virtualenv_version: echo("virtualenv is not installed !!!!", indent+1, Fore.CYAN) echo("ikez (and buildout) requires a virtualenv version > 1.9.1", indent+1, Fore.CYAN) if System.system_name == 'debian': if System.system_major_version == '7': echo("On Wheezy (Debian 7.8), default virtualenv version is too old for ikez (and buildout).", indent=indent+1, color=Fore.CYAN) echo("So we will install recent setuptools (14.1.1) and virtualenv (12.0.7) from pypi.", indent=indent+1, color=Fore.CYAN) echo("Please look there for detail:", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/setuptools", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/virtualenv", indent=indent+1, color=Fore.CYAN) if not args.force: user_permission = (prompt("Are you Ok ? [Y/n] ", indent=indent+1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if not user_permission: return 1 return install_virtualenv_from_pypi(args, indent=indent+1) elif System.system_major_version == '8': echo("On Jessie (Debian 8), default virtualenv version is too old for ikez (and buildout).", indent=indent+1, color=Fore.CYAN) echo("So we will install recent setuptools (14.1.1) and virtualenv (12.0.7) from pypi.", indent=indent+1, color=Fore.CYAN) echo("Please look there for detail:", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/setuptools", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/virtualenv", indent=indent+1, color=Fore.CYAN) if not args.force: user_permission = (prompt("Are you Ok ? [Y/n] ", indent=indent+1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if not user_permission: return 1 return install_virtualenv_from_pypi(args, indent=indent+1) else: echo("You are running ikez on an unsupported Debian version ! ikez supports only" "precise and trusty for now.", color=Fore.RED) raise NotImplementedError() elif System.system_name == 'ubuntu': if System.system_major_version == '12': echo("On Precise (Ubuntu 12), default virtualenv version is too old for ikez (and buildout).", indent=indent+1, color=Fore.CYAN) echo("So we will install recent setuptools (14.1.1) and virtualenv (12.0.7) from pypi.", indent=indent+1, color=Fore.CYAN) echo("Please look there for detail:", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/setuptools", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/virtualenv", indent=indent+1, color=Fore.CYAN) if not args.force: user_permission = (prompt("Are you Ok ? [Y/n] ", indent=indent+1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if not user_permission: return 1 return install_virtualenv_from_pypi(args, indent=indent+1) elif System.system_major_version in ('14', '15',): echo("On Ubuntu 14 and 15, default virtualenv version is ok so we just apt-get it.", indent=indent+1, color=Fore.CYAN) exit_code = pretty_execute("Installing Ubuntu distribution virtualenv", ['sudo', 'apt-get', 'install', '-y', 'python-virtualenv'], args, indent=indent+1) return exit_code else: echo("You are running ikez on an unsupported Ubuntu version ! ikez supports only " "Ubuntu 14 and 15 for now.", color=Fore.RED) raise NotImplementedError() elif System.system_name == 'darwin': echo("On Darwin / MacOS, we install recent setuptools (14.1.1) and virtualenv (12.0.7) from pypi.", indent=indent+1, color=Fore.CYAN) echo("Please look there for detail:", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/setuptools", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/virtualenv", indent=indent+1, color=Fore.CYAN) if not args.force: user_permission = (prompt("Are you Ok ? [Y/n] ", indent=indent+1, color=Fore.RED) or 'Y').lower() in ['y', 'yes', 'o', 'oui'] if not user_permission: return 1 return install_virtualenv_from_pypi(args, indent=indent+1) else: raise NotImplementedError() elif semver.compare(System.virtualenv_version, '1.9.1') > 0: print "No need to install virtualenv ; installed version ('%s') is ok (> '1.9.1')." % System.virtualenv_version return 126 else: echo("Installed virtualenv version '%s' is too old ! " % System.virtualenv_version, indent=indent+1, color=Fore.CYAN) echo("ikez requires virtualenv version > 1.9.1", indent=indent+1, color=Fore.CYAN) echo("Look at: ", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/setuptools", indent=indent+1, color=Fore.CYAN) echo(" - https://pypi.python.org/pypi/virtualenv", indent=indent+1, color=Fore.CYAN) return 1 #
def q2(): person = prompt('who was the person who created megaman') if person == "dr.light": print('you are correct') return True return False
def pick_points(image, points=None, close_fig=False, filename=None): """ Plots an image and allows the user to select points on it. @param points, if not None use this set of points as the inital set instead of the automatic boundary points @param close_fig, Close the figure after displaying @param filename, Save the figure at this file if specified and save-files is specified @return The set of chosen points """ plt.ion() fig = plt.figure() fig_plot = fig.add_subplot(111) # Always want to have points on the boundary if points is None: points = create_boundary_points(image.shape[:2]) sc = fig_plot.scatter(points[:, 0], points[:, 1]) num_points = points.shape[0] texts = [] def pick_event(event): nonlocal points nonlocal num_points nonlocal texts m = event.mouseevent x, y = np.floor([m.xdata, m.ydata]) print(x, y) #allow removing points, if the user clicks approximately near the chosen point # remove it instead of adding another point at the location distance = np.linalg.norm(points - np.array([x, y]), axis=1) points = points[distance > 8] #If the user clicked near an existing point, remove it if points.shape[0] < num_points: num_points = points.shape[0] for text in texts: fig_plot.texts.remove(text) texts = [] for i, p in enumerate(points): texts.append(fig_plot.text(p[0] + .03, p[1] + .03, i + 1)) # Otherwise add the new point to the list else: num_points = points.shape[0] + 1 txt = fig_plot.text(x + .03, y + .03, num_points) texts.append(txt) points = np.append(points, [[x, y]], axis=0) #Update the set of drawn points sc.set_offsets(points) fig.canvas.draw_idle() #Allow the user to select up to 100 points img = fig_plot.imshow(image, picker=100) fig.canvas.mpl_connect('pick_event', pick_event) fig.show() utils.prompt() if utils.save_files and filename is not None: plt.savefig(filename) if close_fig: plt.close() return np.array(points)
def q3(): texture = prompt('use one word to describe the texture of thier magical fur') if texture == "you're not my dad": print('you got all the answers right congradgulations') return True return False