Ejemplo n.º 1
0
    def __init__(self, debug_mode=False):
        self._debug_mode = debug_mode

        if not debug_mode:
            self._display_type = os.environ.get("EPAPER_TYPE", "epd2in7")
            if self._display_type == "epd2in7":
                import epd2in7
                self._display_width = epd2in7.EPD_HEIGHT  # inversed
                self._display_height = epd2in7.EPD_WIDTH
                self._epd = epd2in7.EPD()
                self._epd.init()
            elif self._display_type == "epd4in2":
                import epd4in2
                self._display_width = epd4in2.EPD_WIDTH
                self._display_height = epd4in2.EPD_HEIGHT
                self._epd = epd4in2.EPD()
                self._epd.init()
            else:
                raise "Invalid display config"
        else:
            self._display_width = EPD_WIDTH
            self._display_height = EPD_HEIGHT

        self._time_zone = tzlocal.get_localzone()
        self._str_time = "XXXX"
        self._drawing = drawing.Drawing(self._display_width,
                                        self._display_height)
 def test_string_initialization(self):
     fixture = '''<?xml version="1.0" encoding="utf-8"?>
         <svg height="300" width="300"><title>Example image</title>
         <line class="st0" x1="2000" y1="2000" x2="3000" y2="3000"/>
         </svg>'''
     d = drawing.Drawing(raw=fixture)
     self.assertEqual(len(d.processedroot), 1)
 def test_ignores_unknown_args(self):
     fixture = '''<?xml version="1.0" encoding="utf-8"?>
         <svg height="300" width="300"><title>Example image</title>
         <line class="st0" x1="200" y1="200" x2="300" y2="300"/></svg>'''
     d = drawing.Drawing(raw=fixture)
     expected = ['M 2000.0 2000.0', 'L 3000.0 3000.0', 'M 7500 7500']
     self.assertEqual(d.instructions(), expected)
 def test_g_grouping(self):
     d = drawing.Drawing(filename='./fixtures/tests-fixture2.svg')
     expected = [
         'M 0.0 0.0', 'L 3000.0 0.0', 'L 3000.0 1000.0', 'L 0.0 1000.0',
         'L 0.0 0.0', 'M 0.0 0.0', 'L 900.0 0.0', 'L 900.0 900.0',
         'L 0.0 900.0', 'L 0.0 0.0', 'M 0.0 0.0', 'L 500.0 1000.0',
         'M 7500 7500'
     ]
     self.assertEqual(d.instructions(), expected)
Ejemplo n.º 5
0
    def __init__(self, size=1):
        super(PhysicalBoard, self).__init__(size)
        self.drawing = drawing.Drawing()

        for row in range(size):
            row_width = LINE_SPACING * row
            for line in range(row + 1):
                x = line * LINE_SPACING - row_width / 2.0
                y = TOP_OF_BOARD - row * LINE_HEIGHT * 1.5
                self.drawing.line(x, y, x, y - LINE_HEIGHT)
Ejemplo n.º 6
0
    def __init__(self):
        """Initialize the editor"""
        # Initialize an empty document
        self.document = document.Document()

        # Initialize an empty drawing
        self.drawing = drawing.Drawing()

        self._clients = {}
        self._colors = ['#AAFF00', '#FFAA00', '#FF00AA', '#AA00FF', '#00AAFF']
        self._color_index = 0
 def test_file_initialization(self):
     d = drawing.Drawing(filename='./fixtures/tests-fixture.svg')
     self.assertTrue(isinstance(d.processedroot[0], drawing.Rect))
 def test_ignores_unknown_tags(self):
     d = drawing.Drawing(raw='<svg><title>abc!</title></svg>')
     self.assertEqual(d.instructions(), ['M 7500 7500'])
 def test_empty_instructions(self):
     d = drawing.Drawing(raw='<svg></svg>')
     self.assertEqual(d.instructions(), ['M 7500 7500'])
Ejemplo n.º 10
0
 def test_empty_initialization(self):
     drawing.Drawing(raw='<svg></svg>')
     with self.assertRaises(AttributeError):
         drawing.Drawing(raw='')
Ejemplo n.º 11
0
import colors
import drawing
import matplotlib.pyplot as plt


class Image:
    def __init__(self, image):
        self.image = PIL.Image.open(image)
        self.image = self.image.resize((800, 600))
        self.image_rgb = self.image.convert('RGB')

    def get_size(self):
        return self.image.size

    def generate_grid(self):
        self.width, self.height = self.get_size()
        for row in range(1, self.height):
            for column in range(1, self.width):
                self.simplified = C.check_color(
                    self.image_rgb.getpixel((column, row)))
                D.draw_pixel(column, row, self.simplified)


if __name__ == '__main__':
    IMAGE = 'test-image.jpg'
    GAME_CODE = '8w7uC49AuzIv'
    RGB = Image(IMAGE)
    D = drawing.Drawing(GAME_CODE)
    C = colors.Colours()
    RGB.generate_grid()
Ejemplo n.º 12
0
        for x,y in path:
            #Remove any offset from the origin (clip blank space)
            cx = (x - min_x)
            #Convert to meters
            cx *= ratio
            cx += OFFSET[0]
            
            #Remove any offset from the origin (clip blank space)
            cy = (y - min_y)
            #Convert to meters
            cy *= ratio
            cy += OFFSET[1]
            converted.append((cx,cy))
        converted_paths.append(converted)
    return converted_paths



if __name__ == "__main__":
    svg = etree.XML(open(sys.argv[1]).read())
    inp = raw_input("Place_pen? (y/n)")
    d = drawing.Drawing()
    if inp.startswith("y"):
        d.init()
        inp = raw_input("Press enter when done")
    d.grip_pen()
    paths = get_paths(svg)
    for path in convert_paths(paths):
        d.path(path)

Ejemplo n.º 13
0
 def __init__(self):
     super(PhysicalUI, self).__init__()
     self.drawing = drawing.Drawing()
Ejemplo n.º 14
0
    def set_drawing_information(self):
        """
        Fonction used to extract the information from the database
        for which datetime is
        in [self.datetime_drawing_min, self.datetime_drawing_max]
        and fill the Drawing object.
        """
        start_set_drawing = time.clock()
        db = database.database(self.config)

        #print("check day interval",
        #      self.datetime_drawing_min_day,
        #      self.datetime_drawing_max_day)
        
        try:
            tuple_drawings = db\
                .get_all_in_time_interval("drawings",
                                          self.datetime_drawing_min_day,
                                          self.datetime_drawing_max_day)
            lst_drawings_field = db.get_all_fields("drawings")

            tuple_calibrations = db\
                .get_all_in_time_interval("calibrations",
                                          self.datetime_drawing_min_day,
                                          self.datetime_drawing_max_day)
            tuple_groups = db\
                .get_all_in_time_interval("sGroups",
                                          self.datetime_drawing_min_day,
                                          self.datetime_drawing_max_day)
            lst_groups_field = db.get_all_fields("sGroups")
            
        except AttributeError:
            QtGui.QMessageBox\
                 .warning(self,
                          "Month selection",
                          "You did not specify a month!")

        lst_drawing = [el for el in tuple_drawings]
        lst_calibrations = [el for el in tuple_calibrations]
        lst_groups = [el for el in tuple_groups]
        drawing_lst = []

        for el in lst_drawing:

            drawing_dict = dict(zip(lst_drawings_field, el))
            
            drawing_tmp = drawing.Drawing(drawing_dict)
            drawing_type = lst_drawing[lst_drawing.index(el)][2]
            tuple_drawing_type = db.get_drawing_information("drawing_type",
                                                            drawing_type)
            drawing_tmp.set_drawing_type(tuple_drawing_type[0])

            for calib in lst_calibrations:
                if drawing_tmp.datetime == calib[1]:
                    drawing_tmp.set_calibration(calib)
                    break

            for group in lst_groups:

                group_dict = dict(zip(lst_groups_field, group))
                
                if drawing_tmp.datetime == group[1]:
                    drawing_tmp.set_group(group_dict)

            drawing_lst.append(drawing_tmp)

        end_set_drawing = time.clock()
        # print("time for set drawing: ",
        #      end_set_drawing - start_set_drawing)

        drawing_lst.sort(key=lambda x : x.datetime)
        return drawing_lst
Ejemplo n.º 15
0
    def __init__(self):
        """ Initialise the game systems. """

        # Change directory into the directory above this file - the
        # one containng the 'res' tree.  Note that if we've been built via
        # py2exe, we will actually be in a zip file so account for that.
        path = os.path.dirname(os.path.dirname(__file__))
        if (os.path.basename(path) == "library.zip"):
            path = os.path.dirname(path)
        os.chdir( path )
        sys.path += ["."]

        # Services exposed to the entities.
        self.game_services = SpaceGameServices(self)

        # The resource loader.
        self.resource_loader = resource.ResourceLoader()

        # The configuration.
        if os.path.isfile("./config.txt"):
            self.config = self.resource_loader.load_config_file_from("./config.txt")
        else:
            self.config = self.resource_loader.load_config_file("base_config.txt")

        # Create the renderer.
        renderer_name = self.config.get_or_default("renderer", "src.pygame_renderer.PygameRenderer")
        renderer_class = utils.lookup_type(renderer_name)
        screen_size = (self.config.get_or_default("screen_width", 1024),
                       self.config.get_or_default("screen_height", 768))
        self.renderer = renderer_class(screen_size, self.config, data_path="./res")

        # The resource loaded needs a renderer to load images etc.
        self.resource_loader.set_renderer(self.renderer)

        # The input handling system.
        self.input_handling = None

        # The enemy.
        self.wave_spawner = None

        # Create the entity manager.
        self.entity_manager = ecs.EntityManager(self.game_services)

        # Configure the resource loader.
        self.resource_loader.set_minimise_image_loading(
            self.config.get_or_default("minimise_image_loading", False)
        )

        # The drawing visitor.
        self.drawing = drawing.Drawing(self.game_services)

        # Is the game running?
        self.running = False

        # Should we load the game?
        self.want_load = False

        # Should we pause the game?
        self.want_pause = False

        # Should we unpause the game?
        self.want_resume = False

        # Should we simulate one frame and then pause?
        self.want_step = False
Ejemplo n.º 16
0
def main(make_video=True, estimates=None, plotting=['cam1', 'cam2', 'kalman']):
    print("Hello, world! Let's run a Kalman filter simulation...")
    if estimates:
        d = drawing.Drawing(draw_estimates=estimates)
    else:
        d = drawing.Drawing()

    # some useful constants:
    total_seconds = 18
    total_frames = total_seconds * kc.fps
    center_coords = (kc.img_size[0] / 2, kc.img_size[1] / 2)

    print('Doing simulation...')
    # get the ball motion (a numpy 2xnframes matrix of coords):
    # ball_motion = kc.get_brownian_ball_motion(center_coords, total_frames)
    ball_motion = kc.get_simple_ball_motion(center_coords, total_seconds)
    # ball_motion = kc.get_still_ball_motion(center_coords, total_seconds)

    cam1_estimates = []
    cam2_estimates = []
    # cam3_estimates = []
    average_estimates = []
    closest_camera_estimates = []
    kalman_estimates = []

    # do the kalman filtering:
    A_x = A_y = 0  # velocity of ball (calculated at each time step)
    xhat_x = xhat_y = 0
    P_x = P_y = 0
    xhatminus_x = xhatminus_y = 0
    Pminus_x = Pminus_y = 0
    K_x = K_y = 0

    xhat0_x = xhat0_y = 300
    P0_x = P0_y = 1

    xhatprev_x = xhat0_x
    Pprev_x = P0_x
    xhatprev_y = xhat0_y
    Pprev_y = P0_y
    for cnt, c in enumerate(ball_motion):
        # "PREDICT" (time update)
        xhatminus_x = xhatprev_x + (A_x)
        Pminus_x = Pprev_x + kc.process_uncertainty
        xhatminus_y = xhatprev_y + (A_y)
        Pminus_y = Pprev_y + kc.process_uncertainty

        # Take "measurements":
        (cam1_estimate, cam1_sigma) = kc.get_cam_estimate(c, d.cam1center)
        (cam2_estimate, cam2_sigma) = kc.get_cam_estimate(c, d.cam2center)
        # (cam3_estimate,cam3_sigma) = kc.get_cam_estimate(c, d.cam3center)

        # z = mat([cam1_estimate, cam2_estimate, cam3_estimate])
        (z_x1, z_y1) = cam1_estimate
        (z_x2, z_y2) = cam2_estimate

        # Measurement noise covariance matrix:
        R = pow(cam1_sigma, 2) + pow(cam2_sigma, 2)
        z_x = (pow(cam2_sigma, 2) / (R)) * z_x1 + (pow(cam1_sigma, 2) /
                                                   (R)) * z_x2
        z_y = (pow(cam2_sigma, 2) / (R)) * z_y1 + (pow(cam1_sigma, 2) /
                                                   (R)) * z_y2
        # R = .01

        # "CORRECT" (measurement update)
        K_x = Pminus_x / (Pminus_x + R)
        xhat_x = xhatminus_x + K_x * (z_x - xhatminus_x)
        P_x = (1 - K_x) * Pminus_x
        K_y = Pminus_y / (Pminus_y + R)
        xhat_y = xhatminus_y + K_y * (z_y - xhatminus_y)
        P_y = (1 - K_y) * Pminus_y

        # We assume constant linear motion, so update the A values
        # accordingly for the next iteration:
        if cnt > 0:
            A_x = ball_motion[cnt][0] - ball_motion[cnt - 1][0]
            A_y = ball_motion[cnt][1] - ball_motion[cnt - 1][1]

        # save this result for the next iteration:
        xhatprev_x = xhat_x
        Pprev_x = P_x
        xhatprev_y = xhat_y
        Pprev_y = P_y

        # save measurements for later plotting:
        cam1_estimates.append(cam1_estimate)
        cam2_estimates.append(cam2_estimate)
        # cam3_estimates.append(cam3_estimate)
        kalman_estimates.append((int(xhat_x), int(xhat_y)))

        closest_camera_estimates.append(
            cam1_estimate if cam1_sigma < cam2_sigma else cam2_estimate)

        average_estimates.append(
            (int(average([cam1_estimate[0], cam2_estimate[0]])),
             int(average([cam1_estimate[1], cam2_estimate[1]]))))

    # eo filter loop
    print('Done!')

    # for v1,v2 in zip(closest_camera_estimates, average_estimates):
    #     print v1,v2,kc.get_dist_between_2_points(v1,v2)

    print('Saving images...')
    # plot the actual and estimated trajectories:
    plt.plot([c[0] for c in ball_motion],
             [kc.img_size[1] - c[1] for c in ball_motion],
             kc.plotcolors['actual'],
             label="Actual Trajectory")
    plt.plot(ball_motion[0][0], kc.img_size[1] - ball_motion[0][1], 'ro')
    plt.plot(ball_motion[-1][0], kc.img_size[1] - ball_motion[-1][1], 'go')
    if 'cam1' in plotting:
        plt.plot([c[0] for c in cam1_estimates],
                 [kc.img_size[1] - c[1] for c in cam1_estimates],
                 kc.plotcolors['cam1'],
                 label="Camera 1 Estimate")
    if 'cam2' in plotting:
        plt.plot([c[0] for c in cam2_estimates],
                 [kc.img_size[1] - c[1] for c in cam2_estimates],
                 kc.plotcolors['cam2'],
                 label="Camera 2 Estimate")
    if 'average' in plotting:
        plt.plot([c[0] for c in average_estimates],
                 [kc.img_size[1] - c[1] for c in average_estimates],
                 kc.plotcolors['average'],
                 label="Average Estimate")
    if 'closest' in plotting:
        plt.plot([c[0] for c in closest_camera_estimates],
                 [kc.img_size[1] - c[1] for c in closest_camera_estimates],
                 kc.plotcolors['closest'],
                 label="Closest Camera Estimate")
    if 'kalman' in plotting:
        plt.plot([c[0] for c in kalman_estimates],
                 [kc.img_size[1] - c[1] for c in kalman_estimates],
                 kc.plotcolors['kalman'],
                 label="Kalman Estimate")
    plt.title('Ball Trajectory')
    plt.legend(loc='best')
    plt.xlabel('X Pixel')
    plt.ylabel('Y Pixel')
    plt.savefig(kc.trajectories_filename, format='png')

    plt.cla()
    # plot the x values:
    plt.plot([c[0] for c in ball_motion],
             kc.plotcolors['actual'],
             label="Actual Position")
    if 'cam1' in plotting:
        plt.plot([c[0] for c in cam1_estimates],
                 kc.plotcolors['cam1'],
                 label="Camera 1 Estimate")
    if 'cam2' in plotting:
        plt.plot([c[0] for c in cam2_estimates],
                 kc.plotcolors['cam2'],
                 label="Camera 2 Estimate")
    # plt.plot([c[0] for c in cam3_estimates], label="Camera 3 Estimate")
    if 'average' in plotting:
        plt.plot([c[0] for c in average_estimates],
                 kc.plotcolors['average'],
                 label="Average Estimate")
    if 'closest' in plotting:
        plt.plot([c[0] for c in closest_camera_estimates],
                 kc.plotcolors['closest'],
                 label="Closest Camera Estimate")
    if 'kalman' in plotting:
        plt.plot([c[0] for c in kalman_estimates],
                 kc.plotcolors['kalman'],
                 label="Kalman Estimate")
    plt.title('X Values')
    plt.legend(loc='best')
    plt.xlabel('Frames')
    plt.ylabel('Pixels')
    plt.savefig(kc.x_estimates_filename, format='png')

    plt.cla()
    # plot the y values:
    plt.plot([c[1] for c in ball_motion],
             kc.plotcolors['actual'],
             label="Actual Position")
    if 'cam1' in plotting:
        plt.plot([c[1] for c in cam1_estimates],
                 kc.plotcolors['cam1'],
                 label="Camera 1 Estimate")
    if 'cam2' in plotting:
        plt.plot([c[1] for c in cam2_estimates],
                 kc.plotcolors['cam2'],
                 label="Camera 2 Estimate")
    # plt.plot([c[1] for c in cam3_estimates], label="Camera 3 Estimate")
    if 'average' in plotting:
        plt.plot([c[1] for c in average_estimates],
                 kc.plotcolors['average'],
                 label="Average Estimate")
    if 'closest' in plotting:
        plt.plot([c[1] for c in closest_camera_estimates],
                 kc.plotcolors['closest'],
                 label="Closest Camera Estimate")
    if 'kalman' in plotting:
        plt.plot([c[1] for c in kalman_estimates],
                 kc.plotcolors['kalman'],
                 label="Kalman Estimate")
    plt.title('Y Values')
    plt.legend(loc='best')
    plt.xlabel('Frames')
    plt.ylabel('Pixels')
    plt.savefig(kc.y_estimates_filename, format='png')

    plt.cla()
    # plot the errors:
    cam1errors = [
        kc.get_dist_between_2_points(c[0], c[1])
        for c in zip(ball_motion, cam1_estimates)
    ]
    cam2errors = [
        kc.get_dist_between_2_points(c[0], c[1])
        for c in zip(ball_motion, cam2_estimates)
    ]
    # cam3errors = [kc.get_dist_between_2_points(c[0], c[1]) for c in zip(ball_motion, cam3_estimates)]
    averageerrors = [
        kc.get_dist_between_2_points(c[0], c[1])
        for c in zip(ball_motion, average_estimates)
    ]
    closesterrors = [
        kc.get_dist_between_2_points(c[0], c[1])
        for c in zip(ball_motion, closest_camera_estimates)
    ]
    kalmanerrors = [
        kc.get_dist_between_2_points(c[0], c[1])
        for c in zip(ball_motion, kalman_estimates)
    ]

    if 'cam1' in plotting:
        plt.plot(cam1errors, kc.plotcolors['cam1'], label='Camera 1')
    if 'cam2' in plotting:
        plt.plot(cam2errors, kc.plotcolors['cam2'], label='Camera 2')
    # plt.plot(cam3errors, label='Camera 3')
    if 'average' in plotting:
        plt.plot(averageerrors, kc.plotcolors['average'], label='Average')
    if 'closest' in plotting:
        plt.plot(closesterrors,
                 kc.plotcolors['closest'],
                 label='Closest Camera')
    if 'kalman' in plotting:
        plt.plot(kalmanerrors, kc.plotcolors['kalman'], label='Kalman')
    plt.title('Estimation Errors')
    plt.legend(loc='best')
    plt.xlabel('Frames')
    plt.ylabel('Pixels')
    plt.savefig(kc.cam_errors_filename, format='png')

    w = numpy.bartlett(25)
    cam1errors_filtered = numpy.convolve(w / w.sum(), cam1errors, mode='same')
    cam2errors_filtered = numpy.convolve(w / w.sum(), cam2errors, mode='same')
    # cam3errors_filtered = numpy.convolve(w/w.sum(), cam3errors, mode='same')
    averageerrors_filtered = numpy.convolve(w / w.sum(),
                                            averageerrors,
                                            mode='same')
    closesterrors_filtered = numpy.convolve(w / w.sum(),
                                            closesterrors,
                                            mode='same')
    kalmanerrors_filtered = numpy.convolve(w / w.sum(),
                                           kalmanerrors,
                                           mode='same')

    plt.cla()
    if 'cam1' in plotting:
        # plt.plot(cam1errors_filtered, kc.plotcolors['cam1'], label='Camera 1')
        plt.plot(cam1errors_filtered,
                 kc.plotcolors['cam1'],
                 label='Camera 1',
                 linestyle='--')
    if 'cam2' in plotting:
        # plt.plot(cam2errors_filtered, kc.plotcolors['cam2'], label='Camera 2')
        plt.plot(cam2errors_filtered,
                 kc.plotcolors['cam2'],
                 label='Camera 2',
                 linestyle='--')
    # plt.plot(cam3errors_filtered, label='Camera 3')
    if 'average' in plotting:
        plt.plot(averageerrors_filtered,
                 kc.plotcolors['average'],
                 label='Average',
                 linewidth=2)
    if 'closest' in plotting:
        plt.plot(closesterrors_filtered,
                 kc.plotcolors['closest'],
                 label='Closest',
                 linewidth=2)
    if 'kalman' in plotting:
        plt.plot(kalmanerrors_filtered,
                 kc.plotcolors['kalman'],
                 label='Kalman',
                 linewidth=2)
    plt.title('Smoothed Estimation Errors')
    plt.legend(loc='best')
    plt.xlabel('Frames')
    plt.ylabel('Pixels')
    plt.savefig(kc.cam_errors_filtered_filename, format='png')

    print('Done!')

    if make_video:
        print('Rendering video...')
        # write out the video:
        stiter = iter([
            'Motion: Straight Line', 'Motion: Straight Line',
            'Motion: Sinusoid'
        ])
        for t in xrange(len(ball_motion)):
            # ball coordinates:
            d.ball_coords = ball_motion[t]
            # set up the status text:
            d.cam1_estimate = cam1_estimates[t]
            d.cam2_estimate = cam2_estimates[t]
            # d.cam3_estimate = cam3_estimates[t]
            d.average_estimate = average_estimates[t]
            d.kalman_estimate = kalman_estimates[t]
            d.frame_num = t
            if not (t % (len(ball_motion) / 3)):
                d.status_text = stiter.next()

            # do the drawing
            img = d.get_base_image()

            d.write_frame(img)

        print("Done!")
Ejemplo n.º 17
0
def draw_test_image():
    """If user chooses to draw image"""
    print("For the best results, draw the digits in the middle of the box.")
    drawing.Drawing(300, 100, int(IMG_PIXELS**0.5))
    image = Image.open(os.getcwd().rsplit('\\', 1)[0] + "/drawIn/input.jpg")
    test_image(image, 1.00, False)
Ejemplo n.º 18
0
 def test_parsed_root(self):
     d = drawing.Drawing(filename='./fixtures/tests-fixture.svg')
     self.assertIsInstance(d.root, ET.Element)
Ejemplo n.º 19
0
    def set_drawing_information(self, loc=0):
        """
        Method that add an entry to the database
        corresponding to the new drawing scanned
        """
        db = database.database(self.config)
        answer = QtGui.QMessageBox.Yes
        lst_groups = []

        if db.exist_in_db('drawings', 'DateTime', self.drawing_time):
            tuple_drawings = db\
                .get_all_in_time_interval("drawings",
                                          self.drawing_time,
                                          self.drawing_time)
            lst_drawings_field = db.get_all_fields("drawings")

            tuple_calibrations = db\
                .get_all_in_time_interval("calibrations",
                                          self.drawing_time,
                                          self.drawing_time)
            tuple_groups = db\
                    .get_all_in_time_interval("sGroups",
                                              self.drawing_time,
                                              self.drawing_time)
            lst_groups_field = db.get_all_fields("sGroups")

            lst_groups = [el for el in tuple_groups]
            drawing_type = tuple_drawings[0][2]
            tuple_drawing_type = db.get_drawing_information(
                "drawing_type", drawing_type)
            answer = QtGui\
                .QMessageBox\
                .question(self,
                          "new drawing",
                          "An entry corresponding to this drawing was found in the database. "
                          "Do you want to delete previous data ?",
                          QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

            drawing_dict = dict(zip(lst_drawings_field, tuple_drawings[0]))

            new_drawing = drawing.Drawing(drawing_dict)

            new_drawing.set_drawing_type(tuple_drawing_type[0])

            if self.drawing_time == tuple_calibrations[0][1]:
                new_drawing.set_calibration(tuple_calibrations[0])

            for group in lst_groups:
                group_dict = dict(zip(lst_groups_field, group))
                new_drawing.set_group(group_dict)

            if answer == QtGui.QMessageBox.No:
                db.replace_drawing(new_drawing)

            if answer == QtGui.QMessageBox.Yes:
                # delete the existing groups
                for index in reversed(range(0, len(lst_groups))):
                    new_drawing.delete_group(self.config, index)

        if answer == QtGui.QMessageBox.Yes:
            new_drawing = drawing.Drawing()

            self.config.set_file_path(self.drawing_time)
            filename = self.config.filename

            new_drawing.fill_from_daily_scan(
                drawing_datetime=self.drawing_time,
                observer=str(self.drawing_observer_linedit.text()).upper(),
                operator=str(self.drawing_operator_linedit.text()).upper(),
                drawing_type=str(self.drawing_type.currentText()),
                drawing_quality=str(self.drawing_quality.currentText()),
                drawing_name=filename)

            #db.replace_drawing(new_drawing)

            tuple_drawing_type = db.get_drawing_information(
                "drawing_type", str(self.drawing_type.currentText()))
            new_drawing.set_drawing_type(tuple_drawing_type[0])

        if loc == 1:
            self.config.set_file_path(self.drawing_time)
            filename = self.config.filename

            if os.path.isfile(self.config.file_path):
                new_drawing = drawing.Drawing()
                new_drawing.fill_from_daily_scan(
                    drawing_datetime=self.drawing_time,
                    observer=str(self.drawing_observer_linedit.text()).upper(),
                    operator=str(self.drawing_operator_linedit.text()).upper(),
                    drawing_type=str(self.drawing_type.currentText()),
                    drawing_quality=str(self.drawing_quality.currentText()),
                    drawing_name=filename)

                # db.replace_drawing(new_drawing)

                tuple_drawing_type = db.get_drawing_information(
                    "drawing_type", str(self.drawing_type.currentText()))
                new_drawing.set_drawing_type(tuple_drawing_type[0])

                QtGui.QMessageBox\
                     .information(self,
                              "drawing addition",
                                  "New drawing added in the database for the " +
                                  str(self.drawing_time))

            else:
                QtGui.QMessageBox\
                     .warning(self,
                              "drawing addition",
                              "There is not drawing the image directory correspoding to this date")
                return

        return [new_drawing]
Ejemplo n.º 20
0
    level, height, apex = tet[0],tet[1],tet[2]
    bottom = tetrahedronBottom(height,apex)
    yield (level,height/2.,apex)
    for p in bottom:
        yield (level+1,height/2.,average(apex,p))

def sierpinski(height, x,y,z, level):
    tetrahedra = [(0,height,(x,y,z))]
    for i in range(level):
        out = []
        for tet in tetrahedra:
            out += transform(tet)
        tetrahedra = out
    return tetrahedra

mc = Minecraft()
d = drawing.Drawing(mc)
pos = mc.player.getPos()
height = 240 if not settings.isPE else 128
levels = 7
mc.player.setPos(tetrahedronBottom(height,(pos.x,pos.y+height,pos.z))[0])
tetrahedra = sierpinski(height,pos.x,pos.y+height,pos.z,levels)
mc.postToChat("Drawing")
if len(argv) >= 2:
    specifiedBlock = Block.byName(argv[1])
    b = lambda level : specifiedBlock
else:
    b = lambda level : RAINBOW[level % len(RAINBOW)]
for tet in tetrahedra:
    drawTetrahedron(tet[1],tet[2],b(tet[0]))
Ejemplo n.º 21
0
    def __init__(self, uid, panel_id):
        #Awn Applet configuration
        awn.AppletSimple.__init__(self, 'slickswitcher', uid, panel_id)
        self.dialog = awn.Dialog(self)
        self.dialog.set_skip_pager_hint(True)

        self.set_tooltip_text(_("SlickSwitcher"))

        self.size = self.get_size()

        #Set up Switch - does wnck stuff
        self.switch = switch.Switch()

        #Set up Settings - does awn.Config stuff
        self.settings = settings.Settings(self)
        for key in ['use_custom', 'custom_back', 'custom_border']:
            self.settings.config.notify_add(GROUP_DEFAULT, key, self.update_custom)

        #Set up the dialog colors
        self.dialog_style = self.dialog.get_style()
        self.unmodified_style = self.dialog_style.copy()
        self.dialog.connect('style-set', self.style_set)

        #Set up Drawing - does the shiny drawing stuff
        self.widget = drawing.Drawing(self.switch, self.settings, self)
        self.dialog.add(self.widget)

        #Set up the values for the ViewportSurface
        self.update_backgrounds()
        self.draw_background = False
        self.number = self.switch.get_current_workspace_num()
        num_columns = self.switch.get_num_columns()
        self.row = int((self.number) / float(num_columns)) + 1
        self.column = int((self.number) % num_columns) + 1

        #Set up the text overlay
        self.overlay = awn.OverlayText()
        self.add_overlay(self.overlay)
        self.overlay.props.font_sizing = 21.0
        self.overlay.props.text = str(self.number)
        self.overlay.props.active = not self.settings['use_custom_text']
        self.overlay.props.apply_effects = True
        self.overlay.connect('notify::text-color', self.overlay_notify)
        self.overlay.connect('notify::text-outline-color', self.overlay_notify)
        self.overlay.connect('notify::font-mode', self.overlay_notify)
        self.overlay.connect('notify::text-outline-width', self.overlay_notify)

        self.settings.config.notify_add(GROUP_DEFAULT, 'use_custom_text', self.toggle_custom_text)

        #Connect to signals
        #Applet signals
        self.connect('realize', self.realize_event)
        self.connect('size-changed', self.size_changed)
        self.connect('clicked', self.toggle_dialog)
        self.connect('context-menu-popup', self.show_menu)
        self.connect('scroll-event', self.scroll)
        self.dialog.props.hide_on_unfocus = True
        #Any relevant signal from Wnck
        self.switch.connect(self.update_icon)

        #Start updating the icon every 2 second, in 2 seconds
        gobject.timeout_add_seconds(2, self.timeout_icon)

        #Force the widget to get the background color from the dialog
        #self.dialog.realize()
        self.widget.update_color()