def show_status(self): table_data=[] temp=[] temp.append('Event') for i in range (number_of_players): temp.append(self.event[i]) table_data.append(temp) temp1=[] temp1.append('Diagnosis') for i in range (number_of_players): temp1.append(self.diagnosis[i]) table_data.append(temp1) temp2=[] temp2.append('Tests') for i in range (number_of_players): temp2.append(self.tests[i]) table_data.append(temp2) table=SingleTable(table_data) table.title=Color('{autored}Node ID:'+self.nodeid+' NodeNum:' + self.nodenum+'{/autored}') table.inner_row_border="True" print "" print table.table
def transfer_pokemon(self): pokemon_list = [p for p in self.pokemon if p.get('transfer', False) and not p['is_favorite'] and not p['is_shiny'] and not p['has_costume']] total_transfers = len(pokemon_list) transfers_completed = 0 if not pokemon_list: print u'No Pokémon scheduled to transfer.' return table_data = [ [u'Pokémon', 'CP', 'IV %', 'ATK', 'DEF', 'STA'] ] print 'About to transfer %d Pokémon…' % total_transfers transfer_list = [] for pokemon in pokemon_list: # Remove the Pokémon from the list, so that we don’t try to rename # it later. self.pokemon.remove(pokemon) pokedex_number = pokemon['pokedex_number'] pokemon_name = self.pokemon_list[str(pokedex_number)] table_data.append([ pokemon_name, pokemon['cp'], '{0:.0f}%'.format(pokemon['iv_percent']), pokemon['attack'], pokemon['defense'], pokemon['stamina'] ]) transfer_list.append(pokemon['id']) table = SingleTable(table_data) table.justify_columns = { 0: 'left', 1: 'right', 2: 'right', 3: 'right', 4: 'right', 5: 'right', 6: 'left' } print u'The following Pokémon are about to be transferred:' print table.table # After logging in, wait a while before starting to rename Pokémon, like a # human player would. self.config.min_delay = total_transfers * 2 self.config.max_delay = total_transfers * 4 self.wait_randomly() response = self.api.release_pokemon(pokemon_ids=transfer_list) try: result = response['responses']['RELEASE_POKEMON']['result'] except KeyError: print 'Failed:' print response status = 'error' pass else: if result == 1: status = 'success' print 'Transfer successful.' else: status = 'error' print 'Transfer failed. Error code: %s' % str(result)
def print_compare(self, src, dst, a, b, sym): from colorclass import Color, Windows from terminaltables import SingleTable Windows.enable(auto_colors=True, reset_atexit=True) # Does nothing if not on Windows. max_width = 50 l = [Color('{autocyan}' + self.wrap_text(src, max_width) + '{/autocyan}'), sym[0], Color('{autocyan}' + self.wrap_text(dst, max_width) + '{/autocyan}')] table_data = [] table_data.append(l) for key, value in a.items(): l = [self.wrap_text(key, max_width), sym[1], ""] table_data.append(l) for key, value in b.items(): l = ["", sym[2], self.wrap_text(key, max_width)] table_data.append(l) table = SingleTable(table_data) table.inner_heading_row_border = True table.inner_row_border = True print(table.table)
def print_table(table_headers, table_values, table_title='', table_view='v'): os.system("cls") if table_view == 'v': table_data = [table_headers] for i in range(len(table_values[0])): dataline = [] for j in range(len(table_headers)): dataline.append(str(table_values[j][i])) table_data.append(dataline) elif table_view == 'h': table_data = [] for i in range(len(table_values)): table_data.append([table_headers[i]] + list(map(str, table_values[i]))) table = SingleTable(table_data) table.title = table_title table.justify_columns = {0: 'left', 1: 'left', 2: 'left'} table.inner_row_border = False print(table.table)
def main(): user_inp = str(raw_input('Enter the ip address : ')).strip() ip = IPAddress(str(user_inp)) if ip.version == 4: ipaddr = user_inp elif ip.version == 6: ipaddr = user_inp.replace(":","%3A") else: print "Please enter only a valid ipv4 or ipv6 address" sys.exit() tor_result = torproject(ipaddr) status,asn,owner,isp,continent,country,city,region = blacklist(ipaddr) table_data = [["ASN",asn], ["Owner",owner], ["ISP",isp], ["TorNode",tor_result], ["Blacklist",status], ["City",city], ["Region",region], ["Continent",continent], ["Country",country]] table = SingleTable(table_data) table.title = ipaddr table.justify_columns = {0: 'center', 1: 'center'} table.inner_row_border = True print "" print table.table
def box(cls, width, height, title=''): table_structure = [[' ' * (width - 2)] for x in range(height - 2)] table = SingleTable(table_structure, ' {} '.format(title)) table.inner_row_border = False table.inner_heading_row_border = False return table.table
def list_files(folder_path): ipa_files = [f for f in os.listdir(folder_path) if str(f).endswith(".ipa")] table_data = [[' * ', Color('{autoblue}%-40s{/autoblue}' % f)] for f in ipa_files] table = SingleTable(table_data) table.title = "All ipa files:" table.inner_column_border = False table.inner_heading_row_border = False print(table.table)
def table_server_timings(): """Return table string to be printed.""" table_data = [ [Color('{autogreen}<10ms{/autogreen}'), '192.168.0.100, 192.168.0.101'], [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'], [Color('{autored}>100ms{/autored}'), '192.168.0.105'], ] table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = False return table_instance.table
def test(): #Windows.enable(auto_colors=True, reset_atexit=True) table_data = [ [Color('{autogreen}TITLE{/autogreen}'), '192.168.0.100, 192.168.0.101'], [Color('{autocyan}10ms <= 100ms{/autocyan}'), '192.168.0.102, 192.168.0.103'], [Color('{autored}>100ms{/autored}'), '192.168.0.105'], ] table = SingleTable(table_data) table.inner_heading_row_border = False print(table.table)
def table_server_status(): """Return table string to be printed.""" table_data = [ [Color('Low Space'), Color('{autocyan}Nominal Space{/autocyan}'), Color('Excessive Space')], [Color('Low Load'), Color('Nominal Load'), Color('{autored}High Load{/autored}')], [Color('{autocyan}Low Free RAM{/autocyan}'), Color('Nominal Free RAM'), Color('High Free RAM')], ] table_instance = SingleTable(table_data, '192.168.0.105') table_instance.inner_heading_row_border = False table_instance.inner_row_border = True table_instance.justify_columns = {0: 'center', 1: 'center', 2: 'center'} return table_instance.table
def main(): """Main function.""" table_data = [ ['Long String', ''], # One row. Two columns. Long string will replace this empty string. ] table = SingleTable(table_data) # Calculate newlines. max_width = table.column_max_width(1) wrapped_string = '\n'.join(wrap(LONG_STRING, max_width)) table.table_data[0][1] = wrapped_string print(table.table)
def fancy_table(table_headers, *table_rows): """Creates a fancy table string from the given data :param table_headers: Iterable contains the table's headers :param table_rows: Iterable elements contain the table rows (body) :return: Formatted string represents the newly created table """ table_data = [table_headers] table_data.extend(table_rows) table = SingleTable(table_data=table_data) table.inner_row_border = True return table.table
def _print_deployment_summary(env): table_data = [ ["Project name:", env.project_name], ["Target:", env.target_name], ["User:"******"Host(s):", "; ".join(env.hosts)], ] table = SingleTable(table_data) table.title = Color('{autoyellow}Deployment configuration{/autoyellow}') table.justify_columns = {0: 'left', 1: 'left'} table.inner_row_border = False table.inner_heading_row_border = False _print_table(table)
def show_matches(): from models import Match from terminaltables import SingleTable # Initialize table data data = [['keyword', 'answer']] # List all matches matches = list(Match.select().order_by(Match.keyword, Match.id)) for match in matches: data.append([str(match.keyword), str(match.answer).replace('\n', '↵')[:30]]) # Create and print table table = SingleTable(data) table.title = '{} dialogues'.format(len(matches)) print(table.table)
def show_packet(self): table_data=[ ['SendID', 'RecvID', 'RootEvent'], ['qwe', 'qwe', 'qwe'] ] table=SingleTable(table_data) table.title=Color('{autocyan}Packet 1/2{/autocyan}') print table.table table_data2=[ ['Event', 'From', 'Topology', 'IsTested'], ['to tez tabl', 'to tez', 'to tez'] ] table2=SingleTable(table_data2) table2.title=Color('{autocyan}Packet 2/2{/autocyan}') print "" print table2.table
def fill_tabel(app): table_data = [ ['{0: <20}'.format('Title'),Color('{autoblue}%-50s{/autoblue}' % app.title)], ['{0: <20}'.format('URL'), Color('{autocyan}%s{/autocyan}' % app.url)], ['{0: <20}'.format('Price'), Color('{autogreen}%s{/autogreen}' % app.price)], ['{0: <20}'.format('Category'),Color('{autogreen}%s{/autogreen}' % app.category)], ['{0: <20}'.format('Release'),Color('{autogreen}%s{/autogreen}' % app.release)], ['{0: <20}'.format('Version') ,Color('{autogreen}%s{/autogreen}' % app.version)], ['{0: <20}'.format('Size'),Color('{autogreen}%s{/autogreen}' % app.size)], ['{0: <20}'.format('Language(s)'),Color('{autogreen}%s{/autogreen}' % app.language)], ['{0: <20}'.format('Developer'),Color('{autogreen}%s{/autogreen}' % app.developer)], ['{0: <20}'.format('Compatibility'),Color('{autogreen}%s...{/autogreen}' % ".".join(app.compatibility.split('.')[:2]))], ['{0: <20}'.format('Description:'),Color('{autocyan}%-50s{/autocyan}' % app.description)], ] table = SingleTable(table_data) table.inner_column_border = False table.inner_heading_row_border = False return table
def test_single_line(): """Test single-lined cells.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ['Watermelon', 'green'], [], ] table = SingleTable(table_data, 'Example') table.inner_footing_row_border = True table.justify_columns[0] = 'left' table.justify_columns[1] = 'center' table.justify_columns[2] = 'right' actual = table.table expected = ( u'\u250cExample\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500' u'\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n' u'\u2502 Name \u2502 Color \u2502 Type \u2502\n' u'\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500' u'\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n' u'\u2502 Avocado \u2502 green \u2502 nut \u2502\n' u'\u2502 Tomato \u2502 red \u2502 fruit \u2502\n' u'\u2502 Lettuce \u2502 green \u2502 vegetable \u2502\n' u'\u2502 Watermelon \u2502 green \u2502 \u2502\n' u'\u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500' u'\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n' u'\u2502 \u2502 \u2502 \u2502\n' u'\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500' u'\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518' ) assert actual == expected
def test_single_line(): """Test single-lined cells.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ['Watermelon', 'green'], [], ] table = SingleTable(table_data, 'Example') table.inner_footing_row_border = True table.justify_columns[0] = 'left' table.justify_columns[1] = 'center' table.justify_columns[2] = 'right' actual = table.table expected = ( '\033(0\x6c\033(BExample\033(0\x71\x71\x71\x71\x71\x77\x71\x71\x71\x71\x71\x71\x71\x77\x71\x71\x71\x71\x71\x71' '\x71\x71\x71\x71\x71\x6b\033(B\n' '\033(0\x78\033(B Name \033(0\x78\033(B Color \033(0\x78\033(B Type \033(0\x78\033(B\n' '\033(0\x74\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x6e\x71\x71\x71\x71\x71\x71\x71\x6e\x71\x71\x71\x71' '\x71\x71\x71\x71\x71\x71\x71\x75\033(B\n' '\033(0\x78\033(B Avocado \033(0\x78\033(B green \033(0\x78\033(B nut \033(0\x78\033(B\n' '\033(0\x78\033(B Tomato \033(0\x78\033(B red \033(0\x78\033(B fruit \033(0\x78\033(B\n' '\033(0\x78\033(B Lettuce \033(0\x78\033(B green \033(0\x78\033(B vegetable \033(0\x78\033(B\n' '\033(0\x78\033(B Watermelon \033(0\x78\033(B green \033(0\x78\033(B \033(0\x78\033(B\n' '\033(0\x74\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x6e\x71\x71\x71\x71\x71\x71\x71\x6e\x71\x71\x71\x71' '\x71\x71\x71\x71\x71\x71\x71\x75\033(B\n' '\033(0\x78\033(B \033(0\x78\033(B \033(0\x78\033(B \033(0\x78\033(B\n' '\033(0\x6d\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x71\x76\x71\x71\x71\x71\x71\x71\x71\x76\x71\x71\x71\x71' '\x71\x71\x71\x71\x71\x71\x71\x6a\033(B' ) assert actual == expected
def show_app_item(a): x = lambda s: Color('{autogreen}%s{/autogreen}' % s) y = lambda s: '{0: <20}'.format(s) table_data = [ [y('Title'), x(a.title)], [y('URL'), x(a.url)], [y('Price'), x(a.price)], [y('Category'), x(a.category)], [y('Release'), x(a.release)], [y('Version'), x(a.version)], [y('Size'), x(a.size)], [y('Language(s)'), x(a.language)], [y('Developer'), x(a.developer)], [y('Compatibility'), x(a.compatibility)], [y('Description:'), x(a.description)], ] table = SingleTable(table_data) table.inner_column_border = False table.inner_heading_row_border = False print(table.table)
def do_status(self, line): """ Display process pool status. """ self.clean_tasks() # this prevents from re-displaying the same status table once ENTER is pressed # (marker 'restart' is handled in emptyline() hereafter if line == 'restart' and self.__last_tasklist is not None and \ hash(frozenset(self.tasklist)) == self.__last_tasklist: return self.__last_tasklist = hash(frozenset(copy(self.tasklist))) if len(self.tasklist) == 0: data = [['No task currently running']] else: data = [['Task', 'Status', 'Result']] for task, info in sorted(self.tasklist.items(), key=lambda x: str(x[0])): data.append([str(task).ljust(15), info['status'].ljust(10), str(info['result']).ljust(40)]) table = SingleTable(data, 'Status of opened tasks') table.justify_columns = {0: 'center', 1: 'center', 2: 'center'} print(table.table)
def table_abcd(): """Return table string to be printed. Two tables on one line.""" table_instance = SingleTable([['A', 'B'], ['C', 'D']]) # Get first table lines. table_instance.outer_border = False table_inner_borders = table_instance.table.splitlines() # Get second table lines. table_instance.outer_border = True table_instance.inner_heading_row_border = False table_instance.inner_column_border = False table_outer_borders = table_instance.table.splitlines() # Combine. smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len) smallest += [''] * (len(largest) - len(smallest)) # Make both same size. combined = list() for i, row in enumerate(largest): combined.append(row.ljust(10) + ' ' + smallest[i]) return '\n'.join(combined)
def get_grid(self, astype='table'): from pandas import DataFrame as df geoms = self.geometries().keys() phases = [p.name for p in self.phases().values() if not hasattr(p, 'mixture')] grid = df(index=geoms, columns=phases) for r in grid.index: for c in grid.columns: phys = self.find_physics(phase=self[c], geometry=self[r]) if phys is not None: grid.loc[r][c] = phys.name else: grid.loc[r][c] = '---' if astype == 'pandas': pass elif astype == 'dict': grid = grid.to_dict() elif astype == 'table': from terminaltables import SingleTable headings = [self.network.name] + list(grid.keys()) g = [headings] for row in list(grid.index): g.append([row] + list(grid.loc[row])) grid = SingleTable(g) grid.title = 'Project: ' + self.name grid.padding_left = 3 grid.padding_right = 3 grid.justify_columns = {col: 'center' for col in range(len(headings))} elif astype == 'grid': grid = ProjectGrid() return grid
def main(): user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' headers = { 'User-Agent' : user_agent } trackingid = raw_input("Please enter the trackingid of your UPS package : ") url1 = "https://wwwapps.ups.com/WebTracking/processRequest?HTMLVersion=5.0&Requester=NES&AgreeToTermsAndConditions=yes&loc=en_US&" url2 = "tracknum={0}".format(trackingid) if len(trackingid) < 18: print "The tracking id is wrong" url = url1 + url2 city,country,statusdate,localtime,activity = ups(url,headers) table_data = [["Tracking ID",trackingid], ["City",city], ["Country",country], ["Status Date",statusdate], ["Status Time",localtime], ["Status",activity]] table = SingleTable(table_data) table.title = "UPS Package Status" table.justify_columns = {0: 'center', 1: 'center'} table.inner_row_border = True print "" print table.table
def handleDiscovery(self, dev, isNewDev, isNewData): if not isNewDev: return elif self.opts.mac is not None and dev.addr != self.opts.mac: return elif dev.rssi < self.opts.sensitivity: return vendor = vendors.find(dev.addr) vlabel = yellow( vendor + ' ' ) if vendor is not None else '?' clabel = green( u'\u2713' ) if dev.connectable else red( u'\u2715' ) dlabel = "(no data) " if not dev.scanData else "" title = " %s (%s dBm) %s" % ( bold(dev.addr), dev.rssi, dlabel ) tdata = [ [ 'Vendor', vlabel ], [ 'Allows Connections', clabel ], [ 'Address Type', dev.addrType] ] for ( tag, desc, val ) in dev.getScanData(): if desc == 'Flags': tdata.append([ 'Flags', self._parseFlags(val) ]) # short local name or complete local name elif tag in [8, 9]: try: tdata.append([ desc, yellow( val.decode('utf-8') ) ]) except UnicodeEncodeError: tdata.append([ desc, yellow( repr(val) ) ]) else: tdata.append([ desc, repr(val) ]) table = SingleTable(tdata, title) table.inner_heading_row_border = False print table.table + "\n"
def hinton_diagram(arr, max_arr=None): max_arr = arr if max_arr is None else max_arr max_val = max(abs(np.max(max_arr)), abs(np.min(max_arr))) diagram = [list([hinton_diagram_value(x, max_val) for x in _arr]) for _arr in arr] table = SingleTable(diagram) table.inner_heading_row_border = False table.inner_footing_row_border = False table.inner_column_border = False table.inner_row_border = False table.column_max_width = 1 return table.table
#!/usr/bin/env python """Simple example usage of terminaltables and column_max_width(). Just prints sample text and exits. """ from __future__ import print_function from textwrap import wrap from terminaltables import SingleTable # Setup string and table. long_string = ('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore ' 'et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut ' 'aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum ' 'dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui ' 'officia deserunt mollit anim id est laborum.') table = SingleTable([['Long String', '']]) # Calculate newlines. max_width = table.column_max_width(1) wrapped_string = '\n'.join(wrap(long_string, max_width)) table.table_data[0][1] = wrapped_string print(table.table)
def print_pokemon(self): sorted_mons = sorted(self.pokemon, key=lambda k: (k['pokedex_number'], -k['iv_percent'])) groups = groupby(sorted_mons, key=lambda k: k['pokedex_number']) table_data = [[ u'Pokémon', 'Level', 'CP', 'IV %', 'ATK', 'DEF', 'STA', 'Candy', 'Recommendation' ]] total_evolutions = 0 total_transfers = 0 print u'%d Pokémon found.' % len(sorted_mons) for key, group in groups: group = list(group) pokemon_name = self.pokemon_list[str(key)] best_iv_pokemon = max(group, key=lambda k: k['iv_percent']) best_iv_pokemon['best_iv'] = True candy_count = self.candy[key] result = pogotransfercalc.calculate(pokemon_count=len(group), candy_count=candy_count, pokedex_number=key) evolutions = result['evolutions'] total_evolutions += evolutions if evolutions: for pokemon in group[:evolutions]: pokemon['message'] = 'evolve' transfers = result['transfers'] transfer_count = 0 if transfers: for pokemon in reversed(group[evolutions:]): if pokemon['is_favorite']: pokemon['message'] = u'keep (★)' continue if pokemon['has_costume']: pokemon['message'] = u'keep (costume)' continue if pokemon['is_shiny']: pokemon['message'] = u'keep (shiny)' continue if pokemon['iv_percent'] < self.config.iv: pokemon['message'] = 'transfer' pokemon['transfer'] = True transfer_count += 1 total_transfers += 1 if transfer_count == transfers: break continue for pokemon in group: if pokemon['iv_percent'] >= self.config.iv: iv_msg = u'(IV ≥ %d%%)' % self.config.iv if 'message' in pokemon: pokemon['message'] += ' %s' % iv_msg else: pokemon['message'] = 'keep %s' % iv_msg row_data = [ pokemon_name + pokemon['gender'] + (u'✨' if pokemon['is_shiny'] else '') + (u'☃' if pokemon['has_costume'] else '') + (u'★' if pokemon['is_favorite'] else ''), pokemon['level'], pokemon['cp'], '{0:.0f}%'.format(pokemon['iv_percent']), pokemon['attack'], pokemon['defense'], pokemon['stamina'], candy_count, pokemon.get('message', '') ] table_data.append(row_data) table = SingleTable(table_data) table.justify_columns = { 0: 'left', 1: 'right', 2: 'right', 3: 'right', 4: 'right', 5: 'right', 6: 'right', 7: 'right' } print table.table table = SingleTable([ ['Total suggested transfers', format_number(total_transfers)], ['Total evolutions', format_number(total_evolutions)], [ 'Total XP from evolutions', format_number(total_evolutions * 500) ], [ 'Total XP from evolutions with lucky egg', format_number(total_evolutions * 1000) ], ]) table.inner_heading_row_border = False table.justify_columns = {0: 'left', 1: 'right'} print table.table
def OutputTable(self, msg, select_tables): if self.numberLoop < 6: self.numberLoop = self.numberLoop + 1 else: self.numberLoop = 0 if len(self.all_data) > 6: del self.all_data[-6] self.all_data.append([msg]) data = self.all_data if select_tables == 1: table = AsciiTable(data) print(table.table) elif select_tables == 2: try: self.account_info = self.requestStringNowait( "update.php", accesstoken=self.Configuration["accessToken"]) self.exploits = int(self.account_info["exploits"]) progress = round(int(self.account_info["exp"])) / round( int(self.account_info["expreq"])) account_information = [ ["your account information", "update information"], [ "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}\n{8}: {9}\n{10}: {11}" .format("Your exploits ", self.exploits, "Your spam ", self.account_info["spam"], "Your network speed ", self.account_info["inet"], "Your money ", self.account_info["money"], "Your IP ", self.account_info["ipaddress"], "Your netcoins ", self.account_info["netcoins"]), "{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}, XP({}%)". format("Your SDK ", self.account_info["sdk"], "Your Firewall ", self.account_info["fw"], "Your Antivirus ", self.account_info["av"], "Your BruteForce ", self.account_info["brute"], "Your level ", self.account_info["level"], round(progress * 100, 1)) ] ] except KeyError: account_information = [[ "your account information", "update information" ], ["Error", "Error"]] sys.exit() table1 = SingleTable(data) table2 = SingleTable(account_information) time.sleep(0.3) if self.platform == "Linux": print("\033[H\033[J") else: os.system('cls') req_version = (3, 0) cur_version = sys.version_info # for windows Try to print tables else pass python 2 try: print(table1.table) print(table2.table) if windows is False: sys.stdout.write("""\nCMD: [m] Get Miner info [a] Get All applications [q] Quit Program Waiting for user input : """) with raw_mode(sys.stdin): try: if cur_version <= req_version: while True: ch = sys.stdin.read(1) if ch == "a": p = Player(self) getTask = self.requestString( "tasks.php", accesstoken=self. Configuration["accessToken"]) sdk = p.getHelperApplication( )["SDK"]["level"] ipsp = p.getHelperApplication( )["IPSP"]["level"] bp = p.getHelperApplication( )["BP"]["level"] brute = p.getHelperApplication( )["BRUTE"]["level"] spam = p.getHelperApplication( )["SPAM"]["level"] fw = p.getHelperApplication( )["FW"]["level"] av = p.getHelperApplication( )["AV"]["level"] sys.stdout.write("\n \ SDK: {} \ IPSP: {}\n \ Bank Protect: {} \ BruteForce: {}\n \ SPAM: {} \ Firewall: {}\n \ Antivirus: {}".format(sdk, ipsp, bp, brute, spam, fw, av)) time.sleep(1.5) if ch == "m": self.minefinish = int( self.account_info['minerLeft']) sys.stdout.write( "\nminerLeft {} in secondes". format(self.minefinish)) sys.stdout.write( "\nwaiting until {} --- {}".format( self.tuntin(self.minefinish), datetime.timedelta(seconds=( self.minefinish)))) time.sleep(1) if ch == "q": sys.stdout.write( "\nok ok, good bye ;)\n") sys.exit() else: while True: ch = sys.stdin.read(1) if ch == "a": p = Player(self) getTask = self.requestString( "tasks.php", accesstoken=self. Configuration["accessToken"]) sdk = p.getHelperApplication( )["SDK"]["level"] ipsp = p.getHelperApplication( )["IPSP"]["level"] bp = p.getHelperApplication( )["BP"]["level"] brute = p.getHelperApplication( )["BRUTE"]["level"] spam = p.getHelperApplication( )["SPAM"]["level"] fw = p.getHelperApplication( )["FW"]["level"] av = p.getHelperApplication( )["AV"]["level"] sys.stdout.write("\n \ SDK: {} \ IPSP: {}\n \ Bank Protect: {} \ BruteForce: {}\n \ SPAM: {} \ Firewall: {}\n \ Antivirus: {}".format(sdk, ipsp, bp, brute, spam, fw, av)) time.sleep(1.5) if str(ch) == "m": self.minefinish = int( self.account_info['minerLeft']) sys.stdout.write( "\nminerLeft {} in secondes". format(self.minefinish)) sys.stdout.write( "\nwaiting until {} --- {}".format( self.tuntin(self.minefinish), datetime.timedelta(seconds=( self.minefinish)))) time.sleep(1) if ch == "q": sys.stdout.write( "\nok ok, good bye ;)\n") sys.exit() break except (KeyboardInterrupt, EOFError): pass except IOError as e: pass
def list_all(): print '\n{}ENCODERS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<'))) table_data = [['--NAME--', '--ARCH--', '--DESCRIPTION--', '--RANK--']] encoders = [] for enc in os.walk(PATH+'encoders'): encoders.append(enc) encoders = encoders[0][2] cdrs = [] for enc in encoders: if ('init' in enc or '.pyc' in enc): pass else: cdrs.append(enc.replace('.py', '')) for encoder in cdrs: try: encoder = importlib.import_module('encoders.'+encoder).Encoder() if encoder.rank == 'unstable': rank = logs.red('UNSTABLE') if encoder.rank == 'manual': rank = logs.yellow('MANUAL') elif encoder.rank == 'good': rank = logs.green('GOOD') elif encoder.rank == 'excellent': rank = logs.blue('EXCELLENT') except: rank = 'N/A' table_data.append([encoder.name, encoder.arch, encoder.description, rank]) table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = False table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'} print table_instance.table print '\n{}EGGHUNTERS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<'))) table_data = [['--NAME--', '--PLATFORM--', '--SIZE--', '--EGG SIZE--']] for egg in eggs: table_data.append([egg, eggs[egg][1],'{} bytes'.format(eggs[egg][2]),'{} bytes'.format(eggs[egg][3])]) table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = False table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'} print table_instance.table print '\n{}FORMATS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<'))) table_data = [['--FORMAT--', '--DESCRIPTION--']] for func in dir(wrappers): if "format_" in func: table_data.append([func.replace("format_", ''), eval("wrappers.{}".format(func)).__doc__]) table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = False table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'} print table_instance.table
def visit_stash(player): while True: print( SingleTable([['How much cocaine would you like to deposit?'], [ 'Stash: ' + str(player.stash.cocaine) + ' | Coat: ' + str(player.cocaine) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("cocaine", ans): player.stash.transfer("cocaine", ans) break else: clear() print(SingleTable([["You don't have that much!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear() while True: print( SingleTable([['How much heroin would you like to deposit?'], [ 'Stash: ' + str(player.stash.heroin) + ' | Coat: ' + str(player.heroin) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("heroin", ans): player.stash.transfer("heroin", ans) break else: clear() print(SingleTable([["You don't have that much!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear() while True: print( SingleTable([['How much acid would you like to deposit?'], [ 'Stash: ' + str(player.stash.acid) + ' | Coat: ' + str(player.acid) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("acid", ans): player.stash.transfer("acid", ans) break else: clear() print(SingleTable([["You don't have that much!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear() while True: print( SingleTable([['How much weed would you like to deposit?'], [ 'Stash: ' + str(player.stash.weed) + ' | Coat: ' + str(player.weed) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("weed", ans): player.stash.transfer("weed", ans) break else: clear() print(SingleTable([["You don't have that much!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear() while True: print( SingleTable([['How much speed would you like to deposit?'], [ 'Stash: ' + str(player.stash.speed) + ' | Coat: ' + str(player.speed) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("speed", ans): player.stash.transfer("speed", ans) break else: clear() print(SingleTable([["You don't have that much!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear() while True: print( SingleTable([['How many ludes would you like to deposit?'], [ 'Stash: ' + str(player.stash.ludes) + ' | Coat: ' + str(player.ludes) ]]).table) try: ans = int(input("\n> ")) if ans == 0: break else: if player.stash.can_transfer("ludes", ans): player.stash.transfer("ludes", ans) break else: clear() print(SingleTable([["You don't have that many!"]]).table) except ValueError as e: clear() print(SingleTable([["That isn't a number!"]]).table) clear()
def cops_chase(player): if 1 == randint(1, 10): cops = 0 r = randint(1, 10) if r >= 1 or r <= 6: cops = 2 elif r >= 7 or r <= 9: cops = 3 else: cops = 4 print( SingleTable([[ "Officer Headass and " + str(cops) + " other(s) are chasing you!" ]]).table) if player.guns >= 1: while True: print( SingleTable([["Would you like to (R)un or (F)ight?"], ["HP: " + str(player.health) + "/ 20"] ]).table) a = input("\n> ") aout = check_ans_yn(a) if a == 1: if 1 == randint(1, 6): drug = choice([ "cocaine", "heroin", "acid", "weed", "speed", "ludes" ]) pdrug = p.get_amt(drug) amnt = randint(1, 10) pdrug -= amnt clear() print( SingleTable([[ "You got away but you dropped " + str(amnt) + " bags of " + drug.capitalize() + " while running!!" ]])) input("Press ENTER to Continue") break else: if randint(1, 6) in [1, 6]: player.health -= 1 clear() print( SingleTable([[ "You got hit by one of their shots and lost some health!" ]]).table) else: drug = choice([ "cocaine", "heroin", "acid", "weed", "speed", "ludes" ]) pdrug = p.get_amt(drug) amnt = randint(1, 10) pdrug -= amnt clear() print( SingleTable([[ "You got away but you dropped " + str(amnt) + " bags of " + drug.capitalize() + "while running!!" ]])) input("Press ENTER to Continue") break elif a == 2: if 1 == randint(1, 3): cops -= 1 if cops == 0: break clear() print( SingleTable([["You took one of them out!"]]).table) else: player.health -= 1 clear() print( SingleTable([[ "You got hit by one of their shots and lost some health!" ]]).table) else: while True: print( SingleTable([["Press ENTER to Try and Run"], ["HP: " + str(player.health) + "/ 20"] ]).table) input() if 1 == randint(1, 6): break else: player.health -= 1 clear() print( SingleTable([[ "You got hit by one of their shots and lost some health!" ]]).table) clear() print(SingleTable([["You got away from the pigs!"]]).table) input("Press ENTER to Continue")
def makeDashbTable(self, data): table = SingleTable(data) table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {0: 'center', 1: 'center'} return table
def main(): print colored('Welcome to MVC & MVVM Validation Model for iOS (MMVMi)', 'cyan') print colored('Phase one Massive Controller detector (MCD): ', 'cyan') controllers = [ 'UIViewController', 'UITabBarController', 'UITableViewController', 'UICollectionViewController', 'UIActivityViewController', 'UICloudSharingController', 'UIDocumentInteractionController', 'UIDocumentMenuViewController', 'UIDocumentPickerViewController', 'UIDocumentPickerExtensionViewController', 'UIImagePickerController', 'UIInputViewController', 'UINavigationController', 'UIPageControl', 'UIPageViewController', 'UIPopoverController', 'UIPopoverPresentationController', 'UIPresentationController', 'UIPrinterPickerController', 'UIPrintInteractionController', 'UIReferenceLibraryViewController', 'UIRefreshControl', 'UISearchContainerViewController', 'UISearchController', 'UISearchDisplayController', 'UISplitViewController', 'GLKViewController', 'AVPlayerViewController' ] views = [ 'UIView', 'UICollectionView', 'UICollectionReusableView', 'UITableView', 'UICollectionViewCell', 'UITableViewCell', 'UILabel', 'UIActivityIndicatorView', 'UIButton', 'UIProgressView', 'UIStackView', 'UIImageView', 'UITextView', 'UIScrollView', 'UIPickerView', 'UIVisualEffectView', 'MKMapView', 'MTKView', 'GLKView', 'ARSCNView', 'WKWebView', 'UINavigationBar', 'UIToolbar', 'UITabBar', 'UISearchBar', 'UIContainerView' ] extension = ".swift" extLen = len(extension) anotherCheck = [] allControllers = [] controllers_list = [] view_list = [] path = raw_input(colored("Please enter your project path: ", 'white')) # replace the white space at the end of the project path with '/' project_path = path.replace(' ', '/') controller_pattern = re.compile("class .*: (?=(" + "|".join(map(re.escape, controllers)) + "))") view_pattern = re.compile("class .*: \\b(?=(" + "|".join(map(re.escape, views)) + ")\\b)") for path, subdirs, files in os.walk(project_path): for filename in files: if filename[len(filename) - extLen:] == '.swift': # open the file to read it current_file = open(os.path.join(path, filename)) for line in current_file: for match in re.finditer(view_pattern, line): view_list.append(filename[:-extLen]) for match in re.finditer(controller_pattern, line): # count # of lines for each controller object num_lines = sum( 1 for theLine in open(os.path.join(path, filename)) if theLine.split() and not '//' in theLine) controllers_list.append(filename[:-extLen]) allControllers.append((filename[:-extLen], num_lines)) if not (filename[:-extLen] in controllers_list or filename[:-extLen] in view_list): anotherCheck.append( (filename[:-extLen], os.path.join(path, filename))) # another check is needed to check if a class is a subclass of controller classes project_controllers = re.compile( "class .*: \\b(?=(" + "|".join(map(re.escape, controllers_list)) + ")\\b)") for theFile, thePath in anotherCheck: currentFile = open(thePath) for line in currentFile: for match in re.finditer(project_controllers, line): num_linesy = sum(1 for theLiney in open(thePath) if theLiney.split() and not '//' in theLiney) allControllers.append((theFile, num_linesy)) controllers_list.append(theFile) total_controllers = len(allControllers) print colored( '\nThis project has', 'white'), colored('%d', 'magenta') % total_controllers, colored( 'controllers. \n', 'white') sorted_controllers = sorted(allControllers, key=lambda x: x[1], reverse=True) TABLE_DATA = (('\nController Name', '\nTotal number of lines', '\nController status'), ) for controller_name, lines in sorted_controllers: if lines > 300: TABLE_DATA += (controller_name, lines, "Massive Controller"), elif lines < 150: TABLE_DATA += (controller_name, lines, "Thin Controller"), elif lines >= 150 or lines <= 300: TABLE_DATA += (controller_name, lines, "Take care"), title = 'Massive Controller Detection' # SingleTable. table_instance = SingleTable(TABLE_DATA, title) table_instance.justify_columns[2] = 'left' print(table_instance.table) print colored('Welcome to phase two: Object Relations Validation (ORV)', 'cyan') model_objects = raw_input( colored("Please enter your Model files name: ", 'cyan')) model_list = model_objects.split() # splits the input string on spaces modelView_objects = raw_input( colored("Please enter your Model View files name: ", 'cyan')) modelView_list = modelView_objects.split( ) # splits the input string on spaces rovFile = open("ROV.dot", "w") modelsPattern = re.compile("[^\"]\\b(?=(" + "|".join(map(re.escape, model_list)) + ")\\b)") modelViewPattern = re.compile("[^\"]\\b(?=(" + "|".join(map(re.escape, modelView_list)) + ")\\b)") controllersPattern = re.compile( "[^\"]\\b(?=(" + "|".join(map(re.escape, controllers_list)) + ")\\b)") viewsPattern = re.compile("[^\"]\\b(?=(" + "|".join(map(re.escape, view_list)) + ")\\b)") noDuplicate = {} with open('ROVtemplate.dot', 'r') as f: for line in f: if "Controller" in line: draw.writeOnCluster(rovFile, controllers_list, line) elif "label = \"View Model\"" in line: draw.writeOnCluster(rovFile, modelView_list, line) elif "label = \"View\"" in line: draw.writeOnCluster(rovFile, view_list, line) elif "label = \"Model\"" in line: draw.writeOnCluster(rovFile, model_list, line) else: rovFile.write(line) for path, subdirs, files in os.walk(project_path): for filename in files: # check all the relations between modelView objects and other objects if filename[:-extLen] in modelView_list: modelView_objects = { modelsPattern: "", controllersPattern: "", viewsPattern: "which is a view object. Please fix this forbidden relation. \n" } draw.check_relations(filename, extLen, noDuplicate, rovFile, modelView_objects, modelView_list, path) # check all the relations between model objects and other objects if filename[:-extLen] in model_list: model_objects = { modelViewPattern: "", controllersPattern: "which is a controller object. Please fix this forbidden relation. \n", viewsPattern: "which is a view object. Please fix this forbidden relation. \n" } draw.check_relations(filename, extLen, noDuplicate, rovFile, model_objects, model_list, path) # check all the relations between controllers objects and other objects if filename[:-extLen] in controllers_list: controller_objects = { modelsPattern: "which is a model object. Please fix this forbidden relation. \n", modelViewPattern: "", viewsPattern: "" } draw.check_relations(filename, extLen, noDuplicate, rovFile, controller_objects, controllers_list, path) # check all the relations between view objects and other objects if filename[:-extLen] in view_list: view_objects = { modelsPattern: "which is a model object. Please fix this forbidden relation. \n", modelViewPattern: "", controllersPattern: "" } draw.check_relations(filename, extLen, noDuplicate, rovFile, view_objects, view_list, path) rovFile.write("}") f.close() rovFile.close()
from json import loads from terminaltables import AsciiTable, SingleTable #wczytanie api imgw url = 'https://danepubliczne.imgw.pl/api/data/synop/' print(get(url)) resp = get(url) # print(resp.text) # print(loads(resp.text)) #interfejs programu i wypisanie danych print("Weather forecast") user_city = str(input('Please choose a city: ')) cities = [user_city] api_row = [ ['City', 'Temperature', 'Wind Speed', 'Pressure'] ] for weather_row in loads(resp.text): # print(r) if weather_row['stacja'] in cities: # print(r['stacja'], r['temperatura'], r['predkosc_wiatru'], r['cisnienie']) dane z api imgw - odpowiednie listy api_row.append([ weather_row['stacja'], weather_row['temperatura'], weather_row['predkosc_wiatru'], weather_row['cisnienie'] ]) weather_table = SingleTable(api_row) print(weather_table.table)
CONSIDER = set(["car"]) objCount = {obj: 0 for obj in CONSIDER} frameDict = {} # initialize dictionary which wil contain information regard the device active or not lastActive = {} lastActiveCheck = datetime.now() # printout the detected obj in command line print("[INFO] detecting: {}...".format(", ".join(obj for obj in CONSIDER))) while True: table = SingleTable(tableParkiran) table.title = "Table Parkiran" table.inner_row_border = False print(table.table) # receive RPi name and frame from the RPi and ack (rpiName, frame) = imageHub.recv_image() imageHub.send_reply(b'OK') dtnow = datetime.now().strftime('%H:%M:%S %a-%d-%b') if rpiName not in lastActive.keys(): print("[INFO] receiving data from {}...".format(rpiName)) lastActive[rpiName] = datetime.now()
def create_box_table(box): table_instance = SingleTable(box) table_instance.inner_heading_row_border = False table_instance.inner_row_border = True return table_instance
def printboard(self): table_instance = SingleTable( [[self.name, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], [ '1', self.board[0, 0], self.board[0, 1], self.board[0, 2], self.board[0, 3], self.board[0, 4], self.board[0, 5], self.board[0, 6], self.board[0, 7], self.board[0, 8], self.board[0, 9] ], [ '2', self.board[1, 0], self.board[1, 1], self.board[1, 2], self.board[1, 3], self.board[1, 4], self.board[1, 5], self.board[1, 6], self.board[1, 7], self.board[1, 8], self.board[1, 9] ], [ '3', self.board[2, 0], self.board[2, 1], self.board[2, 2], self.board[2, 3], self.board[2, 4], self.board[2, 5], self.board[2, 6], self.board[2, 7], self.board[2, 8], self.board[2, 9] ], [ '4', self.board[3, 0], self.board[3, 1], self.board[3, 2], self.board[3, 3], self.board[3, 4], self.board[3, 5], self.board[3, 6], self.board[3, 7], self.board[3, 8], self.board[3, 9] ], [ '5', self.board[4, 0], self.board[4, 1], self.board[4, 2], self.board[4, 3], self.board[4, 4], self.board[4, 5], self.board[4, 6], self.board[4, 7], self.board[4, 8], self.board[4, 9] ], [ '6', self.board[5, 0], self.board[5, 1], self.board[5, 2], self.board[5, 3], self.board[5, 4], self.board[5, 5], self.board[5, 6], self.board[5, 7], self.board[5, 8], self.board[5, 9] ], [ '7', self.board[6, 0], self.board[6, 1], self.board[6, 2], self.board[6, 3], self.board[6, 4], self.board[6, 5], self.board[6, 6], self.board[6, 7], self.board[6, 8], self.board[6, 9] ], [ '8', self.board[7, 0], self.board[7, 1], self.board[7, 2], self.board[7, 3], self.board[7, 4], self.board[7, 5], self.board[7, 6], self.board[7, 7], self.board[7, 8], self.board[7, 9] ], [ '9', self.board[8, 0], self.board[8, 1], self.board[8, 2], self.board[8, 3], self.board[8, 4], self.board[8, 5], self.board[8, 6], self.board[8, 7], self.board[8, 8], self.board[8, 9] ], [ '10', self.board[9, 0], self.board[9, 1], self.board[9, 2], self.board[9, 3], self.board[9, 4], self.board[9, 5], self.board[9, 6], self.board[9, 7], self.board[9, 8], self.board[9, 9] ]]) # Get second table lines. table_instance.outer_border = True table_instance.inner_column_border = True table_instance.inner_row_border = True table = table_instance.table.splitlines() return table
tableData = [headers] totalSeq = 0 for tag in stats.keys(): content = [] (fileCount, timeSpan) = stats[tag] meanFC = numpy.mean(fileCount) stdFC = numpy.std(fileCount) meanT = numpy.mean(timeSpan) stdT = numpy.std(timeSpan) totalSeq = totalSeq + len(fileCount) ## TODO - add outlier detection content.append([tag.upper(), str(len(fileCount)), str(round(meanFC,2)), str(round(stdFC,2)), str(int(meanT)), str(int(stdT))]) tableData.extend(content) tableData.append(["T O T A L", str(totalSeq), '', '', '', '']) if PRETTY_PRINT: table = SingleTable(tableData, 'Raw Dataset Stats') # table.inner_row_border = True for i in range(1,6): table.justify_columns[i] = 'center' print(table.table) else: for header in tableData[0]: print(header.replace("\n","").ljust(25), end="") print("\n") for contents in tableData[1:]: for content in contents: print(content.ljust(25), end="") print("\n")
def transfer_pokemon(self): pokemon_list = [ p for p in self.pokemon if p.get('transfer', False) and not p['is_favorite'] and not p['is_shiny'] and not p['has_costume'] ] total_transfers = len(pokemon_list) transfers_completed = 0 if not pokemon_list: print u'No Pokémon scheduled to transfer.' return table_data = [[u'Pokémon', 'CP', 'IV %', 'ATK', 'DEF', 'STA']] print 'About to transfer %d Pokémon…' % total_transfers transfer_list = [] for pokemon in pokemon_list: # Remove the Pokémon from the list, so that we don’t try to rename # it later. self.pokemon.remove(pokemon) pokedex_number = pokemon['pokedex_number'] pokemon_name = self.pokemon_list[str(pokedex_number)] table_data.append([ pokemon_name, pokemon['cp'], '{0:.0f}%'.format(pokemon['iv_percent']), pokemon['attack'], pokemon['defense'], pokemon['stamina'] ]) transfer_list.append(pokemon['id']) table = SingleTable(table_data) table.justify_columns = { 0: 'left', 1: 'right', 2: 'right', 3: 'right', 4: 'right', 5: 'right', 6: 'left' } print u'The following Pokémon are about to be transferred:' print table.table # After logging in, wait a while before starting to rename Pokémon, like a # human player would. self.config.min_delay = total_transfers * 2 self.config.max_delay = total_transfers * 4 self.wait_randomly() response = self.api.release_pokemon(pokemon_ids=transfer_list) try: result = response['responses']['RELEASE_POKEMON']['result'] except KeyError: print 'Failed:' print response status = 'error' pass else: if result == 1: status = 'success' print 'Transfer successful.' else: status = 'error' print 'Transfer failed. Error code: %s' % str(result)
def print_run_table(table_data): table = SingleTable(table_data) table.justify_columns = {0: 'left', 1: 'center', 2: 'left'} table.inner_heading_row_border = False table.inner_column_border = False table.outer_border = False max_width = table.column_max_width(2) for index, row in enumerate(table_data): table.table_data[index][2] = str(row[2][0:max_width].splitlines()[0]) if row[1] == 0: table.table_data[index][1] = colored(str(row[1]), 'green') elif row[1] == 1: table.table_data[index][2] = colored(str(row[1]), 'yellow') elif row[1] == 3: table.table_data[index][2] = colored(str(row[1]), 'grey') else: table.table_data[index][2] = colored(str(row[1]), 'red') print table.table
list1 = [] mgntList = [] list1.append(['Index', 'Title', 'Date Added', 'Size', 'Seeders', 'Leechers']) for i in range(int(num)): item = items[i] tempList = [] tempList.append(str(i + 1)) tempList.append(item.title.text) mgntList.append(item.magneturl.text) tempList.append(item.pubDate.text[5:16]) tempList.append(convertSize(int(item.size.text))) seeders = item.find(attrs={'name': 'seeders'}) tempList.append(seeders['value']) peers = item.find(attrs={'name': 'peers'}) tempList.append(peers['value']) list1.append(tempList) cuteTable = SingleTable(list1) max_width = cuteTable.column_max_width(1) for i in range(1, len(list1)): row = list1[i] wrappedString = '\n'.join(wrap(row[1], max_width)) cuteTable.table_data[i][1] = wrappedString + '\n' print(cuteTable.table) choice = int(input('\nEnter the index--->')) print('\nThe magnet link is :\n') print(mgntList[choice])
def sopa_game(sopa_letras, player): """Función donde se ejecuta las mecánicas del juego. Primero se crea una matriz 15*15 y se coloca en una lista las palabras que tienen que ser repartidas en el tablero, mediante la funcion set_words, a su vez se va verificando que las palabras no se crucen con la función verification_words hasta finalmente llegar a un loop donde tienes que ingresar las palabras que vayas encontrando. Args: [Objeto clase Normal_Game_NR]: sopa_letras, juego normal sin requisitos donde está toda la información del juego. [Player]: información del juegador Returns: [Bool]: True, si se gana el juego """ print(sopa_letras.get_name().replace("_", " de ").title()) print(sopa_letras.get_rules().capitalize()) question_n = random.randint(0, 2) info_question = sopa_letras.send_question(question_n) table_data = [ ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ] palabras = [ info_question["answer_1"].lower(), info_question["answer_2"].lower(), info_question["answer_3"].lower() ] letters = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] while verification_words(table_data, palabras) == False: table_data = [ ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ] set_words(table_data, palabras) for i in range(15): for j in range(15): if table_data[i][j] == "": n = random.randint(0, 25) table_data[i][j] = letters[n] table = SingleTable(table_data) table.inner_row_border = True words_guessed = [] n_clue = 1 av_clues = 3 while len(words_guessed) < 3 and player.get_time_left( ) > datetime.timedelta() and player.get_lives() > 0: print(table.table) guess = input("Ingrese la palabra encontrada: ").lower() if guess not in words_guessed: if guess in palabras: words_guessed.append(guess) os.system("clear") print(f"Bien {len(words_guessed)}/3") else: print("La palabra no está. Pierdes media vida") player.set_lives(player.get_lives() - 0.5) n_clue = get_clue(player, info_question, n_clue, av_clues) else: print("Ya lo habías adivinado. ") if len(words_guessed) == 3: return True
def do_l(self, arg): 'Lists current portfolio' t = Terminal() portfolio = self.trader.portfolios() if portfolio['extended_hours_equity']: equity = float(portfolio['extended_hours_equity']) else: equity = float(portfolio['equity']) eq = '%.2f' % equity previous_close = float(portfolio['adjusted_equity_previous_close']) change = equity - previous_close change_pct = '%.2f' % (change/previous_close * 100.0) # format change = f"{change:.2f}" # colorize change_pct = color_data(change_pct) change = color_data(change) account_details = self.trader.get_account() if 'margin_balances' in account_details: buying_power = account_details['margin_balances']['unallocated_margin_cash'] account_table = SingleTable([['Portfolio Value','Change','Buying Power'],[eq, change+' ('+change_pct+'%)', buying_power]],'Account') print((account_table.table)) # Load Stocks positions = self.trader.securities_owned() instruments = [position['instrument'] for position in positions['results']] symbols = [self.get_symbol(position['instrument']) for position in positions['results']] market_data = self.trader.get_stock_marketdata(instruments) table_data = [] table_data.append(["Symbol", "Last", "Shares", "Equity", "Avg Cost", "Return" , "Day", "EquityChange", "Day %"]) i = 0 for position in positions['results']: quantity = int(float(position['quantity'])) symbol = self.get_symbol(position['instrument']) price = market_data[i]['last_trade_price'] total_equity = float(price) * quantity buy_price = float(position['average_buy_price']) p_l = f"{total_equity - (buy_price * quantity):.2f}" total_equity = f"{total_equity:.2f}" buy_price = f"{buy_price:.2f}" day_change = f"{float(market_data[i]['last_trade_price']) - float(market_data[i]['previous_close']):.2f}" day_change_q_val = f"{float(quantity) * float(day_change):.2f}" day_change_pct = f"{float(day_change) / float(market_data[i]['previous_close']) * 100:.2f}" price = f"{float(price):.2f}" table_data.append([ symbol, price, quantity, total_equity, buy_price, color_data(p_l), color_data(day_change), color_data(day_change_q_val), color_data(day_change_pct) ]) i += 1 table = SingleTable(table_data,'Portfolio') table.inner_row_border = True table.justify_columns = {0: 'center' } print((table.table))
def create_table(dict_devices, dict_failed_check_result): """ Функция для создания отрисовки таблицы Function for creating a table """ table_data = [] table_data_temp = [] hostname = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "HOSTNAME") status = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "STATUS") lost = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "LOST") aver_delay = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "AVERAGE DELAY") max_delay = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "MAXIMUM DELAY") date = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "DATE") table_data.append([ Color(hostname), Color(status), Color(lost), Color(aver_delay), Color(max_delay), Color(date) ]) for key in dict_devices: hostname = key status = dict_devices.get(key)[0] lost = dict_devices.get(key)[1] aver_delay = dict_devices.get(key)[2] max_delay = dict_devices.get(key)[3] color = int(dict_devices.get(key)[4]) if status == "FAILD": hostname = "{autored}" + hostname + "{/autored}" status = "{autored}" + status + "{/autored}" lost = "{autored}" + lost + "{/autored}" aver_delay = max_delay = '{autored}0{/autored}' date = "{autored}" + dict_failed_check_result.get( key) + "{/autored}" table_data_temp.append([ Color(hostname), Color(status), Color(lost), Color(aver_delay), Color(max_delay), Color(date) ]) else: if color == 0: hostname = "{{{0}}}{1}{{/{0}}}".format("autogreen", hostname) status = "{{{0}}}{1}{{/{0}}}".format("autogreen", status) if lost != "0%": lost = "{autocyan}" + lost + "{/autocyan}" else: lost = "{{{0}}}{1}{{/{0}}}".format("autogreen", lost) aver_delay = "{{{0}}}{1}{{/{0}}}".format( "autogreen", aver_delay) max_delay = "{{{0}}}{1}{{/{0}}}".format("autogreen", max_delay) date = '{autored}-{/autored}' table_data_temp.append([ Color(hostname), Color(status), Color(lost), Color(aver_delay), Color(max_delay), Color(date) ]) elif color == 1: hostname = "{{{0}}}{1}{{/{0}}}".format("autoyellow", hostname) status = "{{{0}}}{1}{{/{0}}}".format("autoyellow", status) if lost != "0%": lost = "{autocyan}" + lost + "{/autocyan}" else: lost = "{{{0}}}{1}{{/{0}}}".format("autoyellow", lost) aver_delay = "{{{0}}}{1}{{/{0}}}".format( "autoyellow", aver_delay) max_delay = "{{{0}}}{1}{{/{0}}}".format( "autoyellow", max_delay) date = "{autored}" + dict_failed_check_result.get( key) + "{/autored}" table_data_temp.append([ Color(hostname), Color(status), Color(lost), Color(aver_delay), Color(max_delay), Color(date) ]) else: hostname = "{{{0}}}{1}{{/{0}}}".format("autowhite", hostname) status = "{{{0}}}{1}{{/{0}}}".format("autowhite", status) if lost != "0%": lost = "{autocyan}" + lost + "{/autocyan}" else: lost = "{{{0}}}{1}{{/{0}}}".format("autowhite", lost) aver_delay = "{{{0}}}{1}{{/{0}}}".format( "autowhite", aver_delay) max_delay = "{{{0}}}{1}{{/{0}}}".format("autowhite", max_delay) date = "{autored}" + dict_failed_check_result.get( key) + "{/autored}" table_data_temp.append([ Color(hostname), Color(status), Color(lost), Color(aver_delay), Color(max_delay), Color(date) ]) for i in sorted(table_data_temp): table_data.append(i) table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = False table_instance.justify_columns = { 0: 'center', 1: 'center', 2: 'center', 3: 'center', 4: 'center', 5: 'center' } return table_instance.table
def display_pricing_screen(p): prices = Prices(p) if p.days == 30: clear() print(SingleTable([["GAME OVER", "You Reached 30 Days!"]])) print( SingleTable([[ "Your Total Money:", p.bank.balance + p.money - p.shark.balance ]])) print( SingleTable([[ "Your Score:", str((p.bank.balance + p.money - p.shark.balance) / 1000000 * 100) + " out of 100" ]])) exit() if not p.is_first_round: achoice = choice([ lambda p: cops_chase(p), lambda p: buy_gun(p), lambda p: get_mugged(p), lambda p: find_drugs(p) ]) achoice(p) if prices.action != None and not p.is_first_round: print(SingleTable([[prices.action]]).table) input("Press ENTER to Continue") current_area = p.current_area if not p.is_first_round and current_area == "Bronx": clear() ask_loan_shark(p) ask_bank(p) ask_stash(p) while True: clear() inventory_table = lambda: [ ['Inventory', 'Days Left: ' + str(30 - p.days)], [ 'Cocaine: ' + str(round_down(p.cocaine)), 'Weed: ' + str( round_down(p.weed)) ], [ 'Heroin: ' + str(round_down(p.heroin)), 'Speed: ' + str( round_down(p.speed)) ], [ 'Acid: ' + str(round_down(p.acid)), 'Ludes: ' + str( round_down(p.ludes)) ], ] pricing_table = lambda: [ [ 'Current Area: ' + p.current_area, 'Coat Space: ' + str( p.coat_space()) + " / " + str(p.max_trench) ], [ 'Cocaine: ' + str(round_down(prices.cocaine)), 'Weed: ' + str( round_down(prices.weed)) ], [ 'Heroin: ' + str(round_down(prices.heroin)), 'Speed: ' + str( round_down(prices.speed)) ], [ 'Acid: ' + str(round_down(prices.acid)), 'Ludes: ' + str( round_down(prices.ludes)) ] ] money_table = lambda: [[ 'Debt: ' + str(int(round_down(p.shark.balance))), 'Guns: ' + str( p.guns), 'Bank: ' + str(int(round_down(p.bank.balance))), 'Wallet: ' + str(int(round_down(p.money))) ]] print(SingleTable(inventory_table()).table) print(SingleTable(pricing_table(), title="Prices").table) print(SingleTable(money_table(), title="Money").table) print( SingleTable([["Are you going to (B)uy, (S)ell, or (J)et?"]]).table) ans = input("\n> ") anout = check_ans_bsj(ans) clear() if anout == 1: while True: print(SingleTable(inventory_table()).table) print(SingleTable(pricing_table(), title="Prices").table) print(SingleTable(money_table(), title="Money").table) print(SingleTable([["What would you like to buy?"]]).table) buy = input("\n> ") if not check_drug_inp(buy): clear() print( SingleTable( [["Enter the first letter of a drug to choose!"]])) else: if buy[0].lower() == "c": drug = prices.cocaine elif buy[0].lower() == "h": drug = prices.heroin elif buy[0].lower() == "a": drug = prices.acid elif buy[0].lower() == "w": drug = prices.weed elif buy[0].lower() == "s": drug = prices.speed elif buy[0].lower() == "l": drug = prices.ludes price = int(round_down(drug)) print( SingleTable( [["How much would you like to buy?"], [ "Max Allowed: " + str(p.get_max(check_drug_inp(buy), drug)) ]]).table) try: amnt = int(input("\n> ")) if p.can_buy(price, int(amnt)): p.buy(check_drug_inp(buy), amnt, price) clear() print( SingleTable([[ "You bought " + str(amnt) + " of " + check_drug_inp(buy) ]]).table) break else: clear() print( SingleTable([[ "You don't have enough money/coat space to buy that!" ]]).table) break except ValueError: clear() print(SingleTable([["That isn't a number!"]]).table) elif anout == 2: while True: print(SingleTable(inventory_table()).table) print(SingleTable(pricing_table(), title="Prices").table) print(SingleTable(money_table(), title="Money").table) print(SingleTable([["What would you like to sell?"]]).table) sell = input("\n> ") if not check_drug_inp(sell): clear() print( SingleTable( [["Enter the first letter of a drug to choose!"]])) else: if sell[0].lower() == "c": drug = prices.cocaine elif sell[0].lower() == "h": drug = prices.heroin elif sell[0].lower() == "a": drug = prices.acid elif sell[0].lower() == "w": drug = prices.weed elif sell[0].lower() == "s": drug = prices.speed elif sell[0].lower() == "l": drug = prices.ludes price = int(round_down(drug)) print( SingleTable([["How much would you like to sell?"], [ "You Have: " + str(p.get_amt(check_drug_inp(sell))) ]]).table) try: amnt = int(input("\n> ")) if p.can_sell(amnt, check_drug_inp(sell)): p.sell(check_drug_inp(sell), amnt, price) clear() print( SingleTable([[ "You sold " + str(amnt) + " of " + check_drug_inp(sell) ]]).table) break else: clear() print( SingleTable([[ "You don't have enough to sell that many!" ]]).table) break except ValueError: clear() print(SingleTable([["That isn't a number!"]]).table) elif anout == 3: while True: clear() loc_index = [ 'Bronx', 'Ghetto', 'Central Park', 'Manhatten', 'Coney Island', 'Brooklyn' ] location_table = [['1) Bronx', '2) Ghetto', '3) Central Park'], [ '4) Manhatten', '5) Coney Island', '6) Brooklyn' ]] print( SingleTable( location_table, title="Where you gonna go? Current Location: " + p.current_area).table) try: loc = int(input("\n> ")) - 1 if loc > 5 or loc < 0: clear() print( SingleTable([["Choose a number between 1 and 6!"] ]).table) else: if loc_index[loc] == p.current_area: clear() else: loc += 1 if loc == 1: p.current_area = "Bronx" if loc == 2: p.current_area = "Ghetto" if loc == 3: p.current_area = "Central Park" if loc == 4: p.current_area = "Manhattan" if loc == 5: p.current_area = "Coney Island" if loc == 6: p.current_area = "Brooklyn" p.days += 1 break except ValueError: clear() print(SingleTable([["That isn't a number!"]]).table) else: clear() print( SingleTable([["That isn't an option. Choose B, S, or J"] ]).table) if p.current_area != current_area: break p.is_first_round = False p.bank.interest() p.shark.interest() display_pricing_screen(p)
try: if sys.argv[1] == "-nl": subprocess.call("clear") print("-----------------Tos---------------------") import time time.sleep(2) subprocess.call("clear") a = 'test_a' table_data = [ ['num', 'var.'], ['1. ', 'live'], ['2. ', 'exit'], ] table = SingleTable(table_data) print(table.table) os.system("figlet TBoot") numinstall = input(">_") if numinstall == "1": subprocess.call("clear") system() if numinstall == "2": exit() else: print("Error") if sys.argv[1] == "-s": log() subprocess.call("clear") print("-----------------Tos---------------------") time.sleep(2)
def do_it(pp): ids = [] table_data = [] headers = [] no_section = [] for h in pp["columns"]: headers.append(str(h)) table_data.append(headers) SOURCEKEY = pp["columns"].index("SOURCE") DESTKEY = pp["columns"].index("DESTINATION") SERVICEKEY = pp["columns"].index("SERVICE") for id in pp["ruleSections"]: ids.append(id[1]) for id in pp["ruleSections"]: for rule in pp["rules"]: rule = clean_rule(rule) if u"Any" in rule[SOURCEKEY] or u"Any" in rule[DESTKEY] or u"Any" in rule[SERVICEKEY] or u"Disabled" in rule[0]: if rule[len(rule)-1] == id[1]: table_data.append(rule) pp["rules"].remove(rule) elif rule[len(rule)-1] not in ids: if rule not in no_section: no_section.append(rule) pp["rules"].remove(rule) else: pass if len(table_data) > 1: new_table_data = clean_td(table_data) ascii = AsciiTable(table_data) single = SingleTable(table_data) ascii.inner_row_border = True single.inner_row_border = True a = ascii.table s = single.table write_output(a, id[0]) if (verbose): print "--- SECTION: %s ---" % id[0] print s table_data = [] table_data.append(headers) if len(no_section) > 0: table_data = [] headers = [] for h in pp["columns"]: headers.append(str(h)) table_data.append(headers) for rule in no_section: table_data.append(rule) table_data = clean_td(table_data) ascii = AsciiTable(table_data) single = SingleTable(table_data) single.inner_row_border = True ascii.inner_row_border = True a = ascii.table s = single.table write_output(a, "(NO SECTION DEFINED)") if (verbose): print "--- NO SECTION DEFINED (THESE ARE USUALLY AT THE TOP) ---" print s n = name + "-myCVT-output.txt" print "\033[1;32m[+] Written output to file ./%s\n" % n
def call(args, context): """ This is called when the plugin is invoked """ if not HAS_BOTO: # we can't do anything - ask for an install pip_version = 'pip3' if sys.version[0] == 3 else 'pip' print( "This plugin requires the 'boto' module. Please install it by running " "'{} install boto'".format(pip_version)) sys.exit(2) # requirements not met - we can't go on parser = argparse.ArgumentParser(PLUGIN_BASE, add_help=False) parser.add_argument('command', metavar='COMMAND', nargs='?', type=str, help='The command to execute in object storage') parser.add_argument( '--cluster', metavar='CLUSTER', type=str, help='The cluster to use. Defaults to us-east-1 (presently)') parsed, args = parser.parse_known_args(args) if not parsed.command: # show help if invoked with no command parser.print_help() # additional help print() print("Available commands: ") command_help_map = [[name, func.__doc__.strip()] for name, func in sorted(COMMAND_MAP.items())] tab = SingleTable(command_help_map) tab.inner_heading_row_border = False print(tab.table) print() print( "Additionally, you can regenerate your Object Storage keys using the " "'regenerate-keys' command") print() print('See --help for individual commands for more information') exit(0) # make a client, but only if we weren't printing help access_key, secret_key = _get_s3_creds(context.client) client = _get_boto_client(parsed.cluster or 'us-east-1', access_key, secret_key) if parsed.command in COMMAND_MAP: try: COMMAND_MAP[parsed.command](client, args) except S3ResponseError as e: if e.error_code: print('Error: {}'.format(e.error_code)) else: print(e) sys.exit(4) except S3CreateError as e: print('Error: {}'.format(e)) sys.exit(5) except BotoClientError as e: message_parts = e.message.split(':') if len(message_parts) > 0: message = ':'.join(message_parts[0:]) else: message = e.message print('Error: {}'.format(message)) sys.exit(6) elif parsed.command == "regenerate-keys": print("Regenerating Object Storage keys..") _get_s3_creds(context.client, force=True) print("Done.") print( "Warning: Your old Object Storage keys _were not_ automatically expired! If you want " "to expire them, see `linode-cli object-storage keys-list` and " "`linode-cli object-storage keys-delete [KEYID]`.") else: print('No command {}'.format(parsed.command)) sys.exit(1)
def __init__(self, api_key, id, currency, fiat_currency, dcoin, d2coin, d3coin, d4coin, reload_time): Windows.enable(auto_colors=True, reset_atexit=True) # For just Windows self.key_ = api_key self.id_ = id self.cur_ = currency self.fcur_ = fiat_currency self.coin_ = dcoin self.coin2_ = d2coin self.coin3_ = d3coin self.coin4_ = d4coin self.reload_time_ = int(reload_time) self.crypto_symbols_ = {} self.btc_ = 0.0 # 1 BTC in USD if self.reload_time_ > 1800 or int(reload_time) < 15: print( 'reload_time argument must be between 10 and 1800. For more info, run $ python3 display.py --help' ) exit() self.setSymbols() #print(Color('{autoyellow}benafleck{/autoyellow}')) # lol ;) self.time_str_ = 'Hello world, What time is it?' self.dot_count_ = 0 self.other_cur = False if args.f != None: self.other_cur = True self.dashb_ = False self.dashb2_ = False self.dashb3_ = False self.dashb4_ = False if args.d != None: self.dashb_ = True if args.d2 != None: self.dashb2_ = True if args.d3 != None: self.dashb3_ = True if args.d4 != None: self.dashb4_ = True self.balances_table_data_ = [] self.balances_table_ = SingleTable([]) if self.dashb_: self.dashb_table_data_ = [] self.dashb_table_ = SingleTable([]) if self.dashb2_: self.dashb2_table_data_ = [] self.dashb2_table_ = SingleTable([]) if self.dashb3_: self.dashb3_table_data_ = [] self.dashb3_table_ = SingleTable([]) if self.dashb4_: self.dashb4_table_data_ = [] self.dashb4_table_ = SingleTable([]) self.printDotInfo('Getting values and converting to currencies') self.getStats() self.printTables() if args.n == 'YES': self.displayNonStop() else: exit()
del nums[index] return choices with open('puzzle_cars.json') as data_file: data = json.load(data_file) all_cars = data['cars'] choices = [all_cars[i] for i in pick_five()] Car_Table = [['Order', 'Car']] for (i, item) in enumerate(choices): color = item['color'].upper() if color == 'WHITE': Car_Table.append([ i + 1, getattr(Back, color) + Fore.BLACK + ' ' + item['color'] + ' ' + item['type'] + ' ' + Fore.RESET + Back.RESET ]) else: Car_Table.append([ i + 1, getattr(Back, color) + ' ' + item['color'] + ' ' + item['type'] + ' ' + Back.RESET ]) table_instance = SingleTable(Car_Table, 'Puzzle') table_instance.justify_columns[0] = 'right' print(table_instance.table)
def show_board(game): table_result = SingleTable(game.get_board()) table_result.inner_row_border = True print(table_result.table) print('\n')
def handle_add_driver(driver_repo: Repo, parser: Parser, car_repo: Repo) -> None: """ Handle adding a driver Args: driver_repo (Repo): Driver repository parser (Parser): Input data parser car_repo (Repo): Car repository """ new_id = None new_name = "" new_age = None # Get driver id: done_id = False while not done_id: id_ = input( "Enter driver id (numeric), leave blank for autocomplete > ") if id_ == "": _, last_entity = driver_repo.get(mode="last") id_ = last_entity.id found = False while not found: id_ += 1 if not parser.check_if_already_exists(by_id=True, id=int(id_)): found = True new_id = int(id_) done_id = True print(f"\tAutocomplete succesfull, assigned id {new_id}") else: if not parser.check_if_already_exists(by_id=True, id=int(id_)): new_id = int(id_) done_id = True else: console.clear_console() olt.show( title="Info", message= "This id already exists, you might want to auto-complete, just press enter", go_back=False) # Get driver name: new_name = input("Enter the driver's name > ") # Get driver age: done_age = False while not done_age: age = input("Enter the driver's age (numeric) > ") try: new_age = int(age) done_age = True except ValueError: console.clear_console() olt.show(title="Info", message="The age must be a numeric value, ex: 45", go_back=False) # Deal with car assignment: if input("Do you want to assign a car now? y/n > ").lower() == "y": # Add car: print( "In order to assign a car to a driver you need it's ID, do you know it, or do you want to see all cars" ) input_ = input("Press enter to see all cars or enter an ID > ") if input_ == "": _, car_list = car_repo.get() if len(car_list) == 0 or car_list is None: olt.show( title="Something went wrong", message= "Either there are no cars at this moment or something else went wrong" ) else: table_data = [["ID", "Registration"]] for car in car_list: table_data.append([str(car.id), car.reg]) car_table = SingleTable(table_data, title="Cars") car_table.justify_columns = { 0: "left", 1: "center", } while True: console.clear_console() print(car_table.table) input_ = input("Type b or back to go back > ") if input_ == "b" or input_ == "back": break else: continue console.clear_console() input_ = input( "Enter car id or \"back\" if you want to leave it blank for now > " ) if input_ == "back": # Just add driver with no car assigned driver_repo.add(Driver(new_id, new_name, new_age, None)) else: try: new_car_id = int(input_) resp, car_ = car_repo.get(mode="single", entity_id=new_car_id) if resp == "found": # Add driver with respective car driver_repo.add( Driver(new_id, new_name, new_age, car_)) else: olt.show( title="Warning", message= "ID not found! Leaving blank for now, update via menu" ) driver_repo.add( Driver(new_id, new_name, new_age, None)) except ValueError: olt.show( title="Warning", message= "The id must be numeric. Leaving blank for now, update via menu" ) driver_repo.add(Driver(new_id, new_name, new_age, None)) else: # User gave manual id: try: new_car_id = int(input_) resp, car_ = car_repo.get(mode="single", entity_id=new_car_id) if resp == "found": # Add driver with respective car driver_repo.add(Driver(new_id, new_name, new_age, car_)) else: olt.show( title="Warning", message= "ID not found! Leaving blank for now, update via menu") driver_repo.add(Driver(new_id, new_name, new_age, None)) except ValueError: olt.show( title="Warning", message= "The id must be numeric. Leaving blank for now, update via menu" ) driver_repo.add(Driver(new_id, new_name, new_age, None)) else: # Just add driver with no car assigned driver_repo.add(Driver(new_id, new_name, new_age, None)) _, driver_instance_list = driver_repo.get() save_data(mode="single", only="drivers", driver_instance_list=driver_instance_list) olt.show(title="Success", message="The new driver was added succesfully")
def _chat_history_table(evts: List[Dict[Text, Any]]) -> Text: """Create a table containing bot and user messages. Also includes additional information, like any events and prediction probabilities.""" def wrap(txt, max_width): return "\n".join(textwrap.wrap(txt, max_width, replace_whitespace=False)) def colored(txt, color): return "{" + color + "}" + txt + "{/" + color + "}" def format_user_msg(user_evt, max_width): _parsed = user_evt.get('parse_data', {}) _intent = _parsed.get('intent', {}).get("name") _confidence = _parsed.get('intent', {}).get("confidence", 1.0) _md = _as_md_message(_parsed) _lines = [ colored(wrap(_md, max_width), "hired"), "intent: {} {:03.2f}".format(_intent, _confidence) ] return "\n".join(_lines) def bot_width(_table: AsciiTable) -> int: return _table.column_max_width(1) def user_width(_table: AsciiTable) -> int: return _table.column_max_width(3) def add_bot_cell(data, cell): data.append([len(data), Color(cell), "", ""]) def add_user_cell(data, cell): data.append([len(data), "", "", Color(cell)]) # prints the historical interactions between the bot and the user, # to help with correctly identifying the action table_data = [ ["# ", Color(colored('Bot ', 'autoblue')), " ", Color(colored('You ', 'hired'))], ] table = SingleTable(table_data, 'Chat History') bot_column = [] for idx, evt in enumerate(evts): if evt.get("event") == ActionExecuted.type_name: bot_column.append(colored(evt['name'], 'autocyan')) if evt['confidence'] is not None: bot_column[-1] += ( colored(" {:03.2f}".format(evt['confidence']), 'autowhite')) elif evt.get("event") == UserUttered.type_name: if bot_column: text = "\n".join(bot_column) add_bot_cell(table_data, text) bot_column = [] msg = format_user_msg(evt, user_width(table)) add_user_cell(table_data, msg) elif evt.get("event") == BotUttered.type_name: wrapped = wrap(format_bot_output(evt), bot_width(table)) bot_column.append(colored(wrapped, 'autoblue')) else: e = Event.from_parameters(evt) if e.as_story_string(): bot_column.append(wrap(e.as_story_string(), bot_width(table))) if bot_column: text = "\n".join(bot_column) add_bot_cell(table_data, text) table.inner_heading_row_border = False table.inner_row_border = True table.inner_column_border = False table.outer_border = False table.justify_columns = {0: 'left', 1: 'left', 2: 'center', 3: 'right'} return table.table
def print_table(TABLE_DATA): table_instance = SingleTable(TABLE_DATA, "") table_instance.justify_columns[2] = 'right' print(table_instance.table) print
def main(): ## Command Handling parser = argparse.ArgumentParser("linode-cli", add_help=False) parser.add_argument('command', metavar='COMMAND', nargs='?', type=str, help="The command to invoke in the CLI.") parser.add_argument('action', metavar='ACTION', nargs='?', type=str, help="The action to perform in this command.") parser.add_argument('--help', action="store_true", help="Display information about a command, action, or " "the CLI overall.") parser.add_argument( '--text', action="store_true", help="Display text output with a delimiter (defaults to tabs).") parser.add_argument('--delimiter', metavar='DELIMITER', type=str, help="The delimiter when displaying raw output.") parser.add_argument('--json', action='store_true', help="Display output as JSON") parser.add_argument('--markdown', action='store_true', help="Display output in Markdown format.") parser.add_argument('--pretty', action='store_true', help="If set, pretty-print JSON output") parser.add_argument('--no-headers', action='store_true', help="If set, does not display headers in output.") parser.add_argument( '--page', metavar='PAGE', type=int, default=1, help="For listing actions, specifies the page to request") parser.add_argument( '--all', action='store_true', help="If set, displays all possible columns instead of " "the default columns. This may not work well on " "some terminals.") parser.add_argument( '--format', metavar='FORMAT', type=str, help="The columns to display in output. Provide a comma-" "separated list of column names.") parser.add_argument( '--no-defaults', action='store_true', help="Suppress default values for arguments. Default values " "are configured on initial setup or with linode-cli configure") parser.add_argument( '--as-user', metavar='USERNAME', type=str, help="The username to execute this command as. This user must " "be configured.") parser.add_argument( '--suppress-warnings', action='store_true', help="Suppress warnings that are intended for human users. " "This is useful for scripting the CLI's behavior.") parser.add_argument('--version', '-v', action="store_true", help="Prints version information and exits.") parser.add_argument('--debug', action='store_true', help="Enable verbose HTTP debug output") parsed, args = parser.parse_known_args() # setup cli class if parsed.text: cli.output_handler.mode = OutputMode.delimited elif parsed.json: cli.output_handler.mode = OutputMode.json cli.output_handler.columns = '*' elif parsed.markdown: cli.output_handler.mode = OutputMode.markdown if parsed.delimiter: cli.output_handler.delimiter = parsed.delimiter if parsed.pretty: cli.output_handler.mode = OutputMode.json cli.output_handler.pretty_json = True cli.output_handler.columns = '*' if parsed.no_headers: cli.output_handler.headers = False if parsed.all: cli.output_handler.columns = '*' elif parsed.format: cli.output_handler.columns = parsed.format cli.defaults = not parsed.no_defaults cli.suppress_warnings = parsed.suppress_warnings cli.page = parsed.page cli.debug_request = parsed.debug if parsed.as_user: # if they are acting as a non-default user, set it up early cli.config.set_user(parsed.as_user) if parsed.version: if not parsed.command: # print version info and exit - but only if no command was given print("linode-cli {}".format(VERSION)) print("Built off spec version {}".format(cli.spec_version)) exit(0) else: # something else might want to parse version # find where it was originally, as it was removed from args index = argv.index('--version') - 3 # executable command action args = args[:index] + ['--version'] + args[index:] # handle a bake - this is used to parse a spec and bake it as a pickle if parsed.command == "bake": if parsed.action is None: print("No spec provided, cannot bake") exit(9) print("Baking...") spec_loc = parsed.action try: if os.path.exists(os.path.expanduser(spec_loc)): with open(os.path.expanduser(spec_loc)) as f: spec = yaml.safe_load(f.read()) else: # try to GET it resp = requests.get(spec_loc) if resp.status_code == 200: spec = yaml.safe_load(resp.content) else: raise RuntimeError("Request failed to {}".format(spec_loc)) except Exception as e: print("Could not load spec: {}".format(e)) exit(2) cli.bake(spec) print("Baking bash completions...") # this step would normally happen on laod if '_base_url' in cli.ops: del cli.ops['_base_url'] if '_spec_version' in cli.ops: del cli.ops['_spec_version'] # do the baking cli.bake_completions() print("Done.") exit(0) elif cli.ops is None: # if not spec was found and we weren't baking, we're doomed exit(3) if parsed.command == 'register-plugin': # this is how the CLI discovers third-party plugins - the user registers # them! Registering a plugin gets it set up for all CLI users. if parsed.action is None: print('register-plugin requires a module name!') exit(9) module = parsed.action # attempt to import the module to prove it is installed and exists try: plugin = import_module(module) except ImportError: print('Module {} not installed'.format(module)) exit(10) # get the plugin name try: plugin_name = plugin.PLUGIN_NAME except AttributeError: print('{} is not a valid Linode CLI plugin - missing PLUGIN_NAME'. format(module)) exit(11) # prove it's callable try: call_func = plugin.call except AttributeError: print('{} is not a valid Linode CLI plugin - missing call'.format( module)) exit(11) reregistering = False # check for naming conflicts if plugin_name in cli.ops: print( 'Plugin name conflicts with CLI operation - registration failed.' ) exit(12) elif plugin_name in plugins.available_local: # conflicts with an internal plugin - can't do that print( 'Plugin name conflicts with internal CLI plugin - registration failed.' ) exit(13) elif plugin_name in plugins.available(cli.config): from linodecli.configuration import input_helper # this isn't an internal plugin, so warn that we're re-registering it print("WARNING: Plugin {} is already registered.".format( plugin_name)) print("") answer = input_helper( "Allow re-registration of {}? [y/N] ".format(plugin_name)) if not answer or answer not in 'yY': print('Registration aborted.') exit(0) reregistering = True # looks good - register it already_registered = [] if cli.config.config.has_option('DEFAULT', 'registered-plugins'): already_registered = cli.config.config.get( 'DEFAULT', 'registered-plugins').split(',') if reregistering: already_registered.remove(plugin_name) cli.config.config.remove_option( 'DEFAULT', 'plugin-name-{}'.format(plugin_name)) already_registered.append(plugin_name) cli.config.config.set('DEFAULT', 'registered-plugins', ','.join(already_registered)) cli.config.config.set('DEFAULT', 'plugin-name-{}'.format(plugin_name), module) cli.config.write_config() print('Plugin registered successfully!') print('Invoke this plugin by running the following:') print(' linode-cli {}'.format(plugin_name)) exit(0) if parsed.command == 'remove-plugin': if parsed.action is None: print('remove-plugin requires a plugin name to remove!') exit(9) # is this plugin registered? plugin_name = parsed.action if plugin_name in plugins.available_local: # can't remove first-party plugins print('{} is bundled with the CLI and cannot be removed'.format( plugin_name)) exit(13) elif plugin_name not in plugins.available(cli.config): print('{} is not a registered plugin'.format(plugin_name)) exit(14) # do the removal current_plugins = cli.config.config.get( 'DEFAULT', 'registered-plugins').split(',') current_plugins.remove(plugin_name) cli.config.config.set('DEFAULT', 'registered-plugins', ','.join(current_plugins)) if cli.config.config.has_option('DEFAULT', 'plugin-name-{}'.format(plugin_name)): # if the config if malformed, don't blow up cli.config.config.remove_option( 'DEFAULT', 'plugin-name-{}'.format(plugin_name)) cli.config.write_config() print("Plugin {} removed".format(plugin_name)) exit(0) # handle a help for the CLI if parsed.command is None or (parsed.command is None and parsed.help): parser.print_help() # commands to manage CLI users (don't call out to API) print() print('CLI user management commands:') um_commands = [['configure', 'set-user', 'show-users'], ['remove-user']] table = SingleTable(um_commands) table.inner_heading_row_border = False print(table.table) # commands to manage plugins (don't call out to API) print() print('CLI Plugin management commands:') pm_commands = [['register-plugin', 'remove-plugin']] table = SingleTable(pm_commands) table.inner_heading_row_border = False print(table.table) # commands generated from the spec (call the API directly) print() print("Available commands:") content = [c for c in cli.ops.keys()] proc = [] for i in range(0, len(content), 3): proc.append(content[i:i + 3]) if content[i + 3:]: proc.append(content[i + 3:]) table = SingleTable(proc) table.inner_heading_row_border = False print(table.table) # plugins registered to the CLI (do arbitrary things) if plugins.available(cli.config): # only show this if there are any available plugins print("Available plugins:") plugin_content = [p for p in plugins.available(cli.config)] plugin_proc = [] for i in range(0, len(plugin_content), 3): plugin_proc.append(plugin_content[i:i + 3]) if plugin_content[i + 3:]: plugin_proc.append(plugin_content[i + 3:]) plugin_table = SingleTable(plugin_proc) plugin_table.inner_heading_row_border = False print(plugin_table.table) print() print("To reconfigure, call `linode-cli configure`") print( "For comprehensive documentation, visit https://www.linode.com/docs/api/" ) exit(0) # configure if parsed.command == "configure": if parsed.help: print('linode-cli configure') print() print( 'Configured the Linode CLI. This command can be used to change' ) print( 'defaults selected for the current user, or to configure additional' ) print('users.') exit(0) else: cli.configure() exit(0) # block of commands for user-focused operations if parsed.command == "set-user": if parsed.help or not parsed.action: print('linode-cli set-user [USER]') print() print( 'Sets the active user for the CLI out of users you have configured.' ) print('To configure a new user, see `linode-cli configure`') exit(0) else: cli.config.set_default_user(parsed.action) exit(0) if parsed.command == "show-users": if parsed.help: print('linode-cli show-users') print() print( 'Lists configured users. Configured users can be set as the') print('active user (used for all commands going forward) with the') print('`set-user` command, or used for a single command with the') print( '`--as-user` flag. New users can be added with `linode-cli configure`.' ) print('The user that is currently active is indicated with a `*`') exit(0) else: cli.config.print_users() exit(0) if parsed.command == "remove-user": if parsed.help or not parsed.action: print('linode-cli remove-user [USER]') print() print( 'Removes a user the CLI was configured with. This does not change' ) print( 'your Linode account, only this CLI installation. Once removed,' ) print( 'the user may not be set as active or used for commands unless' ) print('configured again.') exit(0) else: cli.config.remove_user(parsed.action) exit(0) # special command to bake shell completion script if parsed.command == 'bake-bash': cli.bake_completions() # check for plugin invocation if parsed.command not in cli.ops and parsed.command in plugins.available( cli.config): context = plugins.PluginContext(cli.config.get_token(), cli) # reconstruct arguments to send to the plugin plugin_args = argv[1:] # don't include the program name plugin_args.remove(parsed.command) # don't include the plugin name tho plugins.invoke(parsed.command, plugin_args, context) exit(0) if parsed.command not in cli.ops and parsed.command not in plugins.available( cli.config): # unknown commands print('Unrecognized command {}'.format(parsed.command)) # handle a help for a command - either --help or no action triggers this if parsed.command is not None and parsed.action is None: if parsed.command in cli.ops: actions = cli.ops[parsed.command] print("linode-cli {} [ACTION]".format(parsed.command)) print() print("Available actions: ") content = [[action, op.summary] for action, op in actions.items()] header = ['action', 'summary'] table = SingleTable([header] + content) print(table.table) exit(0) # handle a help for an action if parsed.command is not None and parsed.action is not None and parsed.help: if parsed.command in cli.ops and parsed.action in cli.ops[ parsed.command]: operation = cli.ops[parsed.command][parsed.action] print("linode-cli {} {}".format(parsed.command, parsed.action), end='') for param in operation.params: # clean up parameter names - we add an '_' at the end of them # during baking if it conflicts with the name of an argument. # Remove the trailing underscores on output (they're not # important to the end user). pname = param.name.upper() if pname[-1] == '_': pname = pname[:-1] print(' [{}]'.format(pname), end='') print() print(operation.summary) print() if operation.args: print("Arguments:") for arg in sorted(operation.args, key=lambda s: not s.required): print(" --{}: {}{}".format( arg.path, "(required) " if operation.method == 'post' and arg.required else '', arg.description)) elif operation.method == 'get' and parsed.action == 'list': filterable_attrs = ([ attr for attr in operation.response_model.attrs if attr.filterable ]) if filterable_attrs: print("You may filter results with:") for attr in filterable_attrs: print(" --{}".format(attr.name)) exit(0) if parsed.command is not None and parsed.action is not None: cli.handle_command(parsed.command, parsed.action, args)
def handle_update_car(car_repo: Repo, parser: Parser): """ Handle updateing a car Args: car_repo (Repo): Car repository parser (Parser): Input parser """ # Get car id: got_id = False _, car_list = car_repo.get() while not got_id: id_ = input( "Enter car id (numeric) or leave blank to see the car list > ") if id_ == "": table_data = [["ID", "Registration"]] for car in car_list: table_data.append([str(car.id), car.reg]) car_table = SingleTable(table_data, title="Cars") car_table.justify_columns = { 0: "left", 1: "center", } while True: console.clear_console() print(car_table.table) input_ = input("Type b or back to go back > ") if input_ == "b" or input_ == "back": break else: continue else: try: id_ = int(id_) if parser.check_if_already_exists(by_id=True, id=id_): # Id exists, continue: got_id = True done_id = False done_hp = False done_kms = False while not done_id: new_id = input( "If you want to change the ID enter it now, leave blank to skip > " ) if new_id != "": try: new_id = int(new_id) done_id = True except ValueError: console.clear_console() olt.show(title="Info", message= "Invalid ID! The ID Must be numeric", go_back=False) else: new_id = None done_id = True new_reg = input( "If you want to change the Registration No. enter it now, leave blank to skip > " ) if new_reg == "": new_reg = None new_brand = input( "If you want to change the Brand enter it now, leave blank to skip > " ) if new_brand == "": new_brand = None while not done_hp: new_hp = input( "If you want to change the Horsepower enter it now, leave blank to skip > " ) if new_hp != "": try: new_hp = int(new_hp) done_hp = True except ValueError: console.clear_console() olt.show( title="Info", message= "Invalid HP! The Horespower be a numeric value", go_back=False) else: new_hp = None done_hp = True while not done_kms: new_kms = input( "If you want to change the KMs enter them now, leave blank to skip > " ) if new_kms != "": try: new_kms = int(new_kms) done_kms = True except ValueError: console.clear_console() olt.show(title="Info", message= "Invalid KM! The KMs Must be numeric", go_back=False) else: new_kms = None done_kms = True # Actually update-ing: car_repo.update(type_of_entity="car", entity_id=id_, id=new_id, reg=new_reg, brand=new_brand, hp=new_hp, kms=new_kms) save_data(mode="single", only="cars", car_instance_list=car_list) olt.show(title="Success", message="The car was updated succesfully") except ValueError: console.clear_console() olt.show(title="Info", message="Invalid ID! The ID Must be numeric", go_back=False) else: console.clear_console() olt.show(title="Info", message="Invalid ID!", go_back=False)
def handle_update_driver(driver_repo: Repo, parser: Parser, car_repo: Repo): """ Handle updateing a driver Args: driver_repo (Repo): Driver repository parser (Parser): Input data parser car_repo (Repo): Car repository """ # Get driver id: got_id = False _, driver_list = driver_repo.get() while not got_id: id_ = input( "Enter driver id (numeric) or leave blank to see the driver list > " ) if id_ == "": table_data = [["ID", "Name"]] for driver in driver_list: table_data.append([str(driver.id), driver.name]) driver_table = SingleTable(table_data, title="Drivers") driver_table.justify_columns = { 0: "left", 1: "center", } while True: console.clear_console() print(driver_table.table) input_ = input("Type b or back to go back > ") if input_ == "b" or input_ == "back": break else: continue else: try: id_ = int(id_) if parser.check_if_already_exists(by_id=True, id=id_): # Id exists, continue: got_id = True done_id = False done_age = False #new_car = None while not done_id: new_id = input( "If you want to change the ID enter it now, leave blank to skip > " ) if new_id != "": try: new_id = int(new_id) done_id = True except ValueError: console.clear_console() olt.show(title="Info", message= "Invalid ID! The ID Must be numeric", go_back=False) else: new_id = None done_id = True new_name = input( "If you want to change the Name enter it now, leave blank to skip > " ) if new_name == "": new_name = None while not done_age: new_age = input( "If you want to change the Age enter it now, leave blank to skip > " ) if new_age != "": try: new_age = int(new_age) done_age = True except ValueError: console.clear_console() olt.show(title="Info", message= "Invalid ID! The ID Must be numeric", go_back=False) else: new_age = None done_age = True new_car_yn = input( "Do you want to change the driver's car enter \"y\" to change and \"n\" to skip > " ).strip().lower() if new_car_yn == 'y': new_car_id = input( "Enter the new car's ID, leave blank to see all cars, or type \"none\" to delete the car from the driver > " ).strip().lower() if new_car_id == "": _, car_list = car_repo.get() if len(car_list) == 0 or car_list is None: olt.show( title="Something went wrong", message= "Either there are no cars at this moment or something else went wrong" ) else: table_data = [["ID", "Registration"]] for car in car_list: table_data.append([str(car.id), car.reg]) car_table = SingleTable(table_data, title="Cars") car_table.justify_columns = { 0: "left", 1: "center", } while True: console.clear_console() print(car_table.table) input_ = input( "Type b or back to go back > ") if input_ == "b" or input_ == "back": break else: continue new_car_id = input("Enter the new car's ID > ") try: new_car_id = int(new_car_id) resp, car = car_repo.get( mode="single", entity_id=new_car_id) if resp is "found": new_car = car else: olt.show( title="Fail", message= "The car coudn't be found, discarding car changes", go_back=False) except ValueError: olt.show( title="Fail", message= "The car's id must be numeric, discarding car changes", go_back=False) elif new_car_id == "none": new_car = -1 else: try: new_car_id = int(new_car_id) resp, car = car_repo.get(mode="single", entity_id=new_car_id) if resp == "found": new_car = car else: olt.show( title="Fail", message= "The car coudn't be found, discarding car changes", go_back=False) except ValueError: olt.show( title="Fail", message= "222The car's id must be numeric, discarding car changes", go_back=False) else: new_car = None driver_repo.update(type_of_entity="driver", entity_id=id_, id=new_id, name=new_name, age=new_age, car=new_car) save_data(mode="single", only="drivers", driver_instance_list=driver_list) olt.show(title="Success", message="The driver was updated succesfully") except ValueError: console.clear_console() olt.show(title="Info", message="Invalid ID! The ID Must be numeric", go_back=False) else: console.clear_console() olt.show(title="Info", message="Invalid ID!", go_back=False)
def searchCopainsdavant(self, nom, city): url = "http://copainsdavant.linternaute.com/s/?ty=1&prenom=%s&nom=%s&nomjf=&annee=&anneeDelta=&ville=%s" name = nom if " " in name: nom = name.split(" ")[1] prenom = name.split(" ")[0] else: prenom = "" nom = name data = requests.get(url % (prenom, nom, city)).content.decode('utf-8') soup = BeautifulSoup(data, "html.parser") nameList = soup.find_all("div", {"class": "grid_last"}) addresseList = soup.find_all("span", {"class": "app_list--result__search__place"}) urlList = soup.find_all("h3") birthdayList = [] travailList = [] urlList2 = [] for url in urlList: url = url.find("a") urls = str(url) href = re.search(r"/p/([a-zA-Z0-9_-]+)", urls).group() urlList2.append(href) for url in urlList2: data = requests.get("http://copainsdavant.linternaute.com/%s" % (url)).content.decode('utf-8') soup = BeautifulSoup(data, "html.parser") birthdayList0 = soup.find_all("abbr", {"class": "bday"}) item = len(birthdayList0) if item == 0: birthdayList0.append("None") for b in birthdayList0: birthdayList.append(str(b)) travailList0 = soup.find_all("p", {"class": "title"}) item = len(travailList0) if item == 0: travailList0.append("None") for t in travailList0: travailList.append(str(t)) namesList2 = [] addressesList2 = [] birthdayList2 = [] travailList2 = [] for name in nameList: name = name.find("a") namesList2.append(name.string) for addr in addresseList: addressesList2.append(addr.string.strip()) for date in birthdayList: date = date.replace("<abbr class=\"bday\" title=\"", "").replace("00:00:00\">", "- ").replace("</abbr>", "").replace("\">", "") birthdayList2.append(date) for travail in travailList: travail = travail.replace("<p class=\"title\">", "").replace("</p>", "") travailList2.append(travail) regroup = zip(namesList2, addressesList2, birthdayList2, travailList2, urlList2) title = " Copain D'avant " TABLE_DATA = [ ('Name', 'Adresse', 'Date', 'Work', 'url'), ] count = 0 for info in regroup: count += 1 name = info[0] adresse = info[1] adresse = adresse.split(" - ")[0] dateBirthday = info[2] try: dateBirthday = dateBirthday.split(" - ")[1] except: pass travail = info[3] url = info[4] infos = (name, adresse, dateBirthday, travail, url) TABLE_DATA.append(infos) if count > 0: table_instance = SingleTable(TABLE_DATA, title) labl = Label(self, text=table_instance.table, bg="black", fg="green", font=("comicsansms", 15, "bold"), relief=FLAT) labl.place(x=20, y=2) # print(table_instance.table)
def searchPageDor(requete='', num=''): def testResponse(requete): if 'Aucun résultat' in requete.text: return 1 # print("[!] Aucun resultattttt pour votre recherche... o_o' ") page = requete.text #content.decode('utf-8') soup = BeautifulSoup(page, "html.parser") rep = testResponse(requete) if rep == 1: print(warning + " Aucun résultat pour votre recherche... o_o'") if num != '': # phoneNumber(num) pass else: pass else: pass try: nameList = soup.find_all("h2", {"class": "result-item-title"}) # print(nameList) addressList = soup.find_all("li", {"class": "address"}) # print(addressList) numList = soup.find_all("li", {"class": "phone"}) # input(numList) # name = name.string.strip() # adresse = adresse.string.strip() # num = num.string.strip() # printResult(name, adresse, num) except AttributeError: pass namesList2 = [] addressesList2 = [] numesList2 = [] operatorList = [] # try: for name in nameList: namesList2.append(name.text.strip()) for addresse in addressList: addressesList2.append(addresse.text.strip()) for num in numList: phone = searchInfoNumero() phone.search(num.text.strip()) operator = phone.operator operatorList.append(operator) numesList2.append(num.text.strip()) # except: # pass # print("[!] Aucun resultat pour votre recherche... o_o'") regroup = zip(namesList2, addressesList2, numesList2, operatorList) title = " Particulier " TABLE_DATA = [ ('Name', 'Adresse', 'Phone', 'Operateur'), ] listeInfos = [] for infos in regroup: try: TABLE_DATA.append(infos) except AttributeError: pass if rep != 1: table_instance = SingleTable(TABLE_DATA, title) print("\n" + table_instance.table)