How to use fast_time method in hypothesis

Best Python code snippet using hypothesis

main.py

Source:main.py Github

copy

Full Screen

1import itertools2import torch3import time4import matplotlib.pyplot as plt5# Get minimal representation of a string6def getminimal(terms):7 c = 'a'8 skip = [',', "-", ">"]9 dict = {x : x for x in skip}10 for x in terms:11 if x not in skip and x not in dict:12 dict[x] = c13 c = chr(ord(c) + 1)14 return ''.join(dict[c] for c in terms)15def get_mask(term):16 return sum(1 << (ord(c) - ord('a')) for c in term)17def evaluate_path(terms):18 terms = getminimal(terms)19 [prefix, suffix] = terms.split("->")20 vals = [get_mask(term) for term in [*prefix.split(","), suffix]]21 n = len(vals)22 pmask = vals.copy()23 for i in range(1, n):24 pmask[i] = pmask[i-1] | pmask[i]25 smask = vals.copy()26 for i in reversed(range(0, n - 1)):27 smask[i] = smask[i+1] | smask[i]28 res = 029 for i in range(n - 1):30 p = 0 if i == 0 else pmask[i - 1]31 s = smask[i + 1]32 curmask = (p & s) | vals[i]33 res = max(res, bin(curmask).count("1"))34 return res35def find_opt_path_brute_force(terms):36 [prefix, suffix] = terms.split("->")37 ops = prefix.split(",")38 idx = range(len(ops))39 min_score = -140 permute = -141 for per in list(itertools.permutations(idx)):42 path = "->".join([','.join(ops[per[i]] for i in range(len(ops))), suffix])43 # print(path)44 cur_score = evaluate_path(path)45 if min_score == -1 or cur_score < min_score:46 min_score = cur_score47 permute = per48 return (min_score, permute)49def find_opt_path_dp(terms):50 terms = getminimal(terms)51 [prefix, suffix] = terms.split("->")52 vals = [get_mask(term) for term in prefix.split(",")]53 final_mask = get_mask(suffix)54 n = len(vals)55 sum_mask = [0] * (1 << n)56 for mask in range(1 << n):57 for j in range(n):58 if ((mask >> j) & 1) == 1:59 sum_mask[mask] |= vals[j]60 dp = [-1] * (1 << n)61 back = [-1] * (1 << n)62 dp[0] = 063 for mask in range(1 << n):64 for j in range(n):65 if ((mask >> j) & 1) == 0:66 smask = (sum_mask[((1 << n) - 1) ^ (mask | (1 << j))] | final_mask)67 nxtdp = max(dp[mask], bin((sum_mask[mask] & smask) | vals[j]).count("1"))68 if dp[mask | (1 << j)] == -1 or nxtdp < dp[mask | (1 << j)]:69 dp[mask | (1 << j)] = nxtdp70 back[mask | (1 << j)] = j71 permute = []72 cur = (1 << n) - 173 while cur != 0:74 permute.append(back[cur])75 cur ^= (1 << back[cur])76 return (dp[(1 << n) - 1], tuple(reversed(permute)))77def permute_terms(terms, per):78 [prefix, suffix] = terms.split("->")79 ops = prefix.split(",")80 return "->".join([','.join(ops[per[i]] for i in range(len(ops))), suffix])81def fast_einsum(equation, operands):82 [_, p] = find_opt_path_dp(equation)83 new_equation = permute_terms(equation, p)84 print("fast_einsum using new equation: " + new_equation)85 return torch.einsum(new_equation, [operands[i] for i in p])86def benchmark(equation, operands):87 print("benchmarking on equation " + equation + "\n")88 total_einsum = 089 total_fast = 090 for i in range(10):91 print("torch.einsum: ")92 einsum_time = -time.perf_counter()93 torch.einsum(equation, operands)94 einsum_time += time.perf_counter()95 if i >= 5:96 total_einsum += einsum_time97 print("fast_einsum:")98 fast_time = -time.perf_counter()99 fast_einsum(equation, operands)100 fast_time += time.perf_counter()101 if i >= 5:102 total_fast += fast_time103 return total_einsum / 5, total_fast / 5104def plot_time(xs, fast_ein_time, ein_time, plot_title):105 plt.plot(xs, fast_ein_time, label='fast einsum')106 plt.plot(xs, ein_time, label='Pytorch einsum')107 title = plot_title108 plt.title(title)109 plt.yscale('log', basey=10)110 plt.xticks(xs)111 plt.xlabel("n")112 plt.ylabel("Time (ms)")113 plt.legend()114 plt.savefig( f"./path_opt/results/{title}.png")115 plt.show(block=False)116 plt.close() 117y1s = []118y1_ein = []119y2s = []120y2_ein = []121for dim in range(1, 20):122 einsum_time, fast_time = benchmark('bdik,acaj,ikab,ajac,ikbd->abjk', [torch.rand(dim, dim, dim, dim) for i in range(5)])123 y1_ein.append(einsum_time)124 y1s.append(fast_time)125 einsum_time, fast_time = benchmark("ab,cd,ef,fe,dc,ba->a", [torch.rand(dim, dim), torch.rand(dim, dim),126 torch.rand(dim, dim), torch.rand(dim, dim),127 torch.rand(dim, dim), torch.rand(dim, dim)])128 y2_ein.append(einsum_time)129 y2s.append(fast_time)130x = [i for i in range(1, 20)]131plot_time(x, y1s, y1_ein, "bdik,acaj,ikab,ajac,ikbd->abjk")...

Full Screen

Full Screen

spider.py

Source:spider.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2#!/usr/bin/env python3import argparse4import json5import os6import re7import sys8import urllib9import urllib210from dojang.util import parse_config_file11from tornado.options import options12PROJDIR = os.path.abspath(os.path.dirname(__file__))13ROOTDIR = os.path.split(PROJDIR)[0]14try:15 import keepcd16 print('Start keepcd version: %s' % keepcd.__version__)17except ImportError:18 import site19 site.addsitedir(ROOTDIR)20 site.addsitedir(ROOTDIR+"/keepcd")21 print('Development of keepcd: ' + ROOTDIR)22def spider_callback(self, message):23 print message24def run_command(name, second_arg):25 if name == 'dl_eslpod':26 download_eslmp3()27 elif name == "parse_elspod":28 parse_eslmp3()29 else:30 from dojang.util import parse_config_file, import_object31 from easycrawl.models import CrawlSite32 # from keepcd.admin.easycrawl.douban.app import worker33 site = CrawlSite.query.filter_by(name=name).first()34 worker_name = "easycrawl.%s.app.worker" % name35 print worker_name36 worker = import_object(worker_name)37 if second_arg == 'debug':38 print "\nexec debug()\n\n"39 worker.debug()40 worker.finished()41 elif second_arg == 'parse':42 print "\nexec parse()\n\n"43 worker.parse()44 else:45 print "\nexec run()\n\n"46 worker.run()47 worker.finished()48def download_file(url, filename):49 try:50 u = urllib.FancyURLopener()51 u.retrieve(url, filename)52 except IOError as e:53 url = u.headers['Location']54 print e55 print url56 57def download_eslmp3():58 from easycrawl.eslpod.models import EslPod59 pods = EslPod.query.filter_by().all()60 for pod in pods:61 if pod.media:62 media = pod.media63 media_file = media.split('/')64 mp3_file = media_file[-1]65 dest_file = "/Users/zhenng/tmp/eslpod/" + mp3_file 66 if not os.path.exists(dest_file):67 print media68 download_file(media, dest_file)69def parse_eslmp3():70 from easycrawl.eslpod.models import EslPod71 pods = EslPod.query.filter_by().all()72 for pod in pods:73 if pod.media:74 media = pod.media75 media_file = media.split('/')76 mp3_file = media_file[-1]77 mp3_filename = mp3_file.split('.')[0]78 src_file = "/Users/zhenng/tmp/eslpod/old/" + mp3_file79 dest_file = "normal/" + mp3_filename80 #print pod.fast_dialog81 if not os.path.exists(src_file):82 #print "not exists", src_file83 continue84 if pod.fast_dialog:85 fast_time = pod.fast_dialog86 #print "fasttime: type", type(fast_time)87 fast_time = fast_time.replace(":", ".")88 cmd = "mp3splt -o %s %s %s EOF-0.30" % (dest_file, src_file, fast_time)89 print cmd90 os.system(cmd)91if __name__ == "__main__":92 # reload(sys)93 # sys.setdefaultencoding('utf8') 94 parser = argparse.ArgumentParser(95 prog='keep cd',96 description='keep',97 )98 parser.add_argument('command', nargs="*")99 args = parser.parse_args()100 name = args.command[0]101 second_arg = None102 if len(args.command) >= 2:103 second_arg = args.command[1]104 105 parse_config_file("../settings.py")106 107 run_command(name, second_arg)108 # r = "^/movies/\d+[/]*$ || http://imax.im/movies/\d+[/]*$"109 # # r = "^http://movie.douban.com/subject/\d+[/]*$"110 # url = 'http://imax.im/movies/36172'111 # # url = 'http://movie.douban.com/subject/2345'112 # ps = r.split('||')113 # for patten in ps:114 # patten = patten.strip()115 # print patten116 # if re.search(patten, url):117 # print "true", url118 # else:119 # print "false", url120 121 ...

Full Screen

Full Screen

bitz.py

Source:bitz.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3Created on Mon Sep 7 14:37:34 20204@author: maximos5"""6import pandas as pd7import os8import matplotlib.pyplot as plt9import scipy.stats as spst10results = pd.read_csv( os.path.join( 'datasets' , 'bitzounis_results.csv' ) , decimal='.' )11stages = ['circuit', 'carmona', 'sprint', 'laguna']12for s in stages:13 # max14 fast_max = results[ s + '_' + 'fast_max']15 fast_max = fast_max[ ~pd.isna(fast_max) ]16 17 slow_max = results[ s + '_' + 'slow_max']18 slow_max = slow_max[ ~pd.isna(slow_max) ]19 20 w_max = spst.wilcoxon( fast_max , slow_max )[1]21 22 plt.clf()23 plt.boxplot( [slow_max, fast_max] ); plt.title(str( w_max ))24 plt.savefig(os.path.join('figs_bitz', s + '_' + 'max.png'), dpi=300)25 26 # avg27 fast_avg = results[ s + '_' + 'fast_avg']28 fast_avg = fast_avg[ ~pd.isna(fast_avg) ]29 30 slow_avg = results[ s + '_' + 'slow_avg']31 slow_avg = slow_avg[ ~pd.isna(slow_avg) ]32 33 w_avg = spst.wilcoxon( fast_avg , slow_avg )[1]34 35 plt.clf()36 plt.boxplot( [slow_avg, fast_avg] ); plt.title(str( w_avg ))37 plt.savefig(os.path.join('figs_bitz', s + '_' + 'avg.png'), dpi=300)38 39 # time40 fast_time = results[ s + '_' + 'fast_time']41 fast_time = fast_time[ ~pd.isna(fast_time) ]42 43 slow_time = results[ s + '_' + 'slow_time']44 slow_time = slow_time[ ~pd.isna(slow_time) ]45 46 w_time = spst.wilcoxon( fast_time , slow_time )[1]47 48 plt.clf()49 plt.boxplot( [slow_time, fast_time] ); plt.title(str( w_time ))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful