def make_file(inpath, tmpldict, outpath=None): inpath = op.abspath(inpath) if outpath: outpath = render_str(outpath, tmpldict) if op.isdir(outpath): outpath = op.join(outpath, op.basename(inpath)) outpath = render_str(outpath, tmpldict) if is_binary(inpath): qprompt.status("Copying `%s`..." % (outpath), fsys.copy, [inpath, outpath]) return text = render_file(inpath, tmpldict) if text == None: return False # Handle rendered output. if outpath: outpath = op.abspath(outpath) if inpath == outpath: qprompt.fatal("Output cannot overwrite input template!") fsys.makedirs(op.dirname(outpath)) with io.open(outpath, "w", encoding="utf-8") as f: qprompt.status("Writing `%s`..." % (outpath), f.write, [text]) else: qprompt.echo(text) return True
def _ask(self, line): if not line: return qst, ans = self._get_qst_ans(line) msg = Practice._get_msg_base(qst) if ans.lang.hint or ans.lang.dynamic: if ans.lang.dynamic: Record = Query() results = self.db.search(Record.ln == line) # Get most recent results. num_results = 3 results = sorted(results, key=lambda r: r['dt'], reverse=True)[:num_results] oks = [r['ok'] for r in results] while len(oks) < num_results: oks.append(0.7) ratio = 0 if results: ratio = statistics.mean(oks) ans.lang.hint = dynamic_hintnum(ans.rand, ratio) if ans.lang.hint: msg += Practice._get_msg_hint(ans) talk_qst = callstop(talk) tries = 0 while True: q.alert(msg) if qst.lang.talk: talk_qst(qst.rand, qst.lang.name.short) t_start = time.time() rsp = q.ask_str("").lower().strip() sec = time.time() - t_start vld = Practice._get_valid(ans) record = self._prep_record(line, rsp, qst, ans, sec, tries) closest_orig, _ = guess_similarity(rsp, Practice._get_valid_orig(ans)) if rsp in vld: record['ok'] = 1.0 q.echo("[CORRECT] " + ans.text) if self.config.record: self.db.insert(record) else: tries += 1 _, record['ok'] = guess_similarity(rsp, vld) q.error(closest_orig) if self.config.record: self.db.insert(record) if self.config.redo: continue if tries > 0: self.miss.add(line) else: self.okay.add(line) if ans.lang.talk: say, _ = guess_similarity(rsp, Practice._get_valid_orig(ans)) talk(say, ans.lang.name.short, wait=True) return
def count(path): total = 0 for i in listdir(path): try: if not i.endswith(".txt"): continue if i.startswith("__temp"): continue num = len(File(i).readlines()) total += num q.echo("%u\t%s" % (num, op.basename(i))) except: pass q.wrap("Total = %u" % (total))
def start(self): path = get_file(self.config.path) lines = [ line.strip() for line in File(path).read().splitlines() if line ] random.shuffle(lines) lines = lines[:self.config.num] while True: q.clear() self.miss = set() self.okay = set() for num, line in enumerate(lines, 1): q.echo("%s of %s" % (num, len(lines))) self._ask(line) q.hrule() fmiss = File(self.config.path, MISSED_VOCAB) for miss in self.miss: fmiss.append(miss + "\n") q.echo("Results:") q.echo(f"Correct = {len(self.okay)}") q.echo(f"Missed = {len(self.miss)}") q.hrule() if not q.ask_yesno("Retry?", default=False): break if self.miss and q.ask_yesno("Missed only?", default=True): lines = list(self.miss) if q.ask_yesno("Shuffle?", default=True): random.shuffle(lines) lines = lines[:self.config.num]
def check(inpath, echo=False, **kwargs): """Checks the inpath template for variables.""" tvars = check_template(op.basename(inpath)) if op.isfile(inpath): if not is_binary(inpath): with io.open(inpath) as fi: tvars += check_template(fi.read()) else: for r, ds, fs in os.walk(inpath): for x in ds + fs: xpath = op.join(r, x) tvars += check(xpath) tvars = sorted(list(set(tvars))) if echo: qprompt.echo("Found variables:") for var in tvars: qprompt.echo(" " + var) return tvars
def learn(self): path = get_file(self.config.path) lines = [ line.strip() for line in File(path).read().splitlines() if line ] random.shuffle(lines) lines = lines[:self.config.num] q.clear() for num, line in enumerate(lines, 1): q.echo("%s of %s" % (num, len(lines))) qst, ans = self._get_qst_ans(line) vld = Practice._get_valid(ans) q.alert(qst.rand) q.alert(ans.rand) talk(qst.rand, qst.lang.name.short) talk(ans.rand, ans.lang.name.short, slow=True) rsp = "" while rsp not in vld: rsp = q.ask_str("").lower().strip() q.clear() flush_input() talk(ans.rand, ans.lang.name.short, slow=True) q.echo("%s of %s" % (num, len(lines))) ans.lang.hint = len(ans.rand) // 4 rsp = "" while rsp not in vld: msg = Practice._get_msg_base(qst) + Practice._get_msg_hint(ans) q.alert(msg) rsp = q.ask_str("").lower().strip() ans.lang.hint += 1 q.echo("[CORRECT] " + ans.text) talk(ans.rand, ans.lang.name.short, wait=True) q.clear()
def main(): """This function implements the main logic.""" if len(sys.argv) > 1 and op.isfile(sys.argv[1]): args = {} args['--defaults'] = sys.argv[1] args['--file'] = [] args['--keysep'] = "::" args['--string'] = [] args['PATH'] = [] args['VAL'] = [] args['runargs'] = sys.argv[2:] or "" else: args = docopt(__doc__, version="poppage-%s" % (__version__)) utildict, tmpldict = utilconf.parse(args) # Check required conditions. if not utildict.get('inpath'): qprompt.fatal("Must supply INPATH!") # Handle command. if utildict['command'] == "check": check(utildict['inpath'][0], echo=True) elif utildict['command'] == "make": for inpath, outpath in zip(utildict['inpath'], utildict['outpath']): make(inpath, tmpldict, outpath=outpath) elif utildict['command'] == "run": run(utildict['inpath'][0], tmpldict, outpath=utildict['outpath'][0], execute=utildict.get('execute'), runargs=utildict.get('runargs')) elif utildict['command'] == "debug": qprompt.echo("Utility Dictionary:") pprint(utildict) qprompt.echo("Template Dictionary:") pprint(tmpldict)
import time from qprompt import status, echo status("Sleeping...", time.sleep, [1], fin="Awake.") result = status("Adding...", reduce, [lambda x, y: x + y, range(10)]) echo("result = {0}".format(result))
import time from qprompt import status, echo status("Sleeping...", time.sleep, [1], fin="Awake.") result = status("Adding...", sum, [range(10)]) echo("result = {0}".format(result))
from jikanpy import Jikan from AVL import AVL from ABB import ABB import qprompt jikan = Jikan() # action = jikan.genre(type='anime', genre_id=43) #Numero maximo de genero: 43 genre = qprompt.ask_int("Ingrese el ID del genero que desea ver") if genre in range(1, 44): data = jikan.genre(type='anime', genre_id=genre) while True: qprompt.echo("Genero seleccionado: {}\n".format( data["mal_url"]["name"])) menu = qprompt.Menu() menu.add("A", "ABB") menu.add("B", "AVL") menu.add("C", "2-3") menu.add("D", "Salir") qprompt.echo("Elija en que estructura desea guardar la información") choice = menu.show() if choice == "A": info = ABB(data["mal_url"]["name"], data["anime"]) elif choice == "B": info = AVL(data["mal_url"]["name"], data["anime"]) elif choice == "C": info = TwoThree(data["mal_url"]["name"], data["anime"]) elif choice == "D": break
from qprompt import alert, echo, error, warn, info echo("Just a message.") alert("Heads up!") info("Hmm...") warn("Uh oh...") error("OMG this is bad!") error("REALLY BAD", end="!!!!!!!\n")
import sys from qprompt import Menu, echo menu = Menu() menu.add("f", "foo", lambda: echo("foo selected!")) menu.add("b", "bar", lambda: echo("bar selected!")) arg = None for arg in sys.argv[1:]: menu.run(arg) if None == arg: menu.show()