Example #1
0
def create_images_from_boot_images(source,
                                   epoch,
                                   bands,
                                   stokes,
                                   base_path=None):
    """
    :param source:
        Source name.
    :param epoch:
        Sources epoch.
    :param bands:
        Iterable of bands.
    :param base_path: (optional)
        Path to route of directory tree. If ``None`` then use current directory.
        (default: ``None``)
    """

    curdir = os.getcwd()
    print "Stacking bootstrapped images..."
    images = Images()
    for band in bands:
        print " for band ", band
        for stoke in stokes:
            map_path = im_fits_path(source,
                                    band,
                                    epoch,
                                    stoke,
                                    base_path=base_path)
            images.add_from_fits(wildcard=os.path.join(map_path, 'cc_*.fits'))

    return images
Example #2
0
 def update(self):
     if not self.isEmpty():
         bd = Bbdd()
         msg = bd.update(["name", "country"], [self.name, self.country],
                         "bookie", "id=" + self.id)
         bd.close()
         if msg != 0:
             msg = "Se ha producido un error al actualizar la BBDD"
         if self.ruta is not None:
             try:
                 if not os.path.exists(
                         expanduser("~") + "/.betcon/resources/bookies"):
                     os.makedirs(
                         expanduser("~") + "/.betcon/resources/bookies")
                 copy2(
                     self.ruta,
                     expanduser("~") + "/.betcon/resources/bookies/" +
                     self.id + ".png")
                 img = Images(
                     expanduser("~") + "/.betcon/resources/bookies/" +
                     self.id + ".png")
                 img.resize(100, 20)
             except:
                 msg = "Imágen incorrecta"
     else:
         msg = "Faltan datos por introducir"
     return msg
Example #3
0
def parse():
	print "parsing project file..."

	supportedLanguages = []
	images = Images()

	results = { "languages" : supportedLanguages, "images" : images }

	path = os.path.join(constants.getProjectName(), "project.pbxproj")
	plist = os.path.join("lproj", "InfoPlist.strings")

	with open(path) as f:
		for line in f:
			line = line.rstrip()

			if plist in line:
				fileName = stripWhiteSpace(LOCALIZED_DIR_REGEX.sub(regexMatch, line))
				
				addUniqueValue(supportedLanguages, fileName)

			if ".png" in line:
				imageName = stripWhiteSpace(IMAGE_FILE_REGEX.sub(regexMatch, line).rstrip())
				images.addImage(imageName)

	images.orderImages()

	return results
def main():
    command = input("Please select an image number(1 or 2):")
    if command == "1":
        while True:
            image_1 = Images("image_1.png", "RGB", 500, 500, "white")
            try:
                image_1.draw_on_image_version_1(database, 500, 500)
            except RuntimeError:
                continue
            else:
                image_1.save_image()
                img = Image.open('image_1.png')
                img.show()
                break
    elif command == "2":
        while True:
            image_2 = Images("image_2.png", "RGB", 500, 500, "black")
            try:
                image_2.draw_on_image_version_2(database, 500, 500)
            except RuntimeError:
                continue
            else:
                image_2.save_image()
                img = Image.open('image_2.png')
                img.show()
                break
    else:
        print("Not a valid number")
Example #5
0
    def calibrate(self,
                  fns,
                  pattern_size,
                  flag_calib=None,
                  debug=False,
                  square_size=1.):
        # calibrate camera
        images = Images(fns)
        self.w, self.h = images.w, images.h
        images.pattern_size = pattern_size
        obj_pnts, img_pnts = images.find_chess_img_pnts(debug)
        print("find points pair: ", len(img_pnts))

        flag_calib = cv.CALIB_FIX_K3 + cv.CALIB_ZERO_TANGENT_DIST
        rms, matrix, dist, rvecs, tvecs = cv.calibrateCamera(
            obj_pnts.transpose(0, 2, 1),
            img_pnts.transpose(0, 2, 1), (images.w, images.h),
            None,
            None,
            flags=flag_calib)
        self.K = matrix
        self.dist = dist
        self.rvecs = np.array(rvecs)
        self.tvecs = np.array(tvecs)
        return obj_pnts, img_pnts, rms
Example #6
0
    def get_user_image(user):
        result = dict()
        if user:
            if user.userextension.big_image:
                user_image = files.BASE_URL_4_IMAGE + user.userextension.big_image.name
                # Logs.print_log("user_image", user_image)
            else:
                if user.userextension.gender == "M":
                    user_image = USER_DEFAULT_MALE_ICON
                else:
                    user_image = USER_DEFAULT_FEMALE_ICON
        else:
            user_image = USER_DEFAULT_ICON
        memory_file = files.Files.get_memory_file(user_image)
        user_image_path = "/".join(user_image.split("/")[:-1])
        user_image_name = user_image.split("/")[-1]
        big_user_image_name = ".".join(user_image_name.split(".")[:-1]) + "_big." + user_image_name.split(".")[-1]
        small_user_image_name = ".".join(user_image_name.split(".")[:-1]) + "_small." + user_image_name.split(".")[-1]
        big_user_image = user_image_path + "/" + big_user_image_name
        small_user_image = user_image_path + "/" + small_user_image_name
        try:
            Images.resize_image(memory_file, big_user_image, 240)
            Images.resize_image(memory_file, small_user_image, 96)
            result["big_user_image"] = big_user_image
            result["small_user_image"] = small_user_image
        except Exception as ex:
            Logs.print_current_function_name_and_line_number(ex)
            if user.userextension.gender == "M":
                result["big_user_image"] = USER_DEFAULT_MALE_ICON
                result["small_user_image"] = USER_DEFAULT_MALE_ICON
            else:
                result["big_user_image"] = USER_DEFAULT_FEMALE_ICON
                result["small_user_image"] = USER_DEFAULT_FEMALE_ICON

        return result
Example #7
0
    def __init__(self):
        # Initialize attributes of QtWidgets.QMainWindow
        if 3 > sys.version_info[0]:
            # Python 2
            super(MainWindow, self).__init__()

        else:
            # Python 3
            super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Map labelCanvas pointer to the real instance
        self.labelCanvas = self.ui.labelCanvas

        self.imgList = Images(self.ui.listWidgetImgList)

        # Actions
        self.ui.actionImport.triggered.connect(self.actionImportClickEvt)
        self.ui.actionEdit.triggered.connect(self.actionEditClickEvt)
        self.ui.actionExit.triggered.connect(self.actionExitClickEvt)
        self.ui.listWidgetImgList.currentItemChanged.connect(
            self.actionCurrentItemChangedEvt)
        self.show()
Example #8
0
    def __post_init__(self):
        """Randomize self."""
        self.img = pygame.image.load(Images.get_path(r'flora.png'))

        if self.is_home:
            self.img = pygame.image.load(Images.get_path(r'home.png'))
            self.looks_like_home = True

        # Pick which color we are
        self.img_color = random.choice(range(0, 5))
        color_file = Images.color_files[self.img_color]
        color_img = pygame.image.load(Images.get_path(color_file))

        # Apply chosen color
        if not self.is_home:
            Images.color_image(self.img, color_img)

        # Size
        self.block_size = int(self.size_multiple * 32)
        self.img_scale = int(self.size / self.block_size)

        self.size_x = self.block_size * self.img_scale
        self.size_y = self.block_size * self.img_scale
        self.img = pygame.transform.scale(self.img, (int(
            self.size_x * self.img_cols), int(self.size_y * self.img_rows)))

        # Pick which variety we are.
        var_x = self.variety % self.img_cols
        var_y = self.variety % self.img_rows
        self.draw_area = pygame.Rect(var_x * self.block_size * self.img_scale,
                                     var_y * self.block_size * self.img_scale,
                                     self.block_size * self.img_scale,
                                     self.block_size * self.img_scale)

        self.logic()  # Bootstrap our collision rect.
Example #9
0
    def create_boot_pang_errors(self, cred_mass=0.68, n_sigma=None):
        """
        Create dictionary with images of PANG errors calculated from bootstrap
        PANG maps.

        :param cred_mass: (optional)
            Credibility mass. (default: ``0.68``)
        :param n_sigma: (optional)
            Sigma clipping for mask. If ``None`` then use instance's value.
            (default: ``None``)
        :return:
            Dictionary with keys - frequencies & values - instances of ``Image``
            class with error maps.
        """
        print(
            "Calculating maps of PANG errors for each band using bootstrapped"
            " PANG maps...")
        result = dict()
        if n_sigma is not None:
            self.set_common_mask(n_sigma)

        # Fetch common size `I` map on highest frequency for plotting PANG error
        # maps
        i_image = self.cc_cs_image_dict[self.freqs[-1]]['I']
        rms = rms_image(i_image)
        blc, trc = find_bbox(i_image.image,
                             2. * rms,
                             delta=int(i_image._beam.beam[0]))
        for i, freq in enumerate(self.freqs):
            images = self.boot_images.create_pang_images(freq=freq,
                                                         mask=self._cs_mask)
            pang_images = Images()
            pang_images.add_images(images)
            error_image = pang_images.create_error_image(cred_mass=cred_mass)
            # As this errors are used for linear fit judgement only - add EVPA
            # absolute calibration error in quadrature
            evpa_error = np.deg2rad(self.sigma_evpa[i]) * np.ones(
                error_image.image.shape)
            error_image.image = np.sqrt((error_image.image)**2. +
                                        evpa_error**2.)
            result[freq] = error_image
            fig = iplot(i_image.image,
                        error_image.image,
                        x=i_image.x,
                        y=i_image.y,
                        min_abs_level=3. * rms,
                        colors_mask=self._cs_mask,
                        color_clim=[0, 1],
                        blc=blc,
                        trc=trc,
                        beam=self.common_beam,
                        colorbar_label='sigma EVPA, [rad]',
                        slice_points=None,
                        show_beam=True,
                        show=False,
                        cmap='hsv')
            self.figures['EVPA_sigma_boot_{}'.format(freq)] = fig
        self.evpa_sigma_boot_dict = result
        return result
Example #10
0
class MainWindow(WindowWrapper):
    ### Constructor
    def __init__(self):
        # Initialize attributes of QtWidgets.QMainWindow
        if 3 > sys.version_info[0]:
            # Python 2
            super(MainWindow, self).__init__()

        else:
            # Python 3
            super().__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Map labelCanvas pointer to the real instance
        self.labelCanvas = self.ui.labelCanvas

        self.imgList = Images(self.ui.listWidgetImgList)

        # Actions
        self.ui.actionImport.triggered.connect(self.actionImportClickEvt)
        self.ui.actionEdit.triggered.connect(self.actionEditClickEvt)
        self.ui.actionExit.triggered.connect(self.actionExitClickEvt)
        self.ui.listWidgetImgList.currentItemChanged.connect(
            self.actionCurrentItemChangedEvt)
        self.show()

    ### Destructor
    def __del__(self):
        LOG(self, 'Finalizing ' + self.windowTitle() + ' Window')

    ### Event Handlers
    # Display Current Item when it changed
    def actionCurrentItemChangedEvt(self):
        # Get selected row index
        currentRow = self.ui.listWidgetImgList.currentRow()

        # Display selected image
        self.display(self.imgList.images[currentRow])

        # Enable Edit Action
        self.ui.actionEdit.setEnabled(True)

    # Import images
    def actionImportClickEvt(self):
        self.imgList.importImages()

    # Edit selected image
    def actionEditClickEvt(self):
        selectedIndex = self.ui.listWidgetImgList.currentRow()
        selectedImg = self.imgList.images[selectedIndex]
        editor = EditorWindow(self, selectedImg)
        self.subWidgets.append(editor)

    # Exit
    def actionExitClickEvt(self):
        self.close()
Example #11
0
 def boot_images(self):
     if self._boot_images is None:
             self._boot_images = Images()
             for freq in self.freqs:
                 for stokes in self.stokes:
                     # FIXME: to low memory usage for now
                     if stokes not in ('Q', 'U'):
                         continue
                     self._boot_images.add_from_fits(self.cc_boot_cs_fits_dict[freq][stokes])
     return self._boot_images
Example #12
0
    def add_players(self):
        """Create the players.

        Return an array of the players as objects with .draw methods.
        """
        player1 = Player(color=Colors.YELLOW,
                         start_x=self.max_x / 5 * 2,
                         controls=[ControlSet()])
        player1.images = PlayerImages(default=Images.get_path(r'seahorse.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player2 = Player(color=Colors.RED,
                         start_x=self.max_x / 5 * 4,
                         controls=[
                             ControlSet(up=pygame.K_j,
                                        down=pygame.K_k,
                                        left=pygame.K_h,
                                        right=pygame.K_l),
                             ControlSet(up=pygame.K_w,
                                        down=pygame.K_s,
                                        left=pygame.K_a,
                                        right=pygame.K_d)
                         ])
        player2.images = PlayerImages(default=Images.get_path(r'squid.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player3 = Player(color=Colors.BLUE,
                         start_x=self.max_x / 5,
                         controls=[
                             ControlSet(up=pygame.K_3,
                                        down=pygame.K_2,
                                        left=pygame.K_1,
                                        right=pygame.K_4)
                         ])
        player3.images = PlayerImages(default=Images.get_path(r'flounder.png'),
                                      size_x=self.player_size,
                                      size_y=self.player_size)
        player4 = Player(color=Colors.PURPLE,
                         start_x=self.max_x / 5 * 3,
                         controls=[
                             ControlSet(up=pygame.K_7,
                                        down=pygame.K_6,
                                        left=pygame.K_5,
                                        right=pygame.K_8)
                         ])
        player4.images = PlayerImages(
            default=Images.get_path(r'cuttlefish.png'),
            size_x=self.player_size,
            size_y=self.player_size)

        self.players = [player1, player2, player3, player4]
        for player in self.players:
            player.pos_y = self.ground_y - player.size_y / 2
            player.ground_y = self.ground_y
            player.max_x = self.max_x
Example #13
0
    def __post_init__(self):
        """Load some images."""
        self.images = []
        for color in Images.color_files:
            color_img = pygame.image.load(Images.get_path(color))
            horse = pygame.image.load(self.default)
            Images.color_image(base_image=horse, color_image=color_img)
            red_horse = pygame.transform.scale(horse, (int(self.size_x), int(self.size_y)))
            self.images += [red_horse]

        pygame.display.set_icon(self.images[0])
Example #14
0
 def sfm_2plane():
     print("3D images")
     fns = ["./datasets/oppo/test/3d_5.jpg", "./datasets/oppo/test/3d_6.jpg"]
     images_3d = Images(fns)
     points1, points2, num_plane1, num_plane2 = images_3d.find_img_pnts_manual()
     # tripoints3d = triangulation_two([points1[:, :num_plane1], points2[:, :num_plane1]], camera_tan.K)
     tripoints3d = triangulation_two([points1, points2], camera_tan.K)
     vec1, vec2 = plot_tripoints(tripoints3d, num_plane1, num_plane2)
     plt.show()
     angle = np.arccos(np.dot(vec1[:3], vec2[:3]) / np.linalg.norm(vec1) / np.linalg.norm(vec2))
     print(np.dot(vec1[:3], vec2[:3]))
     print(angle*180/np.pi)
Example #15
0
 def __rest_of_init(self, window, color, i):
     self.__images = Images()
     self.__images_list = self.__images.return_images()
     self.__image = choice(self.__images_list)
     self.frame = Frame(window, height=5, width=5, bg=color)
     self.frame.grid(row=i // 8, column=i % 8)
     self.position = '{}{}'.format(chr(97 + (i % 8)), 8 - i // 8)
     self.label = [Label(self.frame, image=self.__image[0], height=50, width=50, bg=color), self.__image[1],
                   self.__image[2]]
     self.label[0].grid()
     self.label[0].bind("<1>", self.__click)
     self.empty_position()
Example #16
0
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Proto-board layout editor")

        self.settings = Settings()
        self.editDlg = None
        self.Bind(wx.EVT_CLOSE, self.onClose)

        self.settings.images = Images(
            os.path.join(self.settings.cmdfolder, "images"))
        self.settings.compImages = Images(
            os.path.join(self.settings.cmdfolder, "components"))

        self.settings.fixedComponentList = FixedComponentList(
            self.settings.compImages)
        self.settings.stretchComponentList = StretchComponentList()
        self.settings.growComponentList = GrowComponentList(
            self.settings.compImages)
        self.settings.cmdFolder = cmd_folder
        self.settings.templDir = os.path.join(self.settings.cmdFolder,
                                              "templates")

        self.fileName = None

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.AddSpacer((50, 20))

        self.bNewTemp = wx.BitmapButton(self,
                                        wx.ID_ANY,
                                        self.settings.images.pngNewtemp,
                                        size=(64, 64))
        self.bNewTemp.SetToolTipString("Create a new Strip-Board template")
        self.Bind(wx.EVT_BUTTON, self.onNewTemp, self.bNewTemp)
        sizer.Add(self.bNewTemp, 1, wx.ALL, 10)

        self.bNew = wx.BitmapButton(self,
                                    wx.ID_ANY,
                                    self.settings.images.pngNew,
                                    size=(64, 64))
        self.bNew.SetToolTipString("Create a new Strip-Board")
        self.Bind(wx.EVT_BUTTON, self.onNew, self.bNew)
        sizer.Add(self.bNew, 1, wx.ALL, 10)

        self.bOpen = wx.BitmapButton(self,
                                     wx.ID_ANY,
                                     self.settings.images.pngOpen,
                                     size=(64, 64))
        self.bOpen.SetToolTipString("Open an existing Strip-Board file")
        self.Bind(wx.EVT_BUTTON, self.onOpen, self.bOpen)
        sizer.Add(self.bOpen, 1, wx.ALL, 10)

        sizer.AddSpacer((50, 20))
        self.SetSizer(sizer)
        self.Fit()
Example #17
0
    def __init__(self, config_file):

        # Set up config and image services
        self._config = ConfigReader(config_file)
        self._images = Images(self._config)

        # Create Flask app and define routes
        self._app = Flask(__name__, static_url_path="/static")
        self._app.add_url_rule("/", "index", self.show_index)
        self._app.add_url_rule("/show_image", "show_image", self.show_image)
        self._app.add_url_rule("/image_tags.csv", "download_tags", self.download_tags)
        self._app.add_url_rule(
            "/store_tags", "store_tags", self.store_tags, methods=["POST"]
        )
Example #18
0
    def camera_trianular(fns, K, dist, pattern_size):
        images_test = Images(fns)
        images_test.pattern_size = pattern_size
        obj_pnts, img_pnts = images_test.find_chess_img_pnts()
        tripoints3d = triangulation_two(img_pnts, K)
        plot_tripoints(tripoints3d)
        plt.savefig("../tri.png")

        camera_test = Camera((w, h), K, dist)
        img_pnts_undistort = camera_test.undistort_points(img_pnts)
        tripoints3d = triangulation_two(img_pnts_undistort, K)
        plot_tripoints(tripoints3d)
        plt.savefig("../tri_undistort.png")

        plt.show()
Example #19
0
 def original_cs_images(self):
     if self._original_cs_images is None:
         self._original_cs_images = Images()
         for freq in self.freqs:
             for stokes in self.stokes:
                 self.original_cs_images.add_image(self.cc_cs_image_dict[freq][stokes])
     return self._original_cs_images
Example #20
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Avengers Assemble")

    #Make a ship
    ship = Ship(ai_settings, screen)
    # Make an alien.
    alien = Alien(ai_settings, screen)
    image = Images(ai_settings, screen)

    bullets = Group()
    aliens = Group()
    booms = Group()

    # Create the fleet of aliens.

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets, image)
        gf.update_screen(ai_settings, screen, ship, aliens, bullets, booms,
                         image)
        if ai_settings.state:
            ship.update(bullets)
            gf.update_bullets(ai_settings, screen, ship, bullets, aliens,
                              booms)
            gf.update_aliens(aliens, ai_settings, screen, ship, bullets, image)
            gf.update_speed(ai_settings, screen, ship, aliens, bullets, booms,
                            image)
            gf.update_boom(booms, ai_settings)
Example #21
0
	def __init__(self, parent):
		wx.Frame.__init__(self, None, wx.ID_ANY, "", size=(600, 600))
		self.Bind(wx.EVT_CLOSE, self.onClose)
		self.settings = Settings(cmdFolder)
		self.parent = parent
		self.log = self.parent.log
		self.images = Images(os.path.join(cmdFolder, "images"))
		self.Show()
		ico = wx.Icon(os.path.join(cmdFolder, "images", "stlview.png"), wx.BITMAP_TYPE_PNG)
		self.SetIcon(ico)
		self.fileName = None
		
		self.gl = StlCanvas(self)
		sizer = wx.BoxSizer(wx.VERTICAL)
		glsizer = wx.BoxSizer(wx.HORIZONTAL)
		glsizer.AddSpacer(10)
		glsizer.Add(self.gl)
		glsizer.AddSpacer(10)
		sizer.Add(glsizer)
		
		bsizer = wx.BoxSizer(wx.HORIZONTAL)

		self.bOpen = wx.BitmapButton(self, wx.ID_ANY, self.images.pngFileopen, size=BUTTONDIM)
		self.bOpen.SetToolTip("Open an STL file for viewing")
		self.Bind(wx.EVT_BUTTON, self.onOpen, self.bOpen)
		bsizer.Add(self.bOpen)
		
		bsizer.AddSpacer(20)
		
		self.bImport = wx.BitmapButton(self, wx.ID_ANY, self.images.pngImport, size=BUTTONDIM)
		self.bImport.SetToolTip("Import the current STL file from the toolbox for viewing")
		self.Bind(wx.EVT_BUTTON, self.onImport, self.bImport)
		self.bImport.Enable(False)
		bsizer.Add(self.bImport)
		
		bsizer.AddSpacer(20)
		
		self.bExport = wx.BitmapButton(self, wx.ID_ANY, self.images.pngExport, size=BUTTONDIM)
		self.bExport.SetToolTip("Export the current STL file to the toolbox for downstream")
		self.Bind(wx.EVT_BUTTON, self.onExport, self.bExport)
		self.bExport.Enable(False)
		bsizer.Add(self.bExport)
		
		bsizer.AddSpacer(20)
		
		self.cbEnqueue = wx.CheckBox(self, wx.ID_ANY, "Enqueue STL file")
		self.cbEnqueue.SetToolTip("Enqueue the current STL file to the end of the slice queue")
		self.Bind(wx.EVT_CHECKBOX, self.onEnqueue, self.cbEnqueue)
		self.cbEnqueue.SetValue(self.settings.autoenqueue)
		self.cbEnqueue.Enable(True)
		bsizer.Add(self.cbEnqueue, 1, wx.TOP, 12)
		
		sizer.AddSpacer(10)
		sizer.Add(bsizer, 1, wx.ALIGN_CENTER_HORIZONTAL, 1)
		sizer.AddSpacer(10)
		
		self.setTitle()
		self.SetSizer(sizer)
		self.Fit()
Example #22
0
def do_all():
    algorithms = ["depthfirst", "breadthfirst", "dijkstra", "Astar"]
    images = ["tiny", "braid200", "normal", "small", "combo400"]

    for a in algorithms:
        for i in images:
            start(Algorithms().__getitem__(a),
                  Images().__getitem__(i), i + '_' + a)
Example #23
0
def main():
    al = Algorithms()
    images = Images()
    parser = argparse.ArgumentParser()
    parser.add_argument("Algorithm",
                        help="Selected Algorithm to use for pathfinding",
                        default=al.default,
                        choices=al.options,
                        nargs='?')
    parser.add_argument("Image",
                        help="Selected Image for pathfinding",
                        default=images.default,
                        choices=images.options,
                        nargs='?')
    parser.add_argument("output_name", nargs='?', default="algorithm")
    args = parser.parse_args()
    # print(args)
    start(al.__getitem__(args.Algorithm), images.__getitem__(args.Image),
          args.output_name)
Example #24
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: MainFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        
        # Menu Bar
        self.main_frame_menubar = wx.MenuBar()
        self.File = wx.Menu()
        self.Exit = wx.MenuItem(self.File, wx.ID_EXIT, _("E&xit\tCtrl-Q"), _("Exit"), wx.ITEM_NORMAL)
        self.File.AppendItem(self.Exit)
        self.main_frame_menubar.Append(self.File, _("&File"))
        self.Help = wx.Menu()
        self.About = wx.MenuItem(self.Help, wx.ID_ABOUT, _("&About"), _("About"), wx.ITEM_NORMAL)
        self.Help.AppendItem(self.About)
        self.main_frame_menubar.Append(self.Help, _("&Help"))
        self.SetMenuBar(self.main_frame_menubar)
        # Menu Bar end
        self.logo_bitmap = wx.StaticBitmap(self, wx.ID_ANY, wx.NullBitmap)
        self.src_dir_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
        self.src_dir_button = wx.Button(self, wx.ID_ANY, _("Source folder"))
        self.dest_dir_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_READONLY)
        self.dst_folder_button = wx.Button(self, wx.ID_ANY, _("Destination folder"))
        self.tiff_checkbox = wx.CheckBox(self, wx.ID_ANY, _("TIFF"))
        self.dng_checkbox = wx.CheckBox(self, wx.ID_ANY, _("DNG"))
        self.thumb_checkbox = wx.CheckBox(self, wx.ID_ANY, _("Thumbnail"))
        self.rotate_checkbox = wx.CheckBox(self, wx.ID_ANY, _("Rotation"))
        self.convert_button = wx.Button(self, wx.ID_ANY, _("Convert"))
        self.status_text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.abort_button = wx.Button(self, wx.ID_ANY, _("Abort"))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.OnClose, self.Exit)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, self.About)
        self.Bind(wx.EVT_BUTTON, self.OnSrcFolder, self.src_dir_button)
        self.Bind(wx.EVT_BUTTON, self.OnDstFolder, self.dst_folder_button)
        self.Bind(wx.EVT_CHECKBOX, self.OnTIFFClicked, self.tiff_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnDNGClicked, self.dng_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnThumbnailClicked, self.thumb_checkbox)
        self.Bind(wx.EVT_CHECKBOX, self.OnRotationClicked, self.rotate_checkbox)
        self.Bind(wx.EVT_BUTTON, self.OnConvert, self.convert_button)
        self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abort_button)
        # end wxGlade
        self.images = Images()
        self.logo_bitmap.SetBitmap(self.images.bmp_logo)
        self.proc = None
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.SetMinSize(self.GetSize())
        self.prefs = Preferences()
        self.dng_checkbox.SetValue(self.prefs.get_dng())
        self.tiff_checkbox.SetValue(self.prefs.get_tiff())
        self.thumb_checkbox.SetValue(self.prefs.get_thumbnail())
        self.rotate_checkbox.SetValue(self.prefs.get_rotate())
Example #25
0
    def __post_init__(self):
        """Size self."""
        self.img = pygame.image.load(Images.get_path(r'firework.png'))

        # Size
        self.block_size = int(self.size_multiple * 32)
        self.img_scale = int(self.size / self.block_size)

        self.size_x = self.block_size * self.img_scale
        self.size_y = self.block_size * self.img_scale

        self.img_color = True

        color = random.choice(Images.color_files)
        color_img = pygame.image.load(Images.get_path(color))
        self.img = Images.color_image(base_image=self.img, color_image=color_img)

        self.img = pygame.transform.scale(self.img,
                                          (int(self.size_x * self.img_cols),
                                           int(self.size_y * self.img_rows)))
Example #26
0
    def _init_vbox(self):
        self._vbox = QtGui.QVBoxLayout()

        self.images = Images(self)
        self._vbox.addWidget(self.images)

        self._init_filters_grid()

        vbox_widget = QtGui.QWidget()
        vbox_widget.setLayout(self._vbox)
        self.setCentralWidget(vbox_widget)
Example #27
0
 def __init__(self, title, width, height):
     """
     ゲームの各パラメータの状態を初期化し、ゲームを開始させる準備をします
     title: ゲームタイトル
     width: 画面幅
     height: 画面高さ
     """
     self.title = title
     self.width = width + Game.UI_WIDTH
     self.height = height
     self.root = tkinter.Tk()
     self.root.bind("<KeyPress>", self.__input)
     self.canvas = tkinter.Canvas(self.root, width=self.width, height=self.height)
     self.stage = Stage(self)
     self.stage.game = self
     self.prev_timer = time.time()
     self.gameover_rendered = False
     self.font_gameover = font.Font(root=self.root, size=50)
     self.images = Images()
     self.reset()
Example #28
0
	def accept(self):
		data = [self.txtName.text()]
		columns = ["name"]

		bbdd = Bbdd()
		bbdd.update(columns, data, "sport", "id="+self.id)
		bbdd.close()

		if self.ruta is not None:
			try:
				if not os.path.exists(expanduser("~") + "/.betcon/resources/sports"):
					os.makedirs(expanduser("~") + "/.betcon/resources/sports")
				copy2(self.ruta, expanduser("~") + "/.betcon/resources/sports/" + self.id + ".png")
				img = Images(expanduser("~") + "/.betcon/resources/sports/" + self.id + ".png")
				img.resize(100, 20)
			except:
				msg = "Imágen incorrecta"

		QMessageBox.information(self, _("Updated"), _("Updated sport."))

		self.close()
Example #29
0
def run_game():
    # create a screen and launch the game
    pygame.mixer.pre_init(44100, -16, 16, 2048)
    pygame.mixer.init()
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    # make a ship, bullet, alien
    sounds = Sounds()
    images = Images()
    bullets = Group()
    aliens = Group()
    stars = Group()
    powerups = Group()
    ship = Ship(ai_settings, screen, images)
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    counter = Counter(ai_settings, screen, stats)

    # create a fleet
    if stats.game_active:
        gf.create_stars(ai_settings, screen, stars)
        gf.create_powerup(ai_settings, screen, powerups)

    # main game loop

    while True:
        gf.check_events(ai_settings, screen, stats, play_button, ship, bullets, sounds, images)
        gf.update_screen(ai_settings, screen, stats, sb, stars, ship, aliens, bullets,
                         play_button, counter, powerups, sounds)
        if stats.game_active:
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets, sb, stats, sounds)
            gf.create_stars(ai_settings, screen, stars, images)
            gf.create_powerup(ai_settings, screen, powerups, images)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets, images)
            gf.update_stars(stars, ai_settings)
            gf.update_powerup(powerups, ai_settings)
            gf.update_timer(ai_settings)
            gf.powerup_check(ship, powerups, ai_settings, images, sounds, stats)
            bullets.update()
            stars.update()
            powerups.update()
            aliens.update()
            ship.update(bullets, ai_settings, screen, ship, sounds, images)
            screen.fill(ai_settings.bg_color)
Example #30
0
def upload_image(file_name: str) -> dict:
    try:
        os.path.isfile(file_name)
        logging.info("file exists")
        with open(file_name, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
            res = s3_operations.write_data_to_s3(encoded_string, 'priya', file_name)
            print(f"res {res}")
            if res['ResponseMetadata']['HTTPStatusCode'] // 100 == 2:
                Images(id=randint(1,100000) + 1,
                       name=file_name).save()
        return {"message": "document stored"}
    except FileNotFoundError:
        logging.error(f"file not found {file_name}")
        return {"error": f"file not found,checking at {os.getcwd()}"}
Example #31
0
class Canvas():
    def __init__(self):
        self.imgs, self.imgsdis = Images().get_images()
        self.cam_rect = pygame.Rect(CAMERA_POS, CAMERA_SIZE)

    def draw(self, screen):
        screen.fill(WHITE)
        for k, v in self.imgs.items():
            surface, rectangle = v
            screen.blit(surface, rectangle)
            pygame.draw.rect(screen, BLACK, self.cam_rect, 3)
        if get_possock() or get_camsock():
            for k, v in self.imgsdis.items():
                surface, rectangle = v
                screen.blit(surface, rectangle)
                get_clikd_btn() == "dc"

    def get_cam_rect(self):
        return self.cam_rect
Example #32
0
 def __init__(self):
     self.screen = pygame.display.set_mode((800, 600))
     pygame.font.init()
     self.font = pygame.font.SysFont("Arial", 25)
     self.score = 0
     self.direction = 0
     self.coordX = 400
     self.coordY = 300
     self.platforms = [
         [400, 500, 0, 0]
     ]  #[положение по оси X, по оси Y, вид, напрвление движения/ сломана или нет]
     self.springs = []  #[положение по оси X, по оси Y, состояние]
     self.monsters = [
     ]  #[положение по оси X, по  Y, сдвиг по Y, up/down, вид, напрвление движения]
     self.cam = 0
     self.jump = 0
     self.gravity = 0
     self.movement = 0
     self.isRed = 0
     self.images = Images()
    def __init__(self, glade_file):
        self.gtk_builder = gtk.Builder()
        self.gtk_builder.add_from_file(glade_file)

        self.gpg = GNUPG(self.gtk_builder.get_object('error_decrypt_dialog'))

        self.window = self.gtk_builder.get_object('mainWindow')
        self.image = self.gtk_builder.get_object('imageView')

        signals = {"on_mainWindow_destroy" : gtk.main_quit,
                   "on_menu_quit_activate" : gtk.main_quit,
                   "on_menu_open_activate" : self.cb_show_file_chooser,
                   "on_go_left_button_clicked" : self.cb_go_left_image,
                   "on_go_right_button_clicked": self.cb_go_right_image,
                  }

        self.gtk_builder.connect_signals(signals)

        self.images = Images()

        self.prev_button = self.gtk_builder.get_object('go_left_button')
        self.next_button = self.gtk_builder.get_object('go_right_button')
        self.gtk_builder.get_object('ok_passphrase_button').grab_default()
Example #34
0
    def get_publish_images(publish):
        result = dict()
        if publish.big_image:
            name_parts = publish.big_image.name.split(".")
            path_parts = publish.big_image.name.split("/")
            mid_path = "/".join(path_parts[:-1])
            big_name = ".".join(name_parts[:-1]) + "_big." + name_parts[-1]
            medium_name = ".".join(name_parts[:-1]) + "_medium." + name_parts[-1]
            small_name = ".".join(name_parts[:-1]) + "_small." + name_parts[-1]
            result["publish_image_url"] = files.BASE_URL_4_IMAGE + publish.big_image.name
            result["publish_image_big_url"] = files.BASE_URL_4_IMAGE + big_name
            result["publish_image_medium_url"] = files.BASE_URL_4_IMAGE + medium_name
            result["publish_image_small_url"] = files.BASE_URL_4_IMAGE + small_name

            img_path = result["publish_image_url"]

            memory_file = files.Files.get_memory_file(img_path)
            new_path = "media_root/" + mid_path + "/"

            new_big_path = new_path + big_name
            new_big_width = 1280
            if not files.Files.exists(new_big_path):
                Images.resize_image(memory_file, new_big_path, new_big_width)

            new_medium_path = new_path + medium_name
            new_medium_width = 640
            if not files.Files.exists(new_medium_path):
                Images.resize_image(memory_file, new_medium_path, new_medium_width)

            new_small_path = new_path + small_name
            new_small_width = 120
            if not files.Files.exists(new_small_path):
                Images.resize_image(memory_file, new_small_path, new_small_width)
        else:
            result["publish_image_url"] = ""
            result["publish_image_medium_url"] = ""
            result["publish_image_small_url"] = ""
        return result
Example #35
0
	def __init__(self):
		wx.Frame.__init__(self, None, wx.ID_ANY, "Node Tester", size=(500, 500))
		self.SetBackgroundColour(wx.Colour(255, 255, 255))
		self.Bind(wx.EVT_CLOSE, self.onClose)
		
		self.CreateStatusBar()
		self.qStatus = queue.Queue()

		menuBar = wx.MenuBar()
		self.menuServer = wx.Menu()
		self.menuServer.Append(MENU_SERVER_NODES, "Nodes Report", "Get Nodes Report")
		self.menuServer.Append(MENU_SERVER_SHUTDOWN, "Shut down", "Shut down server")
		self.menuNode = wx.Menu()
		self.menuNode.Append(MENU_NODE_CONFIG, "Re-Config", "Modify current node configuration")
		self.menuNode.Append(MENU_NODE_INIT, "Init", "Reinit the node communicatione with the server")
		self.menuWindow = wx.Menu()
		self.menuWindow.Append(MENU_WINDOW_INPUTS, "Inputs")
		self.menuWindow.Append(MENU_WINDOW_OUTPUTS, "Outputs")
		self.menuWindow.Append(MENU_WINDOW_SERVOS, "Servos/Turnouts")
		
		menuBar.Append(self.menuServer, "Server")
		menuBar.Append(self.menuNode, "Node")
		menuBar.Append(self.menuWindow, "Window")
		
		self.Bind(wx.EVT_MENU, self.onMenuNodes, id=MENU_SERVER_NODES)		
		self.Bind(wx.EVT_MENU, self.onMenuShutdown, id=MENU_SERVER_SHUTDOWN)		
		self.Bind(wx.EVT_MENU, self.onMenuConfig, id=MENU_NODE_CONFIG)		
		self.Bind(wx.EVT_MENU, self.onMenuInit, id=MENU_NODE_INIT)		
		self.Bind(wx.EVT_MENU, self.onMenuInputs, id=MENU_WINDOW_INPUTS)		
		self.Bind(wx.EVT_MENU, self.onMenuOutputs, id=MENU_WINDOW_OUTPUTS)		
		self.Bind(wx.EVT_MENU, self.onMenuServos, id=MENU_WINDOW_SERVOS)	
		
		self.SetMenuBar(menuBar)
		
		self.images = Images("images")
		self.ipAddress = "192.168.1.142"
		self.httpPort = "8000"
		self.socketPort = "8001"
		self.server = Server()
		self.listener = None
		
		self.inputs = 1
		self.outputs = 1
		self.servos = 1
		self.flags = 0
		self.registers = 0
		self.inputsMap = []
		self.outputsMap = []
		self.servosMap = []
		self.subscribed = False
		self.currentNodeAddr = None

		
		self.timer = wx.Timer(self)
		self.ticks = 0
		self.clearTimer = None
		
		sz = wx.BoxSizer(wx.VERTICAL)
		sz.AddSpacer(2)
		self.dlgInputs = None
		self.dlgOutputs = None
		self.dlgServos = None
		
		boxSvr = wx.StaticBox(self, wx.ID_ANY, " Server ")
		topBorder, botBorder = boxSvr.GetBordersForSizer()
		if os.name != 'nt':
			botBorder += 30
			
		bsizer = wx.BoxSizer(wx.VERTICAL)
		bsizer.AddSpacer(topBorder)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxSvr, wx.ID_ANY, "IP Address:", size=(SVRLABELW, -1)))
		self.teIpAddr = wx.TextCtrl(boxSvr, wx.ID_ANY, self.ipAddress, size=(125, -1))
		self.Bind(wx.EVT_TEXT, self.onTeIpAddrChange, self.teIpAddr)
		self.teIpAddr.Bind(wx.EVT_KILL_FOCUS, self.onTeIpAddrLoseFocus)
		self.teIpAddr.Bind(wx.EVT_SET_FOCUS, self.onTeIpAddrSetFocus)
		hsizer.Add(self.teIpAddr)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
		
		bsizer.AddSpacer(5)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxSvr, wx.ID_ANY, "HTTP Port:", size=(SVRLABELW, -1)))
		self.teHPort = wx.TextCtrl(boxSvr, wx.ID_ANY, self.httpPort, size=(125, -1))
		self.Bind(wx.EVT_TEXT, self.onTeHPortChange, self.teHPort)
		self.teHPort.Bind(wx.EVT_KILL_FOCUS, self.onTeHPortLoseFocus)
		self.teHPort.Bind(wx.EVT_SET_FOCUS, self.onTeHPortSetFocus)
		hsizer.Add(self.teHPort)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
		
		bsizer.AddSpacer(5)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxSvr, wx.ID_ANY, "Socket Port:", size=(SVRLABELW, -1)))
		self.teSPort = wx.TextCtrl(boxSvr, wx.ID_ANY, self.socketPort, size=(125, -1))
		hsizer.Add(self.teSPort)
		hsizer.AddSpacer(10)
		self.bSubscribe = wx.Button(boxSvr, wx.ID_ANY, "Subscribe")
		self.bSubscribe.SetToolTip("Subscribe to receive asynchronous reports from the server")
		self.Bind(wx.EVT_BUTTON, self.onSubscribe, self.bSubscribe)
		hsizer.Add(self.bSubscribe)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
				
		bsizer.AddSpacer(botBorder)

		boxSvr.SetSizer(bsizer)	
		sz.Add(boxSvr, 0, wx.EXPAND|wx.ALL, 5)	
		sz.AddSpacer(10)
			
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(self, wx.ID_ANY, "Node Address:"))
		hsizer.AddSpacer(10)
		
		self.stAddr = wx.StaticText(self, wx.ID_ANY, "   ")
		hsizer.Add(self.stAddr)
		hsizer.AddSpacer(20)
		
		self.bGetAddr = wx.Button(self, wx.ID_ANY, "...", size=(30, -1))
		self.bGetAddr.SetToolTip("Select node address")
		self.Bind(wx.EVT_BUTTON, self.onGetNodeAddr, self.bGetAddr)
		hsizer.Add(self.bGetAddr)
		hsizer.AddSpacer(10)
	
		self.bRefresh = wx.Button(self, wx.ID_ANY, "Refresh")
		self.bRefresh.SetToolTip("Refresh node information by querying the actual node")
		self.Bind(wx.EVT_BUTTON, self.onBRefresh, self.bRefresh)
		hsizer.Add(self.bRefresh)

		sz.Add(hsizer)
		sz.AddSpacer(10)
				
		boxCfg = wx.StaticBox(self, wx.ID_ANY, " Node Config ")
		topBorder, botBorder = boxCfg.GetBordersForSizer()
		if os.name != 'nt':
			botBorder += 30
		bsizer = wx.BoxSizer(wx.VERTICAL)
		bsizer.AddSpacer(topBorder)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxCfg, wx.ID_ANY, "Inputs:", size=(CFGLABELW, -1)))
		self.stInputs = wx.StaticText(boxCfg, wx.ID_ANY, "")
		hsizer.Add(self.stInputs)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxCfg, wx.ID_ANY, "Outputs:", size=(CFGLABELW, -1)))
		self.stOutputs = wx.StaticText(boxCfg, wx.ID_ANY, "")
		hsizer.Add(self.stOutputs)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
		
		hsizer = wx.BoxSizer(wx.HORIZONTAL)
		hsizer.AddSpacer(10)
		hsizer.Add(wx.StaticText(boxCfg, wx.ID_ANY, "Servos:", size=(CFGLABELW, -1)))
		self.stServos = wx.StaticText(boxCfg, wx.ID_ANY, "")
		hsizer.Add(self.stServos)
		hsizer.AddSpacer(10)
		bsizer.Add(hsizer)
		
		bsizer.AddSpacer(botBorder)
		
		self.setConfigValues(1, 1, 1)

		boxCfg.SetSizer(bsizer)	
		sz.Add(boxCfg, 0, wx.EXPAND|wx.ALL, 5)	
		
		sz.AddSpacer(20)
		
		mainsz = wx.BoxSizer(wx.HORIZONTAL)
		mainsz.AddSpacer(20)
		mainsz.Add(sz)
		mainsz.AddSpacer(20)
		
		wsz = wx.BoxSizer(wx.VERTICAL)
		wsz.Add(mainsz)
		
		self.SetSizer(wsz)
		
		self.Layout()
		self.Fit()
		self.Show()
		
		self.enableMenuItems(False)
		
		self.server.setServerAddress(self.teIpAddr.GetValue(), self.teHPort.GetValue())
		self.serverValueChanged = False
		self.hPortValueChanged = False
		
		self.timer.Start(250)
		self.Bind(wx.EVT_TIMER, self.onTimer)
		self.Bind(EVT_DELIVERY, self.onDeliveryEvent)
		self.Bind(EVT_DISCONNECT, self.onDisconnectEvent)
		
		self.sz = self.GetSize()
		print("size = ", self.sz)
Example #36
0
model = create_model_from_fits_file(os.path.join(data_dir, im_fits))
uvdata = UVData(os.path.join(data_dir, uv_fits))
boot = CleanBootstrap([model], uvdata)
os.chdir(data_dir)
boot.run(100, nonparametric=False, use_v=False)
booted_uv_fits = glob.glob(os.path.join(data_dir, 'bootstrapped_data*.fits'))
for i, boot_uv in enumerate(sorted(booted_uv_fits)):
    clean_difmap(boot_uv,
                 'booted_cc_{}.fits'.format(i),
                 'I', (512, 0.1),
                 path=data_dir,
                 path_to_script=path_to_script,
                 outpath=data_dir)
booted_im_fits = glob.glob(os.path.join(data_dir, 'booted_cc*.fits'))

images = Images()
images.add_from_fits(booted_im_fits)
error_image = images.create_error_image()

orig_image = create_clean_image_from_fits_file(os.path.join(data_dir, im_fits))
rms = rms_image_shifted(os.path.join(data_dir, uv_fits),
                        image_fits=os.path.join(data_dir, im_fits),
                        path_to_script=path_to_script)
blc, trc = find_bbox(orig_image.image, level=1.5 * rms)
image_mask = orig_image.image < 2 * rms
label_size = 14
matplotlib.rcParams['xtick.labelsize'] = label_size
matplotlib.rcParams['ytick.labelsize'] = label_size
matplotlib.rcParams['axes.titlesize'] = label_size
matplotlib.rcParams['axes.labelsize'] = label_size
matplotlib.rcParams['font.size'] = label_size
Example #37
0
	def __init__(self):
		# detect args
		parser = OptionParser()
		parser.add_option("-d", "--debug", dest="debug",
				action="store_true", help="set debug mode", default=False)
		parser.add_option("-v", "--verbose", dest="verbose",
				action="store_true", help="verbose mode", default=False)
		parser.add_option("-p", "--page", dest="page",
				help="specify a page to handle")
		parser.add_option("--onepage", dest="onepage",
				action="store_true", help="only handle a single page (similar to `--pages=1')", default=False)
		parser.add_option("--task", dest="task",
				help="run builtin task (use `--task=help' for list of tasks)")
		parser.add_option("--pages", dest="pagestorun",
				help="number of pages to handle")
		parser.add_option("-s", "--search", dest="search",
				help="search string")
		parser.add_option("-t", "--time", dest="time",
				help="set time in format YYYY-MM-DDTHH:MM:SSZ")
		parser.add_option("--titlesearch", dest="titlesearch",
				action="store_true", help="search in titles rather than text", default=False)
		parser.add_option("--writetime", dest="writetime",
				action="store_true", help="write timestamp at end of run, even if other variables would disable that", default=False)
		parser.add_option("-r", "--ref", "--loadref", dest="loadref",
				action="store_true", help="force appearance reference load from wiki", default=False)
		parser.add_option("--localref", dest="localref",
				action="store_true", help="force appearance reference to be loaded locally", default=False)
		parser.add_option("--runtasks", dest="runtasks",
				action="store_true", help="force run tasks", default=False)
		parser.add_option("--changes", dest="changes",
				help="maximum recent changes to run")
		parser.add_option("--nochanges", dest="nochanges",
				action="store_true", help="don't check recent changes", default=False)
		parser.add_option("--donotfixpages", dest="donotfixpages",
				action="store_true", help="no page cleanup", default=False)
		parser.add_option("--donotrunpool", dest="donotrunpool",
				action="store_true", help="don't run changes for the pool", default=False)
		(options, args) = parser.parse_args()
		# set debug mode
		self.debugmode = options.debug
		self.verbose = options.verbose
		self.api = Api(debug=self.debugmode, server="theinfosphere.org")
		self.poolapi = Api(debug=self.debugmode, server="pool.theinfosphere.org")
		if self.debugmode:
			self.log("==== Debug mode!")
		if options.task!=None:
			# oh noes, we need to run a builtin task, so we should not run
			# regular tasks
			taskmanager = Taskmanager(debug=self.debugmode, api=self.api, verbose=self.verbose)
			if options.task == 'help':
				print taskmanager.help_response()
			else:
				self.log("Builtin task run...")
				if self.api.login(userdata.username, userdata.password):
					if not taskmanager.run_task(options.task):
						self.log("Task `%s' did not run properly or does not exist." % options.task)
				else:
					self.log("Could not log in.")
				self.writelog()
		else:
			if not options.nochanges:
				self.changes = Changes(debug=self.debugmode, api=self.api, verbose=self.verbose)
				if options.changes != None:
					self.changes.maximum = options.changes
			self.runtasks = options.runtasks
			self.pages = Pages(debug=self.debugmode, api=self.api, verbose=self.verbose)
			self.pages.singlepage = self.page = options.page
			pagestorun = 0
			if options.onepage:
				pagestorun = 1
			if options.pagestorun != None:
				pagestorun = options.pagestorun
			self.pages.pagestorun = self.pagestorun = pagestorun
			self.pages.search = self.search = options.search
			self.pages.titlesearch = self.titlesearch = options.titlesearch
			if options.time!=None:
				try:
					time.strptime(options.time, "%Y-%m-%dT%H:%M:%SZ")
					self.ts = options.time
					self.log("Using input time of `%s'." % self.ts)
				except ValueError:
					self.log("Input time given `%s' does not match format; ignoring." % self.ts)
					self.ts = None
			if self.debugmode or self.search!=None or self.pagestorun==1 or self.page!=None or self.ts!=None:
				# if any of these are the case, then writing a new time stamp could
				# mess up future runs
				self.writetime = False
			if options.writetime:
				# unless of course, it is forced by the user
				self.writetime = True
			self.pages.ar.loadref = options.loadref
			self.pages.ar.localref = options.localref
			# insure the api knows, so it won't make edits if debug mode
			if self.api.login(userdata.username, userdata.password):
				self.log("Logged in successfully.")
				if self.check_for_lock():		   
					self.initiate()
					if not options.nochanges:
						self.changes.set_ts(self.ts)
					self.pages.set_ts(self.ts)
					if self.runtasks or (self.pagestorun==0 and self.page == None):
						tasks = Tasks(self.debugmode, self.api, self.verbose, self.pages)
						self.log_obtain(tasks)
					if not options.nochanges:
						self.changes.handle_changes()
						self.log_obtain(self.changes)
					else:
						self.log("Not running recent changes checking...")
					if not options.donotfixpages:
						self.pages.routine_run()
					else:
						self.log("Not running page fixing...")
					self.log_obtain(self.pages)
					if not options.donotrunpool:
						self.images = Images(debug=self.debugmode, api=self.api, verbose=self.verbose, poolapi=self.poolapi)
						self.images.routine_job(self.ts)
						self.log_obtain(self.images)
					else:
						self.log("Not running through the pool...")
					self.finish()
			else:
				self.log("Could not log in.")
			self.writelog()
Example #38
0
class TestImages(unittest.TestCase):
    def setUp(self):
        self.images = Images()
        self.image = os.path.dirname(__file__)+'/fixtures/image4.jpg'
        self.first_image = os.path.dirname(__file__)+'/fixtures/image1.jpg'
        self.last_image = os.path.dirname(__file__)+'/fixtures/image9.jpg'
    # setUp()

    def test_load_images(self):
        image = os.path.dirname(__file__)+'/fixtures/image4.jpg'
        self.images.load_images(image)
        self.assertEqual(image, self.images.image)
        self.assertEqual(9, self.images.num_images)
    # test_load_images()

    def test_next_image(self):
        self.images.load_images(self.image)
        next_image = os.path.dirname(__file__)+'/fixtures/image5.jpg'

        self.assertEqual(next_image, self.images.next())
    # test_nextImage()

    def test_prev_image(self):
        self.images.load_images(self.image)
        prev_image = os.path.dirname(__file__)+'/fixtures/image3.jpg'

        self.assertEqual(prev_image, self.images.prev())
    # test_nextImage()

    def test_prev_first(self):
        self.images.load_images(self.image) # image4
        self.images.prev() # image3
        self.images.prev() # image2
        self.images.prev() # image1

        self.assertEqual(self.first_image, self.images.image)

        self.images.prev() # image1

        self.assertEqual(self.first_image, self.images.image)

    # test_prevThanFirst()

    def test_after_last(self):
        self.images.load_images(self.image) # image4
        self.images.next() # image5
        self.images.next() # image6
        self.images.next() # image7
        self.images.next() # image8
        self.images.next() # image9

        self.assertEqual(self.last_image, self.images.image)

        self.images.next() # image9

        self.assertEqual(self.last_image, self.images.image)

    # test_prevThanFirst()

    def test_last_image(self):
        """
        Return last image
        """
        self.images.load_images(self.image)
        self.assertEqual(self.last_image, self.images.get_last())
    # test_lastImage()

    def test_first_image(self):
        """
        Return first Image
        """
        self.images.load_images(self.image)
        self.assertEqual(self.first_image, self.images.get_first())
    # test_lastImage()

    def test_do_nothing_when_empty(self):
        """
        Try to move with no images
        """

        self.assertIsNone(self.images.image)

        self.images.next()

        self.assertIsNone(self.images.image)

        self.images.prev()

        self.assertIsNone(self.images.image)
Example #39
0
 def setUp(self):
     self.images = Images()
     self.image = os.path.dirname(__file__)+'/fixtures/image4.jpg'
     self.first_image = os.path.dirname(__file__)+'/fixtures/image1.jpg'
     self.last_image = os.path.dirname(__file__)+'/fixtures/image9.jpg'
Example #40
0
 def __init__(self):
     self.imgs, self.imgsdis = Images().get_images()
     self.cam_rect = pygame.Rect(CAMERA_POS, CAMERA_SIZE)
Example #41
0
class Svipbot(object):
	api = None
	poolapi = None
	loglines = []
	debugmode = False
	writetime = True
	oldts = None
	ts = None
	newts = None
	pages = None
	images = None
	
	def check_for_lock(self):
		if os.path.exists("botlock"):
			self.log("Botlock file exists.")
			return False
		self.log("No botlock.")
		return True
		
	def log(self, msg=None, view=True):
		if msg==None:
			return self.loglines
		else:
			self.loglines.append(msg)
			if (self.debugmode or self.verbose) and view:
				print msg
	
	def log_obtain(self, obj):
		if obj==None:
			return
		for l in obj.get_log():
			self.log(l, False)
		obj.clear_log()
	
	def initiate(self):
		f = open('botlock', 'w')
		f.write('x')
		f.close()
		self.log("Wrote botlock.")
		try:
			f = open('time', 'r')
			self.ts = f.read().strip()
			self.log("Found time of `%s'." % self.ts)
			f.close()
		except IOError:
			self.ts = None # just to make sure
		# create a timestamp now, because the edits may take time, and someone could
		# make an edit in between, and we want to catch that.
		self.newts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
		
	def finish(self):
		# current time
		if self.newts==None:
			ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
		else:
			ts = self.newts
		if self.writetime:
			f = open('time', 'w')
			f.write(ts)
			f.close()
			self.log("Wrote timestamp of `%s'." % ts)
		# remove botlock
		os.remove("botlock")
		self.log("Removed botlock")
		
	def writelog(self):
		if not self.debugmode:
			# log
			fn = "logs/runlog-%s" % time.strftime("%Y%m%dT%H%M", time.gmtime())
			log = open(fn, 'w')
			log.writelines([unicode("%s\n"%s).encode('utf-8') for s in self.log()])
			log.close()
			
	def __init__(self):
		# detect args
		parser = OptionParser()
		parser.add_option("-d", "--debug", dest="debug",
				action="store_true", help="set debug mode", default=False)
		parser.add_option("-v", "--verbose", dest="verbose",
				action="store_true", help="verbose mode", default=False)
		parser.add_option("-p", "--page", dest="page",
				help="specify a page to handle")
		parser.add_option("--onepage", dest="onepage",
				action="store_true", help="only handle a single page (similar to `--pages=1')", default=False)
		parser.add_option("--task", dest="task",
				help="run builtin task (use `--task=help' for list of tasks)")
		parser.add_option("--pages", dest="pagestorun",
				help="number of pages to handle")
		parser.add_option("-s", "--search", dest="search",
				help="search string")
		parser.add_option("-t", "--time", dest="time",
				help="set time in format YYYY-MM-DDTHH:MM:SSZ")
		parser.add_option("--titlesearch", dest="titlesearch",
				action="store_true", help="search in titles rather than text", default=False)
		parser.add_option("--writetime", dest="writetime",
				action="store_true", help="write timestamp at end of run, even if other variables would disable that", default=False)
		parser.add_option("-r", "--ref", "--loadref", dest="loadref",
				action="store_true", help="force appearance reference load from wiki", default=False)
		parser.add_option("--localref", dest="localref",
				action="store_true", help="force appearance reference to be loaded locally", default=False)
		parser.add_option("--runtasks", dest="runtasks",
				action="store_true", help="force run tasks", default=False)
		parser.add_option("--changes", dest="changes",
				help="maximum recent changes to run")
		parser.add_option("--nochanges", dest="nochanges",
				action="store_true", help="don't check recent changes", default=False)
		parser.add_option("--donotfixpages", dest="donotfixpages",
				action="store_true", help="no page cleanup", default=False)
		parser.add_option("--donotrunpool", dest="donotrunpool",
				action="store_true", help="don't run changes for the pool", default=False)
		(options, args) = parser.parse_args()
		# set debug mode
		self.debugmode = options.debug
		self.verbose = options.verbose
		self.api = Api(debug=self.debugmode, server="theinfosphere.org")
		self.poolapi = Api(debug=self.debugmode, server="pool.theinfosphere.org")
		if self.debugmode:
			self.log("==== Debug mode!")
		if options.task!=None:
			# oh noes, we need to run a builtin task, so we should not run
			# regular tasks
			taskmanager = Taskmanager(debug=self.debugmode, api=self.api, verbose=self.verbose)
			if options.task == 'help':
				print taskmanager.help_response()
			else:
				self.log("Builtin task run...")
				if self.api.login(userdata.username, userdata.password):
					if not taskmanager.run_task(options.task):
						self.log("Task `%s' did not run properly or does not exist." % options.task)
				else:
					self.log("Could not log in.")
				self.writelog()
		else:
			if not options.nochanges:
				self.changes = Changes(debug=self.debugmode, api=self.api, verbose=self.verbose)
				if options.changes != None:
					self.changes.maximum = options.changes
			self.runtasks = options.runtasks
			self.pages = Pages(debug=self.debugmode, api=self.api, verbose=self.verbose)
			self.pages.singlepage = self.page = options.page
			pagestorun = 0
			if options.onepage:
				pagestorun = 1
			if options.pagestorun != None:
				pagestorun = options.pagestorun
			self.pages.pagestorun = self.pagestorun = pagestorun
			self.pages.search = self.search = options.search
			self.pages.titlesearch = self.titlesearch = options.titlesearch
			if options.time!=None:
				try:
					time.strptime(options.time, "%Y-%m-%dT%H:%M:%SZ")
					self.ts = options.time
					self.log("Using input time of `%s'." % self.ts)
				except ValueError:
					self.log("Input time given `%s' does not match format; ignoring." % self.ts)
					self.ts = None
			if self.debugmode or self.search!=None or self.pagestorun==1 or self.page!=None or self.ts!=None:
				# if any of these are the case, then writing a new time stamp could
				# mess up future runs
				self.writetime = False
			if options.writetime:
				# unless of course, it is forced by the user
				self.writetime = True
			self.pages.ar.loadref = options.loadref
			self.pages.ar.localref = options.localref
			# insure the api knows, so it won't make edits if debug mode
			if self.api.login(userdata.username, userdata.password):
				self.log("Logged in successfully.")
				if self.check_for_lock():		   
					self.initiate()
					if not options.nochanges:
						self.changes.set_ts(self.ts)
					self.pages.set_ts(self.ts)
					if self.runtasks or (self.pagestorun==0 and self.page == None):
						tasks = Tasks(self.debugmode, self.api, self.verbose, self.pages)
						self.log_obtain(tasks)
					if not options.nochanges:
						self.changes.handle_changes()
						self.log_obtain(self.changes)
					else:
						self.log("Not running recent changes checking...")
					if not options.donotfixpages:
						self.pages.routine_run()
					else:
						self.log("Not running page fixing...")
					self.log_obtain(self.pages)
					if not options.donotrunpool:
						self.images = Images(debug=self.debugmode, api=self.api, verbose=self.verbose, poolapi=self.poolapi)
						self.images.routine_job(self.ts)
						self.log_obtain(self.images)
					else:
						self.log("Not running through the pool...")
					self.finish()
			else:
				self.log("Could not log in.")
			self.writelog()
class GPGImageViewer(object):
    """
    Image Viewer class
    """

    def __init__(self, glade_file):
        self.gtk_builder = gtk.Builder()
        self.gtk_builder.add_from_file(glade_file)

        self.gpg = GNUPG(self.gtk_builder.get_object('error_decrypt_dialog'))

        self.window = self.gtk_builder.get_object('mainWindow')
        self.image = self.gtk_builder.get_object('imageView')

        signals = {"on_mainWindow_destroy" : gtk.main_quit,
                   "on_menu_quit_activate" : gtk.main_quit,
                   "on_menu_open_activate" : self.cb_show_file_chooser,
                   "on_go_left_button_clicked" : self.cb_go_left_image,
                   "on_go_right_button_clicked": self.cb_go_right_image,
                  }

        self.gtk_builder.connect_signals(signals)

        self.images = Images()

        self.prev_button = self.gtk_builder.get_object('go_left_button')
        self.next_button = self.gtk_builder.get_object('go_right_button')
        self.gtk_builder.get_object('ok_passphrase_button').grab_default()

    def cb_go_left_image(self, cb_data):
        """
        Show previous image
        """
        self.show_image(self.images.prev())
    # cb_go_left_image()

    def cb_go_right_image(self, _data):
        """
        Show to next image
        """
        self.show_image(self.images.next())
    # cb_go_right_image()

    def cb_show_file_chooser(self, _data):
        """
        Show file chooser
        """
        file_chooser = self.gtk_builder.get_object('file_chooser_dialog')
        response = file_chooser.run()
        file_chooser.hide()

        if response != gtk.RESPONSE_OK:
            return

        image_file = file_chooser.get_filename()

        self.images.load_images(image_file)

        self.show_image(image_file)
    # cb_show_file_chooser()

    def is_gpg_file(self, file_type):
        if file_type.startswith('GPG encrypted data'):
            return True

        if file_type.startswith('PGP RSA encrypted'):
            return True

        return False
    # is_gpg_file()

    def show_image(self, image_path):
        """
        Function show_image
        """

        if not image_path:
            return

        self.images.load_images(image_path)

        self.prev_button.set_sensitive(self.images.image != \
                                         self.images.get_first())
        self.next_button.set_sensitive(self.images.image != \
                                       self.images.get_last())

        # detect if it's a supported image type
        #if not check if is encrypted
        # fail otherwise
        if not gtk.gdk.pixbuf_get_file_info(image_path):

            file_type = magic.from_file(image_path)

            if  self.is_gpg_file(file_type):

                pixbuf = self.gpg.decrypt_file(image_path)
            else:
                not_supported_dialog = \
                self.gtk_builder.get_object('not_supported_dialog')

                not_supported_msg = file_type + ' is not a supported file!'
                not_supported_dialog.set_markup(not_supported_msg)
                not_supported_dialog.run()
                not_supported_dialog.hide()
                return

        else:
            pixbuf = gtk.gdk.pixbuf_new_from_file(image_path)


        pixbuf = pixbuf.apply_embedded_orientation()
        width = pixbuf.get_width()
        height = pixbuf.get_height()

        while width > 900 or height > 900:
            width = width * .9
            height = height * .9

        width = int(width)
        height = int(height)

        resize_pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_HYPER)

        main_label = self.gtk_builder.get_object('main_label')
        main_label.set_label("Image " + os.path.basename(image_path) +\
                " size: " + str(width) + " x " + str(height))


        self.image.set_from_pixbuf(resize_pixbuf)

    def __get_user_pw(self):
        """
        This function returns the passphrase that will be used for the GPG
        encrypted files.
        """

        dialog_window = self.gtk_builder.get_object('passwordDialog')
        user_entry = self.gtk_builder.get_object('passphrase_entry')

        response = dialog_window.run()
        text = user_entry.get_text()

        dialog_window.hide()

        if (response == gtk.RESPONSE_OK) and (text != ''):
            return text
        else:
            return None
class ImagesWidget(QWidget, Ui_Images):
    images = None

    def __init__(self, parent, app):
        super(QWidget, self).__init__()
        self.app = app

        self.setupUi(self)

        self.error_msg = QErrorMessage()
        self.error_msg.setWindowTitle("Starter Kit: Blinkenlights Demo " + config.DEMO_VERSION)

        self.slider_frame_rate.valueChanged.connect(self.slider_frame_rate_changed)
        self.spinbox_frame_rate.valueChanged.connect(self.spinbox_frame_rate_changed)
        self.button_choose.pressed.connect(self.choose_pressed)
        self.button_show.pressed.connect(self.show_pressed)
        self.button_default.pressed.connect(self.default_pressed)

        self.update_frame_rate_timer = QTimer(self)
        self.update_frame_rate_timer.timeout.connect(self.update_frame_rate)

        self.default_pressed()

    def start(self):
        self.images = Images(self.app.ipcon)

        self.update_frame_rate()

        self.images.frame_rendered(0)

    def stop(self):
        if self.images:
            self.images.stop_rendering()
            self.images = None

    def spinbox_frame_rate_changed(self, frame_rate):
        self.slider_frame_rate.setValue(frame_rate)
        self.update_frame_rate_timer.start(100)

    def slider_frame_rate_changed(self, frame_rate):
        self.spinbox_frame_rate.setValue(frame_rate)

    def show_pressed(self):
        if self.images:
            files = unicode(self.text_edit_files.toPlainText()).strip()

            if len(files) > 0:
                new_images = files.split('\n')

                try:
                    self.images.set_new_images(new_images)
                except Exception as e:
                    self.error_msg.showMessage(str(e))

                self.images.frame_prepare_next()
                self.images.frame_rendered(0)

    def choose_pressed(self):
        dialog = QFileDialog()
        dialog.setDirectory(QDir.homePath())
        dialog.setFileMode(QFileDialog.ExistingFiles)

        if dialog.exec_():
            filenames = dialog.selectedFiles()
            for filename in filenames:
                self.text_edit_files.append(filename)

    def default_pressed(self):
        self.spinbox_frame_rate.setValue(1)

    def update_frame_rate(self):
        self.update_frame_rate_timer.stop()

        config.IMAGES_FRAME_RATE = self.spinbox_frame_rate.value()

        if self.images:
            self.images.update_frame_rate()
    def start(self):
        self.images = Images(self.app.ipcon)

        self.update_frame_rate()

        self.images.frame_rendered(0)