def main(): ap = ArgumentParser() ap.add_argument('P') P = int(sys.argv[1]) tau = float(sys.argv[2]) delta = float(sys.argv[3]) pic = Picture(sys.argv[4]) prevBeads = BlobFinder(pic, tau).getBeads(P) # for every frame: for i in sys.argv[5:]: currBeads = BlobFinder(Picture(i), tau).getBeads(P) # for every bead in that frame: for currBead in range(len(currBeads)): # intialize shortest_dist with largest possible dimension: shortest_dist = max([pic.width(), pic.height()]) # search for currBead closest to prevBead: for v in range(min([len(currBeads), len(prevBeads)])): d = prevBeads[v].distanceTo(currBeads[currBead]) if d < shortest_dist: shortest_dist = d # confirm that displacement is within delta: if shortest_dist <= delta: # if yes, then show the distance: stdio.writef('%.4f\n', shortest_dist) stdio.writeln() prevBeads = currBeads
def main(): # intialize P, tau, and delta. P, tau = int(sys.argv[1]), float(sys.argv[2]) delta = float(sys.argv[3]) firstPic = BlobFinder(Picture(sys.argv[4]), tau) prevBeads = firstPic.getBeads(P) for v in sys.argv[5:]: # construct blobfinder, currBeads, and a list of beads blobfinder = BlobFinder(Picture(v), tau) currBeads = blobfinder.getBeads(P) for currBead in currBeads: # map distances a = map(lambda x: currBead.distanceTo(x), prevBeads) # filter the list minDist = list(filter(lambda x: x <= delta, a)) # if the list isn't empty, write the min distance if minDist: minDist = min(minDist) stdio.writef('%.4f\n', minDist) # instialize prevBeads wiht currBeads prevBeads = currBeads stdio.writeln()
def main(): P = int(sys.argv[1]) tau = float(sys.argv[2]) delta = float(sys.argv[3]) for i in range(4,len(sys.argv) - 1): pic1 = Picture(sys.argv[i]) pic2 = Picture(sys.argv[i+1]) blobscan = BlobFinder(pic1,tau) blobscan2 = BlobFinder(pic2,tau) blob = blobscan.getBeads(P) blob2 = blobscan2.getBeads(P) for i in range(len(blob2)): least = 0.0000 first = True for j in range(len(blob)): b = blob2[i] bb = blob[j] distance = b.distanceTo(bb) if(distance <= delta and first): least = distance first = False elif(distance <= delta and distance < least): least = distance if(least>0): stdio.writef('%s\n', round(least,4)) stdio.write('\n')
def run_game(): pygame.init() ai_settings = Settings() stats = GameStats() stats.restart() #载入屏幕,背景音乐 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) screen pygame.display.set_caption('zombies invasion!'.title()) pygame.mixer.music.load('music/佐藤直紀 - 3年E組の不安.mp3') pygame.mixer.music.play(-1, 0.0) #此处高能BGM,左边为循环次数,右边为开始时间,从音乐的哪里开始 mainclock = pygame.time.Clock() #载入背景并绘制 background = gf.background_get_rect(ai_settings.screen_width, ai_settings.screen_height) screen.blit(background, (0, 0)) #绘制寒冰射手 snow_pea = Snow_Pea(screen) snow_pea.blitme() #载入开始键 start_button = Button(screen, 'start') picture1 = Picture(screen, 'images/APPROACHING.png') picture2 = Picture(screen, 'images/Credits_wearetheundead.jpg') #制作空弹夹 bullets = Group() stinkies = Group() zombies = Group() buckethead_zombies = Group() float_zombies = Group() mainclock.tick(ai_settings.fps) #开始游戏主循环 while True: gf.check_events(snow_pea, stats, screen, stinkies, start_button) gf.update_screen(snow_pea, screen, bullets, background, zombies, stats, start_button, ai_settings, buckethead_zombies, stinkies, picture1, float_zombies, picture2) gf.level_up(stats, zombies, buckethead_zombies, float_zombies) gf.update_events(bullets, screen, zombies, buckethead_zombies, stinkies, float_zombies) if stats.game_active: gf.fire(stats, ai_settings, snow_pea, screen, bullets, zombies, buckethead_zombies, float_zombies) #检测碰撞 gf.check_bullet_zombie_collisions(bullets, zombies, stats, buckethead_zombies, float_zombies) gf.check_pea_zombie_collision(zombies, snow_pea, ai_settings, stats, background, bullets, buckethead_zombies, float_zombies) gf.check_courtyard_zombie(zombies, ai_settings, stats, screen, bullets, snow_pea, buckethead_zombies, float_zombies)
def main(): P = int(sys.argv[1]) tau = float(sys.argv[2]) delta = float(sys.argv[3]) files = sys.argv[4:] beads1 = BlobFinder(Picture(files[0]), tau).getBeads(P) for i in range(1, len(files)): beads0 = beads1 beads1 = BlobFinder(Picture(files[i]), tau).getBeads(P) for bead in beads0: dist = min(bead.distanceTo(other) for other in beads1) if dist <= delta: stdio.writef('%.4f\n', dist) stdio.writeln()
def initialize(karel_world): """ :param karel_world: World object that this module can draw :return: None """ global _cell_size global _font_size_small global _font_size_large # determine a reasonable canvas cell and canvas size na = karel_world.num_avenues ns = karel_world.num_streets _cell_size = _calculate_cell_size(na, ns) cell_dimensions = (_cell_size, _cell_size) width = _cell_size * (na + 2) + _cell_size // 2 height = _cell_size * ns + (3 * _cell_size) // 4 stddraw.setCanvasSize(int(width), int(height)) stddraw.setXscale(-0.5, float(na) + 2.0) stddraw.setYscale(-0.5, float(ns) + 0.25) # choose a reasonable font size _font_size_small = max(_cell_size // 4, 8) _font_size_large = max(_cell_size // 3, 11) # print('cell size is', _cell_size) # print('font size is', _font_size_small) # create and scale a Picture object for a beeper global _beeper_picture _beeper_picture = Picture(constants.beeper_image_file(_cell_size)) surface = _beeper_picture._surface _beeper_picture._surface = pygame.transform.scale(surface, cell_dimensions) # create and scale a Picture object for Karel's error state global _error_picture _error_picture = Picture(constants.error_image_file()) surface = _error_picture._surface _error_picture._surface = pygame.transform.scale(surface, cell_dimensions) # create, scale, and rotate Picture objects for each of Karel's directions for angle in [90, 0, 270, 180]: pic = Picture(constants.karel_image_file(_cell_size)) pic._surface = pygame.transform.scale(pic._surface, cell_dimensions) pic._surface = pygame.transform.rotate(pic._surface, angle) _karel_pictures.append(pic)
def spider_work(): while True: try: level, url = Spider.SPIDER_QUEUE.get() if level == 1: # 搜索结果页 reqs = requests.get(url, headers=Spider.HEADERS, cookies=Cookie.cookies, timeout=Spider.TIMEOUT) if reqs.status_code == 200: print('搜索页成功:' + url) for details_url in get_details_urls(reqs.text): Spider.SPIDER_QUEUE.put((0, details_url)) else: print('搜索页失败:' + url) elif level == 0: # 图片详情页 reqs = requests.get(url, headers=Spider.HEADERS, cookies=Cookie.cookies) if reqs.status_code == 200: print('详情页成功:' + url) save_picture_info(Picture(*get_picture_info(reqs.text))) else: print('详情页失败:' + url) else: pass except Timeout as e: print(e) except Exception as e: print(e) finally: Spider.SPIDER_QUEUE.task_done()
def test_left(self): self.painter.t.left = MagicMock() line = Picture("-", 10, 90) self.painter.draw(line) self.painter.t.left.assert_called_once_with(90)
def main(): if not os.path.isdir(save_path): os.mkdir(save_path) process = 6 main = Main(process) main.form_parm() for i in range(0, main.cycle_multiproc): pool = Pool(process) cb = pool.map(main.simulate, range(process)) # for recording tmp = [] for k in range(process): tmp.append(cb[k].numneu) print(main.multiproc_co) main.multiproc_co += process # record for k, j in itertools.product(range(process), range(tmp[k])): d = datetime.datetime.today() # generate file name cb[k].parm_dict = str(cb[k].parm_dict) cb[k].parm_dict = cb[k].parm_dict.replace(':', '_') cb[k].parm_dict = cb[k].parm_dict.replace('{', '_') cb[k].parm_dict = cb[k].parm_dict.replace('}', '_') cb[k].parm_dict = cb[k].parm_dict.replace('\'', '') cb[k].parm_dict = cb[k].parm_dict.replace(',', '_') filename = (str(d.year) + '_' + str(d.month) + '_' + str(d.day) + '_' + str(d.hour) + '_' + str(d.minute) + '_' + str(d.second) + '_' + cb[k].parm_dict + '_' + 'N' + str(j) + '_' + "HR.csv") df = pd.DataFrame({ 't': cb[k].tmhist, 'Iext': cb[k].Iext[j, 1], 'x': cb[k].x[j], 'y': cb[k].y[j], 'z': cb[k].z[j], 'Isyn': cb[k].Isyn[j], 'alpha': cb[k].alpha, 'beta': cb[k].beta, 'D': cb[k].D, 'tausyn': cb[k].tausyn, 'Pmax': cb[k].Pmax }) df.to_csv(save_path + '/' + filename) pool.close() pool.join() elapsed_time = time.time() - starttime print("elapsed_time:{0}".format(elapsed_time) + "[sec]\n") pic = Picture(save_path) pic.run() print("ちょう終わりました~♪")
def get_info_list(path): workspace_path = path + "/workspace" pic_info = [] pic_info.append(PIC_SHEET_TITLE) vid_info = [] vid_info.append((VID_SHEET_TITLE)) target_files = [] for root, dirs, files in os.walk(workspace_path): for file in files: tmp_file = root + "/" + file target_files.append(tmp_file) for file in sort_by_creation_time(target_files): _, file_suffix = file.split(".") if file_suffix in PIC_FORMAT: pic = Picture(file) pic_item = pic.get_info() pic_info.append(pic_item) #二维列表 elif file_suffix in VID_FORMAT: vid = Video(file) vid_item = vid.get_info() vid_info.append(vid_item) else: continue return pic_info, vid_info
def test_right(self): self.painter.t.right = MagicMock() line = Picture("+", 10, 90) self.painter.draw(line) self.painter.t.right.assert_called_once_with(90)
def populate_pictures_table(): for r, d, f in os.walk(path): for file in f: filepath = r+"/"+str(file) b = os.path.getsize(filepath) picture = Picture(str(file), b, None) insert_picture(picture)
def on_enter(self): print(self.sm.recent_screen) if self.sm.recent_screen == 'home': if self.picture in self.canvas.children: self.canvas.remove(self.picture) self.picture = Picture(filepath) self.canvas.add(Color(1, 1, 1, 1)) self.canvas.add(self.picture) self.canvas.remove(self.overlay) self.canvas.add(self.overlay) self.settings_button.on_update() self.menu_button.on_update() # reset icon bar self.canvas.remove(self.icon_bar) self.icon_bar = IconBar(self.modes, self.icon_label) self.canvas.add(self.icon_bar) # reset sticker bar if self.sticker_bar in self.canvas.children: self.canvas.remove(self.sticker_bar) self.sticker_bar = StickerBar(self.sticker_label) self.canvas.add(self.sticker_bar) else: self.sticker_bar = StickerBar(self.sticker_label) for h in self.hands: self.canvas.remove(h) self.canvas.add(h) self.on_layout((Window.width, Window.height))
def add_pics(rep, paths, process, recipe=None): """ Add pictures to repository. Arguments: rep -- Add pictures to this repository. paths -- Paths of the pictures to be added (check if path exists). process -- Boolean flag if added pictures should be processed. recipe -- Recipe to use for picture processing. """ for path in paths: if not os.path.exists(path): log.warning("File not found: '%s'. Skipping it." % path) pics = [Picture(path) for path in paths if os.path.exists(path)] rep.index.add(pics) if process: log.info("Processing pictures.") if not recipe: # set up pipeline process_recipe = \ Recipe.fromString(rep.config['recipes.default']) pl = Pipeline('Pipeline1', process_recipe, path=rep.connector.url.path) for pic in pics: pl.put(pic) pl.start() # start processing threads pl.join() # wait until threads exit log.info("Saving index to file.") with rep.connector.connected(): rep.save_index_to_disk() return rep
def test_run_forward(self): self.painter.t.forward = MagicMock() line = Picture("F", 10, 90) self.painter.draw(line) self.painter.t.forward.assert_called_once_with(10)
def main(): p = Picture('heroes-Peter.jpg') w, h, l = write(p) print(w) print(h) for i in range(2): print(l[i])
def scale(source, w, h): target = Picture(w, h) for tCol in range(w): for tRow in range(h): sCol = tCol * source.width() // w sRow = tRow * source.height() // h target.set(tCol, tRow, source.get(sCol, sRow)) return target
def setPicturesFromADirectory(self, name): if os.path.isdir("static/" + name): files = [ f for f in os.listdir("static/" + name) if os.path.isfile(os.path.join("static/" + name, f)) ] for file in files: self.addPicture(Picture(name + "/" + file))
def __init__(self, width, height): game_mouse.Game.__init__(self, "planet", width, height, 10) self.font_height = 12 self.font = pygame.font.SysFont("Courier New", self.font_height) self.mPicture = Picture(width, height) return
def getErrorAndTime(knn, data, tests=100): """ This function returns the runtime and accuracy for a classifier trying two different distance formulas. Parameters ---------- knn : KNN This is the classifier that getErrorAndTime is using to test runtime and accuracy data : MnistData This object contains the testing and training data used to test the inputted knn tests : int This is the amount of testing data the function will test the classifier with Returns ------- tuple - > ((time, time), (accuracy, accuracy)) This tuple contains two tuples containing stats on runtime and accuracy for the classifier. The first time and accuracy in the tuples uses the picture.getDistace method to compare images The second time and accuracy in the tuples uses the picture.grayscaleDistance method to compare images """ count = 0 start_time = time() for x in range(tests): index = randint(0, len(data.test_images) - 1) guessed_label, wasRight = knn.classify_picture( Picture(data.test_images[index]), data.test_labels[index], True) count = count + wasRight end_time = time() first_accuracy = count / tests first_time = end_time - start_time count = 0 start_time = time() for x in range(tests): index = randint(0, len(data.test_images)) guessed_label, wasRight = knn.classify_picture( Picture(data.test_images[index]), data.test_labels[index], False) count = count + wasRight end_time = time() second_accuracy = count / tests second_time = end_time - start_time return (first_time, second_time), (first_accuracy, second_accuracy)
def random_picture(): # 从除了不喜欢的图片中随机选取一张图片 conn = sqlite3.connect(Gallery.DB) with conn: result = conn.execute( "SELECT url, file_size, resolution_ratio, release_date, file_name, file_path, file_exist, islike, create_date FROM gallery WHERE islike!='0' ORDER BY RANDOM() limit 1;") # result = conn.execute("SELECT url, file_size, resolution_ratio, release_date, file_name, file_path, file_exist, islike, create_date FROM gallery WHERE islike!="0" AND file_exist="1" ORDER BY RANDOM() limit 1") for row in result: return Picture(*row)
def generate_latency_picture(dir_term, timestamp_list, producer_info): producer_data = generate_data_by_timestamp(timestamp_list, producer_info) avg_latency_list = [] record_list = [] throughput_list = [] max_latency_list = [] t50latency_list = [] t95latency_list = [] t99latency_list = [] t999latency_list = [] drop_count = 0 for index in sorted(producer_data.keys()): avg_latency = producer_data[index]["avg_latency"] record = producer_data[index]["record"] if record == -1: drop_count += 1 max_latency = producer_data[index]["max_latency"] throughput = producer_data[index]["throughput"] t50latency = producer_data[index]["50th_latency"] t95latency = producer_data[index]["95th_latency"] t99latency = producer_data[index]["99th_latency"] t999latency = producer_data[index]["999th_latency"] avg_latency_list.append(avg_latency) record_list.append(record) max_latency_list.append(max_latency) throughput_list.append(throughput) t50latency_list.append(t50latency) t95latency_list.append(t95latency) t99latency_list.append(t99latency) t999latency_list.append(t999latency) print "--- producer latency ---" print "drop count", drop_count print "avg. num records", round(sum(record_list)/len(record_list), 2), "sent" print "avg. latency", round(sum(avg_latency_list)/len(avg_latency_list), 2), "ms" print "avg. throughput", round(sum(throughput_list)/len(throughput_list), 2), "records/sec" request_list = [] response_list = [] index_list = [] count = 0 message_list = read_transactions() for timestamp in sorted(producer_info.keys()): response = producer_info[timestamp]["record"] response_list.append(response) count += 1 index_list.append(count) request = 0 if count < len(message_list): request = message_list[count] request_list.append(request) if draw_picture: p = Picture(item=dir_term) p.get_latency_picture(sorted(producer_data.keys()), record_list, avg_latency_list) p.get_message_picture(index_list, response_list, request_list)
def main(): P = int(sys.argv[1]) tau = float(sys.argv[2]) delta = float(sys.argv[3]) seq = sys.argv[4:] test = [] for i in range(1, len(seq)): pic = Picture(seq[i - 1]) bf = BlobFinder(pic, tau) beads = bf.getBeads(P) pic = Picture(seq[i]) bf = BlobFinder(pic, tau) beads2 = bf.getBeads(P) for q in beads2: for a in beads: test += [q.distanceTo(a)] if min(test) <= delta: stdio.writef('%.4f\n', min(test)) test = []
def get_first_valid_img(subreddit, path, limit=100): for index, post in enumerate(subreddit.hot(limit=limit)): url = post.url picture = Picture(url, path) if picture.is_valid: picture.publish() return picture else: if os.path.isfile(picture.path): os.remove(picture.path)
def __main__(): min_pixels = int(sys.argv[1]) tau = float(sys.argv[2]) filename = sys.argv[3] picture = Picture(filename) bead = Beadfinder(picture, tau) beads = bead.getBeads(min_pixels) print(len(beads)) for b in beads: print(str(b))
def main(): P = int(sys.argv[1]) tau = float(sys.argv[2]) delta = float(sys.argv[3]) bf = BlobFinder(Picture(sys.argv[4]), tau) prevBeads = bf.getBeads(P) for i in range(5, len(sys.argv)): bf = BlobFinder(Picture(sys.argv[i]), tau) currBeads = bf.getBeads(P) for currBead in currBeads: min_dist = float('inf') for prevBead in prevBeads: d = currBead.distanceTo(prevBead) if d <= delta and d < min_dist: min_dist = d if min_dist != float('inf'): stdio.writef('%.4f\n', min_dist) stdio.writeln() prevBeads = currBeads
def createPicture(): # récupérer toute la post request en dict picture = request.get_json() # convertir le dictionnaire en objet Message picture = Picture(picture['name']) ScraperImage.imageScrape(picture.name, picture.name) return picture.__dict__
def process(source_path, target_path, move): files = common.list_files(source_path) logger.info(f"{len(files)} pictures found") count = 1 for file in files: picture = Picture(file) logger.info(f"{count}/{len(files)} - {picture.file_name}") process_picture(picture, target_path, move) count += 1
def _main(): P = int(sys.argv[1]) Tau = float(sys.argv[2]) Pic = Picture(sys.argv[3]) b = beadfinder(Pic, Tau) Beads = b.getBeads(P) for i in Beads: stdio.writeln(str(i))
def picture_spider(): srequest = Srequests() if srequest.check_cookies(): pass else: print('update cookies !') loginurl = 'https://anime-pictures.net/login/submit' logindata = {'login': '******', 'password': '******', 'time_zone': 'Asia/Shanghai'} srequest.update_cookies(loginurl, logindata) # 搜索图片 taglist = ['girl', 'long hair', 'breasts', 'blush', 'light erotic'] search_tag = '||'.join(taglist) # update_date 0:任何时候 1:上周 2:过去一个月 3:过去的一天 if get_pictures_count() < 200: update_date = 0 else: update_date = 2 # search_url = "https://anime-pictures.net/pictures/view_posts/0?search_tag=%s&aspect=16:9&order_by=date&ldate=%d" \ # "&ext_jpg=jpg&ext_png=png&lang=en" % (search_tag, update_date) search_url = "https://anime-pictures.net/pictures/view_posts/0?search_tag=%s&res_x=1024&res_y=768&res_x_n=1&res_y_n=1&aspect=16:9&order_by=date&ldate=%d&small_prev=1&ext_jpg=jpg&ext_png=png&lang=en" % ( search_tag, update_date) resp = srequest.session.get(search_url, headers=Srequests.headers).text # print(Srequests.headers) details_urls = [] details_urls.extend(get_details_urls(resp)) page_count = get_page_count(resp) search_urls = [ "https://anime-pictures.net/pictures/view_posts/%d?search_tag=%s&res_x=1024&res_y=768&res_x_n=1&res_y_n=1&aspect=16:9&order_by=date&ldate=%d&small_prev=1&ext_jpg=jpg&ext_png=png&lang=en" % ( x, search_tag, update_date) for x in range(1, int(page_count) + 1)] reqs = (grequests.get(url, headers=Srequests.headers, session=srequest.session) for url in search_urls) for r_data in grequests.imap(reqs, size=Wallpaper.REQUEST_THREAD_NUMBER): if r_data.status_code == 200: print('搜索页成功:' + r_data.url) details_urls.extend(get_details_urls(r_data.text)) else: print('搜索页失败:' + r_data.url) # 图片详情页 reqs = (grequests.get(url, headers=Srequests.headers, session=srequest.session) for url in details_urls) for r_data in grequests.imap(reqs, size=Wallpaper.REQUEST_THREAD_NUMBER): if r_data.status_code == 200: print('详情页成功:' + r_data.url) save_picture_info(Picture(*get_picture_info(r_data.text))) else: print('详情页失败:' + r_data.url) srequest.close()