def runner(searchdir="."): """Attempts to locate a build script by checking the search directory and walking up parent directories towards the filesystem root. If found, the build script will be run. When the script exits, the system-level exit() will be called using the return value from the script.""" cdir = op.abspath(searchdir) scriptname = None while True: scriptname = _find_script(cdir) if scriptname: break if cdir == op.abspath(os.sep): break cdir = op.abspath(op.join(cdir, "..")) if not scriptname: alert("Script not found.") return path = op.join(cdir, scriptname) alert(f"Running `{path}`:") with auxly.filesys.Cwd(cdir): cmd = f"python {scriptname}" args = sys.argv[1:] if args: cmd += " " + " ".join(args) sys.exit(auxly.shell.call(cmd))
def build(config): global BUILD BUILD = "release" if not qprompt.ask_yesno("Build release (else debug)?", dft=config['release']): BUILD = "debug" # Build application. call("uic mainwindow.ui >> ui_mainwindow.h") call("qmake") if not os.path.exists(BUILD): os.makedir(BUILD) status = call("make %s" % (BUILD)) try: # Copy over Qt DLLs. for dll in config['qt_dlls']: src = os.path.join(config['qt_bin_dir'], dll) shutil.copy(src, BUILD) # Copy over assets. for ast in config['assets']: shutil.copy(ast, BUILD) # Remove unnecessary files from build dir. for f in os.listdir(BUILD): if any([f.endswith(e) for e in config['build_dir_ext_rm']]): os.remove(os.path.join(BUILD, f)) except: qprompt.alert("File copy failed! Try killing app.") status = 1 # Run app. if status == 0: if qprompt.ask_yesno("Run app?", dft=True): run() else: qprompt.alert("ERROR: Build failed!")
def stop(): global TESTSERVER if not is_running(): warn("Application not running!") return TESTSERVER.stop() TESTSERVER = None alert("Application stopped.")
def stop(): global PROCS if not is_running(): warn("Application not running!") return for p in PROCS: p.stop() PROCS = [] alert("Application stopped.")
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 run(): global BUILD if None == BUILD: qprompt.alert("[WARNING] Build app first!") return retdir = os.getcwd() os.chdir(BUILD) kill() call("start quickwin.exe") os.chdir(retdir)
def run(): global TESTSERVER if is_running(): warn("App server already running!") return with Cwd("app"): TESTSERVER = start("python app.py", "__temp-flask.log") alert("Application starting...") time.sleep(3) if TESTSERVER.isrunning(): alert("Application started.") browse() else: warn("Issue starting application!") stop()
def attempt_shrink(picpath, old_notes): old_size = auxly.filesys.File(picpath).size() tmppath = op.join(gettempdir(), "__temp-shrink.png") cmd = f"pngquant --quality=40-60 --output {tmppath} {picpath}" auxly.shell.silent(cmd) new_size = auxly.filesys.File(tmppath).size() if new_size and old_size: if new_size < old_size: new_notes = scan_notes(tmppath) or "NA" if new_notes == old_notes: if auxly.filesys.move(tmppath, picpath): qprompt.alert( f"Saved {old_size - new_size} bytes shrinking `{picpath}`." ) return True qprompt.alert(f"Could not shrink `{picpath}`.") auxly.filesys.delete(tmppath) return False
def updatePass(): global pragma_input conn = sqlcipher.connect('.passman.db') cur = conn.cursor() cur.execute(pragma_input) print(pd.read_sql_query( "SELECT * FROM passwords", conn)) #display all passwords so user can easily see its ID print("Select the ID of the credentials you wish to EDIT") try: ID = qprompt.ask_int("ID") #ask user for ID of credential to edit except: qprompt.error("ID NOT FOUND") #error if ID is not found retry = qprompt.ask_yesno( "Retry?") #prompt user to retry or exit to main menu if retry == False: mainMenu() else: updatePass() print( "Credential set selected! What would you like to change?" ) #ask user what about the chosen set of credentials they would like to change qprompt.alert("HINT: Use '?' for a list of options") selection = qprompt.ask_str("Edit", valid=["website", "username", "password"]) if selection.lower() == "website": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET WEBSITE = '{}' WHERE ID = '{}'".format( new, ID)) #updates record with new info elif selection.lower() == "username": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET USERNAME = '******' WHERE ID = '{}'".format( new, ID)) elif selection.lower() == "password": new = qprompt.ask_str("Enter new value") cur.execute( "UPDATE passwords SET PASSWORD = '******' WHERE ID = '{}'".format( new, ID)) conn.commit() cur.close() mainMenu()
def run(): global PROCS if is_running(): warn("App server already running!") return with Cwd("app"): if not op.isdir("node_modules"): status("Running NPM install...", silent, ["npm install"]) PROCS.append( start( "node node_modules/rollup/dist/bin/rollup -w -c rollup.config.js" )) PROCS.append(start("python app.py")) alert("Application starting...") time.sleep(3) if all(map(lambda p: p.isrunning(), PROCS)): alert("Application started.") browse() else: warn("Issue starting application!") stop()
def walk(startdir, picdirname): """Walk all directories under startdir and scan when directory name matches picdirname. Existing notes are overwritten.""" if not op.isdir(startdir): qprompt.fatal("Given path must be existing directory!") total_count = {'reused': 0, 'scanned': 0} for d in auxly.filesys.walkdirs(startdir, "pics"): if op.basename(d) != picdirname: continue qprompt.hrule() qprompt.alert(f"Walking through `{d}`...") dirpath = auxly.filesys.Path(d) new_count = create_picnotes(dirpath, False) if new_count: total_count['reused'] += new_count['reused'] total_count['scanned'] += new_count['scanned'] qprompt.alert( f"Walk complete, scanned={total_count['scanned']} reused={total_count['reused']}" ) sys.exit()
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 create_picnotes(dirpath, confirm=True, shrink=False): """Attempts to extract notes from all pics found under the given directory and write them to a file.""" dirpath = op.abspath(dirpath) titlepath = os.sep.join(dirpath.split(os.sep)[-2:]) pics = list(auxly.filesys.walkfiles(dirpath, ".(png|jpg)", recurse=True)) if not pics: qprompt.warn("No pics found under directory!") return pics = sort_pics(pics) qprompt.alert(f"Found {len(pics)} pics found under directory.") doc = auxly.filesys.File(dirpath, "pic_notes.adoc") existing_notes = {} if doc.exists(): existing_notes = parse_picnotes(doc) if confirm: if not qprompt.ask_yesno( f"The `pic_notes.adoc` file already exists with {len(existing_notes)} pic notes found, overwrite it?" ): return doc.empty() qprompt.alert(f"Initialized file `{doc.path}`") doc.appendline(f"= PIC NOTES: `{titlepath}`") doc.appendline(":date: " + datetime.now().strftime("%d %B %Y %I:%M%p")) doc.appendline(":toc:") doc.appendline("") doc.appendline("NOTE: Entries sorted by base filename.") doc.appendline("") count = {'reused': 0, 'scanned': 0} for idx, picpath in enumerate(pics, 1): relpath = op.relpath(picpath, dirpath) msg = f"({idx} of {len(pics)})" if relpath in existing_notes.keys() and auxly.filesys.checksum( picpath) == existing_notes[relpath]['md5']: qprompt.alert(f"{msg} Reusing `{picpath}`.") notes = existing_notes[relpath]['note'] if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['reused'] += 1 else: notes = qprompt.status(f"{msg} Scanning `{picpath}`...", scan_notes, [picpath]) or "NA" if shrink: attempt_shrink(picpath, notes) line = format_adoc_line(relpath, picpath, notes) count['scanned'] += 1 doc.appendline(line) return count
import auxly.shell as sh import sys import qprompt sys.path.append("..") sys.dont_write_bytecode = True from _Check_Versions import VERCHK from _Install_Package import generate_readme, cleanup_readme ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pause = True if len(sys.argv) > 1 and "nopause" == sys.argv[1]: pause = False ver = VERCHK.run() if not ver: qprompt.alert("Issue with version info!") sys.exit(1) if qprompt.ask_yesno("Upload version `%s`?" % (ver)): generate_readme() sh.call("python setup.py sdist upload") cleanup_readme() if pause: qprompt.pause() sys.exit(0)
"""This example deletes all PYC files in the project.""" import auxly import qprompt delfunc = lambda is_test: auxly.filesys.delete("..", "\.pyc$", recurse=True, test=is_test) delfiles = delfunc(True) if len(delfiles): print("Files to delete:") print("\n".join([" " + i for i in delfiles])) if qprompt.ask_yesno("OK to delete?"): if delfunc(False) == delfiles: qprompt.alert("Files deleted.") else: qprompt.warn("Some files not deleted!") else: qprompt.alert("No files to delete.") qprompt.pause()
##==============================================================# ## SECTION: Imports # ##==============================================================# import os import subprocess import sys import qprompt sys.path.append("..") sys.dont_write_bytecode = True from _Check_Versions import VERCHK from _Install_Package import generate_readme, cleanup_readme ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': ver = VERCHK.run() if not ver: qprompt.alert("Issue with version info!") exit() if qprompt.ask_yesno("Upload version `%s`?" % (ver)): generate_readme() subprocess.call("python setup.py sdist upload", shell=True) cleanup_readme()
import qprompt sys.path.append("..") sys.dont_write_bytecode = True from _Check_Versions import VERCHK from _Install_Package import generate_readme, cleanup_readme ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': pause = True if len(sys.argv) > 1 and "nopause" == sys.argv[1]: pause = False ver = VERCHK.run() if not ver: qprompt.alert("Issue with version info!") sys.exit(1) if 0 != qprompt.status("Running tests...", sh.silent, [r"..\tests\_Run_Tests.py nopause"]): qprompt.alert("Issue running tests!") sys.exit(1) if qprompt.ask_yesno("Upload version `%s`?" % (ver)): generate_readme() sh.call("python setup.py sdist upload") cleanup_readme() if pause: qprompt.pause() sys.exit(0)
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")
def run_app(): global ELECTRON path = op.normpath(op.join(ELECTRON, "electron.exe")) qprompt.alert(path) auxly.shell.call(f"start {path} .")