Beispiel #1
0
    def test_set_line_diagonals(self):
        c = 10
        start_idx = 100
        end_idx = 200
        top_left = Pixel(x=start_idx, y=start_idx, c_flag=c)
        bottom_left = Pixel(x=start_idx, y=end_idx, c_flag=c)
        top_right = Pixel(x=end_idx, y=start_idx, c_flag=c)
        bottom_right = Pixel(x=end_idx, y=end_idx, c_flag=c)

        with self.subTest("diagonal test"):
            result = Canvas(width=500,
                            height=500).set_line(top_left, bottom_right)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=i, y=i).c_flag, c)

        with self.subTest("diagonal test"):
            result = Canvas(width=500,
                            height=500).set_line(bottom_right, top_left)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=i, y=i).c_flag, c)

        with self.subTest("botleft to topright test"):
            result = Canvas(width=500,
                            height=500).set_line(bottom_left, top_right)
            for i in range(start_idx, end_idx):
                self.assertEqual(
                    result.get_pixel(x=i, y=end_idx - i).c_flag, c)

        with self.subTest("topright to botleft test"):
            result = Canvas(width=500,
                            height=500).set_line(top_right, bottom_left)
            for i in range(start_idx, end_idx):
                self.assertEqual(
                    result.get_pixel(x=i, y=end_idx - i).c_flag, c)
Beispiel #2
0
def main():

    # Uncomment on first use of program
    #nltk.download('stopwords')
    #nltk.download('punkt')
    #nltk.download('averaged_perceptron_tagger')
    #nltk.download('wordnet')

    if len(sys.argv) > 1:
        name = sys.argv[1]
    else:
        name = 'anna'

    if path.exists('pickles/' + name + '.pkl'):
        convo = pickle.load(open('pickles/' + name + '.pkl', 'rb'))
        painting = Canvas(name, convo)

    elif path.exists('../convos/' + name + '.txt'):
        convo = Convobj('../convos/' + name + '.txt')
        convo.save(name)
        painting = Canvas(name, convo)

    else:
        print('Did not locate a ' + name +
              ' txt or pkl file. Please try again.')
        exit()
Beispiel #3
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.defaultVideoCapture = VideoCapture(0)

        self.webcamCanvas = Canvas(self.parent, self.defaultVideoCapture)
        self.maskCanvas = Canvas(self.parent, self.defaultVideoCapture)

        self.lowHueSlider = Slider(self.parent, "Low Hue", 10, 0, 180)
        self.highHueSlider = Slider(self.parent, "High Hue", 25, 0, 180)
        self.lowSaturationSlider = Slider(self.parent, "Low Saturation", 100,
                                          0, 255)
        self.highSaturationSlider = Slider(self.parent, "High Saturation", 255,
                                           0, 255)
        self.lowValueSlider = Slider(self.parent, "Low Value", 20, 0, 255)
        self.highValueSlider = Slider(self.parent, "High Value", 255, 0, 255)

        self.button = tk.Button(self.parent,
                                text="Get histogram",
                                fg="blue",
                                command=self.drawHSVHHistogram)
        self.button.pack(anchor=tk.CENTER)

        self.updateFrame()
Beispiel #4
0
    def test_create_empty_matrix(self):
        expected = [['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']]
        c = Canvas(3, 3)
        self.assertEqual(expected, c.area)

        c = Canvas(3, 4)
        expected.append(['O', 'O', 'O'])
        self.assertEqual(expected, c.area)
 def test_drawline_inverted_ok(self):
     canvas = Canvas()
     canvas.create(8, 4)
     canvas.draw_line(5, 1, 5, 3)
     canvas2 = Canvas()
     canvas2.create(8, 4)
     canvas2.draw_line(5, 3, 5, 1)
     self.assertTrue((canvas.data == canvas2.data).all())
Beispiel #6
0
 def test_vertical_line(self):
     c = Canvas(4, 4)
     expected = [['O', 'O', 'O', 'O'], ['O', 'W', 'O', 'O'],
                 ['O', 'W', 'O', 'O'], ['O', 'O', 'O', 'O']]
     c.vertical_line(1, 1, 2, 'W')
     self.assertEqual(expected, c.area)
     d = Canvas(4, 4)
     d.vertical_line(1, 2, 1, 'W')
     self.assertEqual(expected, d.area)
Beispiel #7
0
 def test_horizontal_line(self):
     c = Canvas(4, 4)
     expected = [['O', 'O', 'O', 'O'], ['O', 'W', 'W', 'O'],
                 ['O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O']]
     c.horizontal_line(1, 2, 1, 'W')
     self.assertEqual(expected, c.area)
     d = Canvas(4, 4)
     d.horizontal_line(2, 1, 1, 'W')
     self.assertEqual(expected, d.area)
Beispiel #8
0
def run():
    args = get_args()
    with File(args.input_file, 'r') as hist_file:
        x, y, xerr, yerr = get_xy_pts(hist_file['mass_1323'], (100, np.inf))

    pltdir = args.output_directory
    if not os.path.isdir(pltdir):
        os.mkdir(pltdir)
    with Canvas(f'{pltdir}/nothings.pdf') as can:
        can.ax.errorbar(x, y, yerr=yerr, fmt='.')
        can.ax.set_yscale('log')

    ly, lyerr = np.log(y), np.log1p(yerr / y)
    with Canvas(f'{pltdir}/nothings_log.pdf') as can:
        can.ax.errorbar(x, ly, yerr=lyerr, fmt='.')

    get_gp = get_fancy_gp
    initial = [30, 0.56, 100, 1, 1]
    get_gp = get_linear_gp
    # get_gp = get_simple_gp
    initial = [0.1, 10]
    bounds = [(1e-5, 200), (1, 100)]
    # get_gp = get_composite_gp
    # initial = [30.0, 1.0, 0.001, 2000.0]
    # bounds = [(0.1, 100), (-100, 100), (0.001, 10), (200, 8000)]

    ln_prob = LogLike(x, ly, lyerr, get_gp)
    result = minimize(
        ln_prob,
        initial,  #method = 'Nelder-Mead',
        # jac=ln_prob.grad
    )
    print(result)
    best_pars = result.x
    gp = get_gp(best_pars)
    gp.compute(x, lyerr)
    t = np.linspace(np.min(x), np.max(x), 500)
    mu, cov = gp.predict(ly, t)
    std = np.sqrt(np.diag(cov))

    mu_x, cov_x = gp.predict(ly, x)
    signif = (ly - mu_x) / np.sqrt(np.diag(cov_x) + lyerr**2)

    with RatioCanvas(f'{pltdir}/fits_log.pdf') as can:
        can.ax.errorbar(x, ly, yerr=lyerr, fmt='.')
        can.ax.plot(t, mu, '-r')
        can.ax.fill_between(t,
                            mu - std,
                            mu + std,
                            facecolor=(0, 1, 0, 0.5),
                            zorder=5,
                            label=r'GP error = $1\sigma$')
        can.ratio.stem(x, signif, markerfmt='.', basefmt=' ')
Beispiel #9
0
    def get(self) -> Tuple[Canvas, np.ndarray]:

        cube_center = np.array([10, 0, 0])
        edge_length = 3.2
        cube = Cube(cube_center, edge_length)
        cube.rotate(np.array([0, 0, 1]), cube.cube_center, np.radians(15))

        camera = np.array([0, 2, 4])
        canvas_distance = 3
        view_direction = cube_center - camera

        canvas = Canvas(camera, view_direction, canvas_distance)

        horizon = np.array([0, -1, 0])
        canvas.set_horizon(horizon)

        angles_h = np.radians(np.array([-29, 29]))
        angles_v = np.radians(np.array([-25, 25]))
        canvas.set_angles(angles_h, angles_v)

        img_width = 600
        img_height = 400
        canvas.set_pixels_size(img_width, img_height)

        triangles = cube.get_triangles()

        return (
            canvas,
            triangles,
        )
Beispiel #10
0
def init_assignment(ass, name):

    assignment_dir = dir_name(ass)
    os.mkdir(assignment_dir)

    course_dir = config_dir(".", "canvas.yaml")
    with open(os.path.join(course_dir, "canvas.yaml"), "r") as f:
        conf = yaml.load(f)
    course_id = conf['id']

    #    with open(os.path.join(course_dir, "token"), "r") as f:
    #        api_token = f.read().strip()

    assignment = Canvas().course(id=course_id).assignment(name=ass)

    subs = assignment.submissions()

    # get the ids of the students in
    # group set <assignment name>, group <instructor name>
    #members = get_members(name, assignment, course_id, api_token)
    #student_ids  = [m['id'] for m in members]

    #subs = [sub for sub in subs if sub['user_id'] in student_ids]
    make_sub_dirs(assignment_dir, subs)

    return subs
Beispiel #11
0
    def __init__(self):
        # Initialize tk root
        self.master = tk.Tk()
        self._init_master()

        # Initialize canvas
        self.canvas = Canvas(self.master)
def ShowPointsAtMerge(left, right, merge):
    """Função Criada para exibir os pontos durante o Merge

    Parameters:
        left (Array): Lista de Pontos pertecente ao fecho esquerdo
        right (Array): Lista de Pontos pertecente ao fecho direito
        merge (Array): Lista de Pontos pertecente ao fecho combinado

    """
    canvas = Canvas(title="Exibição dos Merge",
                    width=(min_x[0] + max_x[0]),
                    height=(min_y[1] + max_y[1]),
                    inverted=False)

    for p in left:
        canvas.DrawPoint(p, fill='blue')

    for p in right:
        canvas.DrawPoint(p, fill='green')

    firstPoint = None
    lastPoint = None
    for p in merge:
        canvas.DrawPoint(p)

        if (lastPoint == None):
            firstPoint = p
        else:
            canvas.DrawLine(lastPoint, p)

        lastPoint = p

    canvas.DrawLine(lastPoint, firstPoint)

    canvas.Show()
def ShowPointsWithPolygon(points, polygon):
    """Função Criada para exibir os pontos

    Parameters:
        points (Array): Lista de Pontos

    """
    canvas = Canvas(title="Exibição dos Pontos",
                    width=(min_x[0] + max_x[0]),
                    height=(min_y[1] + max_y[1]),
                    inverted=False)

    for p in points:
        canvas.DrawPoint(p, fill='black')

    firstPoint = None
    lastPoint = None
    for p in polygon:
        canvas.DrawPoint(p)

        if (lastPoint == None):
            firstPoint = p
        else:
            canvas.DrawLine(lastPoint, p)

        lastPoint = p

    canvas.DrawLine(lastPoint, firstPoint)

    canvas.Show()
Beispiel #14
0
def main(**args):
    ventana = Ventana((800, 600))
    canvas = Canvas((800, 450), (0, 150))
    particula = Particula()
    canvas.add_particula(particula, 0)
    ventana.add_canvas(canvas, "0")
    ventana.run()
Beispiel #15
0
    def init_docks(self):
        '''初始化的一部分,执行浮动子窗口和canvas的初始化,单列一个函数以提升可读性'''
        self.database_widget = DatabaseWidget()
        self.dataset_tree_dock.setWidget(self.database_widget)
        self.menuView.addAction(self.dataset_tree_dock.toggleViewAction())

        self.series_list_widget = SeriesListWidget()
        self.series_list_dock.setWidget(self.series_list_widget)
        self.menuView.addAction(self.series_list_dock.toggleViewAction())

        self.annotations_list_widget = AnnotationsListWidget()
        self.annotations_list_dock.setWidget(self.annotations_list_widget)
        self.menuView.addAction(self.annotations_list_dock.toggleViewAction())

        self.label_edit_widget = LabelEditWidget()
        self.label_edit_dock.setWidget(self.label_edit_widget)
        self.menuView.addAction(self.label_edit_dock.toggleViewAction())

        self.canvas_area = QScrollArea()
        # TODO: 原理?看了文档还是不懂,需要进行更多研究
        self.canvas_area.setWidgetResizable(True)
        self.scroll_bars = {
            Qt.Vertical: self.canvas_area.verticalScrollBar(),
            Qt.Horizontal: self.canvas_area.horizontalScrollBar()
        }
        self.canvas_widget = Canvas()
        self.canvas_area.setWidget(self.canvas_widget)
        self.setCentralWidget(self.canvas_area)
Beispiel #16
0
 def __init__(self, client):
     super(Window, self).__init__()
     self.canvas = Canvas(self, client)
     self.setCentralWidget(self.canvas)
     self.setGeometry(300, 300, 250, 150)
     self.setWindowTitle('PyQt')
     self.show()
Beispiel #17
0
 def test_set_line_out_of_bounds_low(self):
     c = 10
     out_start = Pixel(x=-50, y=-50, c_flag=c)
     end = Pixel(x=50, y=50, c_flag=c)
     result = Canvas(width=500, height=500).set_line(out_start, end)
     for i in range(0, 51):
         self.assertEqual(result.get_pixel(x=i, y=i).c_flag, c)
Beispiel #18
0
    def __init__(self, master):
        super().__init__(master)

        self.speed = 1
        self.is_paused = True

        self.machines = [ShortestProcessingTime(), Prediction(), RoundRobin()]

        self.name_to_machine = {
            "{} {}".format(m.name, m.id): m
            for m in self.machines
        }
        self.name_to_machine["All machines"] = self.machines

        self.canvas = Canvas(self, self, machines=self.machines)

        self.make_timeline()
        self.make_taskmanager()
        self.show_tools = ShowTools(tk.Toplevel(self), self)
        self.graphs = []

        self.canvas.grid(row=1, column=1)
        self.show_tools.grid(row=1, column=1)

        self.pack()
Beispiel #19
0
  def __init__(self, cfg_game, screen):

    # arguments
    self.cfg_game = cfg_game
    self.screen = screen

    # colors
    self.color_bag = ColorBag()

    # canvas
    self.canvas = Canvas(self.screen)

    # game logic
    self.game_logic = MenuGameLogic(self)

    # actual up down click
    self.ud_click = 0
    self.lr_click = 0

    # click
    self.click = False

    # selection
    self.button_state = 0

    # button dict, selection: button in canvas
    self.button_state_dict = {'start_button': 0, 'help_button': 1, 'end_button': 2}

    # set button state
    self.button_state = self.button_state_dict['start_button']
Beispiel #20
0
    def test_scale(self):
        # SETUP
        expected_report = """\
create_line
    0
    0
    100
    0
    fill='black'
    pensize=1
create_line
    100
    0
    100
    150
    fill='black'
    pensize=1
"""

        # EXEC
        t = MockTurtle(canvas=Canvas())
        t.screen.xscale = 100.0
        t.screen.yscale = 50
        t.fd(1)
        t.right(90)
        t.fd(3)
        report = t.report

        # VERIFY
        self.assertEqual(expected_report.splitlines(), report)
Beispiel #21
0
    def __init__(self):
        self.gladefile = os.path.join(__location__, "pt3.glade")
        self.builder = Gtk.Builder()
        self.builder.add_from_file(self.gladefile)

        #Create & Link canvas
        self.canvas_box = self.builder.get_object("canvasBox")
        self.canvas = Canvas()
        self.watcher = VarWatcher(self.canvas)
        self.canvas.show()
        self.canvas_box.pack_start(self.canvas, True, True, 0)

        # Automatically connect signals to functions defined above
        # as specified in the glade file
        self.builder.connect_signals(self)

        # Get the main window
        self.window = self.builder.get_object("ptWindow")
        self.window.show()

        self.window.connect("key-press-event", self.key_press)

        #Ctrl+C handling
        def handler(signum, frame):
            self.log.warning("INTERRUPT: exiting gracefully")
            self.window_destroy()

        signal.signal(signal.SIGTERM, handler)
        signal.signal(signal.SIGINT, handler)

        #Fire up the main window
        self.log.info("Launching GUI. Welcome to PT3! Press %s for help" %
                      conf.key_binds["help"])
        Gtk.main()
Beispiel #22
0
def main(filename):
    with open(filename) as json_file:
        data = json.load(json_file)
    if "signals" not in data:
        raise ValueError("Input file malformed. Missing 'signals'.")
    if "canvas" not in data:
        raise ValueError("Input file malformed. Missing 'canvas'.")

    signals = deserialize(data["signals"])

    sc = SignalCollection()
    for signal in signals:
        sc.add(signal)

    until_time = 600
    if "time" in data:
        until_time = data["time"]

    while sc.tick(until_time):
        continue

    cvs = Canvas(data["canvas"])
    for signal in signals:
        cvs.add_signal(signal)

    cvs.render()
    cvs.show()
Beispiel #23
0
    def __init__(self):
        self.width = 800
        self.height = 600

        self.window = window.Window(self.width-1, self.height-1)
        self.window.register_event_type('on_update')
        pyglet.clock.schedule(self.update)

        self.canvas = Canvas(self.width, self.height, "Filename", "Path")

        #Create event handlers
        self.on_mouse_drag  = self.window.event(self.on_mouse_drag)
        self.on_draw  = self.window.event(self.on_draw)
        self.on_mouse_press  = self.window.event(self.on_mouse_press)
        self.on_mouse_release  = self.window.event(self.on_mouse_release)

        #Import theme
        self.cobalt = kytten.Theme(os.path.join(os.getcwd(), 'theme'), override={
            "font_size": 10
        })   
        self.bg_group = pyglet.graphics.OrderedGroup(0)
        self.fg_group = pyglet.graphics.OrderedGroup(500)

        #Create GUI
        self.mainDialog()
        self.layerDialog()
Beispiel #24
0
    def paned_window(self):
        self.panedwindow = ttk.Panedwindow(self.parent, orient = tk.HORIZONTAL)
        self.panedwindow.pack(expand = True, fill = tk.BOTH)

        self.left_pane = ttk.Frame(self.panedwindow, height = root.winfo_screenheight() - 140, relief = tk.SUNKEN)
        self.middle_pane = ttk.Frame(self.panedwindow, height = (root.winfo_screenheight() - 140), relief = tk.SUNKEN)
        self.right_pane = ttk.Frame(self.panedwindow, height = (root.winfo_screenheight() - 140), relief = tk.SUNKEN)
        self.panedwindow.add(self.left_pane, weight = 1)
        self.panedwindow.add(self.middle_pane, weight = 1) 
        self.panedwindow.add(self.right_pane, weight = 10)

        self.panedwindow_left = ttk.Panedwindow(self.left_pane, orient = tk.VERTICAL)
        self.panedwindow_left.pack(expand = True, fill = tk.BOTH)
        self.pane_projects = ttk.Frame(self.panedwindow_left, height = (root.winfo_screenheight() - 140) / 2, relief = tk.SUNKEN)
        self.pane_actions = ttk.Frame(self.panedwindow_left, height = (root.winfo_screenheight() - 140) / 2, relief = tk.SUNKEN)
        self.panedwindow_left.add(self.pane_projects, weight = 1)
        self.panedwindow_left.add(self.pane_actions, weight = 1)

        self.panewindow_middle = ttk.PanedWindow(self.middle_pane, orient = tk.VERTICAL)
        self.panewindow_middle.pack(expand = True, fill = tk.BOTH)
        self.pane_canvas = ttk.Frame(self.panewindow_middle, relief = tk.SUNKEN)
        self.pane_resources = ttk.Frame(self.panewindow_middle, width = 100, relief = tk.SUNKEN)
        self.panewindow_middle.add(self.pane_canvas, weight = 5)
        self.panewindow_middle.add(self.pane_resources, weight = 1)

        self.menubar = Menubar(self.parent)
        self.properties = Properties(self.right_pane)
        self.canvas = Canvas(self.properties)
        self.toolbar = Toolbar(self.pane_canvas, self.canvas)
        self.project_explorer = ProjectExplorer(self.pane_projects)
        self.canvas.create_Ui(self.pane_canvas)
        self.actions = Actions(self.pane_actions, self.canvas, self.properties)
        self.resources = Resources(self.pane_resources)
Beispiel #25
0
    def test_set_line_horizontal(self):
        c = 10
        start_idx = 100
        end_idx = 200
        left = Pixel(x=start_idx, y=start_idx, c_flag=c)
        right = Pixel(x=end_idx, y=start_idx, c_flag=c)

        with self.subTest("left right test"):
            result = Canvas(width=500, height=500).set_line(left, right)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=i, y=start_idx).c_flag, c)

        with self.subTest("right left test"):
            result = Canvas(width=500, height=500).set_line(right, left)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=i, y=start_idx).c_flag, c)
Beispiel #26
0
def run():
    args = parse_args()
    with File(args.input_file, 'r') as input_file:
        mass = input_file['mass']
        edges = [mass[x][1:-1] for x in mass if x.startswith('axis')]
        mass_cube = np.asarray(mass['values'])

    if not isdir(args.output_dir):
        os.mkdir(args.output_dir)

    all_pro = []
    for x_ax, y_ax in combinations(range(3), 2):
        name = '{}Vs{}.pdf'.format(FNAME_AXES[y_ax], FNAME_AXES[x_ax])
        out_path = join(args.output_dir, name)
        pro = make_2d(mass_cube, edges, x_ax, y_ax, out_path)
        logged = np.log1p(pro)
        all_pro.append(logged / logged.max())

    colors = np.stack(all_pro, 2).swapaxes(0,1)
    with Canvas(f'{args.output_dir}/colorz.pdf') as can:
        can.ax.imshow(colors, origin='lower')

    for ax in range(3):
        out_path = join(args.output_dir, '{}.pdf'.format(FNAME_AXES[ax]))
        make_1d(mass_cube, edges, ax, out_path)
Beispiel #27
0
    def test_set_line_vertical(self):
        c = 10
        start_idx = 100
        end_idx = 200
        top = Pixel(x=start_idx, y=start_idx, c_flag=c)
        bottom = Pixel(x=start_idx, y=end_idx, c_flag=c)

        with self.subTest("top down test"):
            result = Canvas(width=500, height=500).set_line(top, bottom)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=start_idx, y=i).c_flag, c)

        with self.subTest("bottom up test"):
            result = Canvas(width=500, height=500).set_line(top, bottom)
            for i in range(start_idx, end_idx):
                self.assertEqual(result.get_pixel(x=start_idx, y=i).c_flag, c)
Beispiel #28
0
 def refresh(self):
     text = self.get_displayed_text()
     c = Canvas(self.o)
     self.draw_text(text, c, self.v_scrollbar.width)
     self.v_scrollbar.draw(c)
     self.h_scrollbar.draw(c)
     self.o.display_image(c.get_image())
Beispiel #29
0
 def modify_image_if_needed(self, ui_el, image):
     n = ui_el.name
     if self.uie[n].active:
         c = Canvas(ui_el.o, base_image=image)
         self.draw_icon(c)
         image = c.get_image()
     return image
Beispiel #30
0
 def refresh(self):
     self.update_throbber_angle()
     c = Canvas(self.o)
     self.draw_throbber(c)
     if self.message:
         self.draw_message(c)
     self.o.display_image(c.get_image())