def from_csv(filename=csv_file): # solved with open(filename, newline="", encoding="utf-8") as f: reader = csv.reader(f, delimiter=";") rows_from_csv = [tuple(row) for row in reader] log(len(rows_from_csv)) return rows_from_csv
def findvideos(item): support.log() itemlist = support.server(item, data=item.url) # itemlist = filtertools.get_links(itemlist, item, list_language) autoplay.start(itemlist, item) return itemlist
def __init__(self, pawn, level=1): self.level = level self.board = pawn.board if prop.CACHE_ENABLED: self._memoize_think = PersistentDict(prop.CACHE_AI_FNAME, flag='c') else: self._memoize_think = {} pawn.BOT = self log('Jugador %i es controlado por la A.I.' % pawn.id)
def search(item, texto): support.log("s=", texto) item.url = host + "/?s=" + texto try: return peliculas(item) # Continua la ricerca in caso di errore except: import sys for line in sys.exc_info(): logger.error("%s" % line) return []
def from_html(): # solved # html parsing with open(html_file, "r", encoding="utf-8") as f: contents = f.read() sp = soup(contents, "lxml") rows = [tuple(row) for row in sp.tbody.find_all("tr")] # corrected row rows = list(modifyrows(html_data, rows)) if tb.count("lastrow") == 0: tb.write(rows[0], "lastrow") num_lastrow = len(rows) else: lastrow = tb.read()[0] num_lastrow = rows.index(lastrow) tb.update(rows[0]) log(num_lastrow) return rows[:num_lastrow]
def do_action(self, action: Union[ActionPlaceWall, ActionMovePawn]): player_id = self.current_player.id if isinstance(action, ActionPlaceWall): wdir = 'horizontal' if action.horiz else 'vertical' log('Jugador %i coloca %s pared en (%i, %i)' % (player_id, wdir, action.coord.col, action.coord.row)) self.putWall(self.new_wall(action.coord, action.horiz)) self.current_player.walls -= 1 else: log('Jugador %i se mueve a (%i, %i)' % (player_id, action.dest.row, action.dest.col)) self.current_player.move_to(action.dest) self._state = None for pawn in self.pawns: if pawn.is_network_player: pawn.do_action(action)
def episodios(item): support.log() patron = r'<div class="su-spoiler.*?</i>(.*?)</div>\s+<div class="su-spoiler-content"(.*?)="clearfix">' data = httptools.downloadpage(item.url).data matches = re.compile(patron, re.S).findall(data) if item.args: s = (int(item.args["season"])) try: matches = [matches[s]] except: matches = [matches[(s - 1)]] itemlist = [] for season, block in matches: patron = r'<div class="su-link-ep">\s+<a.*?href="([^"]+)".*?strong>(.*?)</' if item.args: ep = int(item.args["episode"]) patron = r'<div class="su-link-ep">\s+<a.*?href="([^"]+)".*?strong>\s(Episodio ' + str( ep) + r') .*?</' episodes = re.compile(patron, re.MULTILINE).findall(block) for scrapedurl, scrapedtitle in episodes: fixedtitle = scrapertools.get_season_and_episode(season + " " + scrapedtitle) eptitle = re.sub(r"Episodio\s+\d+", "", scrapedtitle).strip() itemlist.append( Item( channel=item.channel, action="findvideos", contentType=item.contentType, title="[B]" + fixedtitle + " " + eptitle + "[/B]", fulltitle=fixedtitle + " " + eptitle, show=fixedtitle + " " + eptitle, url=scrapedurl, extra=item.extra, )) if not item.args: support.videolibrary(itemlist, item) return itemlist
def peliculas(item): support.log() patron = r'<div class="post-thumb">\s*<a href="([^"]+)" title="([^"]+)">\s*<img src="([^"]+)"[^>]+>' list_groups = ["url", "title", "thumb"] if item.args == "latest": patron += r'.*?aj-eps">(.*?)</span>' data = httptools.downloadpage(item.url).data matches = re.compile(patron, re.S).findall(data) itemlist = [] for scrapedurl, scrapedtitle, scrapedthumbnail, scrapedep in matches: s, ep = scrapertools.find_single_match(scrapedep, r'(\d+)x(\d+)\s') itemlist.append( Item(channel=item.channel, action="episodios", contentType=item.contentType, title="[B]" + scrapedtitle + "[/B] " + scrapedep, fulltitle=scrapedtitle, show=scrapedtitle, url=scrapedurl, extra=item.extra, args={ "season": s, "episode": ep })) tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True) return itemlist else: patron_next = r'<a class="next page-numbers" href="(.*?)">' itemlist = support.scrape(item, patron, list_groups, patronNext=patron_next, action="episodios") if itemlist[-1].action != "peliculas": itemlist.pop() return itemlist
def mainlist(item): support.log() itemlist = [] support.menu(itemlist, 'Ultime Uscite', 'peliculas', host + "/category/serie-tv/", "episode") support.menu(itemlist, 'Ultimi Episodi', 'peliculas', host + "/ultimi-episodi/", "episode", 'latest') support.menu(itemlist, 'Categorie', 'menu', host, "episode", args="Serie-Tv per Genere") support.menu(itemlist, 'Cerca...', 'search', host, 'episode', args='serie') autoplay.init(item.channel, list_servers, []) autoplay.show_option(item.channel, itemlist) return itemlist
def _to_mixed(x, generator, **kwargs): """converts any number in base ten to a mixed base this is a generalized form, do not call directly gen_args are a dictionary of input flags fed to the generator generator is a function that gives the mixed base digits via next() """ if not x: return [0] sgn, sep = kwargs.get('sgn', '-'), kwargs.get('sep', '.') gen_args = kwargs.get('gen_args', {}) n, one = abs(x), _sup.mpf(1) whl = int(n) if whl != n: frc = _sup.mpf(n) - int(n) else: frc = 0 # if not enough precision, a "fraction" might appear gw = generator(**gen_args) b = next(gw) while not b: b = next(gw) # base can't start at zero ans = [sgn] if x < 0 else [] while whl: # whole part whl, d = divmod(whl, b) ans.append(d) b = next(gw) ans.reverse() if not frc: return ans # is an integer prc = -int(_sup.log(frc, 10)) + 1 + _sup.prec // 7 # this is a total guess ans.append(sep) gf = generator(**gen_args) b = next(gf) while not b: b = next(gf) while prc > 0: # fractional part d, frc = divmod(frc, one / b) ans.append(int(d)) b *= next(gf) prc -= 1 return ans
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Module # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import support support.log('skye', 18) from support import log log('skye', 18) from sys import path log(path) # __name__ === '__main__' => 表示本身為主運行 # __name__ === '__file_name__ => 表示為加載的模組 print(__name__) support.test() # dir 可以看到這個物件下的所有屬性和函數名 print(dir(support)) print(dir(log)) print('----------------------') print(dir()) print('----------------------') import my_module.fmt.core my_module.fmt.core.fmt_core()
import discord import asyncio from support import log, look_up_dict, token, server_id logger = log('discord', 'discord.log') client = discord.Client() vocab = None @client.event async def on_ready(): global vocab server = client.get_server(id=server_id) vocab = discord.utils.get(server.channels, name='vocabulary') @client.event async def on_message(message): if message.content.startswith('!dic'): words = message.content.split()[1:] for word in words: post = get_meaning(word) await client.send_message(vocab, post) await client.delete_message(message) def get_meaning(word): return look_up_dict(word) if __name__ == '__main__':
def base_prec(prec, newbase, oldbase=2): "gives precision in new base" if newbase.imag: newbase *= mpc(newbase.real, -newbase.imag) if oldbase.imag: oldbase *= mpc(oldbase.real, -oldbase.imag) return int(prec * abs(_sup.log(abs(oldbase), abs(newbase))))
def menu(item): support.log() patron = r'<li class="cat-item.*?href="([^"]+)".*?>(.*?)</a>' return support.scrape(item, patron, ["url", "title"], action="peliculas")
def main() -> int: juego.init() parser = argparse.ArgumentParser() parser.add_argument("-l", "--level", help="Dificultad por defecto -> 0", default=prop.LEVEL, type=int) parser.add_argument('-d', '--debug', action='store_true') parser.add_argument('-C', '--cache', action='store_true') options = parser.parse_args() prop.LEVEL = options.level prop.__DEBUG__ = options.debug prop.CACHE_ENABLED = options.cache log('Quoridor - Complejodad Algorítmica - Grupo 7') log('Iniciando...') start = time.time() pygame.init() clock = pygame.time.Clock() pygame.display.set_mode((800, 600)) pygame.display.set_caption(prop.GAME_TITLE) screen = pygame.display.get_surface() screen.fill(Color(255, 255, 255)) board = juego.BOARD = Board(screen) board.draw() if prop.CACHE_ENABLED: if not os.path.exists(prop.CACHE_DIR): os.makedirs(prop.CACHE_DIR, exist_ok=True) if not os.path.isdir(prop.CACHE_DIR): prop.CACHE_ENABLED = False cont = True while cont: clock.tick(prop.FRAMERATE) pygame.display.flip() if not board.computing and not board.finished: if board.current_player.BOT: board.computing = True thread = threading.Thread(target=board.computer_move) thread.start() cont = dispatch(pygame.event.get(), board) end = time.time() game_time = (end - start) del board.rows pygame.quit() if prop.CACHE_ENABLED: for pawn in board.pawns: if pawn.BOT is not None: pawn.BOT.flush_cache() log('Nodos guardados: %i' % juego.MEMOIZED_NODES) log('Nodos utilizados guardados: %i' % juego.MEMOIZED_NODES_HITS) for pawn in board.pawns: log('Distancias guardadas para [%i]: %i' % (pawn.id, pawn.distances.MEMO_COUNT)) log('Distancias recorridas guardadas [%i]: %i' % (pawn.id, pawn.distances.MEMO_HITS)) log('Tiempo de juego en segundos: ') log(game_time) log('¡Adiós!') return 0