コード例 #1
0
ファイル: transformer.py プロジェクト: pbugnion/ipydataframe
 def __init__(self, df, *args, **kwargs):
     self.filters_list = FiltersList(df)
     self.new_filter = NewFilter()
     self.out_df = df
     super(TransformationsBox, self).__init__(*args, **kwargs)
     self.new_filter.register_new_filter_callback(self.add_filter)
     dlink((self.filters_list, 'out_df'), (self, 'out_df'))
コード例 #2
0
    def __init__(self, path_to_root="../", **kwargs):

        self.path_to_root = path_to_root

        # Send to ELN button.
        send_button = ipw.Button(description="Send to ELN")
        send_button.on_click(self.send_to_eln)

        # Use non-default destination.
        self.modify_settings = ipw.Checkbox(description="Update destination.",
                                            indent=False)
        self.modify_settings.observe(self.handle_output, "value")

        # Used to output additional settings.
        self._output = ipw.Output()

        # Communicate to the user if something isn't right.
        self.message = ipw.HTML()

        children = [
            ipw.HBox([send_button, self.modify_settings]),
            self._output,
            self.message,
        ]
        self.eln, msg = connect_to_eln()
        if self.eln:
            traitlets.dlink((self, "node"), (self.eln, "node"))
        else:
            self.modify_settings.disabled = True
            send_button.disabled = True
            self.message.value = f"""Warning! The access to ELN is not configured. Please follow <a href="{self.path_to_root}/aiidalab-widgets-base/notebooks/eln_configure.ipynb" target="_blank">the link</a> to configure it.</br> </br> More details: {msg}"""

        super().__init__(children=children, **kwargs)
コード例 #3
0
    def _structure_editors(self, editors):
        """Preparing structure editors."""
        if editors and len(editors) == 1:
            link((editors[0], 'structure'), (self, 'structure'))
            if editors[0].has_trait('selection'):
                link((editors[0], 'selection'), (self.viewer, 'selection'))
            if editors[0].has_trait('camera_orientation'):
                dlink((self.viewer._viewer, '_camera_orientation'),
                      (editors[0], 'camera_orientation'))  # pylint: disable=protected-access
            return editors[0]

        # If more than one editor was defined.
        if editors:
            editors_tab = ipw.Tab()
            editors_tab.children = tuple(editors)
            for i, editor in enumerate(editors):
                editors_tab.set_title(i, editor.title)
                link((editor, 'structure'), (self, 'structure'))
                if editor.has_trait('selection'):
                    link((editor, 'selection'), (self.viewer, 'selection'))
                if editor.has_trait('camera_orientation'):
                    dlink((self.viewer._viewer, '_camera_orientation'),
                          (editor, 'camera_orientation'))  # pylint: disable=protected-access
            return editors_tab
        return None
コード例 #4
0
ファイル: tool_timetravel.py プロジェクト: deathbeds/wxyz
 def __init__(self, *args, **kwargs):
     if "layout" not in kwargs:
         kwargs["layout"] = dict(
             flex="1",
             display="flex",
         )
     super().__init__(*args, **kwargs)
     T.dlink(
         (self.repo, "head_history"),
         (self.commits, "options"),
         self._update_history_options,
     )
     T.dlink(
         (self, "enabled"),
         (self.commits.layout, "display"),
         {
             True: "flex",
             False: "none"
         }.get,
     )
     T.link((self, "enabled"), (self.enable_chk, "value"))
     self._dom_classes += (f"{CSS_PREFIX}-box", )
     self.commits.observe(self._on_change_commit, "value")
     self.repo.observe(self._on_head_hash_change, "head_hash")
     self.children = [self.enable_chk, self.commits]
コード例 #5
0
    def __init__(self, **kwargs):
        self._current_view = None

        self.viewer = nglview.NGLWidget()
        self.viewer.camera = "orthographic"
        self.viewer.stage.set_parameters(mouse_preset="pymol")
        self.viewer_box = ipw.Box(
            children=(self.viewer, ),
            layout={
                "width": "auto",
                "height": "auto",
                "border": "solid 0.5px darkgrey",
                "margin": "0px",
                "padding": "0.5px",
            },
        )

        self.download = DownloadChooser(**kwargs)

        super().__init__(
            children=(self.viewer_box, self.download),
            layout={
                "width": "auto",
                "height": "auto",
                "margin": "0px 0px 0px 0px",
                "padding": "0px 0px 10px 0px",
            },
        )

        self.observe(self._on_change_structure, names="structure")

        traitlets.dlink((self, "structure"), (self.download, "structure"))
コード例 #6
0
    def __init__(self, flows, **kwargs):
        super().__init__(1, 3, grid_gap="10px", **kwargs)

        self._selector = ipywidgets.Select(
            layout=ipywidgets.Layout(height="100%", width="initial")
        )
        self._flow_widget = WorkflowWidget(layout=ipywidgets.Layout(flex="1 0 auto"))
        self._vg_widget = VersionGraftWidget(layout=ipywidgets.Layout(flex="1 0 auto"))

        self.flows = flows

        ipywidgets.link((self._selector, "value"), (self, "selected_id"))
        ipywidgets.link((self._flow_widget, "version"), (self, "selected_version"))
        traitlets.dlink(
            (self._selector, "value"),
            (self._flow_widget, "flow"),
            transform=lambda flow_id: self._flows_lookup.get(flow_id, None),
        )
        traitlets.dlink((self._flow_widget, "current_vg"), (self._vg_widget, "vg"))

        self._flow_widget.observe(
            lambda change: self.set_trait("current_flow", change["new"]), names="flow"
        )
        self._flow_widget.observe(
            lambda change: self.set_trait("current_vg", change["new"]),
            names="current_vg",
        )

        self[0, 0] = ipywidgets.VBox(
            children=[ipywidgets.HTML("<h2>Workflows</h2>"), self._selector],
            layout=ipywidgets.Layout(flex="1 0 auto"),
        )

        self[0, 1] = self._flow_widget
        self[0, 2] = self._vg_widget
コード例 #7
0
ファイル: gst_camera.py プロジェクト: akhmedov/ground-droid
 def widget(self):
     if hasattr(self, '_widget'):
         return self._widget   # cache widget, so we don't duplicate links
     from ipywidgets import Image
     from jetbot.image import bgr8_to_jpeg
     image = Image()
     traitlets.dlink((self, 'value'), (image, 'value'), transform=bgr8_to_jpeg)
     self._widget = image
     return image
コード例 #8
0
ファイル: pidgin.py プロジェクト: wd15/pidgin
 def _observe_enabled(self, change):
     for object in (Tangle, Doctest, Weave):
         name = object.__name__.lower()
         self.add_traits(**{name: traitlets.Instance(object)})
         object = object.instance()
         self.set_trait(name, object)
         object.enabled = change["new"]
         object.input = self.input
     traitlets.dlink((self, "input"), (self.tangle, "input"))
     traitlets.dlink((self, "input"), (self.weave, "input"))
コード例 #9
0
ファイル: view.py プロジェクト: xinhen/vaex
 def __init__(self, **kwargs):
     super(ViewBase, self).__init__(**kwargs)
     self.df = self.model.df
     self.progress_indicator = vw.ProgressCircularNoAnimation(size=30, width=5, height=20, color=C0, value=10.4, text='')
     self.progress_text = vw.Status(value=self.model.status_text)
     traitlets.dlink((self.model, 'status_text'), (self.progress_text, 'value'))
     self.progress_widget = v.Container(children=[self.progress_indicator, self.progress_text])
     # self.progress_widget.layout.width = "95%"
     # self.progress_widget.layout.max_width = '500px'
     # self.progress_widget.description = "progress"
     self.model.signal_grid_progress.connect(self.on_grid_progress)
コード例 #10
0
    def __init__(self, *args, **kwargs):
        notebook = kwargs.pop("notebook")

        super(DefaultNotebookView, self).__init__(*args, **kwargs)

        name = W.Text()
        kernels = W.VBox()
        cells = W.VBox()
        save = W.Button(icon="floppy-o")
        load = W.Button(icon="refresh")

        for btn in [save, load]:
            btn.layout.max_width = btn.layout.min_width = "3em"

        name.layout.flex = "1"

        # events

        save.on_click(lambda *x: notebook.save())
        load.on_click(lambda *x: notebook.load())

        def _make_children(ipynb):
            return [
                W.HTML("<code>\n{}\n</code>".format("\n".join(
                    cell.get("source", [])))) for cell in ipynb["cells"]
            ]

        T.link((notebook, "file_name"), (name, "value"))
        T.dlink((notebook, "kernels"), (kernels, "children"),
                lambda children: [c.view() for c in children])
        T.dlink((notebook, "ipynb"), (cells, "children"), _make_children)

        left = W.VBox([
            W.HBox([
                name,
                save,
                load,
            ]),
            cells,
        ])

        right = W.VBox([
            kernels,
        ])

        left.layout.flex = "1"
        right.layout.flex = "1.6"

        self.children = [
            left,
            right,
        ]
コード例 #11
0
ファイル: transformer.py プロジェクト: pbugnion/ipydataframe
 def add_transformation(self, transformation_id):
     try:
         last_child = self.children[-1]
     except IndexError:
         new_transformation = TRANSFORMATION_IDS[transformation_id](
             self.in_df)
         self.children = [new_transformation]
         self.out_df = new_transformation.out_df
         self.in_df_link.unlink()
         self.in_df_link = dlink((self, 'in_df'),
                                 (new_transformation, 'in_df'))
         self.out_df_link = dlink((new_transformation, 'out_df'),
                                  (self, 'out_df'))
コード例 #12
0
ファイル: cytoscape.py プロジェクト: zwelz3/ipyradiant
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.output_title = W.HTML("<h3>Output from Clicks</h3>")
        self.click_output_box.children = [self.output_title, self.click_output]

        T.dlink(
            (self, "show_outputs"),
            (self.click_output_box.layout, "visibility"),
            lambda x: "visible" if x else "hidden",
        )
        self.children = [
            W.HTML("<h1>Cytoscape Visualization</h1>"),
            self.cyto_widget,
        ]
コード例 #13
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.query_input = QueryInput()

        # Inherit traits with links TODO easier way?
        T.link((self.query_input.namespaces, "namespaces"),
               (self, "namespaces"))
        T.link((self.query_input.header, "dropdown_value"),
               (self, "query_type"))
        T.link((self.query_input.header, "header_value"), (self, "query_line"))
        T.link((self.query_input.body.body, "value"), (self, "query_body"))
        T.dlink((self, "query"), (self.formatted_query, "query"))

        self.children = tuple([self.query_input, self.formatted_query])
コード例 #14
0
 def __init__(self):
     print('Setting up camera')
     self.camera = Camera.instance(width=224, height=224)
     print('Set up camera')
     self.robot = Robot()
     self.completed = False
     # Collision Avoidance.
     print('Loading CA model')
     self.ca_model = torchvision.models.alexnet(pretrained=False)
     self.ca_model.classifier[6] = torch.nn.Linear(
         self.ca_model.classifier[6].in_features, 2)
     #self.ca_model.load_state_dict(torch.load('best_model_nvidia.pth'))
     self.device = torch.device('cuda')
     self.ca_model = self.ca_model.to(self.device)
     print('Loaded CA model')
     self.mean = 255.0 * torch.Tensor(np.array([0.485, 0.456, 0.406
                                                ])).cuda().half()
     self.std = 255.0 * torch.Tensor(np.array([0.485, 0.456, 0.406
                                               ])).cuda().half()
     self.normalize = torchvision.transforms.Normalize(self.mean, self.std)
     # Road following support variables.
     self.angle = 0.0
     self.angle_last = 0.0
     # Instantiating the road following network.
     print('Loading RF model')
     self.rf_model = torchvision.models.resnet18(pretrained=False)
     self.rf_model.fc = torch.nn.Linear(512, 2)
     self.rf_model.load_state_dict(torch.load('best_steering_model_xy.pth'))
     self.rf_model = self.rf_model.to(self.device)
     self.rf_model = self.rf_model.eval().half()
     print('Loaded RF Model')
     # Initializing additional variables.
     self.speed_gain = 0.12
     self.steering_gain = 0
     self.steering_dgain = 0.1
     self.steering_bias = 0.0
     self.starttime = 0
     self.cumulative_angle = -1
     self.pitstop = []
     self.startposition = []
     self.start_num = -1
     self.baton_callback = None
     self.pathpoints_callback = None
     self.pathpoints = [[]]
     # Add proper value below.
     self.proportionality_const = -1
     self.image_widget = ipywidgets.Image()
     self.previous_position = -1
     traitlets.dlink((self.camera, 'value'), (self.image_widget, 'value'),
                     transform=bgr8_to_jpeg)
コード例 #15
0
 def __init__(self, parent, b1, b2):
     """A domino has a parent widget and is made of 2 buttons"""
     super(Domino, self).__init__()
     self.geometry = DominoGeometry(b1.position, b2.position)
     self.parent = parent
     self.key = None
     self.first = b1
     self.second = b2
     self.buttons = (b1, b2)
     b1.link = dlink((b1, 'value'), (b2, 'value'))
     b2.link = dlink((b2, 'value'), (b1, 'value'))
     self.link = None
     self.direction = None
     self.orientation = None
     self.compute()
コード例 #16
0
def get_images_and_cameras(image_width=640, image_height=480, fps=5):
    image = widgets.Image(format='jpeg',
                          width=image_width,
                          height=image_height)
    camera = CSICamera(capture_width=3264,
                       capture_height=2464,
                       image_width=image_width,
                       image_height=image_height,
                       fps=fps)
    traitlets.dlink(
        (camera, 'value'),
        (image, 'value'),
        transform=lambda x: bgr8_to_jpeg(x),
    )
    return image, camera
コード例 #17
0
ファイル: tool_commits.py プロジェクト: deathbeds/wxyz
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # move these into watchers
     T.link((self.watch, "value"), (self.repo, "watching"))
     T.dlink(
         (self.repo, "changes"),
         (self.commit_btn, "description"),
         self.change_btn_desc,
     )
     T.dlink(
         (self.repo, "changes"),
         (self.commit_btn, "disabled"),
         lambda changes: not changes,
     )
     self.commit_btn.on_click(self.commit)
     self._dom_classes += (f"{CSS_PREFIX}-box", )
     self.commit_btn._dom_classes += (f"{CSS_PREFIX}-btn", )
     self.message._dom_classes += (f"{CSS_PREFIX}-msg", )
     self.children = [self.watch, self.message, self.commit_btn]
コード例 #18
0
ファイル: view.py プロジェクト: zhenyu-captain/vaex
    def __init__(self, **kwargs):
        self._control = None
        super().__init__(**kwargs)
        self.output = widgets.Output()
        self.plot = self.create_plot()
        self.children = (self.progress_widget, self.plot.widget, self.output)

        widgets.dlink((self, 'tool'), (self.plot, 'tool'))

        # first dlink our model to the plot
        widgets.dlink((self.model.x, 'expression'), (self.plot, 'x_label'),
                      transform=str)
        self.plot.y_label = "count"

        # set before we observe changes
        if self.model.x.min is not None:
            self.plot.x_min = self.model.x.min
        if self.model.x.max is not None:
            self.plot.x_max = self.model.x.max

        # then we sync the limits of the plot with a debouce to the model
        traitlets.dlink((self.plot, 'x_min'), (self.model.x, 'min'))
        traitlets.dlink((self.plot, 'x_max'), (self.model.x, 'max'))

        self.model.observe(self.update_data, ['grid', 'grid_sliced'])
        self.observe(self.update_data, ['normalize', 'dimension_groups'])

        @self.output.capture()
        @vaex.jupyter.debounced(DEBOUNCE_HOVER_SLICED)
        def unhighlight():
            self.plot.highlight(None)
            self.model.x_slice = None

        @self.output.capture()
        # @vaex.jupyter.debounced(DEBOUNCE_SLICE)
        def on_bar_hover(bar, event):
            self.model.x_slice = event['data']['index']
            self.plot.highlight(self.model.x_slice)
            unhighlight()

        self.plot.mark.on_hover(on_bar_hover)
        if self.model.grid is not None:
            self.update_data()
コード例 #19
0
    def __init__(self, path_to_root="../", **kwargs):
        # Used to output additional settings.
        self._output = ipw.Output()

        # Communicate to the user if something isn't right.
        error_message = ipw.HTML()
        super().__init__(children=[error_message], **kwargs)

        eln, msg = connect_to_eln(**kwargs)

        if eln is None:
            url = f"{path_to_root}aiidalab-widgets-base/notebooks/eln_configure.ipynb"
            error_message.value = f"""Warning! The access to ELN is not configured. Please follow <a href="{url}" target="_blank">the link</a> to configure it.</br> More details: {msg}"""
            return

        traitlets.dlink((eln, "node"), (self, "node"))
        with requests_cache.disabled():
            # Since the cache is enabled in AiiDAlab, we disable it here to get correct results.
            eln.import_data()
コード例 #20
0
ファイル: widget.py プロジェクト: bjorncole/pyMBE
    def _make_diagram(self):
        view = ipyelk.diagram.SprottyViewer()
        view.selection.observe(self._update_selected, "ids")

        tools = [
            view.selection,
            view.fit_tool,
            view.center_tool,
            ipyelk.tools.PipelineProgressBar(),
        ]

        toolbar = Toolbar(
            layout=dict(height="auto", width="auto", visibility="visible"),
            tools=tools,
            update_diagram=self._on_update_diagram_button_click,
        )
        trt.dlink(
            (self.lpg, "sysml_projections"),
            (toolbar.projection_selector, "options"),
            lambda x: tuple(x),  # pylint: disable=unnecessary-lambda
        )
        toolbar.projection_selector.options = tuple(self.lpg.sysml_projections)
        toolbar._update_children()
        toolbar.log_out = self.log_out

        # TODO: after ipyelk fix revert this back to ipyelk.Diagram
        diagram = Diagram(
            layout=dict(width="100%"),
            toolbar=toolbar,
            tools=tools,
            view=view,
        )
        trt.link((diagram, "tools"), (toolbar, "tools"))
        trt.link((diagram, "symbols"), (view, "symbols"))

        def update_mapper(change: trt.Bunch):
            if change.new == PipeDisposition.done:
                self.id_mapper = self._make_id_mapper()
                warn("Updating the id_mapper!")

        diagram.pipe.observe(update_mapper, "disposition")

        return diagram
コード例 #21
0
    def _structure_importers(self, importers):
        """Preparing structure importers."""
        if not importers:
            raise ValueError("The parameter importers should contain a list (or tuple) of "
                             "importers, got a falsy object.")

        # If there is only one importer - no need to make tabs.
        if len(importers) == 1:
            # Assigning a function which will be called when importer provides a structure.
            dlink((importers[0], 'structure'), (self, 'input_structure'))
            return importers[0]

        # Otherwise making one tab per importer.
        importers_tab = ipw.Tab()
        importers_tab.children = [i for i in importers]  # One importer per tab.
        for i, importer in enumerate(importers):
            # Labeling tabs.
            importers_tab.set_title(i, importer.title)
            dlink((importer, 'structure'), (self, 'input_structure'))
        return importers_tab
コード例 #22
0
ファイル: tool_remotes.py プロジェクト: deathbeds/wxyz
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.children = [
            W.HBox([self.remotes, self.fetch_btn]),
            W.HBox([self.heads, self.merge_btn, self.push_btn]),
        ]
        T.dlink((self.remotes, "value"), (self, "remote"))
        T.dlink((self.heads, "value"), (self, "head"))
        T.dlink((self, "remote"), (self.heads, "disabled"), lambda x: not x)
        T.dlink((self, "head"), (self.push_btn, "disabled"), lambda x: not x)

        self.fetch_btn.on_click(self._on_fetch_click)
        self.merge_btn.on_click(self._on_merge_click)
コード例 #23
0
    def __init__(self, project_path, canvas_size=(200, 400), image_dir='pics'):
        self._model = BBoxAnnotatorLogic(project_path, image_dir=image_dir)

        super().__init__(canvas_size=canvas_size)

        self._save_btn.on_click(self._model._save_annotations)

        # set correct slider max value based on image number
        dlink((self._model, 'current_im_num'),
              (self._navi.model, 'max_im_number'))

        # draw current image and bbox only when client is ready
        self.on_client_ready(self._model._handle_client_ready)

        # Link image path and bbox coordinates between model and the ImageWithBox widget
        link((self._model, 'image_path'), (self._image_box, 'image_path'))
        link((self._model, 'bbox_coords'), (self._image_box, 'bbox_coords'))

        # Link current image index from controls to annotator model
        link((self._navi.model, 'index'), (self._model, 'index'))
コード例 #24
0
ファイル: tool_remotes.py プロジェクト: deathbeds/wxyz
    def _on_repo(self, change):
        """handle the repo changing (including the first time)"""
        if self._remotes_link:
            self._remotes_link.unlink()

        if change.new:
            self._remotes_link = T.dlink(
                (change.new, "remotes"),
                (self.remotes, "options"),
                self._update_remote_options,
            )
コード例 #25
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.output_title = W.HTML("<h3>Output from Clicks</h3>")
        self.click_output_box.children = [self.output_title, self.click_output]

        T.dlink(
            (self, "show_outputs"),
            (self.click_output_box.layout, "visibility"),
            lambda x: "visible" if x else "hidden",
        )

        if self.show_outputs is True:
            self.children = [
                self.cyto_widget,
                self.click_output_box,
            ]
        else:
            self.children = [
                self.cyto_widget,
            ]
コード例 #26
0
    def _on_repo_changed(self, change):
        """react to the repo changing"""
        if self._repo_link is not None:
            self._repo_link.unlink()
            self._repo_link = None

        if change.new:
            self._repo_link = T.dlink(
                (change.new, "heads"),
                (self.picker, "options"),
                self._format_head_options,
            )
コード例 #27
0
    def __init__(self,
                 project_path,
                 image_dir='pics',
                 image_width=150,
                 image_height=150,
                 n_rows=3,
                 n_cols=3,
                 question=None,
                 filter_files=None):

        super().__init__(image_width, image_height, n_rows, n_cols)

        self._model = CaptureAnnotatorLogic(project_path,
                                            question,
                                            image_dir,
                                            filter_files=filter_files)

        self._save_btn.on_click(self._model._save_annotations)

        self._grid_box.on_click(self._model._handle_grid_click)

        link((self._model, 'all_none'), (self._none_checkbox, 'value'))

        self._none_checkbox.observe(self._model._select_none, 'value')

        # get correct screen image number from gui settings
        dlink((self._screen_im_number, 'value'), (self._model, 'disp_number'))

        # set correct number of screens slider value based on image number
        dlink((self._model, 'num_screens'),
              (self._navi.model, 'max_im_number'))

        # link current image index from controls to annotator model
        link((self._navi.model, 'index'), (self._model, 'index'))

        # link annotation question
        link((self._model, 'question_value'), (self._grid_label, 'value'))

        # link state of model and grid box visualizer
        link((self._model, 'current_state'), (self._grid_box, 'current_state'))
コード例 #28
0
    def __init__(self,
                 project_path,
                 image_dir=None,
                 im_width=100,
                 im_height=100,
                 label_width=150,
                 label_height=150,
                 n_rows=3,
                 n_cols=3,
                 label_autosize=False,
                 question=None):

        super().__init__(im_width, im_height, label_width, label_height,
                         n_rows, n_cols, label_autosize)

        self._model = Im2ImAnnotatorLogic(project_path, question, image_dir)

        self._save_btn.on_click(self._model._save_annotations)

        self._grid_box.on_click(self._model._handle_grid_click)

        # set correct slider max value based on image number
        dlink((self._model, 'current_im_num'),
              (self._navi.model, 'max_im_number'))

        # link current image index from controls to annotator model
        link((self._navi.model, 'index'), (self._model, 'index'))

        # link annotation question
        link((self._model, 'question_value'), (self._grid_label, 'value'))

        #link image vizualizer
        dlink((self._model, 'image_path'), (self._image, 'image_path'))

        # draw current image and bbox only when client is ready
        self.on_client_ready(self._model._handle_client_ready)

        # link state of model and grid box visualizer
        link((self._model, 'label_state'), (self._grid_box, 'current_state'))
コード例 #29
0
 def cam(self,
         cam_type=bcam.JETSON_CAM,
         width_cap=800,
         height_cap=600,
         fps=2,
         flip=0):
     camera = bcam.config(cam_type=cam_type).resolution(
         width_cap, height_cap).fps(fps).flip(flip).build()
     camera.start()
     self.camera_link = traitlets.dlink((camera, 'value'),
                                        (self.image_widget, 'value'),
                                        transform=bgr8_to_jpeg)
     return self.image_widget
コード例 #30
0
 def _on_watching(self, change):
     """react to the watch state (or path) changing"""
     if self._watcher:
         if self._change_link:
             self._change_link.unlink()
             self._change_link = None
         self._watcher.watching = False
         self._watcher = None
     if self.watching:
         self._watcher = Watcher(self.working_dir)
         self._change_link = T.dlink((self._watcher, "changes"),
                                     (self, "changes"),
                                     self._on_watch_changes)
         self._watcher.watching = True
コード例 #31
0
 def dlink(self, name_1, name_2):
     """Same as trailets but applied to Dashboard attribute names"""
     widget_1 = getattr(self, name_1).target
     widget_2 = getattr(self, name_2).target
     setattr(self, 'link_'+name_1+'_'+name_2, traitlets.dlink((widget_1, 'value'),
                                                              (widget_2, 'value')))
コード例 #32
0
ファイル: widget_framework.py プロジェクト: NuGrid/WENDI
    def _update(self, state="default"):
	#print 'update state ',state
        for obj_name in self._object_list:
            ##apply attributes
            default_style = {}
            if obj_name in self._display_list:
                default_style = self._default_display_style
            elif obj_name in self._io_list:
                default_style = self._default_io_style
                
            default_attributes = {}
            if "default" in self._attributes:
                if obj_name in self._attributes["default"]:
                    default_attributes = self._attributes["default"][obj_name]
            
            state_attributes = {}
            if state in self._attributes:
                if obj_name in self._attributes[state]:
                    state_attributes = self._attributes[state][obj_name]
            
            attributes = default_style.copy()
            attributes.update(default_attributes)
            attributes.update(state_attributes)
            
            if not "visibility" in attributes:
                attributes["visibility"] = 'hidden' #CR

            self.set_attributes(obj_name, **attributes)

        ##apply links
        for link_name in self._link_object: #clear link objects
            self._link_object[link_name].unlink()
        self._link_objects = {}

        default_links = {}
        if "default" in self._links:
            default_links = self._links["default"]
        
        state_links = {}
        if state in self._links:
            state_links = self._links[state]
       
        #start from default links and update with state links
        links_dict = default_links.copy()
        links_dict.update(state_links)
       
        #go over all links
        for link_name in links_dict:
            directional, links_list = links_dict[link_name]
            links = []
            for link in links_list:
		obj=self._object_list[link[0]]
		if hasattr(obj,link[1]):
                	links.append((self._object_list[link[0]], link[1]))
		elif hasattr(obj.layout,link[1]):
			links.append((self._object_list[link[0]].layout, link[1]))
			#print 'layout used: ',
		else:
			raise ValueError("the object: "+str(obj)+"does not have attribute "+link[1])
            if directional:
		#print links
                self._link_objects[link_name] = traitlets.dlink(*links)
            else:
                self._link_objects[link_name] = traitlets.link(*links)


        ##callbacks
        default_callbacks = {}
        if "default" in self._callbacks:
            default_callbacks = self._callbacks["default"]
        
        state_callbacks = {}
        if state in self._callbacks:
            state_callbacks = self._callbacks[state]
            
        callbacks = default_callbacks.copy()
        callbacks.update(state_callbacks)
       
        #goes over all callback object list, for each object check methods e.g. on_click and activate
        for obj_name in callbacks:
            for type in callbacks[obj_name]:
                if hasattr(self._object_list[obj_name], type):
                    if type == "on_trait_change":
                        self._object_list[obj_name].on_trait_change(*callbacks[obj_name][type])
                    elif type == "on_click":
                        self._object_list[obj_name].on_click(callbacks[obj_name][type][0])
                    elif type == "on_submit":
                        self._object_list[obj_name].on_submit(callbacks[obj_name][type][0])
                    else:
                        raise ValueError("the object: "+obj_name+" has no method called: "+type)
        ##children
        default_children = {}
        if "default" in self._children:
            default_children = self._children["default"]
            
        state_children = {}
        if state in self._children:
            state_children = self._children[state]
            
        children = default_children.copy()
        children.update(state_children)

        for obj_name in children:
            if children[obj_name][0]:
                for i, title in enumerate(children[obj_name][2]):
                    self._object_list[obj_name].set_title(i, title) 
            children_list = [self._object_list[child_name] for child_name in children[obj_name][1]]
            self._object_list[obj_name].children = children_list