Ejemplo n.º 1
0
def render():
    if gamemode == MENU:
        menu.render(screen)
    elif gamemode == PLAYING:
        screen.fill(SKY)
        world.render(screen, viewport)
        if DEBUG:
            #render debug text
            h = 10
            fpsimg = font.render("fps: " + str(clock.get_fps()), 0, WHITE)
            screen.blit(fpsimg, (10, h))
            h += fpsimg.get_height()
            posimg = font.render("pos: [{0:.2f}".format(player.pos[0]) + ", {0:.2f}]".format(player.pos[1]), 0, WHITE)
            screen.blit(posimg, (10, h))
            h += posimg.get_height()
            chunk = world.loaded_chunks.get(Convert.world_to_chunk(player.pos[0])[1])
            chunkimg = font.render("chunk: " + str(chunk.x), 0, WHITE)
            screen.blit(chunkimg, (10, h))
            h += chunkimg.get_height()
            biomeimg = font.render("biome: " + str(chunk.biome["name"]), 0, WHITE)
            screen.blit(biomeimg, (10, h))
            h += biomeimg.get_height()
        player.render(screen, Convert.world_to_viewport(player.pos, viewport))
        if gui is None:
            target_pos = world.find_pos(world.find_angle(player, pygame.mouse.get_pos(), viewport), 
                                        Convert.pixels_to_viewport(player.pixel_pos(True), viewport), 
                                        pygame.mouse.get_pos(),
                                        player.get_break_distance())
            screen.blit(img_target, [x - y for x, y in zip(target_pos, [dim / 2 for dim in img_target.get_size()])]) #zoo-wee mama!
        else:
            gui.render(screen)
    pygame.display.flip()
Ejemplo n.º 2
0
def CBC_Mode_Decryption(file_name, key, init_vec, block_size=1):
    res = ''
    cur_vec = init_vec
    with open(file_name, 'rb') as f:
        data = f.read()
    key_len = len(key)
    key_idx = 0
    for idx in range(len(data) / block_size):
        temp = data[idx * block_size:(idx + 1) * block_size]
        temp = Convert.to_bin(temp)
        temp = int(temp, 2)
        tmp = ''
        for char in data[idx * block_size:(idx + 1) * block_size]:
            char = ord(char) - key[key_idx % key_len]
            if char < 0:
                char += 256
            tmp += chr(char)
        tmp = int(Convert.to_bin(tmp), 2)
        tmp ^= cur_vec
        tmp = bin(tmp)[2:]
        tmp = '0' * (block_size * 8 - len(tmp)) + tmp
        tmp = Convert.to_str(tmp)
        key_idx += 1
        res += tmp
        cur_vec = temp
    with open(file_name[:file_name.index('_cipher.txt')] + '_plain.txt',
              'w') as f:
        f.write(res)
Ejemplo n.º 3
0
def deploy(config):
    caffe.set_mode_gpu()
    if config.gpu is not None:
        caffe.set_device(int(config.gpu))

    classifier = caffe.Classifier(config.modelPrototxt, config.trainedModel)
    images = Convert.loadImages(config.deployImages)
    if config.deployRange is not None:
        images = images[config.deployRange, ...]

    mirroredImages = Convert.mirrorEdges(config.subImageSize, images,
                                         config.debug) * 0.00390625
    probs = np.zeros((images.size, 2))
    n, h, w = images.shape
    b = config.deployBatch
    imageSize = h * w

    print("Start Deploying")
    for ni in range(n):
        print("\tDeploying Image %s" % config.deployRange[ni])
        for hi in range(h):
            for wi in range(0, w, b):
                batches = []
                for bi in range(wi, wi + b):
                    image = mirroredImages[ni, hi:hi + config.subImageSize,
                                           bi:bi + config.subImageSize]
                    # data is K x H x W X C array, so add channel axis
                    batches.append(image[:, :, np.newaxis])

                prob = classifier.predict(batches, oversample=False)
                i = ni * imageSize + hi * h + wi
                probs[i:i + b] = prob

    probs = probs.reshape(n, h, w, 2)
    np.save(config.likelihood, probs)
Ejemplo n.º 4
0
def main():
    # input
    h = 0.0  # km
    v = 12.5  # m/s
    c = Convert(1.0, 'ft', 'm')
    naca = '2408'
    b = Convert(12.0, 'ft', 'm')
    lam = Convert(0.0, 'deg', 'rad')

    # constants
    gamma = 1.4
    Rgas = 287.15

    # atmosphere
    P, T = atm.atmosphere(h)
    rho = atm.density(P, T)
    mu = atm.viscosity(T)
    a = sqrt(gamma * Rgas * T)
    M = v / a

    # calculations
    Re = (rho * v * c) / mu

    S = b * c  # fix to include lam later
    AR = (b * b) / S
    e = 0.95

    zero_lift, astall, cl, cd = airfoil(naca, Re, M)
Ejemplo n.º 5
0
 def update_telemetry(self, telemetry_data):
     if (self.view_type == ViewTypes.ARDUINO):
         #tlv = ArduinoHelper.create_tlv(telemetry_data)
         tlv_lcd = ArduinoHelper.create_lcd_tlv(telemetry_data)
         tlv_led = ArduinoHelper.create_led_tlv(telemetry_data)
         #print("".join("%02x" % b for b in tlv.serialize()))
         self.serial.write(tlv_lcd.serialize())
         self.serial.write(tlv_led.serialize())
         print("------------SPEED-------------")
         print("           " + str(int(Convert.speed_to_kph(telemetry_data.speed))) + " KPH")
     elif (self.view_type == ViewTypes.GPIO):
         print("------------GEAR-------------")
         print("            " + str(telemetry_data.current_gear))
         print("------------------------------")
         self.gpio.update_all(telemetry_data)
     elif (self.view_type == ViewTypes.CONSOLE):
         os.system('cls' if os.name=='nt' else 'clear')
         print("------------------------------")
         print("-------------RPM--------------")
         print("            " + str(telemetry_data.rpm))
         aux = int((telemetry_data.rpm / telemetry_data.max_rpm) * 10)
         string_rpm = "----["
         for i in range(0,aux):
             string_rpm += '**'
         for i in range(aux, 10):
             string_rpm += '  '
         string_rpm += "]----"
         print(string_rpm)
         print("------------SPEED-------------")
         print("           " + str(int(Convert.speed_to_kph(telemetry_data.speed))) + " KPH")
         print("------------GEAR-------------")
         print("            " + str(telemetry_data.current_gear))
         print("------------------------------")
Ejemplo n.º 6
0
def check_rechts(pivot, rechts, index=0):

    if Convert.convert(rechts[index]) > Convert.convert(pivot[index]):
        return True

    if rechts.lower() == pivot.lower():
        if ord(rechts[0]) < ord(pivot[0]):
            return False
        elif ord(rechts[0]) > ord(pivot[0]):
            return True
        else:
            return False

    try:
        if Convert.convert(rechts[index]) == Convert.convert(pivot[index]):
            return check_rechts(pivot, rechts, index + 1)

    except IndexError:
        if len(rechts) < len(pivot):
            return False
        else:
            return True

    else:
        return False
Ejemplo n.º 7
0
 def generate_structure(self, structure, x):
     if structure["type"] == "column":
         height = random.randint(structure["minheight"], structure["maxheight"])
         for y in range(self.heights[x] - height, self.heights[x]):
             self.blocks[y][x] = World.get_block(structure["block"])
     elif structure["type"] == "json":
         structure_file = open(structure["location"])
         structure_json = json.load(structure_file)
         curr_y = self.heights[x] - len(structure_json["shape"])
         for line in structure_json["shape"]:
             curr_world_x = Convert.chunk_to_world(x, self)
             for char in line:
                 #find the right chunk
                 chunk = self #world.chunks[Convert.world_to_chunk(x)[1]]- can't really do this...
                 curr_chunk_x = Convert.world_to_chunk(curr_world_x)[0]
                 if curr_chunk_x < WIDTH:
                     if char == " ":
                         block = "water"
                     else:
                         block = structure_json["blocks"][char]
                     chunk.blocks[curr_y][curr_chunk_x] = World.get_block(block)
                 curr_world_x += 1
             curr_y += 1
         structure_file.close()
     elif structure["type"] == "other":
         #why did I write this?
         pass
Ejemplo n.º 8
0
 def generate_structure(self, structure, x):
     #TODO: add background blocks defined separately
     if structure["type"] == "column":
         height = random.randint(structure["minheight"], structure["maxheight"])
         for y in range(self.heights[x] - height, self.heights[x]):
             self.set_block_at(x, y, World.get_block(structure["block"]), False)
     elif structure["type"] == "json":
         structure_file = open(structure["location"])
         structure_json = json.load(structure_file)
         curr_y = self.heights[x] - len(structure_json["shape"])
         for line in structure_json["shape"]:
             curr_world_x = Convert.chunk_to_world(x, self)
             for char in line:
                 #find the right chunk
                 chunk = self #world.chunks[Convert.world_to_chunk(x)[1]]- can't really do this...
                 curr_chunk_x = Convert.world_to_chunk(curr_world_x)[0]
                 if curr_chunk_x < WIDTH:
                     if char == " ":
                         block_name = "water"
                     else:
                         block_name = structure_json["blocks"][char]
                     block = World.get_block(block_name)
                     #TODO: add background
                     chunk.set_block_at(curr_chunk_x, curr_y, block, False)
                     if block["entity"] != "":
                         #generate the block entity
                         EntityClass = getattr(importlib.import_module("ent." + block["entity"]), block["entity"])
                         instance = EntityClass([curr_world_x, curr_y], self)
                         self.entities.append(instance)
                 curr_world_x += 1
             curr_y += 1
         structure_file.close()
     elif structure["type"] == "singleblock":
         self.set_block_at(x, self.heights[x] - 1, World.get_block(structure["block"]), False)
Ejemplo n.º 9
0
    def __init__(self, master, typeOfUnit):
        self.setType(typeOfUnit)
        self.start = 0
        self.master = master

        self.menubar = Menu(master)

        self.unitmenu = Menu(self.menubar, tearoff=0)

        self.en = Entry(master, width=30)
        self.en.grid(columnspan=10, sticky="N")

        t = 0
        r = 1
        for i in range(Convert.numberOfUnits(self.ty)):

            self.unitmenu.add_command(label=Convert.unitName(self.ty, i),
                                      command=partial(self.toChange, i))
            self.button = Button(master,
                                 height=2,
                                 width=5,
                                 text=Convert.unitName(self.ty, i),
                                 command=partial(self.changeType, i))
            self.button.grid(row=r, column=i - (r - 1) * 4)

            if t > 2:
                t = 0
                r += 1
            else:
                t += 1

        self.menubar.add_cascade(label="start unit", menu=self.unitmenu)
        master.config(menu=self.menubar)

        self.label = Label(self.master)
Ejemplo n.º 10
0
def CBC_Mode_Encryption(file_name, key=[], key_len=10, block_size=1):
    res = ''
    init_vec = random.randrange(1, 2**(block_size * 8))
    print init_vec
    cur_vec = init_vec
    with open(file_name, 'r') as f:
        data = f.read()
    if len(data) % block_size != 0:
        data += '=' * (block_size - len(data) % block_size)
    if key == []:
        key = []
        for _ in range(key_len):
            key.append(random.randrange(1, 25))
    else:
        key_len = len(key)
    key_idx = 0
    for idx in range(len(data) / block_size):
        tmp = int(
            Convert.to_bin(data[idx * block_size:(idx + 1) * block_size]), 2)
        tmp ^= cur_vec
        tmp = bin(tmp)[2:]
        tmp = '0' * (8 * block_size - len(tmp)) + tmp
        tmp = Convert.to_str(tmp)
        temp = ''
        for char in tmp:
            char = ord(char) + key[key_idx % key_len]
            temp += chr(char % 256)
        key_idx += 1
        cur_vec = int(Convert.to_bin(temp), 2)
        res += temp
    with open(file_name[:-4] + "_cipher.txt", 'wb') as f:
        f.write(res)

    return (init_vec, key)
Ejemplo n.º 11
0
 def test_add_superscript(self):
     self.assertEqual("", Convert.wrap_checkedToneChar_with_superscript(""))
     self.assertEqual(u"^入^",
                      Convert.wrap_checkedToneChar_with_superscript(u"入"))
     self.assertEqual(u"^入^^日^",
                      Convert.wrap_checkedToneChar_with_superscript(u"入日"))
     self.assertEqual(u"江^入^^日^",
                      Convert.wrap_checkedToneChar_with_superscript(u"江入日"))
Ejemplo n.º 12
0
 def break_block(self, player, mouse_pos, viewport):
     angle = self.find_angle(player, mouse_pos, viewport)
     block_pos = Convert.pixels_to_world(self.find_pos(angle, player.pixel_pos(True), Convert.viewport_to_pixels(mouse_pos, viewport), player.get_break_distance())) #it aint right
     chunk = self.loaded_chunks.get(Convert.world_to_chunk(block_pos[0])[1])
     block = self.get_block(block_pos)
     if block["breakable"]:
         chunk.blocks[block_pos[1]][Convert.world_to_chunk(block_pos[0])[0]] = get_block("water")
         chunk.entities.append(BlockDrop.BlockDrop(block_pos, block["name"]))
Ejemplo n.º 13
0
 def update(self):
     for x in range(self.loaded_chunks.first, self.loaded_chunks.end):
         chunk = self.loaded_chunks.get(x)
         for entity in chunk.entities:
             entity.update(self)
             if Convert.world_to_chunk(entity.pos[0])[1] != chunk.x:
                 print("Moving", entity, entity.pos)
                 chunk.entities.remove(entity)
                 self.loaded_chunks.get(Convert.world_to_chunk(entity.pos[0])[1]).entities.append(entity)
Ejemplo n.º 14
0
 def render_break_preview(self, background, world, block, block_pos, screen, viewport):
     chunk = world.loaded_chunks.get(Convert.world_to_chunk(block_pos[0])[1])
     blockimg = world.get_block_render(World.get_block_id(block["name"]), block_pos, block["connectedTexture"], background, chunk, background).copy()
     mask = pygame.mask.from_surface(blockimg)
     olist = mask.outline()
     polysurface = pygame.Surface((Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE), pygame.SRCALPHA)
     color = self.get_color(background)
     pygame.draw.polygon(polysurface, color, olist, 0)
     screen.blit(polysurface, Convert.world_to_viewport(block_pos, viewport))
Ejemplo n.º 15
0
def feature_extraction_L1_L0(parameter_rho_coef, parameter_gamma, parameter_mu,
                             S0, D, itr, thr, lay):

    S0 = 2 * S0
    S0 -= np.mean(S0, axis=(0, 1))
    S = S0

    cri = cr.CSC_ConvRepIndexing(D, S)
    dsz = D.shape

    X = the_minimum_l2_norm_solution(D, S, cri)

    parameter_sigma = setting_sigma(X)

    Df = con.convert_to_Df(D, S, cri)

    Xstep_iteration = itr[0]
    total_iteration = itr[2]

    bar_Lay = tqdm(total=len(parameter_sigma), desc=lay, leave=False)
    for k in parameter_sigma:

        bar_L = tqdm(total=total_iteration, desc='L', leave=False)
        for L in range(total_iteration):

            nabla_x = nabla_x_create(X, k)
            X = X - parameter_mu * nabla_x

            if ((k == parameter_sigma[0]) & (L == 0)):
                Xf = con.convert_to_Xf(X, S, cri)
                Df = con.convert_to_Df(D, S, cri)
                XfDf = np.sum(Xf * Df, axis=cri.axisM)
                XD = con.convert_to_S(XfDf, cri)
                Y = XD - S
                U = np.zeros(S.shape)
            X, Y, U = projection_to_solution_space_by_L1(
                D, X, S, Y, U, parameter_rho_coef, parameter_gamma,
                Xstep_iteration, thr, cri, dsz)

            if (np.sum(X != 0) == 0):
                bar_L.update(total_iteration - L)
                break
            bar_L.update(1)
        bar_L.close()

        if (np.sum(X != 0) == 0):
            bar_Lay.update(len(parameter_sigma) - k)
            break

        bar_Lay.update(1)
    #X = np.where((-parameter_sigma[-1] < X) & (X < parameter_sigma[-1]), 0, X)
    bar_Lay.close()

    l0_norm = np.sum(X != 0)
    print("[" + lay + "] L0 norm: %d " % l0_norm)
    return X, l0_norm
Ejemplo n.º 16
0
 def render(self, screen, pos):
     if self.animating:
         old_pixel_pos = Convert.world_to_pixels(self.old_pos)
         new_pixel_pos = Convert.world_to_pixels(self.pos)
         animation_ratio = 1 - (self.animation_stage / EntityPuzzlePiece.ANIMATION_MAX)
         difference = ((old_pixel_pos[0] - new_pixel_pos[0]) * animation_ratio,
                       (old_pixel_pos[1] - new_pixel_pos[1]) * animation_ratio)
         screen.blit(self.img, (pos[0] + difference[0], pos[1] + difference[1]))
     else:
         screen.blit(self.img, pos)
Ejemplo n.º 17
0
    def __init__(self):

        # holds all kinds of data about SOSS status aliases 
        self.info = Convert.statusInfo()

        # statusConverter object, used to extract and interpret SOSS
        # values in the tables
        self.conv = Convert.statusConverter()

        super(baseSOSSstatusObj, self).__init__()
Ejemplo n.º 18
0
 def __init__(self, pos, imageurl, scale=()):
     self.pos = pos
     self.imageurl = imageurl
     self.scale = scale
     self.load_image()
     #bounding box is in pixels because it can only have ints
     self.bounding_box = pygame.Rect(Convert.world_to_pixel(pos[0]), Convert.world_to_pixel(pos[1]), self.img.get_width(), self.img.get_height())
     self.width = Convert.pixel_to_world(self.img.get_width()) + 1
     self.height = Convert.pixel_to_world(self.img.get_height()) + 1
     self.dir = [0, 0] #direction: -1, 0, 1
     self.vel = [0, 0] #speeds: any numbers
Ejemplo n.º 19
0
 def render_block(self, block, pos, screen, viewport):
     """#fast render water
     if block["name"] == "water":
         screen.blit(World.block_images[block["id"]],
                     Convert.world_to_viewport([Convert.chunk_to_world(pos[0], self), pos[1]], viewport))"""
     #don't render air
     if block["name"] != "air":
         #print(block["name"] + " " + str(block["id"]))
         Game.get_world().render_block(block["id"], [Convert.chunk_to_world(pos[0], self), pos[1]], block["connectedTexture"], screen, viewport)
     if Game.DEBUG:
         #draw bounding box
         pygame.draw.rect(screen, Game.BLACK, pygame.Rect(Convert.chunk_to_viewport(pos, self, viewport), (Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE)), 1)
Ejemplo n.º 20
0
 def tentative_move(self, world, old_pos, index):
     self.pos[index] += self.vel[index]
     if index == 0:
         self.bounding_box.x = Convert.world_to_pixel(self.pos[index])
     else:
         self.bounding_box.y = Convert.world_to_pixel(self.pos[index])
     block_left = int(Convert.world_to_chunk(self.pos[0])[0])
     chunk_left = Convert.world_to_chunk(self.pos[0])[1]
     block_right = math.ceil(Convert.world_to_chunk(self.pos[0] + self.width)[0])
     chunk_right = Convert.world_to_chunk(self.pos[0] + self.width)[1]
     block_top = int(self.pos[1])
     block_bottom = math.ceil(self.pos[1] + self.height)
     col1 = col2 = col3 = col4 = False
     if chunk_left == chunk_right:
         chunk = world.loaded_chunks.get(chunk_left)
         col1 = self.check_collision(chunk, block_left, block_right, block_top, block_bottom, old_pos, index)
     else:
         #need to check from block_left in chunk_left to block_right in chunk_right and all the blocks in any chunks between them
         chunk = world.loaded_chunks.get(chunk_left)
         col2 = self.check_collision(chunk, block_left, Chunk.WIDTH, block_top, block_bottom, old_pos, index)
         for c in range(chunk_left + 1, chunk_right):
             chunk = world.loaded_chunks.get(c)
             col3 = self.check_collision(chunk, 0, Chunk.WIDTH, block_top, block_bottom, old_pos, index)
         chunk = world.loaded_chunks.get(chunk_right)
         col4 = self.check_collision(chunk, 0, block_right, block_top, block_bottom, old_pos, index)
     if col1 or col2 or col3 or col4:
         self.vel[index] = 0 #reset acceleration?
     if index == 0:
         self.bounding_box.x = Convert.world_to_pixel(self.pos[index])
     else:
         self.bounding_box.y = Convert.world_to_pixel(self.pos[index])
Ejemplo n.º 21
0
def dictionary_learning_by_L1_Dstep(Xf, S, G1, H1, G0, H0, parameter_rho_dic,
                                    iteration, cri, dsz):
    GH = con.convert_to_Df(G1 - H1, S, cri)
    GSH = con.convert_to_Sf(G0 + S - H0, cri)
    b = GH + sl.inner(np.conj(Xf), GSH, cri.axisK)
    Df = sl.solvemdbi_ism(Xf, 1, b, cri.axisM, cri.axisK)
    D = con.convert_to_D(Df, dsz, cri)

    XfDf = np.sum(Xf * Df, axis=cri.axisM)
    XD = con.convert_to_S(XfDf, cri)
    G0 = sp.prox_l1(XD - S + H0, (1 / parameter_rho_dic))

    H0 = H0 + XD - G0 - S

    return D, G0, H0, XD
Ejemplo n.º 22
0
 def render_blocks(self, screen, viewport, background):
     top = max(Convert.pixel_to_world(viewport.y), 0)
     bottom = min(Convert.pixel_to_world(viewport.y + viewport.height) + 1, World.HEIGHT - 1)
     for blocky in range(top, bottom):
         leftData = Convert.pixel_to_chunk(viewport.x)
         rightData = Convert.pixel_to_chunk(viewport.x + viewport.width)
         if leftData[1] == self.x:
             for blockx in range(leftData[0], WIDTH):
                 self.render_block(blockx, blocky, screen, viewport, background)
         elif leftData[1] < self.x < rightData[1]:
             for blockx in range(WIDTH):
                 self.render_block(blockx, blocky, screen, viewport, background)
         elif self.x == rightData[1]:
             for blockx in range(0, rightData[0] + 1):
                 self.render_block(blockx, blocky, screen, viewport, background)
Ejemplo n.º 23
0
def projection_to_solution_space_by_L2(D, X, S, parameter_gamma, iteration,
                                       thr, cri, dsz):
    Df = con.convert_to_Df(D, S, cri)
    Xf = con.convert_to_Xf(X, S, cri)

    for i in range(iteration):

        Sf = con.convert_to_Sf(S, cri)
        b = (1 / parameter_gamma) * Xf + np.conj(Df) * Sf
        Xf = sl.solvedbi_sm(Df, (1 / parameter_gamma), b)
        X = con.convert_to_X(Xf, cri)

        Xf = con.convert_to_Xf(X, S, cri)

    return X
Ejemplo n.º 24
0
def show(config):
    images1 = Convert.loadImages(config.deployImages)[config.segmentRange]
    images2 = Convert.loadImages(config.deployLabels)[config.segmentRange]

    start = min(config.segmentRange) - min(config.deployRange)
    images3 = np.load(config.likelihood)[start:, :, :, 1]
    images4 = Convert.loadMHA(glob.glob(config.getResultFile("final_*.mha")))

    def press(event):
        global curr_pos
        # use keyboard to change images
        if event.key == "right":
            curr_pos = (curr_pos + 1) % images3.shape[0]
        elif event.key == "left":
            curr_pos = (curr_pos - 1) % images3.shape[0]
        show()

    def show():
        fig.clear()

        plt.subplot(2, 2, 1)
        plt.title("Origin")
        plt.imshow(images1[curr_pos], cmap="Greys_r")
        plt.axis('off')

        plt.subplot(2, 2, 2)
        plt.title("Labels")
        plt.imshow(images2[curr_pos], cmap="Greys_r")
        plt.axis('off')

        plt.subplot(2, 2, 3)
        plt.title("CNN Result")
        plt.imshow(images3[curr_pos], cmap="Greys_r")
        plt.axis('off')

        plt.subplot(2, 2, 4)
        plt.title("Segment Result")
        plt.imshow(images4[curr_pos])
        plt.axis('off')

        fig.suptitle("Image " + str(config.segmentRange[curr_pos] + 1))
        fig.canvas.draw()

    fig = plt.figure(figsize=(12, 8))
    fig.canvas.mpl_connect('key_press_event', press)
    show()

    plt.show()
Ejemplo n.º 25
0
def main():

    print("Valikko")
    style1()
    print("(1).Luo tiedosto")
    print("(2).Etsi tiedostosta")
    print("(3).Kirjoita tiedostoon")
    print("(4).Poista tiedosto")
    print("(5).Kopioi tiedosto")
    print("(6).Konvertoi kuvat")
    print("(7).test zip")
    style1()
    myInput = input("Valitse numero: ")
    if len(myInput) <= 0:
        pass
    elif len(myInput) >= 30:
        print("liika")
    elif myInput == "1":
        luoTiedosto()
    elif myInput == "2":
        SeachFile()
    elif myInput == "3":
        tiedostot()
    elif myInput == "4":
        pythonFile.poistaTiedosto()
    elif myInput == "5":
        copyFile()
    elif myInput == "6":
        Convert.ConvertImages()
    elif myInput == "7":
        testMe.zip()
Ejemplo n.º 26
0
 def render_actual(self, screen):
     index = int((self.max_decay - self.decay) / FRAME_LENGTH)
     #self.load_image()
     img = self.imgs[index] #TODO: these might all be dead surfaces if loading in
     pos = Convert.world_to_viewport(self.pos, Game.get_viewport())
     center = img.get_rect().center
     screen.blit(img, (pos[0] - center[0], pos[1] - center[1]))
Ejemplo n.º 27
0
 def update(self, world):
     old_chunk = Convert.world_to_chunk(self.pos[0])[1]
     hspeed = min(abs(self.vel[0] + self.acceleration * self.dir[0]), self.max_speed) * self.dir[0]
     vspeed = min(abs(self.vel[1] + self.acceleration * self.dir[1]), self.max_speed) * self.dir[1]
     self.vel = [hspeed, vspeed]
     super(Player, self).update(world)
     new_chunk = Convert.world_to_chunk(self.pos[0])[1]
     if new_chunk != old_chunk:
         world.load_chunks(new_chunk)
     
     entities = self.get_nearby_entities(world)
     for entity in entities:
         if(self.bounding_box.colliderect(entity.bounding_box)):
             if isinstance(entity, ItemDrop):
                 if self.inventory.insert(entity.get_itemstack()) == None:
                     world.loaded_chunks.get(entity.get_chunk()).entities.remove(entity)
Ejemplo n.º 28
0
def convert(src, tgt, txt, nativize, preoptions, postoptions):
    txt = PreProcess.PreProcess(txt, src, tgt)

    if 'siddhamUnicode' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamUnicode'
    if 'LaoNative' in postoptions and tgt == 'Lao':
        tgt = 'Lao2'
    if 'siddhamUnicode' in preoptions and src == 'Siddham':
        src = 'SiddhamUnicode'
    if 'egrantamil' in preoptions and src == 'Grantha':
        src = 'GranthaGrantamil'
    if 'egrantamil' in postoptions and tgt == 'Grantha':
        tgt = 'GranthaGrantamil'

    for options in preoptions:
        txt = getattr(PreProcess, options)(txt)

    transliteration = Convert.convertScript(txt, src, tgt)

    if nativize:
        transliteration = PostOptions.ApplyScriptDefaults(
            transliteration, src, tgt)
        if tgt != 'Tamil':
            transliteration = PostProcess.RemoveDiacritics(transliteration)
        else:
            transliteration = PostProcess.RemoveDiacriticsTamil(
                transliteration)

    for options in postoptions:
        transliteration = getattr(PostProcess, options)(transliteration)

    return transliteration
Ejemplo n.º 29
0
 def use_discrete(self, world, player, mouse_pos, viewport):
     #TODO: different types of projectile
     pos = player.pos[:]
     pixel_player_pos = Convert.world_to_viewport(pos, viewport)
     difference = (mouse_pos[0] - pixel_player_pos[0],
                   mouse_pos[1] - pixel_player_pos[1])
     length = math.sqrt(difference[0] ** 2 + difference[1] ** 2)
     normalized = [difference[0] / length * ToolMagicStaff.PROJECTILE_SPEED, 
                   difference[1] / length * ToolMagicStaff.PROJECTILE_SPEED]
     vel = [player.vel[0] + normalized[0],
                          player.vel[1] + normalized[1]]
     
     damage_source = DamageSourceBullet(pos, 5, 0.5, vel, "img/projectiles/orb.png", player, 60)
     world.create_entity(damage_source)
     
     world.create_entity(EntityEnemy(Convert.viewport_to_world(mouse_pos, viewport), "img/enemies/pinky.png", 10)) #TODO: remove
Ejemplo n.º 30
0
def dictionary_learning_by_L1(X, S, dsz, G1, H1, G0, H0, parameter_rho_dic,
                              iteration, thr, cri):
    Xf = con.convert_to_Xf(X, S, cri)

    bar_D = tqdm(total=iteration, desc='D', leave=False)
    for i in range(iteration):

        D, G0, H0, XD = dictionary_learning_by_L1_Dstep(
            Xf, S, G1, H1, G0, H0, parameter_rho_dic, i, cri, dsz)

        Dr = np.asarray(D.reshape(cri.shpD), dtype=S.dtype)
        H1r = np.asarray(H1.reshape(cri.shpD), dtype=S.dtype)
        Pcn = cr.getPcn(dsz, cri.Nv, cri.dimN, cri.dimCd)
        G1r = Pcn(Dr + H1r)
        G1 = cr.bcrop(G1r, dsz, cri.dimN).squeeze()

        H1 = H1 + D - G1

        Est = sp.norm_l1(XD - S)
        if (i == 0):
            pre_Est = 1.1 * Est

        if ((pre_Est - Est) / pre_Est <= thr):
            bar_D.update(iteration - i)
            break

        pre_Est = Est

        bar_D.update(1)
    bar_D.close()
    return D, G0, G1, H0, H1
Ejemplo n.º 31
0
def main():
    print("Jay Ganesh....")

    print("Enter Character To Convert")
    ch = input()

    Convert.Convert(ch)
Ejemplo n.º 32
0
 def render_block(self, x, y, screen, viewport, background):
     #don't render air
     if background:
         block = World.get_block_from_id(self.background_blocks[y][x])
     else:
         block = World.get_block_from_id(self.foreground_blocks[y][x])
     if block["name"] != "air":
         Game.get_world().render_block(block["id"], [Convert.chunk_to_world(x, self), y], block["connectedTexture"], screen, viewport, background, self)
Ejemplo n.º 33
0
 def update(self, world):
     old_chunk = Convert.world_to_chunk(self.pos[0])[1]
     hspeed = min(abs(self.vel[0] + self.acceleration * self.dir[0]), self.max_speed) * self.dir[0]
     vspeed = min(abs(self.vel[1] + self.acceleration * self.dir[1]), self.max_speed) * self.dir[1]
     self.vel = [hspeed, vspeed]
     super(Player, self).update(world)
     new_chunk = Convert.world_to_chunk(self.pos[0])[1]
     if new_chunk != old_chunk:
         world.load_chunks(new_chunk)
     
     entities = world.loaded_chunks.get(Convert.world_to_chunk(self.pos[0])[1]).entities
     for entity in entities:
         if(self.bounding_box.colliderect(entity.bounding_box)):
             if type(entity) is BlockDrop:
                 if self.pickup(entity.blockname):
                     entities.remove(entity)
                 print(self.inventory)
Ejemplo n.º 34
0
 def render(self, screen, viewport):
     top = max(Convert.pixel_to_world(viewport.y), 0)
     bottom = min(Convert.pixel_to_world(viewport.y + viewport.height) + 1, World.HEIGHT)
     for blocky in range(top, bottom):
         leftData = Convert.pixel_to_chunk(viewport.x)
         rightData = Convert.pixel_to_chunk(viewport.x + viewport.width)
         if leftData[1] == self.x:
             for blockx in range(leftData[0], WIDTH):
                 self.render_block(self.blocks[blocky][blockx], (blockx, blocky), screen, viewport)
         elif leftData[1] < self.x < rightData[1]:
             for blockx in range(WIDTH):
                 self.render_block(self.blocks[blocky][blockx], (blockx, blocky), screen, viewport)
         elif self.x == rightData[1]:
             for blockx in range(0, rightData[0] + 1):
                 self.render_block(self.blocks[blocky][blockx], (blockx, blocky), screen, viewport)
     for entity in self.entities:
         entity.render(screen, Convert.world_to_viewport(entity.pos, viewport))
Ejemplo n.º 35
0
def get_page_data(titles, hyperlinks):
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    options.add_argument("--test-type")
    options.add_argument('--no-sandbox')
    options.add_argument('–disable-dev-shm-usage')
    driver = webdriver.Chrome('C:/ChromeDriver/chromedriver.exe', chrome_options=options)

    browser = webdriver.Chrome(executable_path='C:/ChromeDriver/chromedriver.exe', chrome_options=options)
    page_data = {'country': [], 'genre': [], 'budget': [], 'awards': [], 'award wins': [], 'award nominations': [],
                 'duration': []}
    index = 1
    for hyperlink, title in zip(hyperlinks, titles):
        browser.get(hyperlink)

        # Wait 20 seconds for page to load
        timeout = 20
        try:
            WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.TAG_NAME, 'h1')))
        except TimeoutException:
            print("Timed out waiting for page to load")
            browser.quit()
        a = browser.find_element_by_css_selector("div[class='subtext']").text
        meta_info = a.split(' | ')
        duration = meta_info[1]
        genre = meta_info[2]
        try:
            country = browser.find_element_by_xpath("//h4[contains(text(), 'Country')]/following-sibling::a").text
        except NoSuchElementException:
            country = "Unknown"
        try:
            budget = browser.find_element_by_xpath("//h4[contains(text(), 'Budget')]/..").text[7:-12]
        except NoSuchElementException:
            budget = "Unknown"
        converted_budget = Convert.convert_currency(budget)

        try:
            awards = browser.find_element_by_css_selector("span[class='awards-blurb']").text
            extract_wins_nominations(awards, page_data)
        except NoSuchElementException:
            awards = "0"
            page_data['award wins'].append('0')
            page_data['award nominations'].append('0')
        print(str(index) + " " + title)
        index += 1
        # print("country: " + country)
        page_data['country'].append(country)
        # print("duration: " + duration)
        page_data['duration'].append(duration)
        # print("genre: " + genre)
        page_data['genre'].append(genre)
        # print("budget: " + budget)
        page_data['budget'].append(converted_budget)
        # print("awards: " + awards + "\n")
        page_data['awards'].append(awards)

    browser.quit()
    return page_data
Ejemplo n.º 36
0
    def __init__(self,
                 logger,
                 statusObj,
                 threadPool,
                 ev_quit=None,
                 myhost=None,
                 monchannels=[],
                 loghome=None):
        self.recvTSCTasker = self.processRpcMsgTasker(
            self.processTCSstatRpcMsg)
        self.recvSOSSTasker = self.processRpcMsgTasker(
            self.processSOSSstatRpcMsg)
        self.recvDAQTasker = self.processRpcMsgTasker(self.processDAQgetRpcMsg)

        self.statusObj = statusObj
        self.num_SOSSmonunits = 5
        self.num_TSCmonunits = 1
        self.TSCmonunit = {}
        self.SOSSmonunit = {}
        self.ScreenGet = {}
        self.statusInfo = Convert.statusInfo(version=2)

        # For TSC status logging
        self.loghome = loghome
        self.tsclog = {}
        self.tsclog_lock = threading.RLock()
        self.tsclog_hr = 0

        self.logger = logger
        self.monitor = None
        self.threadPool = threadPool
        self.monchannels = monchannels
        if ev_quit:
            self.ev_quit = ev_quit
        else:
            self.ev_quit = threading.Event()
        self.timeout = 0.1
        self.qtask = None
        self.taskqueue = Queue.Queue()

        # For handling updates to the monitor
        self.monUpdateInterval = 1.0
        self.monUpdateSet = set([])
        self.monUpdateLock = threading.RLock()

        # For DAQ status request handing
        self.hostfilter = None
        self.hostfilter_lock = threading.RLock()
        if not myhost:
            myhost = SOSSrpc.get_myhost(short=True)
        self.myhost = myhost
        self.seq_num = SOSSrpc.rpcSequenceNumber()
        self.clients = {}
        self.client_lock = threading.RLock()

        # For task inheritance:
        self.tag = 'StatusReceiver'
        self.shares = ['logger', 'ev_quit', 'timeout', 'threadPool', 'monitor']
Ejemplo n.º 37
0
def render():
    if gamemode == MAINMENU or gamemode == PAUSEMENU:
        menu.render_background(screen)
        menu.render(screen)
        
    elif gamemode in (PLAYING, OPENGUI):
        player = world.player
        shift = pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT]
        screen.fill(SKY)
        
        #background
        world.render(screen, viewport, True)
        if shift:
            player.draw_block_highlight(world, pygame.mouse.get_pos(), viewport, screen, shift)
        world.render_breaks(screen, viewport, True)
        
        #foreground
        world.render(screen, viewport, False)
        if not shift:
            player.draw_block_highlight(world, pygame.mouse.get_pos(), viewport, screen, shift)
        world.render_breaks(screen, viewport, False)
        player.render(screen, Convert.world_to_viewport(player.pos, viewport))
        
        #add blue overlay- not completely sure this is good
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        overlay.set_alpha(64)
        overlay.fill(BLUE)
        screen.blit(overlay, (0, 0))
        
        if gamemode == PLAYING:
            hotbarGui.render(screen)
        else:
            gui.render(screen)
        
        if DEBUG:
            #render debug text
            chunk = world.loaded_chunks.get(Convert.world_to_chunk(player.pos[0])[1])
            debugtext = ["fps: {0:.2f}".format(clock.get_fps()),
                        "pos: [{0:.2f}".format(player.pos[0]) + ", {0:.2f}]".format(player.pos[1]),
                        "chunk: " + str(chunk.x),
                        "biome: " + str(chunk.biome["name"])]
            debugimg = GUI.render_string_array(debugtext, font, 0, WHITE)
            h = SCREEN_HEIGHT - debugimg.get_height()
            screen.blit(debugimg, (2 * SCALE, h))
    pygame.display.flip()
Ejemplo n.º 38
0
 def update(self):
     for x in range(self.loaded_chunks.first, self.loaded_chunks.end):
         chunk = self.loaded_chunks.get(x)
         for entity in chunk.entities:
             entity.update(self)
             if Convert.world_to_chunk(entity.pos[0])[1] != chunk.x \
                     and self.loaded_chunks.contains_index(Convert.world_to_chunk(entity.pos[0])[1]) \
                     and entity in chunk.entities:
                 chunk.entities.remove(entity)
                 self.create_entity(entity)
     for layer in [True, False]:
         blocks_to_remove = []
         for breaking_block in self.breaking_blocks[layer]:
             breaking_block["progress"] -= 1
             if breaking_block["progress"] <= 0:
                 blocks_to_remove.append(breaking_block)
         for b in blocks_to_remove:
             self.breaking_blocks[layer].remove(b)
Ejemplo n.º 39
0
 def check_collision(self, chunk, left, right, top, bottom, old_pos, index):
     for block_x in range(left, right):
         for block_y in range(top, bottom):
             check_block = World.get_block(chunk.get_block_at(block_x, block_y, self.background))
             if check_block["solid"] and self.collides([Convert.chunk_to_world(block_x, chunk), block_y]):
                 #found a collision! 
                 self.pos[index] = old_pos[index]
                 return True
     return False
Ejemplo n.º 40
0
def update():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            close()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if gamemode == MENU:
                menu.mouse_press()
            if gamemode == PLAYING:
                world.break_block(player, pygame.mouse.get_pos(), viewport)
        elif event.type == pygame.MOUSEBUTTONUP:
            if gamemode == MENU:
                menu.mouse_release()
        elif event.type == pygame.KEYDOWN:
            if pygame.key.get_pressed()[pygame.K_e]:
                global gui
                if gui is None:
                    gui = InventoryGUI.InventoryGUI(player)
                else:
                    gui = None
            if pygame.key.get_pressed()[pygame.K_F3]:
                global DEBUG
                DEBUG = not DEBUG
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_ESCAPE]:
        close()
    
    if gamemode == MENU:
        menu.update()
    
    elif gamemode == PLAYING:
        player.dir = [0, 0]
        if pressed[pygame.K_LEFT] or pressed[pygame.K_a]:
            player.dir[0] -= 1
        if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:
            player.dir[0] += 1
        if pressed[pygame.K_UP] or pressed[pygame.K_w]:
            player.dir[1] -= 1
        if pressed[pygame.K_DOWN] or pressed[pygame.K_s]:
            player.dir[1] += 1
        player.update(world)
        viewport.x = Convert.world_to_pixels(player.pos)[0] - SCREEN_WIDTH / 2 #replace with center
        viewport.y = Convert.world_to_pixels(player.pos)[1] - SCREEN_HEIGHT / 2
        world.update()
Ejemplo n.º 41
0
 def check_collision(self, chunk, left, right, top, bottom, old_pos, index):
     for block_x in range(left, right):
         for block_y in range(top, bottom):
             check_block = chunk.blocks[block_y][block_x]
             #if check_block.is_solid() and self.collides([Convert.chunk_to_world(block_x, chunk), block_y]):
             if check_block["solid"] and self.collides([Convert.chunk_to_world(block_x, chunk), block_y]):
                 #found a collision! 
                 self.pos[index] = old_pos[index]
                 return True
     return False
Ejemplo n.º 42
0
 def render_block_preview(self, background, held_item, world, block_pos, screen, viewport):
     held_block = World.get_block(held_item.name)
     blockimg = world.get_block_render(World.get_block_id(held_block["name"]), block_pos, held_block["connectedTexture"], background, background).copy()
     mask = pygame.mask.from_surface(blockimg)
     olist = mask.outline()
     polysurface = pygame.Surface((Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE), pygame.SRCALPHA)
     screen.blit(polysurface, Convert.world_to_viewport(block_pos, viewport))
     collides = False
     entities = self.get_nearby_entities(world)
     entities.append(self)
     for entity in entities:
         if entity.collides(block_pos) and entity.background == background:
             collides = True
     color = self.get_color(background)
     if collides and World.get_block(held_block["name"])["solid"]:
         color = (color[0], 0, 0, color[3])
     pygame.draw.polygon(polysurface, color, olist, 0)
     blockimg.blit(polysurface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
     screen.blit(blockimg, Convert.world_to_viewport(block_pos, viewport))
Ejemplo n.º 43
0
 def render_breaks(self, screen, viewport, background):
     for breaking_block in self.breaking_blocks[background]:
         break_index = int(breaking_block["progress"] / breaking_block["breaktime"] * Game.BREAK_LENGTH)
         breakimg = Images.break_images[break_index].copy()
         blockimg = block_images[False][get_block_id(breaking_block["name"])] #TODO: make this support CTM
         mask = pygame.mask.from_surface(blockimg)
         olist = mask.outline()
         polysurface = pygame.Surface((Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE), pygame.SRCALPHA)
         pygame.draw.polygon(polysurface, Game.WHITE, olist, 0)
         breakimg.blit(polysurface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
         screen.blit(breakimg, Convert.world_to_viewport(breaking_block["pos"], viewport))
Ejemplo n.º 44
0
 def is_clear(self, world, pos):
     for x in range(int(pos[0]), int(pos[0] + self.width)):
         for y in range(int(pos[1]), int(pos[1] + self.height)):
             if not world.is_loaded_chunk(Convert.world_to_chunk(x)[1]):
                 return False
             if y >= World.HEIGHT:
                 return False
             block = World.get_block(world.get_block_at((x, y), False))
             if block["solid"]:
                 return False
     return True
Ejemplo n.º 45
0
def update_file():
    parser = argparse.ArgumentParser(
        description='Generate a classic book with the desired format.')
    parser.add_argument('sort', type=str, help='simplified or tranditional')
    parser.add_argument('book', type=str, help='a book file')
    args = parser.parse_args()
    filePath = args.book
    sort = args.sort
    try:
        content = None
        with open(filePath, 'r') as file:
            content = file.read().decode("utf-8")
        if sort == 'Simplified':
            content = Convert.Convert(content)
        else:
            content = Convert.wrap_checkedToneChar_with_superscript(content)
        with open(filePath, 'w') as file:
            file.write(content.encode("utf-8"))
    except IOError:
        print("IOError occurs while handling the file (" + filePath + ").")
Ejemplo n.º 46
0
    def changeType(self, newType):
        number = self.en.get()
        self.label.destroy()
        try:
            number = float(number)
        except:
            self.label = Label(self.master, text="type in a number please")
            self.label.grid(columnspan=12, sticky="SE")
            return False

        value = Convert.newUnit(self.ty, number,
                                Convert.unitName(self.ty, self.start),
                                Convert.unitName(self.ty, newType))
        self.en.delete(0, 20)

        self.label = Label(self.master,
                           height=3,
                           text=str(value) + " " +
                           Convert.unitName(self.ty, newType))
        self.label.grid(columnspan=12, sticky="SE")
Ejemplo n.º 47
0
def segment(config):
    # images = Convert.loadImages(config.trainImages)
    # gts = Convert.convertLabels(Convert.loadImages(config.trainLabels))
    # probs = np.load(config.likelihood) * 256

    images = Convert.loadImages(config.trainImages)
    gts = _getGroundTrues(Convert.loadImages(config.trainLabels))
    probs = Convert.loadImages(config.likelihood)

    RandIndex = np.zeros(probs.shape[0])
    VOI = np.zeros(probs.shape[0])
    RE = np.zeros(probs.shape[0])

    for i in range(probs.shape[0]):
        pr = probs[i]
        temp = np.zeros((pr.shape[0] + 2, pr.shape[1] + 2))
        temp[1:pr.shape[0] + 1, 1:pr.shape[1] + 1] = pr[:, :]
        pr = temp
        pr = ndimage.gaussian_filter(pr, sigma=5, mode="constant")
        thres = 0.03
        itk.Water
Ejemplo n.º 48
0
class WinApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.bind('<Destroy>',self.__onDestory)
        self.startBtn = Button(self,text = "START",command = self.__startFn)
        self.startBtn.pack()
        self.stopBtn = Button(self,text = "STOP",command = self.__stopFn)
        self.stopBtn.pack()
        self.__createWidget()
        self.t = threading.Thread(target = self.__running)
        self.__stop = False
        self.__terminate = False
        self.t.start()

    def __onDestory(self,evnet):
        self.inComm.terminate()
        self.outComm.terminate()
        self.__terminate = True

    def __createWidget(self):
        self.inComm = Comm("COM4",57600)
        self.outComm = Comm("COM5",57600)
        self.inComm.start()
        self.outComm.start()
        self.conv = Convert(23,1.21,0)

    def __startFn(self):
        ret,msg = self.inComm.open()
        ret,msg = self.outComm.open()
        self.__stop = False
        
    def __stopFn(self):
        self.__stop = True
        time.sleep(0.5)
        self.inComm.close()
        self.outComm.close()
        

    def __running(self):
        while not self.__terminate:
            if self.__stop:
                continue
            
            ret,data = self.inComm.recv(3)
            if not ret:
                continue
            ret,data = self.conv.conv(data)
            if not ret:
                continue
            
            self.outComm.send((str(data)+'\n').encode('utf8'))
Ejemplo n.º 49
0
 def break_block(self, world, mouse_pos, viewport, background):
     block_pos = self.find_angle_pos(mouse_pos, viewport)
     chunk = world.loaded_chunks.get(Convert.world_to_chunk(block_pos[0])[1])
     #if there's a foreground block covering the background, don't break anything
     if background and world.get_block_at(block_pos, False) != "water":
         return
     block = World.get_block(world.get_block_at(block_pos, background))
     held_item = self.get_held_item()
     if held_item is None:
         harvest_level = 0
         break_speed = 1
     else:
         harvest_level = held_item.get_harvest_level()
         break_speed = held_item.get_break_speed()
     if (not block["breakable"]) or (block["harvestlevel"] > harvest_level):
         return
     block_to_break = None
     breaking_blocks = world.breaking_blocks[background]
     for breaking_block in breaking_blocks:
         if breaking_block["pos"] == block_pos:
             block_to_break = breaking_block
     if block_to_break is None:
         block_to_break = {"pos": block_pos, "name": block["name"], "progress": 0, "breaktime": block["breaktime"]}
         breaking_blocks.append(block_to_break)
     block_to_break["progress"] += 2 * break_speed
     if block_to_break["progress"] >= block_to_break["breaktime"]:
         #remove the block
         breaking_blocks.remove(block_to_break)
         chunk.set_block_at(Convert.world_to_chunk(block_pos[0])[0], block_pos[1], World.get_block("water"), background)
         blockentity = None
         if block["entity"] != "":
             #remove the associated entity
             for entity in chunk.entities:
                 if type(entity).__name__ == block["entity"] and [int(entity.pos[0]), int(entity.pos[1])] == block_pos:
                     chunk.entities.remove(entity)
                     blockentity = entity
                     break
         chunk.entities.append(ItemDrop(block_pos, block["name"], blockentity))
Ejemplo n.º 50
0
 def load_state(self, path):
     savefile = open(path, "rb")
     save_data = pickle.load(savefile)
     savefile.close()
     self.player.set_pos(save_data["player_pos"])
     player_chunk = Convert.world_to_chunk(self.player.pos[0])[1]
     self.loaded_chunks = TwoWayList.TwoWayList()
     self.load_chunks(player_chunk)
     self.player.inventory = save_data["player_inventory"]
     for row in self.player.inventory:
         for item in row:
             if item is not None:
                 item.load_image()
     self.player.selected_slot = save_data["hotbar_slot"]
Ejemplo n.º 51
0
def check_links(pivot, links, index=0):

    if Convert.convert(links[index]) < Convert.convert(pivot[index]):
        return True

    if links.lower() == pivot.lower():
        if ord(links[0]) > ord(pivot[0]):
            return False
        elif ord(links[0]) < ord(pivot[0]):
            return True

    try:
        if Convert.convert(links[index]) == Convert.convert(pivot[index]):
            return check_links(pivot, links, index + 1)

    except IndexError:
        if len(links) > len(pivot):
            return False

        else:
            return True

    return False
Ejemplo n.º 52
0
    def GetSpheCoordinates(self):

        spherical_list = self.entry_3.get() + "," + self.entry_6.get(
        ) + "," + self.entry_9.get()

        print(spherical_list)

        if self.entry_1.get() != '':
            sphe_list = spherical_list.split(',')
            sphe = [float(x.strip()) for x in sphe_list]
            rect = Convert.sph_to_cart(sphe[0], sphe[1], sphe[2])
            cyli = Convert.sph_to_cyl(sphe[0], sphe[1], sphe[2])

        print('Cartesian:   (' + "%.4f" % rect[0] + ', ' + "%.4f" % rect[1] +
              ', ' + "%.4f" % rect[2] + ').')
        print('Cylindrical: (' + "%.4f" % cyli[0] + ', ' + "%.4f" % cyli[1] +
              ', ' + "%.4f" % cyli[2] + ').')
        print('Spherical:   (' + "%.4f" % sphe[0] + ', ' + "%.4f" % sphe[1] +
              ', ' + "%.4f" % sphe[2] + ').')

        self.entry_1.delete(0, tk.END)
        self.entry_1.insert(0, rect[0])
        self.entry_4.delete(0, tk.END)
        self.entry_4.insert(0, rect[1])
        self.entry_7.delete(0, tk.END)
        self.entry_7.insert(0, rect[2])

        self.entry_2.delete(0, tk.END)
        self.entry_2.insert(0, cyli[0])
        self.entry_5.delete(0, tk.END)
        self.entry_5.insert(0, cyli[1])
        self.entry_8.delete(0, tk.END)
        self.entry_8.insert(0, cyli[2])

        self.x, self.y, self.z = rect[0], rect[1], rect[2]
        self.a, self.b, self.c = cyli[0], cyli[1], cyli[2]
        self.i, self.j, self.k = sphe[0], sphe[1], sphe[2]
Ejemplo n.º 53
0
 def load_state(self, path):
     savefile = open(path, "rb")
     save_data = pickle.load(savefile)
     savefile.close()
     self.player = save_data["player"]
     self.seed = save_data["seed"]
     Generate.setup(self.seed)
     player_chunk = Convert.world_to_chunk(self.player.pos[0])[1]
     self.loaded_chunks = TwoWayList.TwoWayList()
     self.load_chunks(player_chunk)
     self.player.load_image()
     for row in self.player.inventory:
         for item in row:
             if item is not None:
                 item.load_image()
Ejemplo n.º 54
0
    def GetRectCoordinates(self):
        rectangular_list = self.entry_1.get() + "," + self.entry_4.get(
        ) + "," + self.entry_7.get()

        print(rectangular_list)

        if self.entry_1.get() != '':
            rect_list = rectangular_list.split(',')
            rect = [float(x.strip()) for x in rect_list]
            cyli = Convert.cart_to_cyl(rect[0], rect[1], rect[2])
            sphe = Convert.cart_to_sph(rect[0], rect[1], rect[2])

        print('Cartesian:   (' + "%.4f" % rect[0] + ', ' + "%.4f" % rect[1] +
              ', ' + "%.4f" % rect[2] + ').')
        print('Cylindrical: (' + "%.4f" % cyli[0] + ', ' + "%.4f" % cyli[1] +
              ', ' + "%.4f" % cyli[2] + ').')
        print('Spherical:   (' + "%.4f" % sphe[0] + ', ' + "%.4f" % sphe[1] +
              ', ' + "%.4f" % sphe[2] + ').')

        self.entry_2.delete(0, tk.END)
        self.entry_2.insert(0, cyli[0])
        self.entry_5.delete(0, tk.END)
        self.entry_5.insert(0, cyli[1])
        self.entry_8.delete(0, tk.END)
        self.entry_8.insert(0, cyli[2])

        self.entry_3.delete(0, tk.END)
        self.entry_3.insert(0, sphe[0])
        self.entry_6.delete(0, tk.END)
        self.entry_6.insert(0, sphe[1])
        self.entry_9.delete(0, tk.END)
        self.entry_9.insert(0, sphe[2])

        self.x, self.y, self.z = rect[0], rect[1], rect[2]
        self.a, self.b, self.c = cyli[0], cyli[1], cyli[2]
        self.i, self.j, self.k = sphe[0], sphe[1], sphe[2]
Ejemplo n.º 55
0
def convert(src, tgt, txt, nativize, preoptions, postoptions):
    txt = PreProcess.PreProcess(txt, src, tgt)

    if 'siddhammukta' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamDevanagari'
    if 'siddhamap' in postoptions and tgt == 'Siddham':
        tgt = 'SiddhamDevanagari'
    if 'siddhammukta' in preoptions and src == 'Siddham':
        src = 'SiddhamDevanagari'
    if 'LaoNative' in postoptions and tgt == 'Lao':
        tgt = 'Lao2'
    if 'egrantamil' in preoptions and src == 'Grantha':
        src = 'GranthaGrantamil'
    if 'egrantamil' in postoptions and tgt == 'Grantha':
        tgt = 'GranthaGrantamil'
    if 'nepaldevafont' in postoptions and tgt == 'Newa':
        tgt = 'Devanagari'
    if 'ranjanalantsa' in postoptions and tgt == 'Ranjana':
        tgt = 'Tibetan'
        nativize = False
    if 'ranjanawartu' in postoptions and tgt == 'Ranjana':
        tgt = 'Tibetan'
        nativize = False

    for options in preoptions:
        txt = getattr(PreProcess, options)(txt)

    transliteration = Convert.convertScript(txt, src, tgt)

    if nativize:
        transliteration = PostOptions.ApplyScriptDefaults(
            transliteration, src, tgt)
        if tgt != 'Tamil':
            transliteration = PostProcess.RemoveDiacritics(transliteration)
        else:
            transliteration = PostProcess.RemoveDiacriticsTamil(
                transliteration)

    for options in postoptions:
        transliteration = getattr(PostProcess, options)(transliteration)

    if src == "Tamil" and tgt == "IPA":
        r = requests.get("http://anunaadam.appspot.com/api?text=" + txt +
                         "&method=2")
        r.encoding = r.apparent_encoding
        transliteration = r.text

    return transliteration
Ejemplo n.º 56
0
    def __init__(self, svcname='status', host=None,
                 suppress_fetch_errors=False,
                 suppress_conversion_errors=False):

        super(g2StatusObj, self).__init__()

        self.svcname = svcname

        # holds all kinds of data about SOSS status aliases 
        self.info = Convert.statusInfo()

        if host:
            ro.init([host])
        else:
            ro.init()

        self.reset()
Ejemplo n.º 57
0
def evaluation_final(config):
    print("Evaluating Final Result")
    images = tifffile.imread(config.deployLabels)
    target = config.getResultFile("final_target.tif")
    tifffile.imsave(target, images[config.segmentRange])

    arr = Convert.loadMHA(glob.glob(config.getResultFile("final_*.mha")))
    arr[arr != 0.0] = 255
    arr = arr.astype(np.uint8)

    final = config.getResultFile("final.tif")
    tifffile.imsave(final, arr)

    p = subprocess.Popen(["java", "-jar", "Evaluation.jar", target, final],
                         stdout=config.logStream,
                         stderr=config.logStream)
    p.wait()
    config.logStream.flush()
Ejemplo n.º 58
0
 def on_click_Convert_OpenFile(self):
     fni = self.ui.myTextInput_Convert_fileIn.text()
     fno = self.ui.myTextInput_Convert_fileOut.text()
     #pos = self.ui.checkBox_POS.isChecked()
     print("Input file to be processed: {}".format(fni))
     print("Output file: {}".format(fno))
     #print("Conversion direction = {}".format(pos))
     self.ui.textBrowser.append(
         "Begin conversion (using OpenCC) on " +
         f"{datetime.datetime.now():%Y-%m-%d at %H:%M:%S}")
     self.ui.textBrowser.repaint()
     # determine conversion direction from UI
     conversion_direction = 's2tw'  # default (see OpenCC docs)
     if self.ui.radioButton_zht2zhs.isChecked():
         conversion_direction = 't2s'
     elif self.ui.radioButton_zhs2zht.isChecked():
         conversion_direction = 's2tw'
     elif self.ui.radioButton_enLowercse.isChecked():
         conversion_direction = 'enlc'
     if os.path.exists(fni) and fno != '':
         #ret = processSegment(fni, fno, LANG, pos, lib, self)
         if conversion_direction in ['s2tw', 't2s']:
             start_time = time.time()
             import Convert
             doc = Convert.ZhtZhsConvert(fni, fno, conversion_direction,
                                         self)
             #line_count = Convert.lineCount(fni)
             ret = doc.convert()
             elapsed_time = round(time.time() - start_time, 2)
             self.ui.textBrowser.append(
                 "Conversion complete in {} seconds".format(elapsed_time))
             self.ui.textBrowser.repaint()
         elif conversion_direction in ['enlc']:
             pass
     else:
         self.ui.textBrowser.append(
             "Input or output file is empty. Nothing to do!")
         self.ui.textBrowser.repaint()
Ejemplo n.º 59
0
def projection_to_solution_space_by_L1(D, X, S, Y, U, parameter_rho_coef,
                                       parameter_gamma, iteration, thr, cri,
                                       dsz):
    Df = con.convert_to_Df(D, S, cri)
    Xf = con.convert_to_Xf(X, S, cri)

    for i in range(iteration):

        YSUf = con.convert_to_Sf(Y + S - U, cri)
        b = (1 / parameter_rho_coef) * Xf + np.conj(Df) * YSUf
        Xf = sl.solvedbi_sm(Df, (1 / parameter_rho_coef), b)
        X = con.convert_to_X(Xf, cri)
        #X = np.where(X <= 0, 0, X)

        Xf = con.convert_to_Xf(X, S, cri)
        DfXf = np.sum(Df * Xf, axis=cri.axisM)
        DX = con.convert_to_S(DfXf, cri)
        Y = sp.prox_l1(DX - S + U, (parameter_gamma / parameter_rho_coef))

        U = U + DX - Y - S

    return X, Y, U
Ejemplo n.º 60
0
def dictionary_learning_by_L2(X, S, dsz, G, H, parameter_rho_dic, iteration,
                              thr, cri):
    Xf = con.convert_to_Xf(X, S, cri)

    bar_D = tqdm(total=iteration, desc='D', leave=False)
    for i in range(iteration):

        Gf = con.convert_to_Df(G, S, cri)
        Hf = con.convert_to_Df(H, S, cri)
        GH = Gf - Hf
        Sf = con.convert_to_Sf(S, cri)
        b = parameter_rho_dic * GH + sl.inner(np.conj(Xf), Sf, cri.axisK)
        Df = sl.solvemdbi_ism(Xf, parameter_rho_dic, b, cri.axisM, cri.axisK)
        D = con.convert_to_D(Df, dsz, cri)

        XfDf = np.sum(Xf * Df, axis=cri.axisM)
        XD = con.convert_to_S(XfDf, cri)

        Dr = np.asarray(D.reshape(cri.shpD), dtype=S.dtype)
        Hr = np.asarray(H.reshape(cri.shpD), dtype=S.dtype)
        Pcn = cr.getPcn(dsz, cri.Nv, cri.dimN, cri.dimCd)
        Gr = Pcn(Dr + Hr)
        G = cr.bcrop(Gr, dsz, cri.dimN).squeeze()

        H = H + D - G

        Est = sp.norm_2l2(XD - S)
        if (i == 0):
            pre_Est = 1.1 * Est

        if ((pre_Est - Est) / pre_Est <= thr):
            bar_D.update(iteration - i)
            break

        pre_Est = Est

        bar_D.update(1)
    bar_D.close()
    return D, G, H