Пример #1
0
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
Пример #2
0
    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))
Пример #3
0
def main() :
    CELL_SIZE, ROUNDS = 6, 500
    try:
        cells, TILESX, TILESY  = fillCells(input("Open board from file: "))
    except FileNotFoundError :
        cells = []
        TILESX, TILESY = 50, 80
        for i in range(TILESY):
            cells.append([False]*TILESX)
        cells[39][40]=1
        cells[40][39]=1
        cells[40][40]=1
        cells[41][40]=1
        cells[39][41]=1
    cells2 = []
    for i in range(TILESY):
        cells2.append([False]*TILESX)
    board = Picture(((TILESX * (CELL_SIZE + 1))+1,1+(TILESY*(CELL_SIZE + 1))))
    # "plays" the game for ROUNDS times
    for i in range(ROUNDS):
        # for each cell...
        for x in range(TILESX):
            for y in range(TILESY):
                neighbors = numNeighbors(cells,y,x,TILESX,TILESY)
                if neighbors == 0:
                    cells2[y][x] = False
                if neighbors == 1:
                    cells2[y][x] = False
                if neighbors == 3:
                    cells2[y][x] = True
                if neighbors >= 4:
                    cells2[y][x] = False
        cells,cells2 = cells2,cells
        board = drawGrid(board,TILESX,TILESY,cells,CELL_SIZE)
        board.display()
Пример #4
0
class PygameStarter(game_mouse.Game):

    def __init__(self, width, height):

        game_mouse.Game.__init__(self, "Pygame Starter",
                                 width,
                                 height,
                                 10)
        
        self.font_height = 12
        self.font = pygame.font.SysFont("Courier New", self.font_height)

        self.mPicture = Picture()
        return
        
        
    def game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        x = mouse_position[0]
        y = mouse_position[1]

        if pygame.K_a in newkeys:
            print "a key pressed"
        
        if 1 in newbuttons:
            print "button clicked"

        return
    
    def paint(self, surface):
        self.mPicture.draw(surface)
        return
Пример #5
0
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
Пример #6
0
def main():
    ifile = input("Open a file: ")
    canvas = Picture(ifile)
    canvas.display()
    print("This program performs the following operations:\n\n",
            "1. Flip Horizontally\n",
            "2. Mirror Horizontally\n",
            "3. Scroll Horizontally\n",
            "4. Make Negative\n",
            "5. Make Grayscale\n",
            "6. Cycle Color Channels\n",
            "7. Zoom\n",
            "8. Posterize\n",
            "9. Change Brightness\n",
            "10. Increase Contrast\n",
            "11. Blur\n",
            "12. Rotate 180 Degrees\n",
            "13. Tiled\n",
            "14. Deuteranopia (Red-Green Colorblindess)\n")
    whatdo = eval(input("Enter the number of the operation you'd like to perform: "))
    if whatdo == 1: canvas = flipHoriz(canvas)
    if whatdo == 2: canvas = mirrorHoriz(canvas)
    if whatdo == 3: canvas = scrollHoriz(canvas)
    if whatdo == 4: canvas = neg(canvas)
    if whatdo == 5: canvas = grayscale(canvas)
    if whatdo == 6: canvas = cycleColorChannels(canvas)
    if whatdo == 7: canvas = zoom(canvas)
    if whatdo == 8: canvas = posterize(canvas)
    if whatdo == 9: canvas = changeBright(canvas)
    if whatdo == 10: canvas = changeContrast(canvas)
    if whatdo == 11: canvas = blur(canvas)
    if whatdo == 12: canvas = rotate180(canvas)
    if whatdo == 13: canvas = tiled(canvas)
    if whatdo == 14: canvas = deuteranopia(canvas)
Пример #7
0
def companies_by_maintenance():
    try:
        cursor.execute(sql_4)
        all_data = cursor.fetchall()
        all_companies = []
        for row in all_data:
            if row[0] != None:
                actual_line = []
                actual_line.append(row[0])
                actual_line.append(row[1])
                actual_line.append(row[2])
                actual_line.append(row[3])
                all_companies.append(actual_line)

        company_objects = []
        for i in all_companies:
            actual = CompaneiesByMaintenance(i[0], i[1], i[2], i[3])
            company_objects.append(actual)

        result = CompaneiesByMaintenance.output_maker(company_objects)

        for i in result:
            Picture.add_to_textboxes(i[1], i[2], i[0])
            # print(i)
        Picture.drawer("companies_by_maintenance.png")

    except Exception as e:
        print(e)
Пример #8
0
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("ちょう終わりました~♪")
Пример #9
0
def companies_by_project_number():
    try:
        cursor.execute(sql_1)
        results_1 = cursor.fetchall()
        cursor.execute(sql_2)
        results_2 = cursor.fetchall()
        dictionary = {}
        for row in results_2:
            if row[0] not in dictionary:
                dictionary.setdefault(row[0], [])
                dictionary[row[0]].append(row[1])
            else:
                dictionary.setdefault(row[0], []).append(row[1])

        for k, v in dictionary.items():
            dictionary[k] = TextBox.avg_color(v)

        for i in results_1:
            if i[1] != 0:
                for k, v in dictionary.items():
                    if i[0] == k:
                        Picture.add_to_textboxes(dictionary[k], 15*int(i[1]), k)

        Picture.drawer("companies_by_project_number.png")

    except Exception as e:
        print(e)
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()
Пример #11
0
def projects_by_currency():
    try:
        cursor.execute(sql_3)
        # Fetch all the rows in a list of lists.
        results_1 = cursor.fetchall()
        all_companies = []
        for row in results_1:
            if row[0] not in all_companies:
                company = []
                company.append(row[0])
                company.append(float(row[1]))
                company.append(row[2])
                company.append(row[3])
                all_companies.append(company)
            else:
                pass
        result = ProjectByCurrency.make_reverse_order(all_companies)
        for i in result:
           i[2] = TextBox.hex_to_rgb(i[2])
        for i in result:
            Picture.add_to_textboxes(i[2], i[1], i[0])
            # print(i)
        Picture.drawer('projects_by_currency.png')

    except Exception as e:
        print(e)
Пример #12
0
class PygameSunset(game_mouse.Game):
    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 game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        x = mouse_position[0]
        y = mouse_position[1]

        if pygame.K_a in newkeys:
            print("a key pressed")

        if 1 in newbuttons:
            print("button clicked")

        return

    def paint(self, surface):
        self.mPicture.draw(surface)
        return
Пример #13
0
def main():
    pic = Picture("crayons.bmp")
    WIDTH = pic.getWidth()
    HEIGHT = pic.getHeight()
    print(WIDTH, HEIGHT)
    pic2 = copyImage(pic)
    input()
Пример #14
0
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')
Пример #15
0
    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 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
Пример #17
0
def flipHoriz(canvas):
    n = Picture((canvas.getWidth(),canvas.getHeight()))
    for x in range(canvas.getWidth()):
        for y in range(canvas.getHeight()):
            r, g, b = canvas.getPixelColor(x,y)
            n.setPixelColor(canvas.getWidth()-x-1,y,r,g,b)
    canvas.close()
    n.display()
    return n
Пример #18
0
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)
Пример #19
0
def rotate180(canvas) :
    w, h = canvas.getWidth(), canvas.getHeight()
    n = Picture((w,h))
    for x in range(w):
        for y in range(h):
            r, g, b = canvas.getPixelColor(x,y)
            n.setPixelColor(w-x-1,h-y-1,r,g,b)
    canvas.close()
    n.display()
    return n
Пример #20
0
def blur(canvas) :
    w, h = canvas.getWidth(), canvas.getHeight()
    n = Picture((w,h))
    for x in range(w):
        for y in range(h):
            r, g, b = getAdjAvg(canvas,x,y)
            n.setPixelColor(x,y,r,g,b)
    canvas.close()
    n.display()
    return canvas
Пример #21
0
def scrollHoriz(canvas) :
    m = eval(input("Scroll by how many pixels: "))
    n = Picture((canvas.getWidth(),canvas.getHeight()))
    for x in range(canvas.getWidth()):
        for y in range(canvas.getHeight()):
            r, g, b = canvas.getPixelColor(x,y)
            n.setPixelColor((x+m)%canvas.getWidth(),y,r,g,b)
    canvas.close()
    n.display()
    return n
Пример #22
0
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)
Пример #23
0
def main():
    canvas = Picture((500, 500))
    canvas.display()
    canvas.setPenColor(200,0,0)
    canvas.drawRectFill(250,250,200,200)
    canvas.display()
    input()
Пример #24
0
def read():
    w = stdio.readInt()
    h = stdio.readInt()
    p = Picture(w, h)
    for col in range(w):
        for raw in range(h):
            r = stdio.readInt()
            g = stdio.readInt()
            b = stdio.readInt()
            c = Color(r, g, b)
            p.set(col, raw, c)
    return p
Пример #25
0
def zoom(canvas):
    w = canvas.getWidth()
    h = canvas.getHeight()
    new_canvas = Picture((w,h))
    canvas.close()
    for i in range(0,w):
        for j in range(0,h):
            r = canvas.getPixelRed(w//4+i//2,h//4+j//2)            
            g = canvas.getPixelGreen(w//4+i//2,h//4+j//2)
            b = canvas.getPixelBlue(w//4+i//2,h//4+j//2)
            new_canvas.setPixelColor(i,j,r,g,b)
    return new_canvas
def slideOne(source,target,n,w,h):
    pic = Picture(w,h)
    for t in range(n):
        for col in range(w):
            for row in range(h):
                c0 = source.get(col, row)
                cn = target.get(col, row)
                alpha = float(t) / float(n)
                c = blend(c0, cn, alpha)
                pic.set(col, row, c)
        stddraw.picture(pic)
        stddraw.show(2000.0/n)  #2秒一张为2000/n
Пример #27
0
def rotate180(canvas):
    w = canvas.getWidth()
    h = canvas.getHeight()
    new_canvas = Picture((w,h))
    canvas.close()
    for i in range(0,w):
        for j in range(0,h):
            r = canvas.getPixelRed(w-1-i,h-1-j)            
            g = canvas.getPixelGreen(w-1-i,h-1-j)
            b = canvas.getPixelBlue(w-1-i,h-1-j)
            new_canvas.setPixelColor(i,j,r,g,b)
    return new_canvas
Пример #28
0
def scrollHorizontally(canvas):
    n = eval(input("How many pixels would you like to scroll? "))
    w = canvas.getWidth()
    h = canvas.getHeight()
    new_canvas = Picture((w,h))
    canvas.close()
    for i in range(0,w):
        for j in range(0,h):
            r = canvas.getPixelRed(i,j)            
            g = canvas.getPixelGreen(i,j)
            b = canvas.getPixelBlue(i,j)
            new_canvas.setPixelColor((i+n)%w,j,r,g,b)
    return new_canvas
Пример #29
0
	def __init__(self, message, quality=20):
		if message.reply_to_message:
			self.PhotoSize_object = message.reply_to_message.photo[-1]
			self.reply_to_message_id = message.reply_to_message.message_id
		else:
			self.PhotoSize_object = message.photo[-1]
			self.reply_to_message_id = None

		self.chat_id = message.chat_id
		self.message_id = message.message_id
		self.file_path = BASE_FILE_PATH.format(self.chat_id, self.message_id)
		self.message = message
		Picture.__init__(self, self.file_path, quality=quality)
def slideShow(p,n,w,h):
    l = len(p)
    #创建黑色图像
    blackP = Picture(w,h)
    for col in range(w):
        for row in range(h):
            blackP.set(col,row,color.BLACK)

    for i in range(l-1):
        slideOne(p[i],blackP,n,w,h)
        slideOne(blackP,p[i+1],n,w,h)
    
    stddraw.picture(p[l-1])
    stddraw.show()
Пример #31
0
    def __init__(self, width, height):
        """
        Constructors for the Drawing class.

        Parameters:
        width: int, the width of the image in pixels
        height: int, the height of the image in pixels
        """
        self.width = width
        self.height = height
        self.picture = Picture(width, height)
        self.pixel_depths = [[float("-inf") for x in range(width)]
                             for y in range(height)]
        self.matrix_stack = [TransformationMatrix.identity()]
        self.view_vector = None
Пример #32
0
    def connect_picture(self, clientId):
        # 最新の絵を取得する
        picture = self.get_current_picture()
        if picture == None:
            # 絵がない場合は、新たな絵を登録する
            clientIds = []
            clientIds.append(clientId)
            picture = Picture(
                              clientIds=clientIds,
                              isCurrent=True,
                              )
        else:
            picture.clientIds.append(clientId)

        picture.put()
Пример #33
0
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()
Пример #34
0
def main():
    canvas = Picture((400, 400))
    sky(canvas)
    ground(canvas)
    pipe(canvas)
    blocks(canvas)
    questionMarks(canvas)
    mario(canvas)
    sun(canvas)
    clouds(canvas)
    horizontalLines(canvas)
    verticalLines(canvas)
    canvas.display()
    canvas.writeFile("cdavies.jpg")
    input("Press enter to end the prgram.")
Пример #35
0
    def __init__(self, message, quality=20):
        if message.reply_to_message:
            self.PhotoSize_object = message.reply_to_message.photo[-1]
            self.reply_to_message_id = message.reply_to_message.message_id
        else:
            self.PhotoSize_object = message.photo[-1]
            self.reply_to_message_id = None

        self.chat_id = message.chat_id
        self.message_id = message.message_id
        self.from_user = message.from_user  # user that send the picture
        self.date = message.date  # date in Unix time
        self.file_path = BASE_FILE_PATH.format(self.chat_id, self.message_id)
        self.message = message
        Picture.__init__(self, self.file_path, quality=quality)
def generate_prometheus_picture(dir_term, timestamp_list, prometheus_query_info, consumer_info):
    prometheus_query_data = generate_data_by_timestamp(timestamp_list, prometheus_query_info)
    consumer_data = generate_data_by_timestamp(timestamp_list, consumer_info)
    prom_query_lag_list = []
    prom_query_log_offset_list = []
    prom_query_current_offset_list = []
    prom_query_log_offset_min_list = []
    prom_query_current_offset_min_list = []
    prom_query_lag_diff_list = []
    for index in sorted(prometheus_query_data.keys()):
        prom_query_lag = prometheus_query_data[index]["lag"]
        prom_query_log_offset = prometheus_query_data[index]["log_offset"]
        prom_query_current_offset = prometheus_query_data[index]["current_offset"]
        prom_query_log_offset_min = prometheus_query_data[index]["log_offset_min"]
        prom_query_current_offset_min = prometheus_query_data[index]["current_offset_min"]
        prom_query_lag_list.append(prom_query_lag)
        prom_query_log_offset_list.append(prom_query_log_offset)
        prom_query_current_offset_list.append(prom_query_current_offset)
        prom_query_log_offset_min_list.append(prom_query_log_offset_min)
        prom_query_current_offset_min_list.append(prom_query_current_offset_min)
        lag_diff = prom_query_log_offset_min - prom_query_current_offset_min
        prom_query_lag_diff_list.append(lag_diff)

    print "--- prometheus query ---"
    avg_prom_query_lag = sum(prom_query_lag_list)/len(prom_query_lag_list)
    print "avg. prom. query lag = ", avg_prom_query_lag
    print "max. prom. query lag = ", max(prom_query_lag_list)
    avg_prom_query_log_offset_min = sum(prom_query_log_offset_min_list)/len(prom_query_log_offset_min_list)
    avg_prom_query_current_offset_min = sum(prom_query_current_offset_min_list)/len(prom_query_current_offset_min_list)
    print "avg. prom. producer processing rate = ", avg_prom_query_log_offset_min
    print "avg. prom. consumer processing rate = ", avg_prom_query_current_offset_min
    # print "avg. Prom. query log offset - current offset =", sum(prom_query_lag_diff_list)/len(prom_query_lag_diff_list)

    cpu_list = []
    cpu_limit_list = []
    for index in sorted(consumer_data.keys()):
        cpu = consumer_data[index].get("cpu", 0)
        cpu_limit = consumer_data[index].get("cpulimit", 0)
        cpu_list.append(cpu)
        cpu_limit_list.append(cpu_limit)
    if len(consumer_data.keys()) < len(prom_query_lag_list):
        diff = len(prom_query_lag_list) - len(consumer_data.keys())
        for i in range(diff):
            prom_query_lag_list.pop(len(prom_query_lag_list)-1)

    if draw_picture:
        p = Picture(item=dir_term)
        p.get_replica_lag_picture(sorted(consumer_data.keys()), cpu_list, cpu_limit_list, prom_query_lag_list)
Пример #37
0
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)
Пример #38
0
def main():
    pic = Picture((800,800))
    pic.setPenColor(128,80,255)
    pic.drawRectFill(0,0,800,800)
    for i in range(0, NUM_BUILDINGS):
        drawBuilding(pic)
    for i in range(0, 24):
        drawSun(pic, i)
        pic.display()

    pic.writeFile("guss.bmp")
    input()
Пример #39
0
    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)
Пример #40
0
def main():
    p = Picture('heroes-Peter.jpg')
    w, h, l = write(p)
    print(w)
    print(h)
    for i in range(2):
        print(l[i])
Пример #41
0
    def __init__(self, parent, down2pc=False):  
        import string
              
        Thread.__init__(self)
        self.parent = parent
        self.config = parent.config
        self.down2pc = down2pc
        self.targetDir = parent.targetDir
        
        self.pictureList = []
        
        
        self.logFile = open("goodbyeCy.log", "a")
        self.downloadedCount = 0        # 포스팅까지 처리완료된 갯수
        self.currentFolder = ""            # 현재 작업중인 사진첩 폴더의 이름
        
        s1="""\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
        s2="""_________________________________!^#$%&!'()$+,-_@0123456789#;&=~%@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{`}~"""
        self.pathNameTransTable = string.maketrans(s1, s2)

        
        self.folderList = []
        # 리스트 박스에서 체크한 폴더만 추려냄
        for idx in range(len(parent.folderList)):
            if parent.folderListChkListBox.IsChecked(idx):
                self.folderList.append(parent.folderList[idx])
        
        self.totalPictureCount = Picture.getTotalCount(self.folderList)
        
        self.isRunning = False
Пример #42
0
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)
Пример #43
0
    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)
Пример #44
0
    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)
Пример #45
0
 def check_skin(self):
     state, img = self.capture.read()
     print(state)
     if state is True:
         p = Picture.fromarray(img)
         x = p.check_skin()
         return x
Пример #46
0
def zoom(canvas) :
    w, h = canvas.getWidth(), canvas.getHeight()
    n = Picture((w,h))
    for x in range(w//4,w-(w//4)):
        for y in range(h//4,h-(h//4)):
            r, g, b = canvas.getPixelColor(x,y)
            c,d = x-(w//4),y-(h//4)
            n.setPixelColor(c*2,d*2,r,g,b)
            n.setPixelColor((c*2)+1,d*2,r,g,b)
            n.setPixelColor(c*2,(d*2)+1,r,g,b)
            n.setPixelColor((c*2)+1,(d*2)+1,r,g,b)
    canvas.close()
    n.display()
    return n
Пример #47
0
def copyImage(pic):
    print (WIDTH, HEIGHT)
    pic2 = Picture((WIDTH, HEIGHT))
    pic2.display()
    input()
    for y in range(0, HEIGHT):
        for x in range(0, WIDTH):
            red = pic.getPixelRed(x, y)
            green = pic.getPixelGreen(x, y)
            blue = pic.getPixelBlue(x, y)
            pic2.setPixelRed(x, y, red)
            pic2.setPixelGreen(x, y, green)
            pic2.setPixelBlue(x, y, blue)
    return pic2
Пример #48
0
def create_initial_pictures():
  """ Create a randomized group of 9 pictures. """
  pictures = []

  for i in xrange(0, 9):
    pic = Picture()
    pic = Picture.create_random(pic, 1)

    pictures.append(pic)

  return pictures
Пример #49
0
 def __init__(self, task_name, task_payload):
     """
     Worker constructor. Prepares the picture to work on.
         :param task_name:
         :param task_payload:
         :return: A Worker object
     """
     self.task_name = task_name
     self.task_payload = task_payload
     p, image_name = task_name.split('--')
     self.pic = Picture('{0}.jpg'.format(image_name))
Пример #50
0
def main():
    width = eval(input("Enter a width/height of the canvas (pixels): "))
    numBricks = eval(input("Enter a number of bricks for the height of the pyramid: "))
    canvas = Picture((width, width))
    canvas.setPenColor(0, 255, 255)
    canvas.drawRectFill(0, 0, width, width)
    sideLength = width // numBricks
    for i in range(0, numBricks):
        drawRow(canvas, i * (sideLength / 2), width - 1 - sideLength * (i+1), numBricks - i, sideLength)
    canvas.display()
Пример #51
0
    def __init__(self, width, height):

        game_mouse.Game.__init__(self, "Pygame Starter",
                                 width,
                                 height,
                                 10)
        
        self.font_height = 12
        self.font = pygame.font.SysFont("Courier New", self.font_height)

        self.mPicture = Picture()
        return
Пример #52
0
class Drawing:
    def __init__(self, width, height):
        """
        Constructors for the Drawing class.

        Parameters:
        width: int, the width of the image in pixels
        height: int, the height of the image in pixels
        """
        self.width = width
        self.height = height
        self.picture = Picture(width, height)
        self.pixel_depths = [[float("-inf") for x in range(width)] for y in range(height)]
        self.matrix_stack = [TransformationMatrix.identity()]
        self.view_vector = None

    def _set_pixel(self, x, y, color, suppress_error=True, z_depth=float("-inf")):
        """
        Sets a pixel on the internal raster with reference to the original
        origin (ignoring the current TransformationMatrix).

        Parameters:
        x: int, the x coordinate of the pixel to set
        y: int, the y coordinate of the pixel to set
        color: Color, the color to set the pixel to
        suppress_error: bool (optional), when set to True, will suppress
        the error if the pixel is out of bounds
        z_depth: float (optional), the depth of the pixel, if this pixel is
        lower in depth than the current pixel, then it will not be drawn
        """
        # The coordinates are reversed because of the way lists of lists
        # work in Python.
        try:
            if z_depth >= self.pixel_depths[y][x]:
                self.pixel_depths[y][x] = z_depth
                self.picture.set_pixel(x, y, color)
        except IndexError, exception:
            if not suppress_error:
                raise exception
Пример #53
0
def main():
    width = eval(input("Please enter the desired width for the canvas: "))
    n = eval(input("Please enter the desired number of blocks for bottom row of the pyramid: "))
    size=width/n
    canvas = Picture((width, width))
    canvas.setPenColor(255,0,0)
    for i in range(0,n): #loop through the rows of the pyramid
        for j in range(i,n): #loop through the bricks
            canvas.drawRectFill(i*size/2+(j-i)*size,width-size*(i+1),size-2,size-1) #draw each rectangle, stopping a pixil short to leave visible lines between each block
    canvas.display() #display the pyramid
    input("Press enter to end the program.") #leave an input so the program doesnt end before we can see the picture
Пример #54
0
def main():
    # Create the canvas and fill in the background
    canvas = Picture((WIDTH, HEIGHT))
    chooseColor(canvas)
    canvas.drawRectFill(0, 0, WIDTH, HEIGHT)
    # Create 13 objects on the canvas
    for i in range(0, 13):
        chooseColor(canvas)
        chooseShape(canvas)
        
    canvas.display()
    canvas.writeFile("mlewisno.bmp")
Пример #55
0
    def __init__(self, width, height):
        """
        Constructors for the Drawing class.

        Parameters:
        width: int, the width of the image in pixels
        height: int, the height of the image in pixels
        """
        self.width = width
        self.height = height
        self.picture = Picture(width, height)
        self.pixel_depths = [[float("-inf") for x in range(width)] for y in range(height)]
        self.matrix_stack = [TransformationMatrix.identity()]
        self.view_vector = None
Пример #56
0
def copyImage(pic):
    WIDTH = pic.getWidth()
    HEIGHT = pic.getHeight()
    pic2 = Picture((WIDTH, HEIGHT))
    for y in range(0, HEIGHT):
        for x in range(0, WIDTH):
            red = pic.getPixelRed(x, y)
            green = pic.getPixelGreen(x, y)
            blue = pic.getPixelBlue(x, y)
            pic2.setPixelRed(x, y, red)
            pic2.setPixelGreen(x, y, green)
            pic2.setPixelBlue(x, y, blue)
    return pic2
Пример #57
0
def main():
    width = eval(input("Enter a width for your canvas:  "))
    height = eval(input("Enter a height for your canvas:  "))
    n = eval(input("How many bricks tall would you like to make this pyramid?  "))
    
    canvas = Picture((width, height))
    x = 0
    y = height - (height/n)
    canvas.setPenColor(0,225,225)
    canvas.drawRectFill(0,0,width,height)

    drawPyramid(canvas, n, x, y, width, height)
    
    canvas.display()
Пример #58
0
def main():
    name = input("Enter the filename of an image you would like to edit: ")
    pic = Picture(name)
    pic.display()
    WIDTH = pic.getWidth()
    HEIGHT = pic.getHeight()
    instructions()
    while True:
        options()
        userInput = input("Enter the number corresponding to the change you want to perform: ")
        if userInput == "exit":
            return
        else:
            userInput = eval(userInput)
            pic = doEdit(userInput, pic)
            pic.display()
def main():
    for num in range(1,4):
        p = Picture("training_data/a" + str(num)+".png")
        c = Char_Repr(p)
        print(c.points)
        p.display()
        raw_input()
    for num in range(1,4):
        p = Picture("training_data/b" + str(num)+".png")
        c = Char_Repr(p)
        print(c.points)
        p.display()
        raw_input()
Пример #60
0
def main():
    # Get the width for the canvas
    width = int(eval(input("How wide do you want the canvas to be? (In pixels) ")))
    # Get the number of bricks tall the user wants the pyramid to be
    numBricks = int(eval(input("How many bricks tall do you want your pyramid to be? ")))
    # Create the canvas
    canvas = Picture((width, width))
    # Fill in the background
    canvas.drawRectFill(0, 0, width, width)
    # Calculate brick height and width
    brickHeight = int(width/numBricks)
    brickWidght = int(width/numBricks)
    # Loop through each row of the pyramid
    for i in range(0, numBricks):
        # Find the y coordinate for every brick in this row
        brickY = brickHeight*(i + 1)
        # Loop through each brick in each row
        for j in range(int(1/2*brickHeight), numBricks - i):
            # Find the x coordinate for each brick as you go along
            brickX = brickHeight(j)
            canvas.setPenColor(0, 0, 0)
            canvas.drawRect(brickX, brickY, brickWidth, brickHeight)
            
    canvas.display()