Beispiel #1
0
def test_set_defaults():
    fake_grid_options_a = {'foo': 'bar'}
    set_defaults(show_toolbar=False, precision=4,
                 grid_options=fake_grid_options_a)

    def assert_widget_vals_a(widget):
        assert not widget.show_toolbar
        assert widget.precision == 4
        assert widget.grid_options == fake_grid_options_a

    df = create_df()
    view = show_grid(df)
    assert_widget_vals_a(view)

    view = QgridWidget(df=df)
    assert_widget_vals_a(view)

    fake_grid_options_b = {'foo': 'buzz'}
    set_defaults(show_toolbar=True, precision=2,
                 grid_options=fake_grid_options_b)

    def assert_widget_vals_b(widget):
        assert widget.show_toolbar
        assert widget.precision == 2
        assert widget.grid_options == fake_grid_options_b

    df = create_df()
    view = show_grid(df)
    assert_widget_vals_b(view)

    view = QgridWidget(df=df)
    assert_widget_vals_b(view)
Beispiel #2
0
 def _ipython_display_(self):
     if self.info.in_df.size:
         display(Markdown('## INPUTS'), qgrid.show_grid(self.info.in_df, grid_options={'editable': False}))
     if self.info.loader_df.size:
         display(Markdown('## LOADERS'), qgrid.show_grid(self.info.loader_df, grid_options={'editable': False}))
     if self.info.out_df.size:
         display(Markdown('## OUTPUTS'), qgrid.show_grid(self.info.out_df, grid_options={'editable': False}))
Beispiel #3
0
def test_set_defaults():
    fake_grid_options_a = {'foo': 'bar'}
    set_defaults(show_toolbar=False,
                 precision=4,
                 grid_options=fake_grid_options_a)

    def assert_widget_vals_a(widget):
        assert not widget.show_toolbar
        assert widget.precision == 4
        assert widget.grid_options == fake_grid_options_a

    df = create_df()
    view = show_grid(df)
    assert_widget_vals_a(view)

    view = QgridWidget(df=df)
    assert_widget_vals_a(view)

    fake_grid_options_b = {'foo': 'buzz'}
    set_defaults(show_toolbar=True,
                 precision=2,
                 grid_options=fake_grid_options_b)

    def assert_widget_vals_b(widget):
        assert widget.show_toolbar
        assert widget.precision == 2
        assert widget.grid_options == fake_grid_options_b

    df = create_df()
    view = show_grid(df)
    assert_widget_vals_b(view)

    view = QgridWidget(df=df)
    assert_widget_vals_b(view)
Beispiel #4
0
 def _createTable(self, tab_index: int) -> qgrid.QgridWidget:
     assert self._dataFrame is not None, " TableManager has not been initialized "
     col_opts = dict(editable=False)  #
     grid_opts = dict(editable=False, maxVisibleRows=40)
     if tab_index == 0:
         data_table = self._dataFrame.sort_values(self._cols[0])
         data_table.insert(len(self._cols) - 1, "Class", 0, True)
         wTable = qgrid.show_grid(data_table,
                                  column_options=col_opts,
                                  grid_options=grid_opts,
                                  show_toolbar=False)
     else:
         empty_catalog = {col: np.empty([0], 'U') for col in self._cols}
         dFrame: pd.DataFrame = pd.DataFrame(empty_catalog,
                                             dtype='U',
                                             index=pd.Int64Index(
                                                 [], name="Index"))
         wTable = qgrid.show_grid(dFrame,
                                  column_options=col_opts,
                                  grid_options=grid_opts,
                                  show_toolbar=False)
     wTable.on(traitlets.All, self._handle_table_event)
     wTable.layout = ipw.Layout(width="auto",
                                height="100%",
                                max_height="1000px")
     #        events = Event(source=wTable, watched_events=['keyup', 'keydown'])
     #        events.on_dom_event(self._handle_key_event)
     #        self._events.append( events )
     return wTable
Beispiel #5
0
def get_set(dfr):
    """
    Widget to populate a single set.

    :param dfr: Dataframe of set contents
    :return: qgrid widget
    """
    in_df = dfr
    in_qg = qgrid.show_grid(in_df, grid_options={'maxVisibleRows': 10})
    out_df = pd.DataFrame()
    out_qg = qgrid.show_grid(out_df, grid_options={'maxVisibleRows': 10})
    button1 = widgets.Button(description='Add to set')
    button2 = widgets.Button(description='Remove from set')

    def on_button_clicked1(b):
        df = out_qg.df.append(in_qg.get_selected_df())
        out_qg.df = df

    button1.on_click(on_button_clicked1)

    def on_button_clicked2(b):
        rows = out_qg.get_selected_rows()
        if len(rows) > 0:
            df = out_qg.df.drop(out_qg.df.index[rows])
            out_qg.df = df

    button2.on_click(on_button_clicked2)

    d.display(button1)
    d.display(in_qg)
    d.display(button2)
    d.display(out_qg)

    return out_qg
Beispiel #6
0
    def show_stats(self):
        if self.cost > 0:
            display_cost_name = 'Total Cost in Euros'
            display_cost_value = int(self.cost)
        else:
            display_cost_name = 'Total Savings in Euros'
            display_cost_value = -int(self.cost)

        old_gini = gini(
            list(x[self._target_variable]
                 for x in self._population._population))
        new_gini = gini(self.simulated_results)

        result_frame = pd.DataFrame({
            display_cost_name: [display_cost_value],
            'Average change / family / month in Euros': [int(self.error) / 12],
            'People losing money':
            str(100 * self.pissed) + '%',
            'Old Gini':
            old_gini,
            'New Gini':
            new_gini,
        })

        result_frame.set_index(display_cost_name, inplace=True)
        qgrid.show_grid(result_frame)
Beispiel #7
0
    def __init__(self, bd: BudgetData, cats=None, **kwargs):
        self.bd = bd

        if not hasattr(self.bd, '_df'):
            self.bd.load_sql()

        if cats is None:
            cats = bd._sel.columns.tolist()

        qgrid_opts['column_definitions']['Description']['width'] = 150
        qgrid_opts['grid_options']['forceFitColumns'] = True

        kwargs['children'] = [
            widgets.HBox(children=[
                freq_dropdown(),
                widgets.Dropdown(
                    options=cats, value=cats[0], layout={'width': '300px'}),
                widgets.ToggleButton(description='Apply Notes', value=True)
            ]),
            widgets.HBox(children=[
                widgets.Box(children=[
                    qgrid.show_grid(pd.DataFrame(
                        columns=bd.df.columns), **qgrid_opts),
                ],
                            layout={
                                'display': 'flex',
                                'width': '200px',
                                'padding': '5px'
                            }),
                widgets.Box(children=[
                    qgrid.show_grid(pd.DataFrame(
                        columns=bd.df.columns), **qgrid_opts),
                ],
                            layout={
                                'display': 'flex',
                                'flex': '1 1',
                                'width': 'auto',
                                'padding': '5px'
                            }),
            ]),
            widgets.Output()
        ]

        if 'layout' not in kwargs:
            bar_layout['flex_flow'] = 'row wrap'
            kwargs['layout'] = bar_layout
        super().__init__(**kwargs)

        for child in self.children[0].children:
            child.observe(self.show_report, 'value')
        self.report.on('selection_changed', self.show_transactions)

        self.show_report()
Beispiel #8
0
def listShots(criterion=None,attrList=None,gui=False):
    """Display the list of discharges with the associated parameters

    criterion: String to select discharges based on the value of the parameters
    attrList: list of parameters to display
    
    Returns: pandas DataFrame
    """    
    
    result=sm.listShots(criterion,attrList)    
    if gui==True:
        qgrid.show_grid(result)     
    return result
Beispiel #9
0
def show_results(results_table, short_titles=True):
    if short_titles:
        columns = [
            'label_grouping_key', 'feature_extractor_key', 'estimator_key',
            'score_key', 'score_train_', 'score_test_'
        ]
    else:
        columns = [
            'label_grouping_title', 'feature_extractor_title',
            'estimator_title', 'score_title', 'score_train_', 'score_test_'
        ]
    qgrid.show_grid(results_table[columns],
                    precision=3,
                    grid_options={'enableColumnReorder': True})
Beispiel #10
0
    def show_constraints_value(self, constraint):
        assert constraint in ['benefit', 'tax_rate', 'tax_threshold']
        coefficients = []
        variables = []
        for parameter in self.final_parameters:
            if parameter['type'] == constraint:
                coefficients.append(parameter['value'])
                variables.append(parameter['variable'])

        result_frame = pd.DataFrame({
            'Variables': variables,
            constraint + ' coef': coefficients
        })
        result_frame.set_index('Variables', inplace=True)
        qgrid.show_grid(result_frame)
Beispiel #11
0
    def token_selection_change(self, change):
        "First click."
        with self.out1:
            clear_output()

            # Process the involved dataframe.
            token_selected = self.qgrid_token_obj.get_selected_df(
            ).reset_index()['string'].iloc[0]
            selected_token = self._select_token(token_selected, self._range1,
                                                self._range2)
            df_selected_token = selected_token.drop(
                ['page_id', 'o_editor', 'token', 'o_rev_id', 'article_title'],
                axis=1)
            new_cols = ['token_id', 'action', 'rev_time', 'editor', 'rev_id']
            df_selected_token = df_selected_token[new_cols].rename(
                {'editor': 'editor_id'}, axis=1)
            df_selected_token['token_id'] = df_selected_token[
                'token_id'].astype(str)
            df_selected_token['rev_id'] = df_selected_token['rev_id'].astype(
                str)
            df_selected_token.set_index('token_id', inplace=True)

            qgrid_selected_token = qgrid.show_grid(df_selected_token)
            self.qgrid_selected_token = qgrid_selected_token
            display(
                md(f'**With string *{token_selected}*, select one revision you want to investigate:**'
                   ))
            display(self.qgrid_selected_token)

            self.out2 = Output()
            display(self.out2)
            self.qgrid_selected_token.observe(self.revid_selection_change,
                                              names=['_selected_rows'])
Beispiel #12
0
def test_object_dtype_categorical():
    cat_series = pd.Series(
        pd.Categorical(my_object_vals, categories=my_object_vals))
    widget = show_grid(cat_series)
    constraints_enum = widget._columns[0]["constraints"]["enum"]
    assert not isinstance(constraints_enum[0], dict)
    assert not isinstance(constraints_enum[1], dict)

    widget._handle_qgrid_msg_helper({
        "type": "show_filter_dropdown",
        "field": 0,
        "search_val": None
    })
    widget._handle_qgrid_msg_helper({
        "field": 0,
        "filter_info": {
            "field": 0,
            "selected": [0],
            "type": "text",
            "excluded": [],
        },
        "type": "change_filter",
    })
    assert len(widget._df) == 1
    assert widget._df[0][0] == cat_series[0]
Beispiel #13
0
    def create_faults_relations_qgrid(self):
        faults_object = self._geo_model.faults

        # We need to add the qgrid special columns to categories if does not exist
        try:
            faults_object.faults_relations_df.columns = faults_object.faults_relations_df.columns.add_categories(
                ['index', 'qgrid_unfiltered_index'])
        except ValueError:
            pass

        qgrid_widget = qgrid.show_grid(faults_object.faults_relations_df,
                                       grid_options={'sortable': False, 'highlightSelectedCell': True},
                                       show_toolbar=False)

        def handle_set_fault_relation(event, widget, debug=False):
            if debug is True:
                print(event)
                print(widget)

            # This data frame is quite independent to anything else:
            self._geo_model.set_fault_relation(qgrid_widget.get_changed_df().values)

            # faults_object.faults_relations_df.update(qgrid_widget.get_changed_df())

            self.update_qgrd_objects()
            self.update_plot()
        qgrid_widget.on('cell_edited', handle_set_fault_relation)
        return qgrid_widget
Beispiel #14
0
    def create_options_qgrid(self):
        options_object = self._geo_model.additional_data.options

        qgrid_widget = qgrid.show_grid(options_object.df,
                                       show_toolbar=False,
                                       grid_options={'sortable': False, 'highlightSelectedCell': True})

        def handle_row_edit(event, widget, debug=False):
            if debug is True:
                print(event)
                print(widget)
                print(self)
                print(qgrid_widget._df)

            if event['column'] == 'verbosity':
                import numpy as np
                value = np.fromstring(event['new'][1:-1], sep=',')
            else:
                value = event['new']
            self._geo_model.modify_options(event['column'], value)
            self.update_qgrd_objects()
            self.update_plot()

        qgrid_widget.on('cell_edited', handle_row_edit)
        return qgrid_widget
Beispiel #15
0
    def show(self, show_raw=False):
        """
        used to show the data base as a qgrid object or if not installed pandas data frame
        :return: data frame as qgrid object or pandas object
        """
        self.wait()
        if found_qgrid:
            from IPython.display import display
            import ipywidgets as widgets
            rows = [
                d for d in self.column_sorting
                if d in list(self.df.keys()) and d not in self.columns_ignore
            ]
            rows += [
                d for d in list(self.df.keys()) if d not in self.column_sorting
                and d not in self.columns_ignore
            ]

            _openSelected = widgets.Button(description='open selected',
                                           disabled=False,
                                           button_style='',
                                           tooltip='open selected')
            _openSelected.on_click(self._on_openSelected_clicked)

            _batch_modifier = widgets.Button(
                description='for all selected rows',
                tooltip=
                'Change the selected attribute to the specified value for all rows selected.'
            )
            _batch_modifier.key_dd = widgets.Dropdown(options=rows,
                                                      description="Set")
            _batch_modifier.value_tf = widgets.Text(value='',
                                                    placeholder='Value',
                                                    description='to:')
            _batch_modifier.on_click(self._batch_change_attribute)

            display(
                widgets.HBox([
                    _openSelected, _batch_modifier.key_dd,
                    _batch_modifier.value_tf, _batch_modifier
                ]))

            if show_raw or "rating" not in self.df.keys():
                df = self.df.copy()
            else:
                df = self.df.copy()[self.df['rating'] > 0]
            self.grid = qd.show_grid(
                df[rows],
                show_toolbar=False,
                grid_options={'enableColumnReorder': True})
            self.grid.observe(self._on_row_selected, names=['_selected_rows'])
            self.grid.observe(
                self._grid_observer, names=['_selected_rows']
            )  #Quick fix to also work with newer versions of qgrid. Should be changed to the .on() event mechanism at some point, but this requires newer qgrid version.
            return self.grid
        else:
            if show_raw or "rating" not in self.df.keys():
                return self.df
            else:
                return self.df[self.df['rating'] > 0]
Beispiel #16
0
    def displayPrepare(self, env):
        '''
        准备数据
        :param env: 当前环境
        :return: 
        '''
        self.env = env
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        else:
            self.boxParams = VBox()
            self.boxParams.layout = Layout(flex_flow = 'column', display = 'flex')
            self.packageWidgets()
            display(self.boxParams)

            self.gdParamValue = qgrid.show_grid(pd.DataFrame([]),
                                                grid_options = {'filterable': False, 'autoHeight': True,
                                                                'editable': False})
            self.gdParamValue.layout = Layout(width = '90%')
            self.packageParams()
            self.txtBodyValue = Textarea(value = self.data if self.data is not None else '')
            self.txtBodyValue.layout = Layout(width = '90%', height = '200px', margin = '6px 2px 2px 2px')

            boxRequest = Box([
                VBox([Label(value = '请求参数值:'), self.gdParamValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto')),
                VBox([Label(value = '请求体参数值:'), self.txtBodyValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto'))],
                layout = Layout(flex_flow = 'row', display = 'flex'))
            acRef = Accordion(children = [boxRequest])
            acRef.set_title(0, '输入参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)
Beispiel #17
0
def test_object_dtype_categorical():
    cat_series = pd.Series(
        pd.Categorical(my_object_vals, categories=my_object_vals))
    widget = show_grid(cat_series)
    constraints_enum = widget._columns[0]['constraints']['enum']
    assert not isinstance(constraints_enum[0], dict)
    assert not isinstance(constraints_enum[1], dict)

    widget._handle_qgrid_msg_helper({
        'type': 'get_column_min_max',
        'field': 0,
        'search_val': None
    })
    widget._handle_qgrid_msg_helper({
        'field': 0,
        'filter_info': {
            'field': 0,
            'selected': [0],
            'type': "text",
            'excluded': []
        },
        'type': "filter_changed"
    })
    assert len(widget._df) == 1
    assert widget._df[0][0] == cat_series[0]
Beispiel #18
0
def load_image_log(watchfolder, optional_column_names=[]):
    try:
        existing_df = load_qgrid.loaded_qgrid.get_changed_df().dropna()
    except:
        existing_df = None
    try:
        if watchfolder != load_image_log.old_watchfolder:
            existing_df = None
            load_qgrid.loaded_qgrid.close()
    except:
        pass
    df = get_newest_df(watchfolder,
                       optional_column_names=optional_column_names,
                       existing_df=existing_df)
    load_image_log.old_watchfolder = watchfolder
    for column in optional_column_names:
        if column not in df.columns:
            df[column] = nan
    df.index = range(len(df.index))

    col_opts = {'editable': False}
    col_defs = {}
    for col_name in optional_column_names + ['badshot', 'notes']:
        col_defs[col_name] = {'editable': True}
    col_defs['badshot']['ColumnWidth'] = 50
    qgrid_widget = qgrid.show_grid(df,
                                   grid_options={
                                       'forceFitColumns': False,
                                       'defaultColumnWidth': 100
                                   },
                                   column_options=col_opts,
                                   column_definitions=col_defs)
    qgrid_widget.on('cell_edited', save_image_log)
    display(qgrid_widget)
    return qgrid_widget
Beispiel #19
0
    def __init__(self, expenses=None, **kwargs):
        if 'layout' not in kwargs:
            kwargs['layout'] = {'width': 'auto'}

        if expenses is not None and all(
            [isinstance(e, Expense) for e in expenses]):
            self.expense_section = ExpenseSection(expenses=expenses)
        else:
            self.expense_section = ExpenseSection()

        kwargs['children'] = [
            self.expense_section,
            widgets.Button(description='Add Expense'),
            widgets.HBox(children=[
                widgets.Label('Projection Length'),
                widgets.IntText(value=90, layout={'width': '100px'}),
                widgets.Button(description='Plot', layout={'width': '60px'})
            ],
                         layout=bar_layout),
            qgrid.show_grid(pd.DataFrame()),
            widgets.Output()
        ]

        super().__init__(**kwargs)
        self.project()

        self.setup_expense_bar()
        self.children[1].on_click(self.add_expense)
        self.children[2].children[1].observe(self.project, 'value')
        self.children[2].children[2].on_click(self.plot)
 def lista_ppgs(self):
     df = self.df_ppgs[['nm_programa_ies', 'sg_entidade_ensino', 'nm_area_avaliacao','sg_uf_programa','bow','tfidf']]\
                               .sort_values(by=['sg_uf_programa','nm_area_avaliacao'])
     df.columns = [
         'Nome', 'IES', 'Área', 'UF', 'Conceitos mais frequentes',
         'Conceitos particulares ao PPG'
     ]
     qg = qgrid.show_grid(df,\
                   show_toolbar=True,\
       grid_options={\
          'forceFitColumns': False, \
          'editable': False, \
          'fullWidthRows': True \
          }, \
       column_options={\
          'enableTextSelectionOnCells':True,\
          'enableColumnReorder':True \
          },\
       column_definitions={'Conceitos mais frequentes':{'width':500}, \
                                       'Conceitos particulares ao PPG':{'width':500}, \
                                       'Nome': {'width':240}, \
                                       '_id': {'width':120}, \
                                       'IES': {'width':40}, \
                                       'UF':{'width':40}})
     display(qg)
Beispiel #21
0
 def listen(self, _range1, _range2, stopwords):
     if stopwords == 'Not included':
         if self.conflicts_dict["Not included"] is None:
             conflicts_not_included = remove_stopwords(self.sources["tokens_source"]["conflicts_all"],self.lng).reset_index(drop=True)
             self.conflicts_dict["Not included"] = self.add_columns(conflicts_not_included)
             self.conflicts_dict["Not included"] = self.get_displayed_df(_range1, _range2, self.conflicts_dict["Not included"])
             conflicts = self.conflicts_dict["Not included"]
         else:
             conflicts = self.conflicts_dict["Not included"]
             
     else:
         if self.conflicts_dict["Included"] is None:
             link_df = self.sources["tokens_source"]["conflicts_all"]
             self.conflicts_dict["Included"] = link_df
             del link_df
             conflicts_included = self.add_columns(self.conflicts_dict["Included"])
             self.conflicts_dict["Included"] = self.add_columns(conflicts_included)
             self.conflicts_dict["Not Included"] = self.get_displayed_df(_range1, _range2, self.conflicts_dict["Included"])
             conflicts = self.conflicts_dict["Included"]
         else:
             conflicts = self.conflicts_dict["Included"]
         
     
     if len(conflicts) > 0:
         qgrid_token_obj = qgrid.show_grid(conflicts,grid_options={'forceFitColumns':False})
         display(qgrid_token_obj)
         
     else:
         display(md(f'**There are no conflicting tokens in this page.**'))
         display(HTML(f'<a href="{get_previous_notebook()}" target="_blank">Go back to the previous workbook</a>'))
Beispiel #22
0
def test_object_dtype_categorical():
    cat_series = pd.Series(
        pd.Categorical(my_object_vals,
                       categories=my_object_vals)
    )
    widget = show_grid(cat_series)
    constraints_enum = widget._columns[0]['constraints']['enum']
    assert not isinstance(constraints_enum[0], dict)
    assert not isinstance(constraints_enum[1], dict)

    widget._handle_qgrid_msg_helper({
        'type': 'show_filter_dropdown',
        'field': 0,
        'search_val': None
    })
    widget._handle_qgrid_msg_helper({
        'field': 0,
        'filter_info': {
            'field': 0,
            'selected': [0],
            'type': "text",
            'excluded': []
        },
        'type': "change_filter"
    })
    assert len(widget._df) == 1
    assert widget._df[0][0] == cat_series[0]
Beispiel #23
0
    def create_kriging_parameters_qgrid(self):
        kriging_parameters_object = self._geo_model._additional_data.kriging_data

        qgrid_widget = qgrid.show_grid(
            kriging_parameters_object.df,
            show_toolbar=False,
            grid_options={
                'sortable': False,
                'highlightSelectedCell': True
            },
        )

        def handle_row_edit(event, widget, debug=False):

            if debug is True:
                print(event)
                print(widget)
                print(qgrid_widget._df)

            self._geo_model.modify_kriging_parameters(event['column'],
                                                      event['new'])
            self.update_qgrd_objects()
            self.update_plot()

        qgrid_widget.on('cell_edited', handle_row_edit)
        return qgrid_widget
Beispiel #24
0
def show_results_jup(results):
    import pandas as pd
    from IPython.display import display
    import qgrid
    from sklearn.metrics import accuracy_score,precision_score, recall_score, f1_score

    df = pd.DataFrame(dict((x, results[x]) for x in results)).set_index('sentence')
    col_options = {
        'width': 80,
    }
    col_defs = {
        'sentence': {
            'width': 1000,
        }
    }
    for x in 'label prediction'.split():
        df[x] = df[x].astype('bool')

    df['correct'] = (df['label'] == df['prediction'])
    q=qgrid.show_grid(df, row_edit_callback=lambda x: False, column_options=col_options,
                    column_definitions=col_defs, show_toolbar=False, grid_options={'forceFitColumns': True})
    for x in accuracy_score,precision_score, recall_score, f1_score:
        score = x(df.label.values, df.prediction.values)
        print('%s: %.1f%%' % (x.__name__.replace('_score', '').capitalize().ljust(15), score * 100))
    display(q)
Beispiel #25
0
    def create_faults_qgrid(self):
        faults_object = self._geo_model.faults

        qgrid_widget = qgrid.show_grid(faults_object.df,
                                       show_toolbar=False,
                                       grid_options={'sortable': False, 'highlightSelectedCell': True},
                                       column_options={'editable': True},
                                       column_definitions={'isFinite': {'editable': True}})

        def handle_set_is_fault(event, widget, debug=False):
            if debug is True:
                print(event)
                print(widget)

            if event['column'] == 'isFault':
                idx = event['index']
                #      cat_idx = qgrid_widget.df.loc[idx, 'series_names']

                self._geo_model.set_is_fault([idx], toggle=True)
                self.update_plot()

            if event['column'] == 'isFinite':
                idx = event['index']
                #      cat_idx = qgrid_widget.df.loc[idx, 'series_names']

                self._geo_model.set_is_finite_fault([idx], toggle=True)
                self.update_plot()

            self.update_qgrd_objects()
            self.qgrid_fr._rebuild_widget()

        qgrid_widget.on('cell_edited', handle_set_is_fault)

        return qgrid_widget
Beispiel #26
0
 def loadDataInMemory(self, b):
     """
     Load numpy array with selected entries from tree into memory
     Temporary data.csv file created
     TODO: make in memory transformation
     :return: success stratus
     """
     varSet = set()
     for var in self.sliderArray.fVariableList:
         varSet.add(var)
     for var in self.drawVarArray.fVariableList:
         varSet.add(var)
     variables = ""
     for var in varSet:
         variables += var + ":"
     value = ROOT.AliTreePlayer.selectWhatWhereOrderBy(
         self.fTree, str(variables), str(self.drawSelection.value), "", 0,
         10000000, "csvroot", "data.csv")
     print(value)
     if value <= 0: return value
     self.fDataFrame = readDataFrame('data.csv')
     self.boxAll.children = [
         x for x in self.boxAll.children if x != self.fQgrid
     ]
     self.fQgrid = qgrid.show_grid(self.fDataFrame)
     self.boxAll.children += (self.fQgrid, )
Beispiel #27
0
 def on_select_change(self, change):
     "First click."
     with self.out:
         clear_output()
         date_selected = self.qgrid_obj.get_selected_df().reset_index()["rev_time"].iloc[0]
         editor_selected = self.qgrid_obj.get_selected_df().reset_index()["editor_id"].iloc[0]
         editor_name = self.qgrid_obj.get_selected_df().reset_index()["editor"].iloc[0]
         page_title = self.all_tokens["article_title"].unique()[0]
         
         display(md("Loading revisions info..."))
         second_df = self.revision_manager.get_main(date_selected, editor_selected, self.current_freq)
         clear_output()
         
         display(md(f"Within **{self.current_freq}** timeframe, you have selected **{editor_name}** (id: {editor_selected})"))
         display(HTML(f"The revisions fall in <a href='https://{self.lng}.wikipedia.org/w/index.php?date-range-to={date_selected}&tagfilter=&title={page_title}&action=history' target='_blank'>{date_selected}</a>"))
         
         second_df.rename({"main_opponent": "main_op", "stopwords_ratio": "SW_ratio",
                          "productivity": "prod"}, axis=1, inplace=True)
         columns_set = {"rev_time": {"width": 165}, "rev_id": {"width": 85}, "adds": {"width": 50}, "dels": {"width": 50},
            "reins": {"width": 50}, "prod": {"width": 50, "toolTip": "productivity"}, "conflict": {"width": 70},
            "SW_ratio": {"width": 82, "toolTip": "stopwords ratio"},
            "main_op": {"width": 80, "toolTip": "main opponent"},
            "min_react": {"width": 132, "toolTip": "min reaction time"},
            "Damaging": {"width": 92}, "Goodfaith": {"width": 90}}
         self.second_qgrid = qgrid.show_grid(second_df, grid_options={'forceFitColumns': True,
                                                 'syncColumnCellResize': True}, column_definitions=columns_set)
         display(self.second_qgrid)
         
         self.out2 = Output()
         display(self.out2)
         self.second_qgrid.observe(self.on_select_revision, names=['_selected_rows'])
Beispiel #28
0
    def qgridDisplay(self, result_df, mycnt):

        # Determine the height of the qgrid (number of Visible Rows)
        def_max_rows = int(self.opts['display_qg_maxVisibleRows'][0])
        def_min_rows = int(self.opts['display_qg_maxVisibleRows'][0])
        max_rows = def_max_rows
        min_rows = def_min_rows
        if mycnt >= def_max_rows:
            max_rows = def_max_rows
            min_rows = def_min_rows
        elif mycnt + 2 <= def_max_rows:
            max_rows = def_max_rows
            min_rows = mycnt + 2

        mygridopts = {'forceFitColumns': False, 'maxVisibleRows': max_rows, 'minVisibleRows': min_rows, 'defaultColumnWidth': int(self.opts['display_qg_defaultColumnWidth'][0])}
        mycoldefs = {}

        # Determine Index width
        if int(self.opts['display_qg_display_idx'][0]) == 1:
            mydispidx = True
        else:
            mydispidx = False
            mycoldefs['index'] = { 'maxWidth': 0, 'minWidth': 0, 'width': 0 }
        if self.debug:
            print("mydispidx: %s" % mydispidx)

        # Handle Column Autofit
        if self.opts['display_qg_autofit_cols'][0] == True:
            maxColumnLenghts = []
            for col in range(len(result_df.columns)):
                maxColumnLenghts.append(max(result_df.iloc[:,col].astype(str).apply(len)))
            dict_size = dict(zip(result_df.columns.tolist(), maxColumnLenghts))
            text_factor = self.opts['display_qg_text_factor'][0]
            colmin = self.opts['display_qg_colmin'][0]
            colmax = self.opts['display_qg_colmax'][0]
            header_autofit = self.opts['display_qg_header_autofit'][0]
            header_pad = self.opts['display_qg_header_pad'][0]
            for k in dict_size.keys():
                if mydispidx or k != "index":
                    if header_autofit:
                        col_size = len(str(k)) + int(header_pad)
                        if dict_size[k] > col_size :
                            col_size = dict_size[k]
                    else:
                        col_size = dict_size[k]
                    mysize =  text_factor * col_size
                    if mysize < colmin:
                         mysize = colmin
                    if mysize > colmax:
                        mysize = colmax
                    mycoldefs[k] = {'width': mysize}


        if self.debug:
            print("mygridopts: %s" % mygridopts)
            print("")
            print("mycoldefs: %s" % mycoldefs)
        # Display the QGrid
        display(qgrid.show_grid(result_df, grid_options=mygridopts, column_definitions=mycoldefs))
Beispiel #29
0
 def make_default_qgridw(self):
     qgridw = qgrid.show_grid(
         DataFrame(),
         grid_options={"editable": False},
         column_options={"editable": False},
         column_definitions={"index": {"width": "20"}},
     )
     return qgridw
Beispiel #30
0
def grid_m():
    df1 = pd.DataFrame(monster_data)
    df1 = df1.astype(object).replace('None', np.nan)
    for row in df1.iterrows():
        row[1]['langage_prog']=str(row[1]['langage_prog'])+", "+str(row[1]['langage2'])+", "+str(row[1]['langage3'])+", "+str(row[1]['langage4'])
    df = df1.drop(["langage4", "langage2", "langage3"], axis = 1)    
    df_qgrid = qgrid.show_grid(df, show_toolbar=True)
    return df_qgrid
Beispiel #31
0
    def listen(self):
        main_df = self.get_editor_month()
        #main_df.index.name = "year_month"

        self.qg_obj = qgrid.show_grid(main_df)
        display(self.qg_obj)
        display(self.out)
        self.qg_obj.observe(self.on_selection_change, names=['_selected_rows'])
    def _buildEdit(self):
        """
        Creates the link qgrid widget
        """

        self._listLinkSource = ['']
        self._listLinkTarget = ['']
      
        parse = os.path.split(self._datas['Path'])[0]
        parsing = pparse.model_parser(parse)

        for i in parsing:
            if 'unit.{}.xml'.format(i.name) in self._listmodel: 
                for j in i.inputs:
                    self._listLinkTarget.append('{}.{}'.format(i.name, j.name))

                for k in i.outputs:
                    self._listLinkSource.append('{}.{}'.format(i.name, k.name))

        for model in self._listmodel:
            if ':' in model:
                pkgname, model_attr = model.split(':')
                model_attr = model_attr.split('.')
                path, = [i for i in self._listextpkg if pkgname in os.path.split(i)[1]]

                if model_attr[0] == 'composition':
                    pkg, = model_parser(path+os.path.sep+'crop2ml'+os.path.sep+'composition.{}.xml'.format(model_attr[1]))
                    for j in pkg.inputs:
                        self._listLinkTarget.append('{}.{}'.format(model_attr[1], j))
                    for k in pkg.outputs:
                        self._listLinkSource.append('{}.{}'.format(model_attr[1], k))
                
                else:
                    pkg = pparse.model_parser(path)
                    for m in pkg:
                        if m.name == model_attr[1]:
                            for y in m.inputs:
                                self._listLinkTarget.append('{}.{}'.format(model_attr[1], y.name))
                            for z in m.outputs:
                                self._listLinkSource.append('{}.{}'.format(model_attr[1], z.name))
                            break


        if self._iscreate:
            self._dfLink = pandas.DataFrame(data={
                'Link type': pandas.Categorical([''], categories=['','InputLink','InternalLink','OutputLink'], ordered=True),
                'Source': pandas.Categorical([''], categories=self._listLinkSource),
                'Target': pandas.Categorical([''], categories=self._listLinkTarget)
                })
        
        else:
            self._dfLink = pandas.DataFrame(data={
                'Link type': pandas.Categorical([i['Link type'] for i in self._listlink], categories=['','InputLink','InternalLink','OutputLink'], ordered=True),
                'Source': pandas.Categorical([i['Source'] if i['Source'] in self._listLinkSource else '' for i in self._listlink], categories=self._listLinkSource),
                'Target': pandas.Categorical([i['Target'] if i['Target'] in self._listLinkTarget else '' for i in self._listlink], categories=self._listLinkTarget)
                })
        
        self._dfLinkqgrid = qgrid.show_grid(self._dfLink, show_toolbar=True)
Beispiel #33
0
def qgrid(*args, **kwargs):
    import qgrid
    return qgrid.show_grid(*args,
                           **kwargs,
                           grid_options={
                               'forceFitColumns': False,
                               'defaultColumnWidth': 200
                           },
                           show_toolbar=True)
Beispiel #34
0
def show_grid(z, force_fit=False):
    import qgrid

    qgrid.set_defaults(remote_js=True, precision=4)

    new = pd.DataFrame()
    for x in z.columns:
        new[" ".join(x)] = z[x]
    return qgrid.show_grid(new, grid_options={"forceFitColumns": force_fit, "defaultColumnWidth": 120})
Beispiel #35
0
def test_instance_created():
    event_history = init_event_history(All)
    qgrid_widget = show_grid(create_df())

    assert event_history == [
        {
            'name': 'instance_created'
        }
    ]
    assert qgrid_widget.id
Beispiel #36
0
    def jsdf(self, line):
        """
        defines ``%jsdf``
        which displays a pandas dataframe into a notebook using qgrid (javascript)

        .. nbref::
            :title: jsdf

            The magic command ``%jsdf`` displays a dataframe using
            `qgrid <https://qgrid.readthedocs.io/en/latest/>`_ module.
            The code is the following::

                import qgrid
                if firt_call:
                    qgrid.set_defaults(precision=<precision>)
                    self.first_jsdf_call = False

                df = args.df
                grid_options = dict(defaultColumnWidth=<defaultColumnWidth>,
                                    enableColumnReorder=<enableColumnReorder>,
                                    multiColumnSort=<multiColumnSort>,
                                    rowHeight=<rowHeight>,
                                    showHeaderRow=<showHeaderRow>,
                                    forceFitColumns=<forceFitColumns>,
                                    autoHeight=<autoHeight>,
                                    enableCellNavigation=<enableCellNavigation>)
                qgrid.show_grid(df, grid_options=grid_options)
        """
        parser = self.get_parser(MagicNotebook.jsdf_parser, "jsdf")
        args = self.get_args(line, parser)

        if not hasattr(self, "first_jsdf_call") or self.first_jsdf_call:
            if args is not None:
                qgrid.set_defaults(precision=args.precision)
            else:
                qgrid.set_defaults()
            self.first_jsdf_call = False

        if args is not None:
            df = args.df
            grid_options = dict(defaultColumnWidth=args.defaultColumnWidth,
                                enableColumnReorder=args.enableColumnReorder,
                                multiColumnSort=args.multiColumnSort,
                                rowHeight=args.rowHeight,
                                showHeaderRow=args.showHeaderRow,
                                forceFitColumns=args.forceFitColumns,
                                autoHeight=args.autoHeight,
                                enableCellNavigation=args.enableCellNavigation,
                                editable=args.editable)
            res = qgrid.show_grid(df, grid_options=grid_options)
            return "" if res is None else res
Beispiel #37
0
    def display_fancy(self, results):
        if isinstance(results, ResultSet):
            results = results.DataFrame()

        if len(results) == 0:
            print("No results found.")
            return

        num_results = len(self.results)
        width = int(math.ceil(math.log10(len(results))))
        fmt_str = "#{{result}}.{{row:0>{width}}}".format(width=width)
        index = Series(fmt_str.format(result=num_results, row=row) for row in range(len(results)))

        results.insert(0, '#', index)
        results = results.set_index('#')

        results = self.process_rows(results)

        self.results.append(results)

        return qgrid.show_grid(results, remote_js=True)
Beispiel #38
0
def test_interval_index():
    df = create_interval_index_df()
    df.set_index('time_bin', inplace=True)
    show_grid(df)
Beispiel #39
0
 def _ipython_display(self):
     if qgrid:
         return qgrid.show_grid(self, remote_js=nbviewer_mode())
     else:
         print
         return display(self)
# First time you use it you have to run, in a notebook, the following code:  
# ```
# import qgrid
# qgrid.nbinstall(overwrite=True)
# ```
# 
# Using it is simple:

# In[16]:

from qgrid import show_grid


# In[17]:

show_grid(df_auto)


# **Several things to note:** 
# - If you save the notebook with these `qgrids` it is going to increase the file-size dramatically, it essentially saves the data with the notebook. Try to avoid this, use it only for inspection.
# - Opening very big dataframes using `show_grid()` is usually not a good idea.  
# - These `qgrids` will only display locally, not on GitHub. Therefore, if you see this on GitHub, you will not see the actual `qgrid`.
# - There are a bunch of options you can use with `show_grid()`, you can for example add `show_toolbar=True`.

# ## Select parts of the dataframe

# It is a very helpful skill to be able to quickly generate a view that you want.   

# ### View entire dataframe

# In[18]:
Beispiel #41
0
def test_multi_interval_index():
    df = create_interval_index_df()
    df['A'] = np.array([3] * 1000, dtype='int32')
    df.set_index(['time', 'time_bin'], inplace=True)
    show_grid(df)
Beispiel #42
0

# ## Notebook extensions
# 
# Check out http://nbviewer.ipython.org/github/quantopian/qgrid/blob/master/qgrid_demo.ipynb for more (including demo)
# 

# In[ ]:

import qgrid # Best practices is to put imports at the top of the Notebook.
qgrid.nbinstall(overwrite=True)


# In[ ]:

qgrid.show_grid(dframe[['MSHA_ID', 'Year', 'Mine_Name', 'Mine_State', 'Mine_County']], remote_js=True)


# ## SQL queries
# 
# An updated implementation SQL magic command from Christian Perez at SVDS https://github.com/cfperez/ipython-sql

# In[ ]:

get_ipython().magic(u'load_ext sql')
get_ipython().magic(u'reload_ext sql')


# In[ ]:

get_ipython().magic(u'config SqlMagic.autopandas=True')