def __init__(self, root):
        super().__init__(root)

        self.canvas = cv.Canvas(self)
        self.add_canvas()

        self.x = [-10, 10, 0.1]
        self.z = [-10, 10, 0.1]
        self.ox = 0
        self.oy = 0
        self.oz = 0
        self.scale = None

        self.frame_color = tk.Frame(self)
        self.color = 'black'
        self.color_win = None
        self.add_color()

        self.frame_funcs = tk.Frame(self)
        self.func = tk.IntVar()
        self.func.set(0)
        self.add_funcs()

        self.frame_limits = tk.Frame(self)
        self.dx = []
        self.dz = []
        self.add_limits()

        self.frame_entries = tk.Frame(self)
        self.add_entry()

        self.frame_buttons = tk.Frame(self)
        self.add_buttons()
Exemple #2
0
def main():
    P = [[40], [40]]
    V0 = [[30], [30]]
    V1 = [[40], [70]]
    V2 = [[50], [30]]
    points = [V0, V1, V2]
    aspect_correct = [[1, 0], [0, 4 / 7]]
    home = "\N{escape}[H"
    wakeup_time = time.time()
    print(home + "\N{escape}[J\N{escape}[?25l")
    t = 0
    try:
        while True:
            kanvas = canvas.Canvas()
            rot = matrix.rotate_2D(t * 0.5)
            r_points = []
            for point in points:
                C = matrix.sub(point, P)
                C = matrix.mult(rot, C)
                C = matrix.add(P, C)
                C = matrix.mult(aspect_correct, C)
                r_points.append(C)
            t += 1
            kanvas.triangle(round(r_points[0][0][0]), round(r_points[0][1][0]),
                            round(r_points[1][0][0]), round(r_points[1][1][0]),
                            round(r_points[2][0][0]), round(r_points[2][1][0]))
            image = home + kanvas.get_image()
            print(image)
            wakeup_time += 0.05
            time.sleep(max(0, wakeup_time - time.time()))
    finally:
        print(home + "\N{escape}[J \N{escape}[?25h")
Exemple #3
0
    def test_ppm_ends_with_newline(self):
        """Satisfy picky image viewers by ensuring the ppm file ends in a
        newline
        """

        c = canvas.Canvas(5, 3)
        ppm_content = c._get_ppm_file_content()
        self.assertEqual(ppm_content[-1:], "\n")
Exemple #4
0
def main():
    P = [[40],
         [40],
         [0]]
    Axis = [[10],
            [5],
            [3]]
#    V0 = [[30],
#          [30],
#          [0]]
#    V1 = [[40],
#          [70],
#          [0]]
#    V2 = [[50],
#          [30],
#          [0]]
#    points = [V0, V1, V2]
    points = []
    for i in range(15):
        points.append([[random.randint(20, 60)],
                       [random.randint(30, 60)],
                       [random.randint(-20, 20)]])

    aspect_correct = [[1, 0, 0],
                      [0, 4/7, 0],
                      [0, 0, 1]]
    home = "\N{escape}[H"
    wakeup_time = time.time()
    print(home + "\N{escape}[J\N{escape}[?25l")
    t = 0
    try:
        while True:
            kanvas = canvas.Canvas()
            rot = matrix.rotate_3D(t * 0.1, Axis)
            r_points = [] 
            for point in points:
                C = matrix.sub(point, P)
                C = matrix.mult(rot, C)
                C = matrix.add(P, C)
                C = matrix.mult(aspect_correct, C)
                r_points.append(C)
            t += 1
            for r_point in r_points:
                kanvas.dab(round(r_point[0][0]),
                           round(r_point[1][0]))

#            kanvas.triangle(round(r_points[0][0][0]),
#                            round(r_points[0][1][0]),
#                            round(r_points[1][0][0]),
#                            round(r_points[1][1][0]),
#                            round(r_points[2][0][0]),
#                            round(r_points[2][1][0]))
            image = home + kanvas.get_image()
            print(image)
            wakeup_time += 0.05
            time.sleep(max(0, wakeup_time - time.time()))
    finally:
        print(home + "\N{escape}[J \N{escape}[?25h")
Exemple #5
0
    def test_write_to_canvas(self):
        """Test we can write to and read from a canvas"""

        c = canvas.Canvas(10, 20)
        red = colors.Color(1, 0, 0)

        c.set(2, 3, red)

        self.assertEqual(c.canvas[2][3], red)
Exemple #6
0
    def GroupGraph(self):
        #graphics and toolbars
        Rd = canvas.Canvas(self.main_widget, width=5, height=5, dpi=100)
        self.dataCanvas = Rd
        Cd = canvas.Canvas(self.main_widget, width=5, height=5, dpi=100)
        self.errorCanvas = Cd
        toolbarRd = NavigationToolbar(Rd, self)
        toolbarCd = NavigationToolbar(Cd, self)

        groupBoxGraph = QGroupBox('Graphics and toolbars')
        vbox = QVBoxLayout()
        vbox.addWidget(toolbarRd)
        vbox.addWidget(Rd)
        vbox.addWidget(toolbarCd)
        vbox.addWidget(Cd)
        vbox.addStretch(1)
        groupBoxGraph.setLayout(vbox)

        return groupBoxGraph
Exemple #7
0
    def test_empty_canvas(self):
        """Test that an empty canvas is filled with black pixels"""

        c = canvas.Canvas(10, 20)

        self.assertEqual(len(c.canvas), 10)
        self.assertEqual(len(c.canvas[0]), 20)

        for i in range(10):
            for j in range(20):
                self.assertEqual(c.canvas[i][j],
                                 colors.Color(0, 0, 0))
Exemple #8
0
    def build_ui(self):
        # using grid system to set the widgets in the window
        self.cnv = canvas.Canvas(self)
        self.cnv.grid(row=0, column=0, columnspan=2, rowspan=2)

        self.res = predictions_ui.Results(self)

        bl = tk.Button(self, text="Clear Canvas", command=self.clear_all)
        bl.grid(row=2, column=0)

        br = tk.Button(self, text="Predict Drawing", command=self.predict)
        br.grid(row=2, column=1)
Exemple #9
0
def main():

    PAUSE = False

    print('Initializing canvas...')
    canv = canvas.Canvas(*RESOLUTION)
    canv.render_single_frame(pause=PAUSE)

    print('Drawing borders...')
    canv.draw_borders()
    canv.render_single_frame(pause=PAUSE)

    NUM_CIRCLES = 16
    print('Adding', NUM_CIRCLES, 'circles...')
    RADIUS_RANGE = (8, 8)
    VELOCITY_RANGE = (4, 4)
    border_zone = 20
    CX = RESOLUTION[1] / 2
    CY = RESOLUTION[0] / 2
    for count in range(NUM_CIRCLES):
        radius = random.randint(*RADIUS_RANGE)
        # Leave space for the dodger to start in the middle
        SPACE = 70
        cx = double_interval_random(border_zone + radius, CX - SPACE,
                                    CX + SPACE,
                                    RESOLUTION[1] - (border_zone + radius))
        cy = double_interval_random(border_zone + radius, CY - SPACE,
                                    CY + SPACE,
                                    RESOLUTION[0] - (border_zone + radius))
        velocity = random.uniform(*VELOCITY_RANGE)
        theta = random.uniform(0, 2 * np.pi)
        vx = velocity * np.cos(theta)
        vy = velocity * np.sin(theta)
        canv.add_circle(cx, cy, radius, vx, vy)
    canv.render_single_frame(pause=PAUSE)

    DODGER_SPEED = 200
    MODEL = 2
    print('Adding dodger...')
    theta = random.uniform(0, 2 * np.pi)
    canv.create_dodger(CX, CY, theta, DODGER_SPEED, MODEL)
    canv.render_single_frame(pause=True)

    # motion
    SECONDS = 15
    EMPIRICAL_FPS = 64
    TOTAL_FRAMES = SECONDS * EMPIRICAL_FPS
    canv.main_game_loop()
Exemple #10
0
    def test_ppm_long_line_splitting(self):
        """Test that we split longer lines at or before 70 characters"""

        c = canvas.Canvas(10, 2)
        for i in range(c.width):
            for j in range(c.height):
                c.set(i, j, colors.Color(1, 0.8, 0.6))

        ppm_content = c._get_ppm_file_content()
        ppm_lines = ppm_content.split("\n")

        self.assertEqual(ppm_lines[3],
            "255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204")
        self.assertEqual(ppm_lines[4],
            "153 255 204 153 255 204 153 255 204 153 255 204 153")
        self.assertEqual(ppm_lines[5],
            "255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204")
        self.assertEqual(ppm_lines[6],
            "153 255 204 153 255 204 153 255 204 153 255 204 153")
def main():
    client = canvas.Canvas("https://fhict.instructure.com", read_api_key())

    previous_day = datetime.datetime.now(
        datetime.timezone.utc) - datetime.timedelta(days=5)
    ok, announcements_or_error = client.get_announcements_after(previous_day)
    if not ok:
        print("error: {}".format(announcements_or_error))
        return
    announcements = announcements_or_error
    for announcement in announcements:
        title = announcement["title"]
        author = announcement["author"]["display_name"]
        post_time = announcement["posted_at"]
        message = announcement["message"]
        print(announcement)
        print(
            "title: {}\n\tpost time: {}\n\tauthor: {} \n\tmessage: {}".format(
                title, post_time, author, message))
Exemple #12
0
 def open_image(self,
                path,
                bitDepth=16,
                enableAutoWB=False,
                brightness=20,
                blackLevel=50):
     if not path == '':
         canvas_widget = canvas.Canvas(self, self.config)
         self.connect_canvas(canvas_widget)
         self.CANVAS_SCALE_FACTOR_CHANGED.emit(self.scaleFactor)
         img_array = self.load_image(canvas_widget, path, bitDepth,
                                     enableAutoWB, brightness, blackLevel)
         self.photoList.append(img_array)
         self.pathList.append(path)
         self.mainTab.addTab(canvas_widget, os.path.basename(path))
         self.mainTab.setCurrentIndex(self.mainTab.count() - 1)
         canvas_widget.fit_canvas()
         canvas_widget.toggle_mode(self._mode)
         self.currentPath = path
         self.FILE_OPENED.emit(path)
Exemple #13
0
    def __init__(self, root):
        super().__init__(root)

        self.canvas = cv.Canvas(self)
        self.add_canvas()

        self.img = None
        self.add_image()

        self.frame_input = tk.Frame(self)
        self.coors = None
        self.add_input()

        self.frame_color = tk.Frame(self)
        self.color = tk.IntVar()
        self.color.set(0)
        self.add_color()

        self.frame_buttons = tk.Frame(self)
        self.mode = tk.IntVar()
        self.mode.set(0)
        self.add_buttons()
Exemple #14
0
    def test_ppm_file_content(self):
        """Test the content of the PPM header is correct"""

        c = canvas.Canvas(5, 3)
        c1 = colors.Color(1.5, 0, 0)
        c2 = colors.Color(0, 0.5, 0)
        c3 = colors.Color(-0.5, 0, 1)

        c.set(0, 0, c1)
        c.set(2, 1, c2)
        c.set(4, 2, c3)

        ppm_content = c._get_ppm_file_content()

        ppm_lines = ppm_content.split("\n")

        self.assertEqual(ppm_lines[0], "P3")
        self.assertEqual(ppm_lines[1], "5 3")
        self.assertEqual(ppm_lines[2], "255")
        self.assertEqual(ppm_lines[3], "255 0 0 0 0 0 0 0 0 0 0 0 0 0 0")
        self.assertEqual(ppm_lines[4], "0 0 0 0 0 0 0 128 0 0 0 0 0 0 0")
        self.assertEqual(ppm_lines[5], "0 0 0 0 0 0 0 0 0 0 0 0 0 0 255")
Exemple #15
0
def main():
   # Initialize canvas
   print('Initializing canvas...')
   canvas_object = canvas.Canvas(*kResolution)
   canvas_object.RenderSingleFrame(kPause)
   # Draw borders
   print('Drawing borders...')
   canvas_object.DrawBorders()
   canvas_object.RenderSingleFrame(kPause)
   # Draw circles
   print('Adding', kNumCircles, 'circles...')
   for count in range(kNumCircles):
      radius = random.randint(*kCircleRadiusRange)
      # Leave space for the dodger to start in the middle
      xmin, xmax = canvas_object.playable_area_xrange_
      ymin, ymax = canvas_object.playable_area_yrange_
      cx = math_util.RandomSlicedInterval(xmin, xmax, kMiddleSpawnBufferRatio)
      cy = math_util.RandomSlicedInterval(ymin, ymax, kMiddleSpawnBufferRatio)
      velocity = random.uniform(*kCircleVelocityRange)
      theta = math_util.RandomAngle()
      vx = velocity * np.cos(theta)
      vy = velocity * np.sin(theta)
      canvas_object.AddCircle(cx, cy, radius, vx, vy)
   canvas_object.RenderSingleFrame(kPause)
   # Draw dodger
   print('Adding dodger...')
   xmin, xmax = canvas_object.playable_area_xrange_
   ymin, ymax = canvas_object.playable_area_yrange_
   cx = math_util.RoundToInt(0.5 * (xmin + xmax))
   cy = math_util.RoundToInt(0.5 * (ymin + ymax))
   theta = math_util.RandomAngle()
   canvas_object.CreateDodger(cx, cy, theta, kDodgerSpeed, kDodgerTurningRate)
   canvas_object.RenderSingleFrame(pause=True)
   # Motion
   #SECONDS = 15
   #EMPIRICAL_FPS = 64
   #TOTAL_FRAMES = SECONDS*EMPIRICAL_FPS
   canvas_object.MainGameLoop()
Exemple #16
0
    def render(self, scene: scenes.Scene):
        """Renders a scene and returns a filled in canvas"""

        logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

        time_0 = time.time()
        logging.info(f"Starting to render scene with size "
                     f"{self.hsize}, {self.vsize}")
        image = canvas.Canvas(self.hsize, self.vsize)

        for y in range(self.vsize):
            print(y)
            for x in range(self.hsize):
                ray = self.ray_for_pixel(x, y)
                color, _ = scene.color_at(ray)
                image.set(x, y, color)

        time_1 = time.time()
        logging.info(
            f"Rendered scene in {round(time_1-time_0, 2)}s "
            f"({round(self.hsize*self.vsize/(time_1-time_0), 2)} pps)")

        return image
    def __init__(self, root):
        super().__init__(root)

        self.canvas = cv.Canvas(self)
        self.add_canvas()

        self.frame_cutter = tk.Frame(self)
        self.cutter_coors = None
        self.cutter = []
        self.add_cutter()

        self.frame_section = tk.Frame(self)
        self.section_coors = None
        self.section = []
        self.add_section()

        self.frame_color = tk.Frame(self)
        self.color_wins = dict()
        self.colors = {'cutter': 'black', 'section': 'red', 'result': 'blue'}
        self.add_color()

        self.frame_buttons = tk.Frame(self)
        self.add_buttons()
Exemple #18
0
 def scan_trace(self, file):
     mycanvas = canvas.Canvas()
     for line in file:
         line = line.split()
         event_type = line[0]
         timestamp = float(line[1])
         hop_src_node = int(line[2])
         hop_dst_node = int(line[3])
         packet_name = line[4]  # TCP or ACK
         packet_size = int(line[5])
         packet_flag = line[6]  # C is a control packet
         #			print packet_flag[0]
         ip_src_node = int(line[2])  # todo : change this
         ip_dst_node = int(line[3])  # todo : change this
         src_port = 0  # todo : change this
         dst_port = 0  # todo : change this
         packet_id = int(line[11])
         sequence_number = int(line[10])
         mycanvas.add_event(timestamp, packet_id, packet_name, event_type,
                            hop_src_node, hop_dst_node, ip_src_node,
                            ip_dst_node, src_port, dst_port,
                            sequence_number, packet_flag, packet_size)
     return mycanvas
Exemple #19
0
def index():
    # Start the webcam camera
    cap = cv2.VideoCapture(1)

    # Initialize variables
    paper_contour = np.array([])
    bg_thresh = None
    finger_thresh = None
    thresh2 = None
    finger_thresh2 = None
    stable_threshold = 0.01
    farthest = None  # Point tracking the fingertip of the user
    current_position = None
    num_frames = 4
    history = paper_buffer.Paper_Buffer(num_frames)
    click_threshold = 8

    while (True):
        # Capture a video frame-by-frame
        ret, frame = cap.read()

        # Find the edges in each frame
        gray = cv2.cvtColor(
            frame,
            cv2.COLOR_BGR2GRAY)  # Turn image frame into grayscale version
        blur = cv2.GaussianBlur(
            gray, (5, 5),
            0)  # Execute a Gaussian blur to remove noise from the frame
        thresh = cv2.threshold(blur.copy(), 127, 255,
                               cv2.THRESH_BINARY)[1]  # Create a binary image
        edges = cv2.Canny(thresh, 50, 200)  # Isolate the edges in the picture

        # Find contours in the edged image, keep only the largest ones, and initialize our screen contour
        _, temp_contours, _ = cv2.findContours(edges.copy(), cv2.RETR_TREE,
                                               cv2.CHAIN_APPROX_SIMPLE)
        contours = sorted(temp_contours, key=cv2.contourArea,
                          reverse=True)[:10]

        # Loop over contours to find which contour belongs to the paper
        count = 0
        for contour in contours:
            # Approximate how many points the perimeter of the contour has
            perimeter = cv2.arcLength(contour, True)
            area = cv2.contourArea(contour)
            approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)

            # If the approximated contour has 4 points, we can assume we have found our paper
            if len(approx) == 4 and perimeter > 1000 and area > 2000:
                # Save the paper contour
                paper_contour = approx

                # Save the canvas thresholds
                bg_thresh = np.zeros(thresh.shape, dtype=np.uint8)
                finger_thresh = np.zeros(thresh.shape, dtype=np.uint8)

                # Store the canvas information for use in future calculations
                paper_canvas = canvas.Canvas(map(lambda x: x[0],
                                                 paper_contour))

                # Fill in the paper to filter out the canvas later (when extracting the user's hand)
                cv2.fillConvexPoly(bg_thresh, paper_contour, 255)
                break

        # Draw red circles at the corners of the paper
        for point in paper_contour:
            cv2.circle(frame, (point[0][0], point[0][1]), 5, (0, 0, 255), 3)

        # Draw a green outline around the edges of the paper
        cv2.polylines(frame, [paper_contour], True, (0, 255, 0), 3)

        # Create a mask of the frame to prepare for bitwise operations
        _, mask = cv2.threshold(blur, 127, 255, cv2.THRESH_BINARY)
        mask_inv = cv2.bitwise_not(mask)

        # Check if the threshold and mask are the same size before performing operations
        if np.shape(bg_thresh) == np.shape(mask):
            # Isolate the user's hand in the binary image
            mask_clean = cv2.bitwise_and(mask, bg_thresh)
            bg_thresh_clean = cv2.bitwise_and(bg_thresh, bg_thresh)
            finger_thresh2 = cv2.bitwise_xor(mask_clean, bg_thresh)

            # Get rid of leftover noise at the paper edges
            cv2.polylines(finger_thresh2, [paper_contour], True, (0, 0, 0), 3)

            # Calculate the differential value
            temp = cv2.bitwise_xor(finger_thresh,
                                   finger_thresh2,
                                   mask=bg_thresh)
            dif_value = np.sum(temp / (np.sum(finger_thresh2) + 0.1))

            # Calculate the lowest point of the finger mask, corresponding to the fingertip
            if dif_value > stable_threshold:
                # Collect the coordinates where the finger threshold is above a certain height
                y_values, x_values = np.where(finger_thresh2 > 0)

                # Find the y-value with the highest magnitude, corresponding to the lowest point on the screen
                if len(y_values > 0):
                    # Track the current position of the user's fingertip
                    index = np.argmax(y_values)
                    farthest = (x_values[index], y_values[index])
                    current_position = farthest

                    # Initialize booleans used to check if a click has occurred
                    click_pre = False
                    click_down = False
                    click_up = False

                    time.sleep(0.008)
                    for element in np.roll(history.array, history.head,
                                           axis=0):
                        distance = canvas.distance_point_point(
                            element, current_position)
                        #print distance

                        if click_up:
                            continue
                        if click_down and distance > 10:
                            click_up = True
                            print '=========================== CLICK ====================='
                            paper_canvas.get_button(current_position)
                            history.clear()
                            click_up = False
                            click_down = False
                            click_pre = False
                        elif click_pre and distance > 5 and distance < 20:
                            click_down = True
                            print '================ DOWN ==============='
                        elif distance < 5:
                            click_pre = True

                    # Update history queue
                    history.enqueue(current_position)

            # Place a blue circle to mark the fingertip
            cv2.circle(frame, farthest, 5, (255, 0, 0), 3)

            # Display the resulting frame
            cv2.imshow('frame', frame)
        else:
            # Display the resulting frame
            cv2.imshow('frame', frame)

        # Display the resulting frame
        if cv2.waitKey(1) & 0xFF == ord('q'):
            paper_canvas.replay()
            break

    # When everything is done, release the capture
    cap.release()
    cv2.destroyAllWindows()
                    help="Directory where PrairieLearn repo is stored")
parser.add_argument("pl_course_instance",
                    help="Course instance where assessment will be created")
parser.add_argument("-s",
                    "--assessment-set",
                    default="Quiz",
                    help="Assessment set to assign this assessment to")
parser.add_argument("-n",
                    "--assessment-number",
                    default="",
                    help="Assessment set to assign this assessment to")
parser.add_argument("--topic",
                    default="None",
                    help="Assessment set to assign this assessment to")
args = parser.parse_args()
canvas = canvas.Canvas(args=args)

if not os.path.exists(os.path.join(args.pl_repo, 'infoCourse.json')):
    raise Exception("Provided directory is not a PrairieLearn repository")

print('Reading data from Canvas...')
course = canvas.course(args.course, prompt_if_needed=True)
print('Using course: %s / %s' %
      (course['term']['name'], course['course_code']))

quiz = course.quiz(args.quiz, prompt_if_needed=True)
print('Using quiz: %s' % (quiz['title']))

# Reading questions
print('Retrieving quiz questions from Canvas...')
(questions, groups) = quiz.questions()
Exemple #21
0
    def __init__(self):
        super(Window, self).__init__()
        self.image_worker = process.Image()
        self.image_crop = [800, 1800, 1650, 2650]
        self.current_status = {}
        self.canvas_config = configparser.ConfigParser()
        self.canvas_config.read('./configuration.ini')
        self.mainSplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
        self.topSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
        self.canvasFrame = QtWidgets.QWidget()
        self.canvasFrameGrid = QtWidgets.QHBoxLayout(self.canvasFrame)
        self.canvas = canvas.Canvas(self, self.canvas_config)
        self.digital_tile = digital_tile.DigTile(self)
        self.controlPanel = QtWidgets.QWidget(self)
        self.controlPanelGrid = QtWidgets.QGridLayout(self.controlPanel)
        self.supportedFormates = {'*.3fr','*.ari','*.arw','*.srf', '*.sr2','*.bay','*.cri','*.crw', '*.cr2',     '*.cr3', '*.cap','*.iiq','*.eip',\
                                     '*.dcs','*.dcr','*.drf','*.k25', '*.kdc','*.dng','*.erf','*.fff', '*.mef',     '*.mdc', '*.mos','*.mrw','*.nef',\
                                     '*.nrw','*.orf','*.pef','*.ptx', '*.pxn','*.r3d','*.raf','*.raw', '*.rw2',     '*.rwl', '*.rwz','*.srw','*.x3f',\
                                     '*.3FR','*.ARI','*.ARW','*.SRF', '*.SR2','*.BAY','*.CRI','*.CRW', '*.CR2',     '*.CR3', '*.CAP','*.IIQ','*.EIP',\
                                     '*.DCS','*.DCR','*.DRF','*.K25', '*.KDC','*.DNG','*.ERF','*.FFF', '*.MEF',     '*.MDC', '*.MOS','*.MRW','*.NEF',\
                                     '*.NRW','*.ORF','*.PEF','*.PTX', '*.PXN','*.R3D','*.RAF','*.RAW', '*.RW2',     '*.RWL', '*.RWZ','*.SRW','*.X3F',\
                                     '*.bmp','*.eps','*.gif','*.icns','*.ico','*.im', '*.jpg','*.jpeg','*.jpeg2000','*.msp', '*.pcx','*.png','*.ppm',\
                                     '*.sgi','*.tiff','*.tif','*.xbm','*.BMP','*.EPS','*.GIF','*.ICNS','*.ICO',     '*.IM',  '*.JPG','*.JPEG','*.JPEG2000',\
                                     '*.MSP','*.PCX','*.PNG','*.PPM','*.SGI','*.TIFF','*.TIF','*.XBM'}

        self.open_label = QtWidgets.QLabel('Choose image file:\n')
        self.open_label.setMaximumHeight(100)
        self.open_button = QtWidgets.QPushButton('Browse...')
        self.open_button.clicked.connect(self.browse_image)
        self.browser_widget = browser.Browser(self, self.supportedFormates)
        self.IMAGE_CHOSEN.connect(self.browser_widget.tree_update)
        self.browser_widget.FILE_DOUBLE_CLICKED.connect(self.open_image)
        self.browser_widget.setMaximumHeight(400)

        self.nbs_label = QtWidgets.QLabel('Number of scales:')
        self.nba_label = QtWidgets.QLabel('Number of angles:')
        self.ac_label = QtWidgets.QLabel('Use curvet at the coarest scale?')
        self.nbs = QtWidgets.QComboBox()
        for s in range(3, 20):
            self.nbs.addItem(str(s))
        self.nbs.setCurrentText('5')
        self.nbs.currentTextChanged.connect(self.nbs_changed)
        self.nba = QtWidgets.QComboBox()
        for a in [8, 16, 32, 64]:
            self.nba.addItem(str(a))
        self.nba.currentTextChanged.connect(self.nba_changed)
        self.ac = QtWidgets.QCheckBox()
        self.ac.setChecked(True)
        self.ac.stateChanged.connect(self.ac_changed)
        self.wedge_index_label = QtWidgets.QLabel('Current wedge index:')

        self.threshold_label = QtWidgets.QLabel('Threshold ({})'.format(30))
        self.threshold_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
        self.threshold_slider.setMinimum(0)
        self.threshold_slider.setMaximum(255)
        self.threshold_slider.setValue(30)
        self.threshold_slider.valueChanged.connect(self.threshold_changed)

        self.cursor_selections_label = QtWidgets.QLabel(
            'Cursor selection rule:')
        self.cursor_selections = QtWidgets.QComboBox()
        self.cursor_selections.addItem('cell')
        self.cursor_selections.addItem('level')
        self.cursor_selections.currentTextChanged.connect(
            self.digital_tile.set_cursor_selection_rule)
        self.click_functions_label = QtWidgets.QLabel('Click function:')
        self.click_functions = QtWidgets.QComboBox()
        self.click_functions.addItem('select')
        self.click_functions.addItem('show')
        self.click_functions.currentTextChanged.connect(
            self.digital_tile.set_click_function_rule)
        self.previous_difference_scale_factor = 10
        self.difference_scale_factor_label = QtWidgets.QLabel(
            'Difference gain ({})'.format(
                self.previous_difference_scale_factor))
        self.difference_scale_factor_slider = QtWidgets.QSlider(
            QtCore.Qt.Horizontal)
        self.difference_scale_factor_slider.setMinimum(1)
        self.difference_scale_factor_slider.setMaximum(100)
        self.difference_scale_factor_slider.setValue(
            self.previous_difference_scale_factor)
        self.difference_scale_factor_slider.valueChanged.connect(
            self.difference_scale_factor_changed)

        self.button_group = QtWidgets.QGroupBox()
        self.button_group_grid = QtWidgets.QVBoxLayout(self.button_group)
        self.show_selected_cells_button = QtWidgets.QPushButton(
            "Show Selected Cells")
        self.show_selected_cells_button.clicked.connect(
            self.show_selected_cells)
        self.show_selected_cells_button.setEnabled(False)
        self.close_all_button = QtWidgets.QPushButton("Close All")
        self.close_all_button.setEnabled(False)
        self.close_all_button.clicked.connect(self.clear_all)
        self.load_curvelet_button = QtWidgets.QPushButton(
            "Load Curvelet Digital Tile")
        self.load_curvelet_button.clicked.connect(self.load_curvelet_transform)
        self.load_curvelet_button.setEnabled(False)
        self.show_modified_image_button = QtWidgets.QPushButton("Show Results")
        self.show_modified_image_button.clicked.connect(self.show_modified)
        self.show_modified_image_button.setEnabled(False)
        self.apply_threshold_button = QtWidgets.QPushButton(
            'Apply Threshold Denoise')
        self.apply_threshold_button.clicked.connect(self.threshold_denoise)
        self.apply_threshold_button.setEnabled(False)
        self.button_group_grid.addWidget(self.show_selected_cells_button)
        self.button_group_grid.addWidget(self.close_all_button)
        self.button_group_grid.addWidget(self.load_curvelet_button)
        self.button_group_grid.addWidget(self.show_modified_image_button)
        self.button_group_grid.addWidget(self.apply_threshold_button)
        self.button_group_grid.setAlignment(QtCore.Qt.AlignTop)

        self.controlPanelGrid.setAlignment(QtCore.Qt.AlignTop)
        self.controlPanelGrid.addWidget(self.open_label, 0, 0, 1, 6)
        self.controlPanelGrid.addWidget(self.open_button, 1, 0, 1, 6)
        self.controlPanelGrid.addWidget(self.browser_widget, 2, 0, 1, 6)
        self.controlPanelGrid.addWidget(self.nbs_label, 10, 0, 1, 2)
        self.controlPanelGrid.addWidget(self.nbs, 10, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.nba_label, 11, 0, 1, 2)
        self.controlPanelGrid.addWidget(self.nba, 11, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.ac_label, 12, 0, 1, 2)
        self.controlPanelGrid.addWidget(self.ac, 12, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.threshold_label, 13, 0, 1, 2)
        self.controlPanelGrid.addWidget(self.threshold_slider, 13, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.difference_scale_factor_label, 14,
                                        0, 1, 2)
        self.controlPanelGrid.addWidget(self.difference_scale_factor_slider,
                                        14, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.cursor_selections_label, 20, 0, 1,
                                        2)
        self.controlPanelGrid.addWidget(self.cursor_selections, 20, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.click_functions_label, 21, 0, 1,
                                        2)
        self.controlPanelGrid.addWidget(self.click_functions, 21, 2, 1, 4)
        self.controlPanelGrid.addWidget(self.wedge_index_label, 22, 0, 1, 6)
        self.controlPanelGrid.addWidget(self.digital_tile, 30, 0, 1, 5)
        self.controlPanelGrid.addWidget(self.button_group, 30, 5, 1, 1)

        self.statusBar = QtWidgets.QGroupBox("Log")
        self.statusBar.setStyleSheet('QGroupBox::title {color:blue;}')
        self.statusGrid = QtWidgets.QGridLayout(self.statusBar)
        self.progressBar = QtWidgets.QProgressBar()
        self.progressBar.setVisible(False)
        self.progressBar.setOrientation(QtCore.Qt.Horizontal)
        self.progressBarSizePolicy = self.progressBar.sizePolicy()
        self.progressBarSizePolicy.setRetainSizeWhenHidden(True)
        self.progressBarSizePolicy.setHorizontalPolicy(
            QtWidgets.QSizePolicy.Expanding)
        self.progressBar.setSizePolicy(self.progressBarSizePolicy)
        self.logBox = QtWidgets.QTextEdit(QtCore.QTime.currentTime().toString("hh:mm:ss")+\
                                    "\u00A0\u00A0\u00A0\u00A0Initialized!")
        self.logCursor = QtGui.QTextCursor(self.logBox.document())
        self.logCursor.movePosition(QtGui.QTextCursor.End)
        self.logBox.setTextCursor(self.logCursor)
        self.logBox.ensureCursorVisible()
        self.logBox.setAlignment(QtCore.Qt.AlignTop)
        self.logBox.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.logBoxScroll = QtWidgets.QScrollArea()
        self.logBoxScroll.setWidget(self.logBox)
        self.logBoxScroll.setWidgetResizable(True)
        self.logBoxScroll.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.statusGrid.addWidget(self.logBoxScroll, 0, 0)
        self.statusGrid.setAlignment(self.progressBar, QtCore.Qt.AlignRight)

        self.canvasFrameGrid.addWidget(self.canvas, 1)
        self.topSplitter.addWidget(self.canvasFrame)
        self.topSplitter.addWidget(self.controlPanel)
        self.topSplitter.setSizes([800, 400])
        self.topSplitter.setStretchFactor(0, 1)
        self.topSplitter.setStretchFactor(1, 1)
        self.topSplitter.setCollapsible(0, False)
        self.topSplitter.setCollapsible(1, False)
        self.mainSplitter.addWidget(self.topSplitter)
        self.mainSplitter.addWidget(self.statusBar)
        self.mainSplitter.setSizes([800, 100])
        self.mainSplitter.setStretchFactor(0, 1)
        self.mainSplitter.setStretchFactor(1, 1)
        self.mainSplitter.setCollapsible(0, False)
        self.mainSplitter.setCollapsible(1, False)
        self.setCentralWidget(self.mainSplitter)
Exemple #22
0
 def show_modified(self):
     if hasattr(self, 'fdct_worker'):
         Ct = self.fdct_worker.vect(self.curvelet_structure.structure)
         self.image_modified = pilImage.fromarray(
             self.fdct_worker.inv(Ct)).convert('L')
         self.image_diff = pilImage.eval(
             pilChops.difference(self.image, self.image_modified),
             lambda x: x * self.difference_scale_factor_slider.value())
         if not hasattr(self, 'canvas_modified'):
             self.canvas_modified = canvas.Canvas(self, self.canvas_config)
             self.canvas_diff = canvas.Canvas(self, self.canvas_config)
             self.canvas_modified.set_photo(
                 self.image_worker.pilImg2qPixImg(self.image_modified))
             self.canvas_diff.set_photo(
                 self.image_worker.pilImg2qPixImg(self.image_diff))
             self.canvas.WHEEL_EVENT.connect(
                 self.canvas_modified.wheelEvent)
             self.canvas.WHEEL_EVENT.connect(self.canvas_diff.wheelEvent)
             self.canvas.verticalScrollBar().valueChanged.connect(
                 self.canvas_modified.verticalScrollBar().setValue)
             self.canvas.horizontalScrollBar().valueChanged.connect(
                 self.canvas_modified.horizontalScrollBar().setValue)
             self.canvas.verticalScrollBar().rangeChanged.connect(
                 self.canvas_modified.verticalScrollBar().setRange)
             self.canvas.horizontalScrollBar().rangeChanged.connect(
                 self.canvas_modified.horizontalScrollBar().setRange)
             self.canvas_modified.verticalScrollBar().valueChanged.connect(
                 self.canvas.verticalScrollBar().setValue)
             self.canvas_modified.horizontalScrollBar(
             ).valueChanged.connect(
                 self.canvas.horizontalScrollBar().setValue)
             self.canvas_modified.verticalScrollBar().rangeChanged.connect(
                 self.canvas.verticalScrollBar().setRange)
             self.canvas_modified.horizontalScrollBar(
             ).rangeChanged.connect(
                 self.canvas.horizontalScrollBar().setRange)
             self.canvas.verticalScrollBar().valueChanged.connect(
                 self.canvas_diff.verticalScrollBar().setValue)
             self.canvas.horizontalScrollBar().valueChanged.connect(
                 self.canvas_diff.horizontalScrollBar().setValue)
             self.canvas.verticalScrollBar().rangeChanged.connect(
                 self.canvas_diff.verticalScrollBar().setRange)
             self.canvas.horizontalScrollBar().rangeChanged.connect(
                 self.canvas_diff.horizontalScrollBar().setRange)
             self.canvas_diff.verticalScrollBar().valueChanged.connect(
                 self.canvas.verticalScrollBar().setValue)
             self.canvas_diff.horizontalScrollBar().valueChanged.connect(
                 self.canvas.horizontalScrollBar().setValue)
             self.canvas_diff.verticalScrollBar().rangeChanged.connect(
                 self.canvas.verticalScrollBar().setRange)
             self.canvas_diff.horizontalScrollBar().rangeChanged.connect(
                 self.canvas.horizontalScrollBar().setRange)
             self.canvas_modified.WHEEL_EVENT.connect(
                 self.canvas.wheelEvent)
             self.canvas_modified.WHEEL_EVENT.connect(
                 self.canvas_diff.wheelEvent)
             self.canvas_diff.WHEEL_EVENT.connect(self.canvas.wheelEvent)
             self.canvas_diff.WHEEL_EVENT.connect(
                 self.canvas_modified.wheelEvent)
             self.canvasFrameGrid.addWidget(self.canvas_modified, 1)
             self.canvasFrameGrid.addWidget(self.canvas_diff, 1)
             self.canvas.fit_canvas()
             self.canvas_modified.fit_canvas()
             self.canvas_diff.fit_canvas()
             self.update_log('[SUCCESS] Modified image showed!')
         else:
             self.canvas_modified.set_photo(
                 self.image_worker.pilImg2qPixImg(self.image_modified))
             self.canvas_diff.set_photo(
                 self.image_worker.pilImg2qPixImg(self.image_diff))
             self.update_log('[SUCCESS] Modified image updated!')
         self.show_modified_image_button.setEnabled(False)
     else:
         self.update_log(
             '[ERROR] Please load the curvelet transform first!')
Exemple #23
0
import canvas

if (1 == 0):
    cv = canvas.Canvas()
    cv.printme()

if (1 == 0):
    cv = canvas.Canvas()
    cv.draw_hlne(1, 0, 1, 1)
    cv.printme()

#     def draw_triangle(self, x_top, y_top, height, y0, y1, value = 1)
if (0 == 1):
    cv = canvas.Canvas()
    cv.draw_triangle(x_top=0, y_top=0, height=5, y0=0, y1=5, value=1)
    cv.printme()

#     def draw_triangle(self, x_top, y_top, height, y0, y1, value = 1)
if (0 == 1):
    cv = canvas.Canvas()
    cv.draw_triangle(x_top=0, y_top=5, height=5, y0=0, y1=5, value=1)
    cv.draw_triangle(x_top=0, y_top=0, height=5, y0=0, y1=5, value=1)
    cv.printme()

#     def draw_triangle(self, x_top, y_top, height, y0, y1, value = 1)
if (1 == 0):
    cv = canvas.Canvas()
    cv.draw_rectangle(x_top=0, y_top=0, height=5, width=2)
    cv.printme()

#     def draw_triangle(self, x_top, y_top, height, y0, y1, value = 1)
Exemple #24
0
pygame.display.set_caption('Shoe generator')
clock = pygame.time.Clock()
pygame.init()

gameDisplay = pygame.display.set_mode((1250, 600),
                                      pygame.DOUBLEBUF)  # Create display
controller = events.EventManager()

cGAN = network.CGAN().cuda()

# Load cGAN parameters
checkpoint = torch.load(constants.NETWORK_FILE_NAME)
cGAN.generator.load_state_dict(checkpoint['g_state_dict'])
cGAN.discriminator.load_state_dict(checkpoint['d_state_dict'])

draw_canvas = canvas.Canvas(512, 20, 44, gameDisplay, evManager=controller)
render_canvas = canvas.Preview(512,
                               1250 - 20 - 512,
                               44,
                               gameDisplay,
                               draw_canvas,
                               cGAN,
                               evManager=controller)

# Define input box here so python doesnt immediatly put it in garbage after creating it
input_box = False


def input_func():
    global input_box
    input_box = gui.InputBox(625 - 240,
Exemple #25
0
def main():
	"""
	Conway's Game of Life.
	"""
	
	(width, height) = (800, 600)
	cell_size = 16
	fps = 60
	update_rate = 500
	update_event_id = 24
	animation = True
	starting_cells = 1000

	try:
		f = open("init.txt", 'r')
		for line in f:
			param = line.split("=")
			if param[0] == "width":
				width = int(param[1])
			elif param[0] == "height":
				height = int(param[1])
			elif param[0] == "cellsize":
				cell_size = int(param[1])
			elif param[0] == "fps":
				fps = int(param[1])
			elif param[0] == "updaterate":
				update_rate = int(param[1])
			elif param[0] == "startingcells":
				starting_cells = int(param[1])
	except:
		f = open("init.txt", "w")
		f.write(
			"width=800\n" +
			"height=600\n" +
			"cellsize=16\n" +
			"fps=60\n" +
			"updaterate=500\n" +
			"startingcells=1000\n"
		)
	
	grid_size = (width/cell_size, height/cell_size)
	grid = g.Grid(grid_size)
	canvas = c.Canvas((width, height), cell_size, grid_size)
	events = e.GameEvent(update_event_id, fps, update_rate, grid, canvas)
	
	message = "none"
	params = []
	pause = False
				

	grid.randomize_cells(starting_cells)

	pygame.init()

	# main game loop
	while message != "quit":
		message, params = events.run()
		
		if message == "update grid" and not pause:
			grid.update_cells()
		elif message == "pause":
			pause = True
		elif message == "resume":
			pause = False
		elif message == "place cell":
			grid.add_cell(*params)
		elif message == "remove cell":
			grid.remove_cell(*params)
		else:
			pass

		canvas.draw_grid(grid, *params)
Exemple #26
0
# Preliminary Declarations
import os
import random
import player
import canvas
import secretboss
from mrsun import Mr_Sun
from painting import Painting

player = player.Player("")
canvas = canvas.Canvas()
secret_boss = secretboss.Secret_Boss()
al = Mr_Sun()
painting = Painting()

min_roll = 1
max_roll = 6
roll_it = False
enable_secret = False

# Game Begins
al.cool_face()
print("""
> Howdy there! I'm the sun, but my friends call me Al, and you can too.
> Welcome to Paint Attack!
> You're a just humble artist who recently has been struck with a bad case of artist's block.
> But today's the day you finally fight back and create another masterpiece.
> The object of the game is to work on your piece (i.e. fight your canvas) until it's completed.
""")

player_name = raw_input("> Soooooooo... what's your name? ")
Exemple #27
0
logger = logging.getLogger(__name__)
logging.getLogger().addHandler(logging.StreamHandler())

def read_canvas_api_key():
    with open('canvas-api-key.txt', 'r') as api_key_file:
        api_key = api_key_file.readline().strip()
        return api_key


def read_telegram_api_key():
    with open('telegram-api-key.txt', 'r') as api_key_file:
        api_key = api_key_file.readline().strip()
        return api_key

sub_manager = subscribermanager.SubscriberManager('subscribers.txt')
announcement_reader = canvas.Canvas(fhict_canvas_url, read_canvas_api_key())

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
Exemple #28
0
    '-r',
    '24',  # frames per second
    '-i',
    '-',  # The imput comes from a pipe
    '-an',  # Tells FFMPEG not to expect any audio
    '-vcodec',
    'mpeg4',
    'my_output_videofile.mp4'
]

pipe = sp.Popen(command, stdin=sp.PIPE, stderr=sp.PIPE)

# fourcc = VideoWriter_fourcc(*'mp4v')
# video  = VideoWriter('./triangle.mp4', fourcc, float(FPS), (width, height))

my_canvas = canvas.Canvas(width, height)

vertices = np.array([[200, 200], [300, 300], [400, 200], [200, 200]])
my_triangle = polygon.Polygon(vertices)

for frameNum in range(0, FPS * seconds):
    # blank canvas to redraw the triangle in its new state
    my_canvas.image = np.array(my_canvas.background)

    # draw the triangle
    my_canvas.draw(my_triangle)
    image = my_canvas.image

    # transform the triangle object
    if frameNum < FPS * seconds / 3:
        my_triangle.translate(np.array([2, 2]))
Exemple #29
0
def bmp(request, comp=False):
    event, event1 = calcGet(request.GET, comp)
    response = HttpResponse(mimetype='image/bmp')
    p = canvas.Canvas(response)

    mx, my = 0, 0
    p.translate(375, 375)
    R = 360

    p.pen = p.pens[1.5]
    p.setStrokeColorRGB(1, 0, 0)
    #p.setLineWidth(0.5)
    p.circle(mx, my, R)
    p.setStrokeColorRGB(0, 0, 0)
    p.circle(mx, my, 1.01 * R)
    p.circle(mx, my, 0.15 * R)
    p.circle(mx, my, 0.85 * R)
    p.circle(mx, my, 0.7 * R)

    for b in bhavas:
        i = int(((event[b] - event["I"]) / 3600 + 450) % 360)
        p.rotate(i)
        p.line(0.15 * R, 0, 0.7 * R, 0)
        p.rotate(-i)

    h = 35
    tp = 820
    bits = open("astro/chart/words.bmp", 'rb').read()
    rashiw = [
        canvas.readBits(bits, 0, tp - (y + 1) * h, 120, tp - y * h)
        for y in range(12)
    ]
    h = 26.5
    tp = 400
    grahaw = [
        canvas.readBits(bits, 0, tp - (y + 1) * h, 80, tp - y * h)
        for y in range(12)
    ]
    tp = 815
    h = 24
    nktw = [
        canvas.readBits(bits, 130, tp - (y + 1) * h, 300, tp - y * h)
        for y in range(27)
    ]

    for a in range(0, 360, 30):
        i = a + 90 - event["I"] / 3600
        call(p, [
            ("rotate", (i, )),
            ("line", (
                0.7 * R,
                0,
                0.85 * R,
                0,
            )),
            ("rotate", (15, )),
            ('translate', (0.75 * R, 0)),
            [('rotate', (90 * ifDownHalf(i + 15), )),
             ('addPoints', (rashiw[a / 30], ))],
        ])
    for a in range(108):
        i = a * 10.0 / 3 + 90 - event["I"] / 3600
        call(p, [
            ("rotate", (i, )),
            ("line", (
                0.85 * R,
                0,
                (0.9 + (a % 4 == 0 and 0.1)) * R,
                0,
            )),
        ])
        if not a % 4 == 0:
            continue
        call(p, [
            ("rotate", (i + 20.0 / 3, )),
            ('translate', (0.95 * R + 3 * ifDownHalf(i + 20.0 / 3), 0)),
            [('rotate', (90 * ifDownHalf(i), )),
             ('addPoints', (nktw[a / 4], ))],
        ])

    p.setStrokeColorRGB(0, 0, 1)
    p.pen = p.pens[3]
    for ndx, plnt in enumerate(wheel.planets):
        i = (event[plnt] - event["I"]) / 3600 + 90
        call(
            p,
            [
                ("rotate", (i, )),
                ("line", (
                    0.8 * R,
                    0,
                    0.85 * R,
                    0,
                )),
                ('translate', (0.65 * R, 0)),  #+ 3 * ifDownHalf(i)
                ("rotate", (-i, )),
                ('addPoints', (grahaw[ndx], )),
            ])

    if comp:
        p.setStrokeColorRGB(1, 0, 0)
        p.pen = p.pens[3]
        for ndx, plnt in enumerate(wheel.planets):
            i = (event1[plnt] - event["I"]) / 3600 + 90
            call(
                p,
                [
                    ("rotate", (i, )),
                    ("line", (
                        0.8 * R,
                        0,
                        0.85 * R,
                        0,
                    )),
                    ('translate', (0.65 * R, 0)),  #+ 3 * ifDownHalf(i)
                    ("rotate", (-i, )),
                    ('addPoints', (grahaw[ndx], )),
                ])

    p.pen = p.pens[2]
    if 'orb' in event:
        orb = eval(event['orb'])
    else:
        orb = seiyo_trans if comp else seiyo
    f = orb.getAspectColor
    #f=seiyo.getAspectColor
    for p1 in range(len(sinhala_planets_short)):
        for p2 in range(p1 + 1, len(sinhala_planets_short)):
            ps = sinhala_planets_short.keys()[p1], sinhala_planets_short.keys(
            )[p2]
            a = abs(event[ps[0]] - event1[ps[1]]) / 3600.00
            clr = f(ps[0], ps[1], a)
            if len(clr):
                CC = getattr(colors, clr)
                p.setStrokeColorRGB(*CC.rgb())
                pp = polar2xy(0.6 * R, (event[ps[0]]-event["I"])/3600+90), \
                     polar2xy(0.6 * R, (event1[ps[1]]-event["I"])/3600+90)
                p.line(pp[0][0], pp[0][1], pp[1][0], pp[1][1])

    p.save()
    return response
Exemple #30
0
def circlechart(request, key=None):
    event = calc(key) if key else calcGet(request.GET)
    response = HttpResponse(mimetype='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Horoscope.pdf'  #%re.sub(r'\s',"_",event['name']))#.encode('utf-8','ignore')
    p = canvas.Canvas(response)  #MyCanvas(response)#
    mx, my = 0, 0
    p.translate(298, 600)
    R = 200

    p.setStrokeColorRGB(1, 0, 0)
    p.setLineWidth(0.5)
    p.circle(mx, my, R)
    p.setStrokeColorRGB(0, 0, 0)
    p.circle(mx, my, 1.01 * R)
    p.circle(mx, my, 0.15 * R)
    p.circle(mx, my, 0.85 * R)
    p.circle(mx, my, 0.7 * R)

    pdfmetrics.registerFont(
        TTFont('kaputa', r"astro/chart/kaputa.ttf")
    )  #r'D:\kendra-python\workspace\mysitedjando_101226\mysite\astro\chart\kaputa.ttf'))
    p.setFont('kaputa', 12)
    for b in bhavas:
        i = int(((event[b] - event["I"]) / 3600 + 450) % 360)
        p.rotate(i)
        p.line(0.15 * R, 0, 0.7 * R, 0)
        p.rotate(-i)

    for a in range(0, 360, 30):
        i = a + 90 - event["I"] / 3600
        call(p, [
            ("rotate", (i, )),
            ("line", (
                0.7 * R,
                0,
                0.85 * R,
                0,
            )),
            ("rotate", (15, )),
            ('translate', (0.775 * R + 3 * ifDownHalf(i + 15), 0)),
            [('rotate', (90 * ifDownHalf(i + 15), )),
             ('drawCentredString', (0, 0, getKaputa(sinhala_rashis[a / 30])))],
        ])
    for a in range(108):
        i = a * 10.0 / 3 + 90 - event["I"] / 3600
        call(p, [
            ("rotate", (i, )),
            ("line", (
                0.85 * R,
                0,
                (0.9 + (a % 4 == 0 and 0.1)) * R,
                0,
            )),
        ])
        if not a % 4 == 0:
            continue
        call(p, [
            ("rotate", (i + 20.0 / 3, )),
            ('translate', (0.95 * R + 3 * ifDownHalf(i + 20.0 / 3), 0)),
            [('rotate', (90 * ifDownHalf(i), )),
             ('drawCentredString',
              (0, 0, getKaputa(sinhala_nakshatra_short[a / 4])))],
        ])

    p.setStrokeColor(colors.blue)
    p.setLineWidth(1)
    for plnt in sinhala_planets_short:
        i = (event[plnt] - event["I"]) / 3600 + 90
        call(
            p,
            [
                ("rotate", (i, )),
                ("line", (
                    0.8 * R,
                    0,
                    0.85 * R,
                    0,
                )),
                #("rotate",(ifLeftHalf(i)*5,)),
                ('translate', (0.65 * R, 0)),  #+ 3 * ifDownHalf(i)
                ("rotate", (-i, )),
                (funcOn(i),
                 (0, funcOn(i) != "drawCentredString"
                  and -4, getKaputa(readUnicode(sinhala_planets_short[plnt]))))
            ])

    p.setLineWidth(0.75)
    for p1 in range(len(sinhala_planets_short)):
        for p2 in range(p1 + 1, len(sinhala_planets_short)):
            ps = sinhala_planets_short.keys()[p1], sinhala_planets_short.keys(
            )[p2]
            a = abs(event[ps[0]] - event[ps[1]]) / 3600.00
            clr = seiyo.getAspectColor(ps[0], ps[1], a)
            if len(clr):
                p.setStrokeColor(getattr(colors, clr))
                pp = map(
                    lambda ps: polar2xy(0.6 * R,
                                        (event[ps] - event["I"]) / 3600 + 90),
                    ps)
                p.line(pp[0][0], pp[0][1], pp[1][0], pp[1][1])

    p.showPage()
    p.save()
    return response