Beispiel #1
0
 def create_gridbox(self, widget, box=True):
     grid = QGridLayout()
     grid.setColumnMinimumWidth(0, 50)
     grid.setColumnStretch(1, 1)
     box = gui.widgetBox(widget, box=box, orientation=grid)
     # This must come after calling widgetBox, since widgetBox overrides it
     grid.setVerticalSpacing(8)
     return box
Beispiel #2
0
 def create_gridbox(self, widget, box=True):
     grid = QGridLayout()
     grid.setColumnMinimumWidth(0, 50)
     grid.setColumnStretch(1, 1)
     box = gui.widgetBox(widget, box=box, orientation=grid)
     # This must come after calling widgetBox, since widgetBox overrides it
     grid.setVerticalSpacing(8)
     return box
    def __init__(self):
        super().__init__()
        self.dataset = None

        self.attrs = DomainModel(valid_types=Orange.data.DiscreteVariable,
                                 separators=False)
        cb = gui.comboBox(self.controlArea,
                          self,
                          "attribute",
                          box=True,
                          model=self.attrs,
                          callback=self.update_scene,
                          contentsLength=12)
        grid = QGridLayout()
        self.legend = gui.widgetBox(gui.indentedBox(cb.box), orientation=grid)
        grid.setColumnStretch(1, 1)
        grid.setHorizontalSpacing(6)
        self.legend_items = []
        self.split_vars = DomainModel(
            valid_types=Orange.data.DiscreteVariable,
            separators=False,
            placeholder="None",
        )
        self.split_combobox = gui.comboBox(self.controlArea,
                                           self,
                                           "split_var",
                                           box="Split by",
                                           model=self.split_vars,
                                           callback=self.update_scene)
        self.explode_checkbox = gui.checkBox(self.controlArea,
                                             self,
                                             "explode",
                                             "Explode pies",
                                             box=True,
                                             callback=self.update_scene)
        gui.rubber(self.controlArea)
        gui.widgetLabel(
            gui.hBox(self.controlArea, box=True),
            "The aim of this widget is to\n"
            "demonstrate that pie charts are\n"
            "a terrible visualization. Please\n"
            "don't use it for any other purpose.")

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        self.view.setRenderHints(QPainter.Antialiasing
                                 | QPainter.TextAntialiasing
                                 | QPainter.SmoothPixmapTransform)
        self.mainArea.layout().addWidget(self.view)
        self.mainArea.setMinimumWidth(500)
Beispiel #4
0
 def render(self):
     """
     Return a QWidget object that can be added to a layout.
     """
     grid = QGridLayout()
     grid.setColumnStretch(2, 1)
     for row, field in enumerate(self.fields):
         if not field.hidden:
             grid.addWidget(
                 QLabel(f"{field.title}: ", font=APP_FONT, alignment=Qt.AlignRight),
                 row,
                 1,
             )
             grid.addWidget(field.render(), row, 2)
     return grid
    def __init__(self):
        super().__init__()
        self.dataset = None

        self.attrs = DomainModel(
            valid_types=Orange.data.DiscreteVariable, separators=False)
        cb = gui.comboBox(
            self.controlArea, self, "attribute", box=True,
            model=self.attrs, callback=self.update_scene, contentsLength=12)
        grid = QGridLayout()
        self.legend = gui.widgetBox(gui.indentedBox(cb.box), orientation=grid)
        grid.setColumnStretch(1, 1)
        grid.setHorizontalSpacing(6)
        self.legend_items = []
        self.split_vars = DomainModel(
            valid_types=Orange.data.DiscreteVariable, separators=False,
            placeholder="None", )
        gui.comboBox(
            self.controlArea, self, "split_var", box="Split by",
            model=self.split_vars, callback=self.update_scene)
        gui.checkBox(
            self.controlArea, self, "explode", "Explode pies", box=True,
            callback=self.update_scene)
        gui.rubber(self.controlArea)
        gui.widgetLabel(
            gui.hBox(self.controlArea, box=True),
            "The aim of this widget is to\n"
            "demonstrate that pie charts are\n"
            "a terrible visualization. Please\n"
            "don't use it for any other purpose.")

        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        self.view.setRenderHints(
            QPainter.Antialiasing | QPainter.TextAntialiasing |
            QPainter.SmoothPixmapTransform)
        self.mainArea.layout().addWidget(self.view)
        self.mainArea.setMinimumWidth(600)
Beispiel #6
0
    def __init__(self):
        OWWidget.__init__(self)
        ConcurrentWidgetMixin.__init__(self)
        self.api = None
        self.api_dlg = self.APICredentialsDialog(self)
        self.api_dlg.accept()

        # Set API key button
        gui.button(
            self.controlArea,
            self,
            "Twitter API Key",
            callback=self.open_key_dialog,
            tooltip="Set the API key for this widget.",
            focusPolicy=Qt.NoFocus,
        )

        # Query
        query_box = gui.hBox(self.controlArea, "Query")
        layout = QGridLayout()
        layout.setVerticalSpacing(5)
        layout.setColumnStretch(2, 1)  # stretch last columns
        layout.setColumnMinimumWidth(1, 15)  # add some space for checkbox
        ROW = 0
        COLUMNS = 3

        def add_row(label, items):
            nonlocal ROW, COLUMNS
            layout.addWidget(QLabel(label), ROW, 0)
            if isinstance(items, tuple):
                for i, item in enumerate(items):
                    layout.addWidget(item, ROW, 1 + i)
            else:
                layout.addWidget(items, ROW, 1, 1, COLUMNS - 1)
            ROW += 1

        # Query input
        add_row(
            "Query word list:",
            ListEdit(
                self,
                "word_list",
                "Multiple lines are joined with OR.",
                80,
                self,
            ),
        )

        # Search mode
        add_row(
            "Search by:",
            gui.comboBox(self,
                         self,
                         "mode",
                         items=self.MODES,
                         callback=self.mode_toggle),
        )

        # Language
        langs = (("Any", None), ) + tuple(
            (code2lang[l], l) for l in SUPPORTED_LANGUAGES)
        self.language_combo = ComboBox(self, "language", items=langs)
        add_row("Language:", self.language_combo)

        # Max tweets
        add_row(
            "Max tweets:",
            gui.spin(
                self,
                self,
                "max_tweets",
                minv=1,
                maxv=10000,
                checked="limited_search",
            ),
        )

        # Retweets
        self.retweets_checkbox = gui.checkBox(self,
                                              self,
                                              "allow_retweets",
                                              "",
                                              minimumHeight=30)
        add_row("Allow retweets:", self.retweets_checkbox)

        # Collect Results
        add_row("Collect results:", gui.checkBox(self, self, "collecting", ""))

        query_box.layout().addLayout(layout)

        # Buttons
        self.search_button = gui.button(
            self.buttonsArea,
            self,
            "Search",
            self.start_stop,
            focusPolicy=Qt.NoFocus,
        )

        self.mode_toggle()
        self.setFocus()  # to widget itself to show placeholder for query_edit
Beispiel #7
0
    def __init__(self):
        super().__init__()
        self._current_path = ""
        icon_open_dir = self.style().standardIcon(QStyle.SP_DirOpenIcon)

        # Top grid with file selection combo box
        grid = QGridLayout()
        lb = QLabel("File:")
        lb.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.recent_combo = cb = QComboBox(
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            minimumContentsLength=20,
            toolTip="Select a recent file")
        self.recent_model = cb.model()  # type: QStandardItemModel
        self.recent_combo.activated[int].connect(self._select_recent)

        browse = QPushButton("...",
                             autoDefault=False,
                             icon=icon_open_dir,
                             clicked=self.browse)

        # reload = QPushButton("Reload", autoDefault=False, icon=icon_reload)

        grid.addWidget(lb, 0, 0, Qt.AlignVCenter)
        grid.addWidget(cb, 0, 1)
        grid.addWidget(browse, 0, 2)
        # grid.addWidget(reload, 0, 3)

        self.summary_label = label = QLabel("", self)
        label.ensurePolished()
        f = label.font()
        if f.pointSizeF() != -1:
            f.setPointSizeF(f.pointSizeF() * 5 / 6)
        else:
            f.setPixelSize(f.pixelSize() * 5 / 6)
        label.setFont(f)
        grid.addWidget(label, 1, 1, 1, 3)

        self.controlArea.layout().addLayout(grid)

        box = gui.widgetBox(self.controlArea,
                            "Headers and Row Labels",
                            spacing=-1)
        hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        self.header_rows_spin = spin = QSpinBox(box,
                                                minimum=0,
                                                maximum=3,
                                                value=self._header_rows_count,
                                                keyboardTracking=False)
        spin.valueChanged.connect(self.set_header_rows_count)
        hl.addWidget(QLabel("Data starts with", box))
        hl.addWidget(self.header_rows_spin)
        hl.addWidget(QLabel("header row(s)", box))
        hl.addStretch(10)
        box.layout().addLayout(hl)

        hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        self.header_cols_spin = spin = QSpinBox(box,
                                                minimum=0,
                                                maximum=3,
                                                value=self._header_cols_count,
                                                keyboardTracking=False)
        spin.valueChanged.connect(self.set_header_cols_count)

        hl.addWidget(QLabel("First", box))
        hl.addWidget(self.header_cols_spin)
        hl.addWidget(QLabel("column(s) are row labels", box))
        hl.addStretch(10)
        box.layout().addLayout(hl)

        self.data_struct_box = box = gui.widgetBox(self.controlArea,
                                                   "Input Data Structure")
        gui.radioButtons(box,
                         self,
                         "_cells_in_rows", [
                             "Genes in rows, samples in columns",
                             "Samples in rows, genes in columns"
                         ],
                         callback=self._invalidate)

        box = gui.widgetBox(self.controlArea, "Sample Data", spacing=-1)

        grid = QGridLayout()
        grid.setContentsMargins(0, 0, 0, 0)
        box.layout().addLayout(grid)

        self.sample_rows_cb = cb = QCheckBox(checked=self._sample_rows_enabled)

        spin = QSpinBox(minimum=0,
                        maximum=100,
                        value=self._sample_rows_p,
                        enabled=self._sample_rows_enabled)
        spin.valueChanged.connect(self.set_sample_rows_p)
        suffix = QLabel("% of Samples", enabled=self._sample_rows_enabled)
        cb.toggled.connect(self.set_sample_rows_enabled)
        cb.toggled.connect(spin.setEnabled)
        cb.toggled.connect(suffix.setEnabled)

        grid.addWidget(cb, 0, 0)
        grid.addWidget(spin, 0, 1)
        grid.addWidget(suffix, 0, 2)

        self.sample_cols_cb = cb = QCheckBox(checked=self._sample_cols_enabled)
        spin = QSpinBox(minimum=0,
                        maximum=100,
                        value=self._sample_cols_p,
                        enabled=self._sample_cols_enabled)
        spin.valueChanged.connect(self.set_sample_cols_p)
        suffix = QLabel("% of genes", enabled=self._sample_cols_enabled)
        cb.toggled.connect(self.set_sample_cols_enabled)
        cb.toggled.connect(spin.setEnabled)
        cb.toggled.connect(suffix.setEnabled)

        grid.addWidget(cb, 1, 0)
        grid.addWidget(spin, 1, 1)
        grid.addWidget(suffix, 1, 2)
        grid.setColumnStretch(3, 10)

        self.annotation_files_box = box = gui.widgetBox(
            self.controlArea, "Cell && Gene Annotation Files")
        form = QFormLayout(
            formAlignment=Qt.AlignLeft,
            rowWrapPolicy=QFormLayout.WrapAllRows,
        )
        box.layout().addLayout(form)

        self.row_annotations_cb = cb = QCheckBox(
            "Cell annotations", checked=self._row_annotations_enabled)
        self._row_annotations_w = w = QWidget(
            enabled=self._row_annotations_enabled)
        cb.toggled.connect(self.set_row_annotations_enabled)
        cb.toggled.connect(w.setEnabled)
        hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        w.setLayout(hl)
        self.row_annotations_combo = QComboBox(
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            minimumContentsLength=18)
        self.row_annotations_combo.activated.connect(self._invalidate)
        hl.addWidget(self.row_annotations_combo)
        hl.addWidget(
            QPushButton("...",
                        box,
                        autoDefault=False,
                        icon=icon_open_dir,
                        clicked=self.browse_row_annotations))
        # hl.addWidget(QPushButton("Reload", box, autoDefault=False,
        #                          icon=icon_reload))
        form.addRow(cb, w)

        self.col_annotations_cb = cb = QCheckBox(
            "Gene annotations", checked=self._col_annotations_enabled)
        self._col_annotations_w = w = QWidget(
            enabled=self._col_annotations_enabled)
        cb.toggled.connect(self.set_col_annotations_enabled)
        cb.toggled.connect(w.setEnabled)
        hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        w.setLayout(hl)
        self.col_annotations_combo = QComboBox(
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            minimumContentsLength=18)
        self.col_annotations_combo.activated.connect(self._invalidate)
        hl.addWidget(self.col_annotations_combo)
        hl.addWidget(
            QPushButton("...",
                        box,
                        autoDefault=False,
                        icon=icon_open_dir,
                        clicked=self.browse_col_annotations))
        # hl.addWidget(QPushButton("Reload", box, autoDefault=False,
        #                          icon=icon_reload))
        form.addRow(cb, w)

        self.controlArea.layout().addStretch(10)
        self.load_data_button = button = VariableTextPushButton(
            "Load data",
            autoDefault=True,
            textChoiceList=["Load data", "Reload"])
        self.load_data_button.setAutoDefault(True)
        button.clicked.connect(self.commit, Qt.QueuedConnection)
        self.controlArea.layout().addWidget(button, alignment=Qt.AlignRight)

        init_recent_paths_model(
            self.recent_model,
            [RecentPath.create(p, []) for p in self._recent],
        )
        init_recent_paths_model(
            self.row_annotations_combo.model(),
            [RecentPath.create(p, []) for p in self._recent_row_annotations])
        init_recent_paths_model(
            self.col_annotations_combo.model(),
            [RecentPath.create(p, []) for p in self._recent_col_annotations])
        self._update_summary()
        self._update_warning()

        if self._last_path != "" and os.path.exists(self._last_path):
            self.set_current_path(self._last_path)
        else:
            self.recent_combo.setCurrentIndex(-1)
Beispiel #8
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.api = None
        self.corpus = None
        self.api_dlg = self.APICredentialsDialog(self)
        self.api_dlg.accept(silent=True)

        # Set API key button
        gui.button(self.controlArea, self, 'Twitter API Key',
                   callback=self.open_key_dialog,
                   tooltip='Set the API key for this widget.',
                   focusPolicy=Qt.NoFocus)

        # Query
        query_box = gui.hBox(self.controlArea, 'Query')
        layout = QGridLayout()
        layout.setVerticalSpacing(5)
        layout.setColumnStretch(2, 1)           # stretch last columns
        layout.setColumnMinimumWidth(1, 15)     # add some space for checkbox
        ROW = 0
        COLUMNS = 3

        def add_row(label, items):
            nonlocal ROW, COLUMNS
            layout.addWidget(QLabel(label), ROW, 0)
            if isinstance(items, tuple):
                for i, item in enumerate(items):
                    layout.addWidget(item, ROW, 1+i)
            else:
                layout.addWidget(items, ROW, 1, 1, COLUMNS-1)
            ROW += 1

        # Query input
        add_row('Query word list:',
                ListEdit(self, 'word_list',
                         'Multiple lines are joined with OR.', 80, self))

        # Search mode
        add_row('Search by:',
                gui.comboBox(self, self, 'mode', items=self.MODES,
                             callback=self.mode_toggle))

        # Language
        self.language_combo = ComboBox(self, 'language',
                                       items=(('Any', None),) +
                                             tuple(sorted(lang2code.items())))
        add_row('Language:', self.language_combo)

        # Max tweets
        add_row('Max tweets:',
                gui.spin(self, self, 'max_tweets', minv=1, maxv=10000,
                         checked='limited_search'))

        # Retweets
        self.retweets_checkbox = gui.checkBox(self, self, 'allow_retweets', '', minimumHeight=30)
        add_row('Allow retweets:', self.retweets_checkbox)

        # Collect Results
        add_row('Collect results:',
                gui.checkBox(self, self, 'collecting', ''))

        query_box.layout().addLayout(layout)

        self.controlArea.layout().addWidget(
            CheckListLayout('Text includes', self, 'text_includes',
                            self.attributes, cols=2,
                            callback=self.set_text_features))

        self.tweets_info_label = gui.label(self.controlArea, self,
                                           self.tweets_info.format(0),
                                           box='Info')

        # Buttons
        self.button_box = gui.hBox(self.controlArea)
        self.button_box.layout().addWidget(self.report_button)

        self.search_button = gui.button(self.button_box, self, 'Search',
                                        self.start_stop,
                                        focusPolicy=Qt.NoFocus)

        self.mode_toggle()
        self.setFocus()  # to widget itself to show placeholder for query_edit
Beispiel #9
0
    def __init__(self):
        widget.OWWidget.__init__(self)
        RecentPathsWidgetMixin.__init__(self)
        self.domain = None
        self.data = None
        self.loaded_file = ""
        self.sheets = []

        self.lb = gui.listBox(self.controlArea, self, "file_idx")

        layout = QGridLayout()
        gui.widgetBox(self.controlArea, margin=0, orientation=layout)

        file_button = gui.button(None,
                                 self,
                                 '  ...',
                                 callback=self.browse_files,
                                 autoDefault=False)
        file_button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        file_button.setSizePolicy(Policy.Maximum, Policy.Fixed)
        layout.addWidget(file_button, 0, 0)

        remove_button = gui.button(None,
                                   self,
                                   'Remove',
                                   callback=self.remove_item)

        clear_button = gui.button(None, self, 'Clear', callback=self.clear)

        layout.addWidget(remove_button, 0, 1)
        layout.addWidget(clear_button, 0, 2)

        reload_button = gui.button(None,
                                   self,
                                   "Reload",
                                   callback=self.load_data,
                                   autoDefault=False)
        reload_button.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserReload))
        reload_button.setSizePolicy(Policy.Fixed, Policy.Fixed)
        layout.addWidget(reload_button, 0, 7)

        self.sheet_box = gui.hBox(None, addToLayout=False, margin=0)
        self.sheet_combo = gui.comboBox(None,
                                        self,
                                        "xls_sheet",
                                        callback=self.select_sheet,
                                        sendSelectedValue=True)
        self.sheet_combo.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed)
        self.sheet_label = QLabel()
        self.sheet_label.setText('Sheet')
        self.sheet_label.setSizePolicy(Policy.MinimumExpanding, Policy.Fixed)
        self.sheet_box.layout().addWidget(self.sheet_label, Qt.AlignLeft)
        self.sheet_box.layout().addWidget(self.sheet_combo, Qt.AlignVCenter)
        layout.addWidget(self.sheet_box, 2, 1)
        self.sheet_box.hide()

        layout.addWidget(self.sheet_box, 0, 5)

        label_box = gui.hBox(None, addToLayout=False, margin=0)
        label = gui.lineEdit(label_box,
                             self,
                             "label",
                             callback=self.set_label,
                             label="Label",
                             orientation=Qt.Horizontal)
        layout.addWidget(label_box, 0, 6)

        layout.setColumnStretch(3, 2)

        box = gui.widgetBox(self.controlArea, "Columns (Double click to edit)")
        self.domain_editor = DomainEditor(self)
        self.editor_model = self.domain_editor.model()
        box.layout().addWidget(self.domain_editor)

        for i, rp in enumerate(self.recent_paths):
            self.lb.addItem(rp.abspath)

        # TODO unresolved paths just disappear! Modify _relocate_recent_files

        box = gui.hBox(self.controlArea)
        gui.rubber(box)
        box.layout().addWidget(self.report_button)
        self.report_button.setFixedWidth(170)

        self.apply_button = gui.button(box,
                                       self,
                                       "Apply",
                                       callback=self.apply_domain_edit)
        self.apply_button.setEnabled(False)
        self.apply_button.setFixedWidth(170)
        self.editor_model.dataChanged.connect(
            lambda: self.apply_button.setEnabled(True))

        self._update_sheet_combo()
        self.load_data()
    def __init__(self):
        super().__init__()
        self.data = None

        # The following lists are of the same length as self.active_rules

        #: list of pairs with counts of matches for each patter when the
        #     patterns are applied in order and when applied on the entire set,
        #     disregarding the preceding patterns
        self.match_counts = []

        #: list of list of QLineEdit: line edit pairs for each pattern
        self.line_edits = []
        #: list of QPushButton: list of remove buttons
        self.remove_buttons = []
        #: list of list of QLabel: pairs of labels with counts
        self.counts = []

        combo = gui.comboBox(
            self.controlArea, self, "attribute", label="From column: ",
            box=True, orientation=Qt.Horizontal, callback=self.update_rules,
            model=DomainModel(valid_types=(StringVariable, DiscreteVariable)))
        # Don't use setSizePolicy keyword argument here: it applies to box,
        # not the combo
        combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        patternbox = gui.vBox(self.controlArea, box=True)
        #: QWidget: the box that contains the remove buttons, line edits and
        #    count labels. The lines are added and removed dynamically.
        self.rules_box = rules_box = QGridLayout()
        patternbox.layout().addLayout(self.rules_box)
        box = gui.hBox(patternbox)
        gui.button(
            box, self, "+", callback=self.add_row, autoDefault=False, flat=True,
            minimumSize=(QSize(20, 20)))
        gui.rubber(box)
        self.rules_box.setColumnMinimumWidth(1, 70)
        self.rules_box.setColumnMinimumWidth(0, 10)
        self.rules_box.setColumnStretch(0, 1)
        self.rules_box.setColumnStretch(1, 1)
        self.rules_box.setColumnStretch(2, 100)
        rules_box.addWidget(QLabel("Name"), 0, 1)
        rules_box.addWidget(QLabel("Substring"), 0, 2)
        rules_box.addWidget(QLabel("#Instances"), 0, 3, 1, 2)
        self.update_rules()

        gui.lineEdit(
            self.controlArea, self, "class_name",
            label="Name for the new class:",
            box=True, orientation=Qt.Horizontal)

        optionsbox = gui.vBox(self.controlArea, box=True)
        gui.checkBox(
            optionsbox, self, "match_beginning", "Match only at the beginning",
            callback=self.options_changed)
        gui.checkBox(
            optionsbox, self, "case_sensitive", "Case sensitive",
            callback=self.options_changed)

        layout = QGridLayout()
        gui.widgetBox(self.controlArea, orientation=layout)
        for i in range(3):
            layout.setColumnStretch(i, 1)
        layout.addWidget(self.report_button, 0, 0)
        apply = gui.button(None, self, "Apply", autoDefault=False,
                           callback=self.apply)
        layout.addWidget(apply, 0, 2)

        # TODO: Resizing upon changing the number of rules does not work
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.api = None
        self.corpus = None
        self.api_dlg = self.APICredentialsDialog(self)
        self.api_dlg.accept(silent=True)

        # Set API key button
        gui.button(self.controlArea,
                   self,
                   'Twitter API Key',
                   callback=self.open_key_dialog,
                   tooltip='Set the API key for this widget.',
                   focusPolicy=Qt.NoFocus)

        # Query
        query_box = gui.hBox(self.controlArea, 'Query')
        layout = QGridLayout()
        layout.setVerticalSpacing(5)
        layout.setColumnStretch(2, 1)  # stretch last columns
        layout.setColumnMinimumWidth(1, 15)  # add some space for checkbox
        ROW = 0
        COLUMNS = 3

        def add_row(label, items):
            nonlocal ROW, COLUMNS
            layout.addWidget(QLabel(label), ROW, 0)
            if isinstance(items, tuple):
                for i, item in enumerate(items):
                    layout.addWidget(item, ROW, 1 + i)
            else:
                layout.addWidget(items, ROW, 1, 1, COLUMNS - 1)
            ROW += 1

        # Query input
        add_row(
            'Query word list:',
            ListEdit(self, 'word_list', 'Multiple lines are joined with OR.',
                     80, self))

        # Search mode
        add_row(
            'Search by:',
            gui.comboBox(self,
                         self,
                         'mode',
                         items=self.MODES,
                         callback=self.mode_toggle))

        # Language
        self.language_combo = ComboBox(self,
                                       'language',
                                       items=(('Any', None), ) +
                                       tuple(sorted(lang2code.items())))
        add_row('Language:', self.language_combo)

        # Max tweets
        add_row(
            'Max tweets:',
            gui.spin(self,
                     self,
                     'max_tweets',
                     minv=1,
                     maxv=10000,
                     checked='limited_search'))

        # Retweets
        self.retweets_checkbox = gui.checkBox(self,
                                              self,
                                              'allow_retweets',
                                              '',
                                              minimumHeight=30)
        add_row('Allow retweets:', self.retweets_checkbox)

        # Collect Results
        add_row('Collect results:', gui.checkBox(self, self, 'collecting', ''))

        query_box.layout().addLayout(layout)

        self.controlArea.layout().addWidget(
            CheckListLayout('Text includes',
                            self,
                            'text_includes',
                            self.attributes,
                            cols=2,
                            callback=self.set_text_features))

        self.tweets_info_label = gui.label(self.controlArea,
                                           self,
                                           self.tweets_info.format(0),
                                           box='Info')

        # Buttons
        self.button_box = gui.hBox(self.controlArea)
        self.button_box.layout().addWidget(self.report_button)

        self.search_button = gui.button(self.button_box,
                                        self,
                                        'Search',
                                        self.start_stop,
                                        focusPolicy=Qt.NoFocus)

        self.mode_toggle()
        self.setFocus()  # to widget itself to show placeholder for query_edit
Beispiel #12
0
class OWDictionary(OWWidget):
    name = "Dictionary"
    description = "Create a dictionary"
    icon = "icons/dictionary.svg"
    priority = 10

    want_main_area = False
    resizing_enabled = True
    
    queries = Setting([["", ""], ["", ""]])
    querytable = None
    querytable_attr = []
    querytable_metas = []
    querytable_vars = []
    querytable_vars2 = []
    label_in = [None]
    query_in = [None]
    weight_in = [None]
    add_quotes = Setting(True)
    sync = Setting(False)
    send = Setting(False)


    class Inputs:
        data = Input("Table", Orange.data.Table)

    class Outputs:
        dictionary = Output("Dictionary", Orange.data.Table)

    class Error(OWWidget.Error):
        no_query = Msg('You need to select a query column to import, select or sync a dictionary.')

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

        self.query_edits = []
        self.remove_buttons = []
        
        # GUI
        scrollArea = QScrollArea()
       

        #### header
        head_box = gui.hBox(self.controlArea)
        head_box.setMaximumHeight(200)
        
        info_box = gui.widgetBox(head_box, 'Info')
        self.info = gui.widgetLabel(info_box,
           ("Import and/or create queries\n\n" +
            "If a Table with a dictionary is connected as input,\n" +
            "it can be imported, in which case multiple query\n" +
            "terms with the same label will be combined.\n\n" +
            "If the label is a number, or if negative weights are\n" +
            "used (e.g. sentiment dictionaries), the query will be\n" +
            "split into positive and negative parts.\n\n"
            "If a row in the dictionary contains multiple terms\n" +
            "separated with spaces, it will be seen as a phrase\n" +
            "(by adding quotes). This can be turned of in case\n" +
            "rows are already boolean queries."))

        ## from input
        input_box = gui.widgetBox(head_box, "Create queries from dictionary file")
        input_box.setMaximumWidth(350)

        gui.button(input_box, self, 'multiple words are phrases', toggleButton=True, value='add_quotes',
                   buttonType=QCheckBox)
        inputline_box = gui.hBox(input_box)
        inputline_box.setMinimumHeight(70)
        gui.listBox(inputline_box, self, 'query_in', labels='querytable_vars', box = 'Query column', callback=self.update_if_sync)
        gui.listBox(inputline_box, self, 'label_in', labels='querytable_vars2', box = 'Label column', callback=self.update_if_sync)
        self.weight_select = gui.listBox(inputline_box, self, 'weight_in', labels='querytable_vars2', box = 'Weight column', callback=self.update_if_sync)

        input_button_box = gui.hBox(input_box)
        gui.button(input_button_box, self, 'Keep synchronized', self.sync_on_off, toggleButton=True, value='sync', buttonType=QCheckBox)
        gui.button(input_button_box, self, 'Import', self.import_queries)
        gui.button(input_button_box, self, 'Append', self.append_queries)

        ## query field
        query_box = gui.widgetBox(self.controlArea)
        
        self.queries_box = QGridLayout()
        query_box.layout().addLayout(self.queries_box)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll.setWidget(query_box)

        querygridbox = gui.widgetBox(self.controlArea, 'Query')
        querygridbox.layout().addWidget(scroll)       
        
        querygridbox.setMinimumHeight(200)
        querygridbox.setMinimumWidth(500)
        gui.rubber(query_box)

        self.queries_box.setColumnMinimumWidth(0, 5)
        self.queries_box.setColumnMinimumWidth(1, 60)
        self.queries_box.setColumnMinimumWidth(2, 350)
        self.queries_box.setColumnStretch(1, 0)
        self.queries_box.setColumnStretch(2, 100)
        self.queries_box.addWidget(QLabel("Label"), 0, 1)
        self.queries_box.addWidget(QLabel("Query"), 0, 2)
        self.update_queries()

        gui.button(query_box, self, "add query", callback=self.add_row, autoDefault=False)

        ## buttons
        scarybuttonbox = gui.hBox(self.controlArea)
        scarybuttonbox.layout().setAlignment(Qt.AlignRight)
        gui.button(scarybuttonbox, self, "remove all queries", callback=self.remove_all, width=150)

        QTimer.singleShot(0, self.send_queries) ## for send on startup

    def update_if_sync(self):
        if self.sync:
            self.import_queries()
    
    def query_changed(self):
        self.sync = False
        self.send_queries()
            
    def get_queries(self):
        for l, q in self.query_edits:
            l = l.text()
            l = re.sub('[#?]', '', l)
            q = q.text()
            yield [l, q]

    def send_queries(self):
        #if self.send:
        self.queries = list(self.get_queries())
        self.update_queries()
        valid_queries = [[label, query] for label, query in self.queries if not query == '']
        self.send_dictionary(valid_queries) 

    def send_dictionary(self, queries):
        domain = Orange.data.Domain([], metas = [
                                     Orange.data.StringVariable("label"),
                                     Orange.data.StringVariable("query")])
        out = Dictionary(domain, queries)
        self.Outputs.dictionary.send(out)

    def send_output(self, queries):
        domain = Orange.data.Domain([], metas = [
                                 Orange.data.StringVariable("label"),
                                 Orange.data.StringVariable("query")])

    def adjust_n_query_rows(self):
        def _add_line():
            self.query_edits.append([])
            n_lines = len(self.query_edits)
                            
            label_edit = gui.LineEditWFocusOut(self, self.query_changed)
            label_edit.setMaxLength(500000)
            self.query_edits[-1].append(label_edit)
            self.queries_box.addWidget(label_edit, n_lines, 1)

            query_edit = gui.LineEditWFocusOut(self, self.query_changed)
            query_edit.setMaxLength(500000)
            self.query_edits[-1].append(query_edit)
            self.queries_box.addWidget(query_edit, n_lines, 2)

            button = gui.button(
                None, self, label='×', flat=True, height=20,
                styleSheet='* {font-size: 16pt; color: silver}'
                           '*:hover {color: black}',
                autoDefault=False, callback=self.remove_row)
            button.setMinimumSize(QSize(3, 3))
            self.remove_buttons.append(button)
            self.queries_box.addWidget(button, n_lines, 0)
            for coli, kwargs in enumerate(
                    (dict(alignment=Qt.AlignRight),
                     dict(alignment=Qt.AlignLeft, styleSheet="color: gray"))):
                label = QLabel(**kwargs)
                self.queries_box.addWidget(label, n_lines, 3 + coli)

        def _remove_line():
            for edit in self.query_edits.pop():
                edit.deleteLater()
            self.remove_buttons.pop().deleteLater()

        n = len(self.queries)
        while n > len(self.query_edits):
            _add_line()
        while len(self.query_edits) > n:
            _remove_line()

    def add_row(self):
        self.queries.append(["", ""])
        self.adjust_n_query_rows()

    def remove_row(self):
        remove_idx = self.remove_buttons.index(self.sender())
        del self.queries[remove_idx]
        self.update_queries()

    def remove_all(self):
        self.queries = []
        self.update_queries()
       
    def update_queries(self):
        self.adjust_n_query_rows()
        self.queries_to_edits()

    def queries_to_edits(self):
        for editr, textr in zip(self.query_edits, self.queries):
            for edit, text in zip(editr, textr):
                edit.setText(text)

    def sync_on_off(self):
        valid_input = self.query_in is not None
        if self.sync and valid_input:
            self.Warning.no_query.clear()
            self.import_queries()
            self.sync = True ## ugly workaround around for unsetting sync with append_queries
            #self.send = True
            self.send_queries()
        else:
            self.Error.no_query()
            #self.send=False
            self.sync = False ## disable synchronize if label_in or query_in are not specified


    def import_queries(self):
        self.queries = []
        self.append_queries()
        
    def append_queries(self):
        self.sync = False
        self.send = False
        label_col = self.querytable_vars2[self.label_in[0]] if not self.label_in[0] is None else None
        query_col = self.querytable_vars[self.query_in[0]] if not self.query_in[0] is None else None
        weight_col = self.querytable_vars2[self.weight_in[0]] if not self.weight_in[0] is None else None
        if label_col == '[not used]': label_col = None
        if weight_col == '[not used]': weight_col = None

        if self.querytable is not None and query_col is not None:
            self.Error.no_query.clear()
            add_queries = self.querytable.import_dictionary(label_col, query_col, weight_col, self.add_quotes)
            self.queries = self.queries + add_queries
            self.update_queries()
        else:
            self.Error.no_query()
        self.send_queries()

    @Inputs.data
    def set_data(self, data):
        if data is not None:
            self.querytable = Dictionary(data)
            self.querytable_attr = self.querytable.attrnames()
            self.querytable_meta = self.querytable.metanames()
            self.querytable_vars = self.querytable_attr + self.querytable_meta
            self.querytable_vars2 = ['[not used]'] + self.querytable_vars
        else:
            self.querytable = None
            self.querytable_attr, self.querytable_metas, self.querytable_vars, self.querytable_vars2 = [], [], [], []
            self.label_in, self.query_in = [None], [None]
    def __init__(self):
        widget.OWWidget.__init__(self)
        RecentPathsWidgetMixin.__init__(self)
        self.domain = None
        self.data = None
        self.loaded_file = ""
        self.sheets = []

        self.lb = gui.listBox(self.controlArea, self, "file_idx",
                              selectionMode=QListWidget.MultiSelection)

        layout = QGridLayout()
        gui.widgetBox(self.controlArea, margin=0, orientation=layout)

        file_button = gui.button(
            None, self, '  ...', callback=self.browse_files, autoDefault=False)
        file_button.setIcon(self.style().standardIcon(
            QStyle.SP_DirOpenIcon))
        file_button.setSizePolicy(Policy.Maximum, Policy.Fixed)
        layout.addWidget(file_button, 0, 0)

        remove_button = gui.button(
            None, self, 'Remove', callback=self.remove_item)

        clear_button = gui.button(
            None, self, 'Clear', callback=self.clear)

        layout.addWidget(remove_button, 0, 1)
        layout.addWidget(clear_button, 0, 2)

        reload_button = gui.button(
            None, self, "Reload", callback=self.load_data, autoDefault=False)
        reload_button.setIcon(self.style().standardIcon(QStyle.SP_BrowserReload))
        reload_button.setSizePolicy(Policy.Fixed, Policy.Fixed)
        layout.addWidget(reload_button, 0, 7)

        self.sheet_box = gui.hBox(None, addToLayout=False, margin=0)
        self.sheet_combo = gui.comboBox(None, self, "xls_sheet",
                                        callback=self.select_sheet,
                                        sendSelectedValue=True)
        self.sheet_combo.setSizePolicy(
            Policy.MinimumExpanding, Policy.Fixed)
        self.sheet_label = QLabel()
        self.sheet_label.setText('Sheet')
        self.sheet_label.setSizePolicy(
            Policy.MinimumExpanding, Policy.Fixed)
        self.sheet_box.layout().addWidget(
            self.sheet_label, Qt.AlignLeft)
        self.sheet_box.layout().addWidget(
            self.sheet_combo, Qt.AlignVCenter)
        layout.addWidget(self.sheet_box, 2, 1)
        self.sheet_box.hide()

        layout.addWidget(self.sheet_box, 0, 5)

        label_box = gui.hBox(None, addToLayout=False, margin=0)
        label = gui.lineEdit(label_box, self, "label", callback=self.set_label,
                             label="Label", orientation=Qt.Horizontal)
        layout.addWidget(label_box, 0, 6)

        layout.setColumnStretch(3, 2)

        box = gui.widgetBox(self.controlArea, "Columns (Double click to edit)")
        self.domain_editor = DomainEditor(self)
        self.editor_model = self.domain_editor.model()
        box.layout().addWidget(self.domain_editor)

        for i, rp in enumerate(self.recent_paths):
            self.lb.addItem(rp.abspath)

        # TODO unresolved paths just disappear! Modify _relocate_recent_files

        box = gui.hBox(self.controlArea)
        gui.rubber(box)
        box.layout().addWidget(self.report_button)
        self.report_button.setFixedWidth(170)

        self.apply_button = gui.button(
            box, self, "Apply", callback=self.apply_domain_edit)
        self.apply_button.setEnabled(False)
        self.apply_button.setFixedWidth(170)
        self.editor_model.dataChanged.connect(
            lambda: self.apply_button.setEnabled(True))

        self._update_sheet_combo()
        self.load_data()
Beispiel #14
0
    def __init__(self):
        super().__init__()
        self.data = None

        # The following lists are of the same length as self.active_rules

        #: list of pairs with counts of matches for each patter when the
        #     patterns are applied in order and when applied on the entire set,
        #     disregarding the preceding patterns
        self.match_counts = []

        #: list of list of QLineEdit: line edit pairs for each pattern
        self.line_edits = []
        #: list of QPushButton: list of remove buttons
        self.remove_buttons = []
        #: list of list of QLabel: pairs of labels with counts
        self.counts = []

        combo = gui.comboBox(
            self.controlArea, self, "attribute", label="From column: ",
            box=True, orientation=Qt.Horizontal, callback=self.update_rules,
            model=DomainModel(valid_types=(StringVariable, DiscreteVariable)))
        # Don't use setSizePolicy keyword argument here: it applies to box,
        # not the combo
        combo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        patternbox = gui.vBox(self.controlArea, box=True)
        #: QWidget: the box that contains the remove buttons, line edits and
        #    count labels. The lines are added and removed dynamically.
        self.rules_box = rules_box = QGridLayout()
        patternbox.layout().addLayout(self.rules_box)
        box = gui.hBox(patternbox)
        gui.button(
            box, self, "+", callback=self.add_row, autoDefault=False, flat=True,
            minimumSize=(QSize(20, 20)))
        gui.rubber(box)
        self.rules_box.setColumnMinimumWidth(1, 70)
        self.rules_box.setColumnMinimumWidth(0, 10)
        self.rules_box.setColumnStretch(0, 1)
        self.rules_box.setColumnStretch(1, 1)
        self.rules_box.setColumnStretch(2, 100)
        rules_box.addWidget(QLabel("Name"), 0, 1)
        rules_box.addWidget(QLabel("Substring"), 0, 2)
        rules_box.addWidget(QLabel("#Instances"), 0, 3, 1, 2)
        self.update_rules()

        gui.lineEdit(
            self.controlArea, self, "class_name",
            label="Name for the new class:",
            box=True, orientation=Qt.Horizontal)

        optionsbox = gui.vBox(self.controlArea, box=True)
        gui.checkBox(
            optionsbox, self, "match_beginning", "Match only at the beginning",
            callback=self.options_changed)
        gui.checkBox(
            optionsbox, self, "case_sensitive", "Case sensitive",
            callback=self.options_changed)

        layout = QGridLayout()
        gui.widgetBox(self.controlArea, orientation=layout)
        for i in range(3):
            layout.setColumnStretch(i, 1)
        layout.addWidget(self.report_button, 0, 0)
        apply = gui.button(None, self, "Apply", autoDefault=False,
                           callback=self.apply)
        layout.addWidget(apply, 0, 2)

        # TODO: Resizing upon changing the number of rules does not work
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)