问:
GTK3 C program push button in GTKScrolled Window with GTKTreeView with GTKListStore to scroll row into view
I ported a program to GTK3 in C language and everything works perfect except one thing. Say the TreeView that only shows 10 rows at a time, but is populated with 100 rows, the other rows out of view of course with tree view set to Single select rows with multple colums.

I use a button callback function to highlight and then select row 0, then increment a static index++ at end of call. Next button press highlights and selects row 1, and so forth.

When highlighted and selected row gets to the 11th row, which is out of view, I can't figure out how to scroll the tree view so that the next 11th row comes into view. The rows keep getting highlighted, cause I have printf statements for feedback. I googled for weeks, seen examples and everything, but not so much for C, although I had to translate some other code to C that I used to figure out how to select and highlight the rows, but in C couldn't figure out the scrolling part.

Using Glade, I have a main window with a child GtkFixed, with a button, progress bar, and in the GtkFixed is a GtkScrolledWindow, which contains a GtkViewPort, in which inside that is the GtkTreeView with string based columns.

Thanks for any feedback and or links. Not sure if the TreeView needs to be inside a GtkViewPort, but might have looked at older code during development and research.

my callback function

```<code>void single_button_clicked_cb(GtkWidget *widget, gpointer data)
{
    static int         index = 0;
    GtkTreeIter iter;
    char buf[9];
    GtkTreeModel *model;
    GtkAdjustment *vadjustment;
    int i;

    printf("\nScroll Active test row to %d\n",index);

    sprintf(buf,"%d",index);

    gtk_widget_grab_focus (GTK_WIDGET(gtk_tree_view));

    GtkTreePath *path = gtk_tree_path_new_from_string(buf);

    gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW (gtk_tree_view),path, NULL,FALSE, 0.0, 0.0);

    gtk_tree_view_set_cursor (gtk_tree_view,path,NULL,FALSE); // works but doesn't scroll

    gtk_tree_path_free(path);

    index++;
}
</code>```

Glade File

```<code><?xml version="1.0" encoding="UTF-8"?>
<interface>
  <!-- interface-requires gtk+ 3.0 -->
  <!-- interface-naming-policy toplevel-contextual -->
  <object class="GtkAdjustment" id="adjustment1">
    <property name="upper">100</property>
    <property name="step_increment">1</property>
    <property name="page_increment">10</property>
  </object>
  <object class="GtkListStore" id="gtk_list_store">
    <columns>
      <!-- column-name Test -->
      <column type="gchararray"/>
      <!-- column-name Test1 -->
      <column type="gchararray"/>
      <!-- column-name Test2 -->
      <column type="gchararray"/>
      <!-- column-name Test3 -->
      <column type="gchararray"/>
      <!-- column-name Test4 -->
      <column type="gchararray"/>
      <!-- column-name Pass -->
      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="main_window">
    <property name="width_request">1050</property>
    <property name="height_request">810</property>
    <property name="can_focus">False</property>
    <property name="border_width">3</property>
    <property name="resizable">False</property>
    <property name="window_position">center</property>
    <property name="gravity">center</property>
    <signal name="destroy" handler="on_main_window_destroy" swapped="no"/>
    <child>
      <object class="GtkFixed" id="gtk_fixed">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkButton" id="start_button">
            <property name="label" translatable="yes">Start</property>
            <property name="width_request">100</property>
            <property name="height_request">48</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="start_button_clicked_cb" swapped="no"/>
          </object>
          <packing>
            <property name="x">935</property>
            <property name="y">605</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="single_button">
            <property name="label" translatable="yes">Single</property>
            <property name="width_request">100</property>
            <property name="height_request">48</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="single_button_clicked_cb" swapped="no"/>
          </object>
          <packing>
            <property name="x">6</property>
            <property name="y">605</property>
          </packing>
        </child>
        <child>
          <object class="GtkProgressBar" id="progress_bar">
            <property name="width_request">1030</property>
            <property name="height_request">25</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
          </object>
          <packing>
            <property name="x">1</property>
            <property name="y">100</property>
          </packing>
        </child>
        <child>
          <object class="GtkScrolledWindow" id="scrolled_window">
            <property name="width_request">1030</property>
            <property name="height_request">465</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="vadjustment">adjustment1</property>
            <property name="hscrollbar_policy">never</property>
            <property name="vscrollbar_policy">automatic</property>
            <child>
              <object class="GtkViewport" id="gtk_viewport">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <child>
                  <object class="GtkTreeView" id="gtk_tree_view">
                    <property name="visible">True</property>
                    <property name="can_focus">True</property>
                    <property name="model">gtk_list_store</property>
                    <property name="headers_clickable">False</property>
                    <property name="enable_grid_lines">both</property>
                    <signal name="cursor-changed" handler="selected_row_index_cb" swapped="no"/>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_description">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Description</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_description"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_number">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Number</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_number"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_limits">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Limits</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_limits"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_measurement">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Measurement</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_measurement"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_units">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Units</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_units"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_pass_fail">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Pass / Fail</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_pass_fail"/>
                        </child>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">132</property>
          </packing>
        </child>
        <child>
          <object class="GtkMenuBar" id="menu">
            <property name="width_request">180</property>
            <property name="height_request">30</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <child>
              <object class="GtkMenuItem" id="gtk_file_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_File</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_file_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_new">
                        <property name="label">gtk-new</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_open">
                        <property name="label">gtk-open</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                        <signal name="activate" handler="open_limits_file" swapped="no"/>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_save">
                        <property name="label">gtk-save</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_save_as">
                        <property name="label">gtk-save-as</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSeparatorMenuItem" id="separatormenuitem1">
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_quit">
                        <property name="label">gtk-quit</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                        <signal name="activate" handler="on_main_window_destroy" swapped="no"/>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_edit_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Edit</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_edit_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem6">
                        <property name="label">gtk-cut</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem7">
                        <property name="label">gtk-copy</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem8">
                        <property name="label">gtk-paste</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem9">
                        <property name="label">gtk-delete</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_view_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_View</property>
                <property name="use_underline">True</property>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_help_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Help</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_help_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem10">
                        <property name="label">gtk-about</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="x">-1</property>
            <property name="y">-1</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="test_name">
            <property name="width_request">1030</property>
            <property name="height_request">80</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="use_markup">True</property>
            <property name="justify">center</property>
            <property name="single_line_mode">True</property>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">667</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="test_command">
            <property name="width_request">1030</property>
            <property name="height_request">80</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="use_markup">True</property>
            <property name="justify">center</property>
            <property name="single_line_mode">True</property>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">32</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>
</code>```

答:
I finally found the issue. Another example I found had the treeview as a child of a view port. Maybe from a previous version of GTK.

From Documentation Gnome Developer Documentation for GtkScrolledWindow

The scrolled window can work in two ways. Some widgets have native scrolling support; these widgets implement the GtkScrollable interface. Widgets with native scroll support include GtkTreeView, GtkTextView, and GtkLayout.

For widgets that lack native scrolling support, the GtkViewport widget acts as an adaptor class, implementing scrollability for child widgets that lack their own scrolling capabilities. Use GtkViewport to scroll child widgets such as GtkGrid, GtkBox, and so on.

Body:
I ported a program to GTK3 in C language and everything works perfect except one thing. Say the TreeView that only shows 10 rows at a time, but is populated with 100 rows, the other rows out of view of course with tree view set to Single select rows with multple colums.

I use a button callback function to highlight and then select row 0, then increment a static index++ at end of call. Next button press highlights and selects row 1, and so forth.

When highlighted and selected row gets to the 11th row, which is out of view, I can't figure out how to scroll the tree view so that the next 11th row comes into view. The rows keep getting highlighted, cause I have printf statements for feedback. I googled for weeks, seen examples and everything, but not so much for C, although I had to translate some other code to C that I used to figure out how to select and highlight the rows, but in C couldn't figure out the scrolling part.

Using Glade, I have a main window with a child GtkFixed, with a button, progress bar, and in the GtkFixed is a GtkScrolledWindow, which contains a GtkViewPort, in which inside that is the GtkTreeView with string based columns.

Thanks for any feedback and or links. Not sure if the TreeView needs to be inside a GtkViewPort, but might have looked at older code during development and research.

my callback function

void single_button_clicked_cb(GtkWidget *widget, gpointer data)
{
    static int         index = 0;
    GtkTreeIter iter;
    char buf[9];
    GtkTreeModel *model;
    GtkAdjustment *vadjustment;
    int i;

    printf("\nScroll Active test row to %d\n",index);

    sprintf(buf,"%d",index);

    gtk_widget_grab_focus (GTK_WIDGET(gtk_tree_view));

    GtkTreePath *path = gtk_tree_path_new_from_string(buf);

    gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW (gtk_tree_view),path, NULL,FALSE, 0.0, 0.0);

    gtk_tree_view_set_cursor (gtk_tree_view,path,NULL,FALSE); // works but doesn't scroll

    gtk_tree_path_free(path);

    index++;
}

Glade File

<?xml version="1.0" encoding="UTF-8"?>
<interface>

  <object class="GtkAdjustment" id="adjustment1">
    <property name="upper">100</property>
    <property name="step_increment">1</property>
    <property name="page_increment">10</property>
  </object>
  <object class="GtkListStore" id="gtk_list_store">
    <columns>

      <column type="gchararray"/>

      <column type="gchararray"/>

      <column type="gchararray"/>

      <column type="gchararray"/>

      <column type="gchararray"/>

      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="main_window">
    <property name="width_request">1050</property>
    <property name="height_request">810</property>
    <property name="can_focus">False</property>
    <property name="border_width">3</property>
    <property name="resizable">False</property>
    <property name="window_position">center</property>
    <property name="gravity">center</property>
    <signal name="destroy" handler="on_main_window_destroy" swapped="no"/>
    <child>
      <object class="GtkFixed" id="gtk_fixed">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkButton" id="start_button">
            <property name="label" translatable="yes">Start</property>
            <property name="width_request">100</property>
            <property name="height_request">48</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="start_button_clicked_cb" swapped="no"/>
          </object>
          <packing>
            <property name="x">935</property>
            <property name="y">605</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="single_button">
            <property name="label" translatable="yes">Single</property>
            <property name="width_request">100</property>
            <property name="height_request">48</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <signal name="clicked" handler="single_button_clicked_cb" swapped="no"/>
          </object>
          <packing>
            <property name="x">6</property>
            <property name="y">605</property>
          </packing>
        </child>
        <child>
          <object class="GtkProgressBar" id="progress_bar">
            <property name="width_request">1030</property>
            <property name="height_request">25</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
          </object>
          <packing>
            <property name="x">1</property>
            <property name="y">100</property>
          </packing>
        </child>
        <child>
          <object class="GtkScrolledWindow" id="scrolled_window">
            <property name="width_request">1030</property>
            <property name="height_request">465</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="vadjustment">adjustment1</property>
            <property name="hscrollbar_policy">never</property>
            <property name="vscrollbar_policy">automatic</property>
            <child>
              <object class="GtkViewport" id="gtk_viewport">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <child>
                  <object class="GtkTreeView" id="gtk_tree_view">
                    <property name="visible">True</property>
                    <property name="can_focus">True</property>
                    <property name="model">gtk_list_store</property>
                    <property name="headers_clickable">False</property>
                    <property name="enable_grid_lines">both</property>
                    <signal name="cursor-changed" handler="selected_row_index_cb" swapped="no"/>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_description">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Description</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_description"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_number">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Number</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_number"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_limits">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Limits</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_limits"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_measurement">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Measurement</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_measurement"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_units">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Test Units</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_units"/>
                        </child>
                      </object>
                    </child>
                    <child>
                      <object class="GtkTreeViewColumn" id="col_test_pass_fail">
                        <property name="resizable">True</property>
                        <property name="title" translatable="yes">Pass / Fail</property>
                        <property name="alignment">0.5</property>
                        <child>
                          <object class="GtkCellRendererText" id="col_renderer_pass_fail"/>
                        </child>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">132</property>
          </packing>
        </child>
        <child>
          <object class="GtkMenuBar" id="menu">
            <property name="width_request">180</property>
            <property name="height_request">30</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <child>
              <object class="GtkMenuItem" id="gtk_file_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_File</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_file_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_new">
                        <property name="label">gtk-new</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_open">
                        <property name="label">gtk-open</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                        <signal name="activate" handler="open_limits_file" swapped="no"/>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_save">
                        <property name="label">gtk-save</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_save_as">
                        <property name="label">gtk-save-as</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkSeparatorMenuItem" id="separatormenuitem1">
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="gtk_quit">
                        <property name="label">gtk-quit</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                        <signal name="activate" handler="on_main_window_destroy" swapped="no"/>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_edit_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Edit</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_edit_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem6">
                        <property name="label">gtk-cut</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem7">
                        <property name="label">gtk-copy</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem8">
                        <property name="label">gtk-paste</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem9">
                        <property name="label">gtk-delete</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_view_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_View</property>
                <property name="use_underline">True</property>
              </object>
            </child>
            <child>
              <object class="GtkMenuItem" id="gtk_help_menu_item">
                <property name="visible">True</property>
                <property name="can_focus">False</property>
                <property name="label" translatable="yes">_Help</property>
                <property name="use_underline">True</property>
                <child type="submenu">
                  <object class="GtkMenu" id="gtk_help_menu">
                    <property name="visible">True</property>
                    <property name="can_focus">False</property>
                    <child>
                      <object class="GtkImageMenuItem" id="imagemenuitem10">
                        <property name="label">gtk-about</property>
                        <property name="visible">True</property>
                        <property name="can_focus">False</property>
                        <property name="use_underline">True</property>
                        <property name="use_stock">True</property>
                      </object>
                    </child>
                  </object>
                </child>
              </object>
            </child>
          </object>
          <packing>
            <property name="x">-1</property>
            <property name="y">-1</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="test_name">
            <property name="width_request">1030</property>
            <property name="height_request">80</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="use_markup">True</property>
            <property name="justify">center</property>
            <property name="single_line_mode">True</property>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">667</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="test_command">
            <property name="width_request">1030</property>
            <property name="height_request">80</property>
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="use_markup">True</property>
            <property name="justify">center</property>
            <property name="single_line_mode">True</property>
          </object>
          <packing>
            <property name="x">3</property>
            <property name="y">32</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>


来源: stackexchange

问:
Drawbacks to Passing an Instance to ASP.NET Core Dependency Injection
I have a class that needs a connection string as a parameter to its constructor:

```<code>public class MyClassHere
{
     private string connectionString;

     public MyClassHere(string connectionString)
     {
        this.connectionString = connectionString;
     }
}
</code>```

I have added that class as a singleton to my service like this:

```<code>services.AddSingleton<MyClassHere>();
</code>```

Clearly this does not work, because it takes a string in the constructor.

I have seen examples that say do this:

```<code>services.AddSingleton<MyClassHere>(new MyClassHere("Some Connnection String"));
</code>```

But I have also read vague things say that when you do this the dependency injection system will not clean up your objects for you.

What (if any) are the drawbacks to passing an instance into the dependency injection system (rather than just letting it make it for you)?

答:
One drawback of doing this is that if the constructor of MyClassHere were to change, you'd have to update the usage of it in your DI registration. Which may or may not be trivial depending on how it's used.

Regardless, one way to handle this scenario in .NET Core while maintaining all of the benefits of dependency injection is by using the Options pattern.

Here's what that might look like given your example:

```<code>public class MyOptions
{
    public string ConnectionString { get; set; }
}

public class MyClassHere
{
    private readonly string _connectionString;

    public MyClassHere(IOptions<MyOptions> options)
    {
        _connectionString = options.Value.ConnectionString;
    }

    public void Foo() => Console.WriteLine(_connectionString);
}
</code>```

And here's an example of the registration:

```<code>static void Main(string[] args)
{
    var myClass = new ServiceCollection()
        .Configure<MyOptions>(o =>
        {
            o.ConnectionString = "bar";
        })
        .AddSingleton<MyClassHere>()
        .BuildServiceProvider()
        .GetService<MyClassHere>();

    myClass.Foo();

    Console.ReadLine();
}
</code>```

Which outputs "bar" as expected.

ContentLicense: CC BY-SA 4.0

Body:
I have a class that needs a connection string as a parameter to its constructor:

public class MyClassHere
{
     private string connectionString;

     public MyClassHere(string connectionString)
     {
        this.connectionString = connectionString;
     }
}

I have added that class as a singleton to my service like this:

services.AddSingleton<MyClassHere>();

Clearly this does not work, because it takes a string in the constructor.

I have seen examples that say do this:

services.AddSingleton<MyClassHere>(new MyClassHere("Some Connnection String"));

But I have also read vague things say that when you do this the dependency injection system will not clean up your objects for you.

What (if any) are the drawbacks to passing an instance into the dependency injection system (rather than just letting it make it for you)?

Body:
One drawback of doing this is that if the constructor of MyClassHere were to change, you'd have to update the usage of it in your DI registration. Which may or may not be trivial depending on how it's used.

Regardless, one way to handle this scenario in .NET Core while maintaining all of the benefits of dependency injection is by using the Options pattern.

Here's what that might look like given your example:

public class MyOptions
{
    public string ConnectionString { get; set; }
}

public class MyClassHere
{
    private readonly string _connectionString;

    public MyClassHere(IOptions<MyOptions> options)
    {
        _connectionString = options.Value.ConnectionString;
    }

    public void Foo() => Console.WriteLine(_connectionString);
}

And here's an example of the registration:

static void Main(string[] args)
{
    var myClass = new ServiceCollection()
        .Configure<MyOptions>(o =>
        {
            o.ConnectionString = "bar";
        })
        .AddSingleton<MyClassHere>()
        .BuildServiceProvider()
        .GetService<MyClassHere>();

    myClass.Foo();

    Console.ReadLine();
}

Which outputs "bar" as expected.


问:
GROUP BY multiple different values together in SQL Query
```<code>+---------+----+-------+-----+---------+
|   cat   | pn | color | qty |   po    |
+---------+----+-------+-----+---------+
| marbles | 12 | blue  |  10 | 2019-01 |
| marbles | 12 | blue  |  10 | 2019-05 |
| marbles | 12 | blue  |  10 | 2019-08 |
| marbles | 13 | red   |  10 | 2019-01 |
| marbles | 13 | red   |  10 | 2019-05 |
| marbles | 13 | red   |  10 | 2019-08 |
| marbles | 14 | white |  10 | 2019-01 |
| marbles | 14 | white |  10 | 2019-05 |
| marbles | 14 | white |  10 | 2019-08 |
| marbles | 15 | clear |  10 | 2019-01 |
| marbles | 15 | clear |  10 | 2019-05 |
| marbles | 15 | clear |  10 | 2019-08 |
+---------+----+-------+-----+---------+
</code>```

Using Microsoft SQL Server 2008. I've got the above table. It is an inventory of marbles.

I want to get a sum of qty grouped by color, but I need the white and clear colors grouped together.

My query

```<code>SELECT SUM([qty]) AS [colorqty], [color]
FROM [inventory].[dbo].[marbles]
WHERE [qty] > 0
GROUP BY [color]
</code>```

results

```<code>+----------+-------+
| colorqty | color |
+----------+-------+
|       30 | blue  |
|       30 | clear |
|       30 | red   |
|       30 | white |
+----------+-------+
</code>```

I'd like to get the following result while both clear and white have quantity available. Clear is counted as white as long as white is available.

```<code>+----------+-------+
| colorqty | color |
+----------+-------+
|       30 | blue  |
|       60 | white |
|       30 | red   |
+----------+-------+
</code>```

Once no more white available, I'd like the clear to be counted as clear again.

```
    +---------+----+-------+-----+---------+
    |   cat   | pn | color | qty |   po    |
    +---------+----+-------+-----+---------+
    | marbles | 12 | blue  |  10 | 2019-01 |
    | marbles | 12 | blue  |  10 | 2019-05 |
    | marbles | 12 | blue  |  10 | 2019-08 |
    | marbles | 13 | red   |  10 | 2019-01 |
    | marbles | 13 | red   |  10 | 2019-05 |
    | marbles | 13 | red   |  10 | 2019-08 |
    | marbles | 14 | white |   0 | 2019-01 |
    | marbles | 14 | white |   0 | 2019-05 |
    | marbles | 14 | white |   0 | 2019-08 |
    | marbles | 15 | clear |  10 | 2019-01 |
    | marbles | 15 | clear |  10 | 2019-05 |
    | marbles | 15 | clear |  10 | 2019-08 |
    +---------+----+-------+-----+---------+
```

Results in

```
    +----------+-------+
    | colorqty | color |
    +----------+-------+
    |       30 | blue  |
    |       30 | clear |
    |       30 | red   |
    +----------+-------+
```

答:
You just want to sum the quantity, and display the max color when grouped by color except that color clear should be treated as color white when grouping:</p>

```<code>select sum(qty) qty
     , max(color) color
  from marbles
 group by case color
            when 'clear' then 'white'
            else color
          end
</code>```

Body:
+---------+----+-------+-----+---------+
|   cat   | pn | color | qty |   po    |
+---------+----+-------+-----+---------+
| marbles | 12 | blue  |  10 | 2019-01 |
| marbles | 12 | blue  |  10 | 2019-05 |
| marbles | 12 | blue  |  10 | 2019-08 |
| marbles | 13 | red   |  10 | 2019-01 |
| marbles | 13 | red   |  10 | 2019-05 |
| marbles | 13 | red   |  10 | 2019-08 |
| marbles | 14 | white |  10 | 2019-01 |
| marbles | 14 | white |  10 | 2019-05 |
| marbles | 14 | white |  10 | 2019-08 |
| marbles | 15 | clear |  10 | 2019-01 |
| marbles | 15 | clear |  10 | 2019-05 |
| marbles | 15 | clear |  10 | 2019-08 |
+---------+----+-------+-----+---------+

Using Microsoft SQL Server 2008. I've got the above table. It is an inventory of marbles.

I want to get a sum of qty grouped by color, but I need the white and clear colors grouped together.

My query

SELECT SUM([qty]) AS [colorqty], [color]
FROM [inventory].[dbo].[marbles]
WHERE [qty] > 0
GROUP BY [color]

results

+----------+-------+
| colorqty | color |
+----------+-------+
|       30 | blue  |
|       30 | clear |
|       30 | red   |
|       30 | white |
+----------+-------+

I'd like to get the following result while both clear and white have quantity available. Clear is counted as white as long as white is available.

+----------+-------+
| colorqty | color |
+----------+-------+
|       30 | blue  |
|       60 | white |
|       30 | red   |
+----------+-------+

Once no more white available, I'd like the clear to be counted as clear again.

    +---------+----+-------+-----+---------+
    |   cat   | pn | color | qty |   po    |
    +---------+----+-------+-----+---------+
    | marbles | 12 | blue  |  10 | 2019-01 |
    | marbles | 12 | blue  |  10 | 2019-05 |
    | marbles | 12 | blue  |  10 | 2019-08 |
    | marbles | 13 | red   |  10 | 2019-01 |
    | marbles | 13 | red   |  10 | 2019-05 |
    | marbles | 13 | red   |  10 | 2019-08 |
    | marbles | 14 | white |   0 | 2019-01 |
    | marbles | 14 | white |   0 | 2019-05 |
    | marbles | 14 | white |   0 | 2019-08 |
    | marbles | 15 | clear |  10 | 2019-01 |
    | marbles | 15 | clear |  10 | 2019-05 |
    | marbles | 15 | clear |  10 | 2019-08 |
    +---------+----+-------+-----+---------+

Results in

    +----------+-------+
    | colorqty | color |
    +----------+-------+
    |       30 | blue  |
    |       30 | clear |
    |       30 | red   |
    +----------+-------+

Body:
You just want to sum the quantity, and display the max color when grouped by color except that color clear should be treated as color white when grouping:

select sum(qty) qty
     , max(color) color
  from marbles
 group by case color
            when 'clear' then 'white'
            else color
          end


问:
ConfigureAwait(false) in F#
I am using a library which has been written in C# and uses the async/await pattern. In C# I can await something by calling it with ConfigureAwait(false) but when I use the library from F# I don't see a way of doing the same thing?

Currently I do SomeMethodAsync() |> Async.AwaitTask to convert it into an Async F# workflow, but how can I do the same as ConfigureAwait(false) from F# as well when calling SomeMethodAsync?

EDIT:

With some awesome help in the F# Slack channel and some additional googling I found a good explanation of how to switch context here: http://tomasp.net/blog/async-non-blocking-gui.aspx/

答:
It's as simple as calling ConfigureAwait before converting it to an F# Task.

```<code>SomeMethodAsync().ConfigureAwait(false) |>  Async.AwaitTask
</code>```

However, if you are mostly dealing with C# async tasks. It's cleaner to us the TaskBuilder.fs computational expression. Available in nuget using dotnet add package TaskBuilder.fs.

You don't have to manually call ConfigureAwait(false) instead just

```<code>open FSharp.Control.Tasks.V2.ContextInsensitive
</code>```

And then every time you let! it will automatically be .ConfigureAwait(false)

ContentLicense: CC BY-SA 3.0

Title: ConfigureAwait(false) in F#

Body:
It's as simple as calling ConfigureAwait before converting it to an F# Task.

SomeMethodAsync().ConfigureAwait(false) |>  Async.AwaitTask

However, if you are mostly dealing with C# async tasks. It's cleaner to us the TaskBuilder.fs computational expression. Available in nuget using dotnet add package TaskBuilder.fs.

You don't have to manually call ConfigureAwait(false) instead just

open FSharp.Control.Tasks.V2.ContextInsensitive

And then every time you let! it will automatically be .ConfigureAwait(false)


问:
Does flyway support Auth key based credentials for Snowflake
Using flyway to manage our snowflake objects, but would like NOT to use user/password based authentication and instead use user+ Auth-key based authentication mechanism supported by Snowflake.

```<code>flyway.url=jdbc:snowflake://<myaccount>.snowflakecomputing.com/?private_key_file=<abs_path_to>/.ssh/rsa_key_fdb_user.pem&db=mydb&warehouse=etl_dev_wh&role=etl_dev_role&user=etl_dev_user
</code>```

However, with the flyway.url set to above pointing to my location of private_key_file, it simply prompts me for a "Database password:" from the command line -

```<code>./flywaydb/flyway -configFiles=<absolute_basepath>/conf/flyway-dw.conf info
</code>```

I was hoping that the user's Auth would get done based on the private key provided.

答:
Please edit your config file and enter a dummy password as flyway.password:

```<code>flyway.password=wrongpassword
</code>```

It should stop asking password and connect to Snowflake with the private key, in case you configured your user with rsa_public_key:

https://docs.snowflake.net/manuals/user-guide/jdbc-configure.html#privatekey-property-in-connection-properties

Body:
Using flyway to manage our snowflake objects, but would like NOT to use user/password based authentication and instead use user+ Auth-key based authentication mechanism supported by Snowflake.

flyway.url=jdbc:snowflake://<myaccount>.snowflakecomputing.com/?private_key_file=<abs_path_to>/.ssh/rsa_key_fdb_user.pem&db=mydb&warehouse=etl_dev_wh&role=etl_dev_role&user=etl_dev_user

However, with the flyway.url set to above pointing to my location of private_key_file, it simply prompts me for a "Database password:" from the command line -

./flywaydb/flyway -configFiles=<absolute_basepath>/conf/flyway-dw.conf info

I was hoping that the user's Auth would get done based on the private key provided.

Body:
Please edit your config file and enter a dummy password as flyway.password:

flyway.password=wrongpassword

It should stop asking password and connect to Snowflake with the private key, in case you configured your user with rsa_public_key:

https://docs.snowflake.net/manuals/user-guide/jdbc-configure.html#privatekey-property-in-connection-properties


问:
Service for identifying an un-tagged mp3
Is there an open source service that I can call from a program, where it passes information about a un-tagged mp3, and it responds with details about the song(e.g. artist, album, track, etc.)?  If not, is there an alternative I can use to identify songs?</p>

答: MusicBrainz is one that works pretty well.  It uses an "acoustic fingerprint" to look up potential matches.</p>


问:
How to multiply a dataframe's column by a log using julia?
I have a dataframe. I want to multiply column "b" by a "log" and then replace NaN by 0s.

How can I do that in Julia?
I am checking this: DataFrames.jl
But I do not understand.

```<code>df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]),
           b = repeat([2, 1], outer=[4]),
           c = randn(8))
</code>```

答:
Use a generator:

```<code>( v <= 0. ? 0. : log(v) for v in df.c )
</code>```

If you want to add a new column:

```<code>df[!, :d] .= ( v <= 0. ? 0. : log(v) for v in df.c)
</code>```

This is faster than using map (those tests assume that df.d already exits:

```<code>julia> using BenchmarkTools

julia> @btime $df[!, :d] .= ( v <= 0.0 ? 0.0 : log(v) for v in $df.c)
  1.440 μs (14 allocations: 720 bytes)

julia> @btime $df[!, :d] .= map( x -> x <= 0.0 ? 0.0 : log(x), $df.c);
  1.570 μs (14 allocations: 720 bytes)
</code>```

Body:
I have a dataframe. I want to multiply column "b" by a "log" and then replace NaN by 0s.

How can I do that in Julia?
I am checking this: DataFrames.jl
But I do not understand.

df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]),
           b = repeat([2, 1], outer=[4]),
           c = randn(8))

Body:
Use a generator:

( v <= 0. ? 0. : log(v) for v in df.c )

If you want to add a new column:

df[!, :d] .= ( v <= 0. ? 0. : log(v) for v in df.c)

This is faster than using map (those tests assume that df.d already exits:

julia> using BenchmarkTools

julia> @btime $df[!, :d] .= ( v <= 0.0 ? 0.0 : log(v) for v in $df.c)
  1.440 μs (14 allocations: 720 bytes)

julia> @btime $df[!, :d] .= map( x -> x <= 0.0 ? 0.0 : log(x), $df.c);
  1.570 μs (14 allocations: 720 bytes)


问:
How can I run this flask app using gunicorn
I Refactored my code after making it which turns out to be a mistake and now I am not able to get it run using gunicorn. If you have advice for structuring or factoring from here on then that's welcome too.
I am trying to get it run from 5 days now, Struggling a lot.

Directory Structure

```<code>app--
     --db.sqlite
     --__init__.py
     --models.py
     --MyFunctions.py
     --routes.py
     --schemas.py
     --sockets.py
app.py
</code>```

Inside app.py

```<code>from app import *

from app.MyFunctions import *
from app.models import *
from app.schemas import *
from app.routes import *
from app.sockets import *

port=os.environ.get("PORT")

if port is None or port == "":
    port = 3000

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=port) # when running on heroku
</code>```

Inside init.py

```<code>import jwt
from flask import (
    Flask,
    request,
    jsonify,
    make_response,
)
from flask_socketio import (
    SocketIO,
    send,
    emit,
    join_room,
    leave_room,
)
from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    ForeignKey,
    DateTime,
    Sequence,
    Float,
)
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from os import environ

def debug(msg):
    print('\n\n\n'+str(msg)+'\n\n\n'+'\n\nType:\t'+str(type(msg))+'\n\n')

from .models import *
socketio = SocketIO(app, cors_allowed_origins='*')
</code>```

Inside models.py (only import related things not models, my most of the imports are lying here only)

```<code>from flask import (
    Flask,
    request,
    jsonify,
    make_response,
    redirect,
)
from flask_socketio import (
    SocketIO,
    send,
    emit,
    join_room,
    leave_room,
)
from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    ForeignKey,
    DateTime,
    Sequence,
    Float,
)
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
from os import environ
from flask_cors import CORS, cross_origin

app = Flask(__name__)
root = os.path.dirname(os.path.abspath(__file__))
CORS(app, support_credentials=True)
basedir = os.path.abspath(os.path.dirname(__file__))

PG = os.environ.get("DATABASE_URL")

if PG is None or PG=="":
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
        os.path.join(basedir, 'db.sqlite')
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = PG

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = environ.get('STRIPE_API_KEY')

db = SQLAlchemy(app)

ma = Marshmallow(app)

bcrypt = Bcrypt(app)

socketio = SocketIO(app, cors_allowed_origins='*')
</code>```

edit:
Currently I am using python only to run the app on heroku so my Procfile looks like

```<code>web: python app.py
</code>```

And yes I have tried many other formats like

```<code>web: gunicorn app:app
web: gunicorn models:app
web: gunicorn app/models:app
</code>```

Tried by making different run file also and many other methods
I am afraid that I need to change it's structure to make it work.

答:
I renamed my app.py file and then it worked

Inside Procfile

```<code>web: gunicorn gettingstarted.wsgi
web: gunicorn runner:app
</code>```

Body:
I Refactored my code after making it which turns out to be a mistake and now I am not able to get it run using gunicorn. If you have advice for structuring or factoring from here on then that's welcome too.
I am trying to get it run from 5 days now, Struggling a lot.

Directory Structure

app--
     --db.sqlite
     --__init__.py
     --models.py
     --MyFunctions.py
     --routes.py
     --schemas.py
     --sockets.py
app.py

Inside app.py

from app import *

from app.MyFunctions import *
from app.models import *
from app.schemas import *
from app.routes import *
from app.sockets import *

port=os.environ.get("PORT")

if port is None or port == "":
    port = 3000

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=port) # when running on heroku

Inside init.py

import jwt
from flask import (
    Flask,
    request,
    jsonify,
    make_response,
)
from flask_socketio import (
    SocketIO,
    send,
    emit,
    join_room,
    leave_room,
)
from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    ForeignKey,
    DateTime,
    Sequence,
    Float,
)
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from os import environ

def debug(msg):
    print('\n\n\n'+str(msg)+'\n\n\n'+'\n\nType:\t'+str(type(msg))+'\n\n')

from .models import *
socketio = SocketIO(app, cors_allowed_origins='*')

Inside models.py (only import related things not models, my most of the imports are lying here only)

from flask import (
    Flask,
    request,
    jsonify,
    make_response,
    redirect,
)
from flask_socketio import (
    SocketIO,
    send,
    emit,
    join_room,
    leave_room,
)
from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    ForeignKey,
    DateTime,
    Sequence,
    Float,
)
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
from os import environ
from flask_cors import CORS, cross_origin

app = Flask(__name__)
root = os.path.dirname(os.path.abspath(__file__))
CORS(app, support_credentials=True)
basedir = os.path.abspath(os.path.dirname(__file__))

PG = os.environ.get("DATABASE_URL")

if PG is None or PG=="":
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
        os.path.join(basedir, 'db.sqlite')
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = PG

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = environ.get('STRIPE_API_KEY')

db = SQLAlchemy(app)

ma = Marshmallow(app)

bcrypt = Bcrypt(app)

socketio = SocketIO(app, cors_allowed_origins='*')

edit:
Currently I am using python only to run the app on heroku so my Procfile looks like

web: python app.py

And yes I have tried many other formats like

web: gunicorn app:app
web: gunicorn models:app
web: gunicorn app/models:app

Tried by making different run file also and many other methods
I am afraid that I need to change it's structure to make it work.

Body:
I renamed my app.py file and then it worked

Inside Procfile

web: gunicorn gettingstarted.wsgi
web: gunicorn runner:app


问:
Laravel Passport token lifetime
I don't get what I'm doing wrong.
I can't set token expiration time.

```<code><?php

namespace App\Providers;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        Passport::tokensExpireIn(Carbon::now()->addDays(1));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }
}
</code>```

BUT when I call $user->createToken(), for example like this:

```<code><?php
// as a demo
namespace App\Http\Middleware;

class ParseSpecialToken
{
    public function handle($request, Closure $next)
    {
        $user = User::find(1);
        $accessToken = $user->createToken('Some token')->accessToken;
        $request->headers->add(['Authorization' => 'Bearer '. $accessToken]);

        return $next($request);
    }
}
</code>```

Token expiration is still 1 year, not 1 day. Why? How to change exp time?

答:
I was able to extend the lifetime of the Personal access token by creating a PassportServiceProvider in my project that extends the PassportServiceProvider from the laravel-passport package. Then I just added this method to override the one from the PassportServiceProvider.

```<code>

    /**
     * Register the authorization server.
     *
     * @return void
     */
    protected function registerAuthorizationServer()
    {
        $this->app->singleton(AuthorizationServer::class, function () {
            return tap($this->makeAuthorizationServer(), function ($server) {
                $server->enableGrantType(
                    $this->makeAuthCodeGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    $this->makeRefreshTokenGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    $this->makePasswordGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    new PersonalAccessGrant(), Passport::tokensExpireIn() // this is the line that was updated from the original method
                );

                $server->enableGrantType(
                    new ClientCredentialsGrant(), Passport::tokensExpireIn()
                );

                if (Passport::$implicitGrantEnabled) {
                    $server->enableGrantType(
                        $this->makeImplicitGrant(), Passport::tokensExpireIn()
                    );
                }
            });
        });
    }
</code>```

Then I just updated the provider in the app.php config file to use the one from my project.

Title: Laravel Passport token lifetime

Body:
I don't get what I'm doing wrong.
I can't set token expiration time.

<?php

namespace App\Providers;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerPolicies();

        Passport::tokensExpireIn(Carbon::now()->addDays(1));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
    }
}

BUT when I call $user->createToken(), for example like this:

<?php
// as a demo
namespace App\Http\Middleware;

class ParseSpecialToken
{
    public function handle($request, Closure $next)
    {
        $user = User::find(1);
        $accessToken = $user->createToken('Some token')->accessToken;
        $request->headers->add(['Authorization' => 'Bearer '. $accessToken]);

        return $next($request);
    }
}

Token expiration is still 1 year, not 1 day. Why? How to change exp time?

Body:
I was able to extend the lifetime of the Personal access token by creating a PassportServiceProvider in my project that extends the PassportServiceProvider from the laravel-passport package. Then I just added this method to override the one from the PassportServiceProvider.

    /**
     * Register the authorization server.
     *
     * @return void
     */
    protected function registerAuthorizationServer()
    {
        $this->app->singleton(AuthorizationServer::class, function () {
            return tap($this->makeAuthorizationServer(), function ($server) {
                $server->enableGrantType(
                    $this->makeAuthCodeGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    $this->makeRefreshTokenGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    $this->makePasswordGrant(), Passport::tokensExpireIn()
                );

                $server->enableGrantType(
                    new PersonalAccessGrant(), Passport::tokensExpireIn() // this is the line that was updated from the original method
                );

                $server->enableGrantType(
                    new ClientCredentialsGrant(), Passport::tokensExpireIn()
                );

                if (Passport::$implicitGrantEnabled) {
                    $server->enableGrantType(
                        $this->makeImplicitGrant(), Passport::tokensExpireIn()
                    );
                }
            });
        });
    }

Then I just updated the provider in the app.php config file to use the one from my project.


问:
Get Selected Row's Specific Col Value via script (Google Sheets)
I've been trying to get this one to work without success so far.
I need to get the TaskNumber on the first column of the row I'm on and bring it to the destination sheet, so that I can update it there.
I have the following, which I'm tweaking to achieve my goal, but I guess I've bumped into my limitation walls:

```<code>function jump() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var TaskNumberSheet = ss.getSheetByName('To-Do List');
  var TaskNoRow = TaskNumberSheet.getActiveCell();
  var TaskNoCol = TaskNoRow.getColumn() == 1
  var TaskNo = TaskNoCol.getValue;
  var sheet = ss.getSheetByName('Updates');
  //var Tasks = ss.getSheetByName("To Do List").getActiveRange(Tasks.getColum(1)).getValue();

  var values = sheet.getRange("B:B").getValues();
  var maxIndex = values.reduce(function(maxIndex, row, index) {
    return row[0] === "" ? maxIndex : index;
  }, 0);
  sheet.setActiveRange(sheet.getRange(maxIndex + 2,2)).setValue(TaskNo);
}
</code>```

Any help is appreciate.

Cheers,
A

答:
```<code>function jump() {
  var TargetRow=?;//Fillin target row
  var TargetCol=?;//Fillin target column
  var ss=SpreadsheetApp.getActive();
  var TaskNumberSheet=ss.getSheetByName('To-Do List');
  var TaskNoRow=TaskNumberSheet.getActiveCell().getRow();//Getting row from active cell
  var TaskNoCol=1
  var TaskNo=TaskNumberSheet.getRange(TaskNoRow,TaskNoCol).getValue();
  ss.getSheetByName('Updates').getRange(targetRow,targetCol).setValue(TaskNo);
}
</code>```

Body:
I've been trying to get this one to work without success so far.
I need to get the TaskNumber on the first column of the row I'm on and bring it to the destination sheet, so that I can update it there.
I have the following, which I'm tweaking to achieve my goal, but I guess I've bumped into my limitation walls:

function jump() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var TaskNumberSheet = ss.getSheetByName('To-Do List');
  var TaskNoRow = TaskNumberSheet.getActiveCell();
  var TaskNoCol = TaskNoRow.getColumn() == 1
  var TaskNo = TaskNoCol.getValue;
  var sheet = ss.getSheetByName('Updates');
  //var Tasks = ss.getSheetByName("To Do List").getActiveRange(Tasks.getColum(1)).getValue();

  var values = sheet.getRange("B:B").getValues();
  var maxIndex = values.reduce(function(maxIndex, row, index) {
    return row[0] === "" ? maxIndex : index;
  }, 0);
  sheet.setActiveRange(sheet.getRange(maxIndex + 2,2)).setValue(TaskNo);
}

Any help is appreciate.

Cheers,
A


问:
How can I correctly flag the end of the first sequence of a group?
This is an example of the the type of dataframe that I'm using and the desired column output.

```<code>reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))
</code>```

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

```<code>    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )
</code>```

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

```<code>reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))
</code>```

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes

答:
Surely there's something less convoluted, but this would likely work:

```<code>library(dplyr)

reprEx %>%
  group_by(id) %>%
  mutate(idx = cumsum(stage1 != lag(stage1, default = first(stage1))),
         desiredResult = case_when(
           idx != lag(idx, default = first(idx)) & stage1 != 'open' ~ 1,
           lead(idx, default = last(idx)) != idx & stage1 == 'open' & idx == min(idx[stage1 == 'open']) ~ 1,
           TRUE ~ 0
         ),
         idx = NULL
  )
</code>```

Output:

```<code>   id   stage1 desiredResult
1   1     open             0
2   1     open             0
3   1     open             1
4   1 approved             1
5   1 approved             0
6   1     open             0
7   1 declined             1
8   2     open             0
9   2     open             0
10  2     open             1
11  2 declined             1
12  3     open             1
13  3 approved             1
14  3 declined             1
</code>```

Body:
This is an example of the the type of dataframe that I'm using and the desired column output.

reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))

I am trying to use dplyr to correctly flag whenever a stage changes within a grouped id. The approved and declined flags are easy because I only have to flag the first case of a declined or approved appearing with:

    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
  mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
                                ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
                                )
  )

The issue is with the open stage. I only want to apply a flag for when the first sequences of opens ends within a group of id's. With the code that I have now it is choosing the last open within the group, even if it wasn't part of the first sequence of opens. for example:

reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
             stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
             notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))

In this case, within id1 I would need the flag to show up where the sequence reaches the last open before approved appears, and not in the open after approved appears. I only need the flag in the row of the last occurrence of open if that succession of opens is the first succession within the id. Sorry for any confusion, I would be happy to further elaborate. This is just to correctly identify stage transitions for recording purposes

Body:
Surely there's something less convoluted, but this would likely work:

library(dplyr)

reprEx %>%
  group_by(id) %>%
  mutate(idx = cumsum(stage1 != lag(stage1, default = first(stage1))),
         desiredResult = case_when(
           idx != lag(idx, default = first(idx)) & stage1 != 'open' ~ 1,
           lead(idx, default = last(idx)) != idx & stage1 == 'open' & idx == min(idx[stage1 == 'open']) ~ 1,
           TRUE ~ 0
         ),
         idx = NULL
  )

Output:

   id   stage1 desiredResult
1   1     open             0
2   1     open             0
3   1     open             1
4   1 approved             1
5   1 approved             0
6   1     open             0
7   1 declined             1
8   2     open             0
9   2     open             0
10  2     open             1
11  2 declined             1
12  3     open             1
13  3 approved             1
14  3 declined             1


问:
Data Studio Apps Script - Default Config / Set Config Value
I have a config process that has multiple steps. For most users, the first and second steps only have 1 option, so I would like to do something like cc.setConfigParams({...}) to update the config's current value, but this seems not possible.

To do "default" config in other places, I use a config option (in SELECT_SINGLE) with value="", but in this case, I need to know what the value was, so I can't use empty string.

I've looked over the documentation and couldn't find anything related - https://developers.google.com/apps-script/reference/data-studio/config

答: Default values are not currently supported for community connector configs. If you're interested in seeing this feature added, please file an issue. </p>


问:
ReactJS - .JS vs .JSX
There is something I find very confusing when working in React.js.

There are plenty of examples available on internet which use .js files with React but many others use .jsx files.

I have read about JSX files and my understanding is that they just let you write HTML tags within your JavaScript.
But the same thing can be written in JS files as well.

So what is the actual difference between .js and .jsx ?

答:
As other mentioned JSX is not a standard Javascript extension. It's better to name your entry point of Application based on .js and for the rest components, you can use .jsx.

I have an important reason for why I'm using .JSX for all component's file names.
Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.

Title: ReactJS - .JS vs .JSX


问:
How to hide the all the content until the user searches for a specific item in this table?
I want to create a table with hidden contents from the user but is available if they typed the specific items. So, basically, I just want to have a search bar as the only thing displayed.

Here is what I already have, and this is from w3schools:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

My Customers

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

      Name
      Country

      Alfreds Futterkiste
      Germany

      Berglunds snabbkop
      Sweden

      Island Trading
      UK

      Koniglich Essen
      Germany

      Laughing Bacchus Winecellars
      Canada

      Magazzini Alimentari Riuniti
      Italy

      North/South
      UK

      Paris specialites
      France

```

And lastly, how would I be able to add a clickable link on an item? I've seen a website with those features and I tried to find the answer on my own but can't. I'm also a beginner and have zero background in coding, although I've learned quite fast these past few weeks. So I would appreciate it if you use will use words I can understand.

If you want to know what I'm gonna do with this is I'm planning to build a free books blog where people can just search their favorite author or book title and it will appear on the search bar if it's available.
Thanks a lot!

答:
You were almost there. Just add in the css the property display: none on your rows to hide them. You can then reappear them in javascript using the diplay: table-row property:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

My Customers

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

      Name
      Country

      Alfreds Futterkiste
      Germany

      Berglunds snabbkop
      Sweden

      Island Trading
      UK

      Koniglich Essen
      Germany

      Laughing Bacchus Winecellars
      Canada

      Magazzini Alimentari Riuniti
      Italy

      North/South
      UK

      Paris specialites
      France

```

Body:
I want to create a table with hidden contents from the user but is available if they typed the specific items. So, basically, I just want to have a search bar as the only thing displayed.

Here is what I already have, and this is from w3schools:

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

My Customers

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

      Name
      Country

      Alfreds Futterkiste
      Germany

      Berglunds snabbkop
      Sweden

      Island Trading
      UK

      Koniglich Essen
      Germany

      Laughing Bacchus Winecellars
      Canada

      Magazzini Alimentari Riuniti
      Italy

      North/South
      UK

      Paris specialites
      France

And lastly, how would I be able to add a clickable link on an item? I've seen a website with those features and I tried to find the answer on my own but can't. I'm also a beginner and have zero background in coding, although I've learned quite fast these past few weeks. So I would appreciate it if you use will use words I can understand.

If you want to know what I'm gonna do with this is I'm planning to build a free books blog where people can just search their favorite author or book title and it will appear on the search bar if it's available.
Thanks a lot!

Body:
You were almost there. Just add in the css the property display: none on your rows to hide them. You can then reappear them in javascript using the diplay: table-row property:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      box-sizing: border-box;
    }

    #myInput {
      background-image: url('/css/searchicon.png');
      background-position: 10px 10px;
      background-repeat: no-repeat;
      width: 100%;
      font-size: 16px;
      padding: 12px 20px 12px 40px;
      border: 1px solid #ddd;
      margin-bottom: 12px;
    }

    #myTable {
      border-collapse: collapse;
      width: 100%;
      border: 1px solid #ddd;
      font-size: 18px;
    }

    #myTable th,
    #myTable td {
      text-align: left;
      padding: 12px;
    }

    #myTable tr:not(.header) {
      display: none;   /* <-- Hide all items (but not header) on init */
    }

    #myTable tr {
      border-bottom: 1px solid #ddd;
    }

    #myTable tr.header,
    #myTable tr:hover {
      background-color: #f1f1f1;
    }
  </style>
</head>

<body>

  <h2>My Customers</h2>

  <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

  <table id="myTable">
    <tr class="header">
      <th style="width:60%;">Name</th>
      <th style="width:40%;">Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Berglunds snabbkop</td>
      <td>Sweden</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Koniglich Essen</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Italy</td>
    </tr>
    <tr>
      <td>North/South</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Paris specialites</td>
      <td>France</td>
    </tr>
  </table>

  <script>
    function myFunction() {
      var input, filter, table, tr, td, i, txtValue;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "table-row"; // <-- Show matching items
          } else {
            tr[i].style.display = "none";
          }
        }
      }
    }
  </script>

</body>

</html>


问:
Change count to percentage on faceted, filled geom_bar()/stat_count() plot in ggplot2 R
I have this dataset from a survey:

```<code>                         Var1                 by variable value
1           Strongly disagree  Cluster 1 (n = 9)        A     0
2           Strongly disagree Cluster 2 (n = 15)        A     0
3           Somewhat disagree  Cluster 1 (n = 9)        A     0
4           Somewhat disagree Cluster 2 (n = 15)        A     0
5  Neither agree nor disagree  Cluster 1 (n = 9)        A     2
6  Neither agree nor disagree Cluster 2 (n = 15)        A     0
7              Somewhat agree  Cluster 1 (n = 9)        A     1
8              Somewhat agree Cluster 2 (n = 15)        A     0
9              Strongly agree  Cluster 1 (n = 9)        A     6
10             Strongly agree Cluster 2 (n = 15)        A    15
11          Strongly disagree  Cluster 1 (n = 9)        B     1
12          Strongly disagree Cluster 2 (n = 15)        B     0
13          Somewhat disagree  Cluster 1 (n = 9)        B     0
14          Somewhat disagree Cluster 2 (n = 15)        B     0
15 Neither agree nor disagree  Cluster 1 (n = 9)        B     1
16 Neither agree nor disagree Cluster 2 (n = 15)        B     0
17             Somewhat agree  Cluster 1 (n = 9)        B     4
18             Somewhat agree Cluster 2 (n = 15)        B     1
19             Strongly agree  Cluster 1 (n = 9)        B     3
20             Strongly agree Cluster 2 (n = 15)        B    14
21          Strongly disagree  Cluster 1 (n = 9)        C     0
22          Strongly disagree Cluster 2 (n = 15)        C     0
23          Somewhat disagree  Cluster 1 (n = 9)        C     0
24          Somewhat disagree Cluster 2 (n = 15)        C     0
25 Neither agree nor disagree  Cluster 1 (n = 9)        C     3
26 Neither agree nor disagree Cluster 2 (n = 15)        C     0
27             Somewhat agree  Cluster 1 (n = 9)        C     1
28             Somewhat agree Cluster 2 (n = 15)        C     3
29             Strongly agree  Cluster 1 (n = 9)        C     5
30             Strongly agree Cluster 2 (n = 15)        C    12
</code>```

I originally plotted it like so using ggplot2 to display the count of responses:

```<code>( p5 <- ggplot(q5, aes(x = Var1, y = value, fill = variable)) +
    geom_bar(stat = "identity", width = 0.5, position=position_dodge2(reverse = TRUE)) +
    coord_flip() +
    theme(plot.title = element_text(size = 16), axis.text.x = element_text(size = 16),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    legend.text=element_text(size=16),
    legend.title=element_text(size=16),
    strip.text.x = element_text(size = 16)) +
    ylim(0,20) +
    scale_x_discrete(limits=c("Strongly disagree", "Somewhat disagree", "Neither agree nor disagree", "Somewhat agree", "Strongly agree")) +
    labs(x = "", y = "# of Responses", fill = "Question") +
    facet_grid(. ~ by) )
</code>```

which gave me this:

However, I want to display the data as a percentage rather than count.

Following this post, I changed the code accordingly to:

```<code>( p5 <- ggplot(q5, aes(x = Var1, group = by, fill = variable)) +
    stat_count(mapping = aes(y = ..prop..)) +
    coord_flip() +
    theme(plot.title = element_text(size = 16), axis.text.x = element_text(size = 16),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    legend.text=element_text(size=16),
    legend.title=element_text(size=16),
    strip.text.x = element_text(size = 16)) +
    scale_y_continuous(limits = c(0,1),labels = scales::percent_format(accuracy = 5L)) +
    scale_x_discrete(limits=c("Strongly disagree", "Somewhat disagree", "Neither agree nor disagree", "Somewhat agree", "Strongly agree")) +
    labs(x = "", y = "% of Responses", fill = "Question") +
    facet_grid(. ~ by) )
</code>```

However, this gives me this plot:

It seems like the plot is not recognizing my fill argument or the ..prop.. argument for y.

How can I fix this?

答:
I have problems copying-pasting the data so I make an example like your data:

```<code>set.seed(111)
df = expand.grid(Var1=c("strong disagree","disagree","strong agree","agree","neither"),
by=1:2,variable=LETTERS[1:3])
df$value=rnbinom(nrow(df),mu=5,size=0.5)
df$value[df$Var1=="disagree" & df$by==1]=0
</code>```

The error you have above is trying to do stat_count with on its own group. The easier solution i think is to count the proportions first and just plot:

```<code>library(ggplot2)
library(tidyr)
library(dplyr)

df %>% group_by(by,variable) %>%
mutate(value=replace_na(value/sum(value),0)) %>%
ggplot(aes(x=Var1,y=value,fill=variable)) +
geom_col(position="dodge") + facet_wrap(~by) +
scale_y_continuous(labels = scales::percent_format()) +
coord_flip()
</code>```

Body:
I have this dataset from a survey:

                         Var1                 by variable value
1           Strongly disagree  Cluster 1 (n = 9)        A     0
2           Strongly disagree Cluster 2 (n = 15)        A     0
3           Somewhat disagree  Cluster 1 (n = 9)        A     0
4           Somewhat disagree Cluster 2 (n = 15)        A     0
5  Neither agree nor disagree  Cluster 1 (n = 9)        A     2
6  Neither agree nor disagree Cluster 2 (n = 15)        A     0
7              Somewhat agree  Cluster 1 (n = 9)        A     1
8              Somewhat agree Cluster 2 (n = 15)        A     0
9              Strongly agree  Cluster 1 (n = 9)        A     6
10             Strongly agree Cluster 2 (n = 15)        A    15
11          Strongly disagree  Cluster 1 (n = 9)        B     1
12          Strongly disagree Cluster 2 (n = 15)        B     0
13          Somewhat disagree  Cluster 1 (n = 9)        B     0
14          Somewhat disagree Cluster 2 (n = 15)        B     0
15 Neither agree nor disagree  Cluster 1 (n = 9)        B     1
16 Neither agree nor disagree Cluster 2 (n = 15)        B     0
17             Somewhat agree  Cluster 1 (n = 9)        B     4
18             Somewhat agree Cluster 2 (n = 15)        B     1
19             Strongly agree  Cluster 1 (n = 9)        B     3
20             Strongly agree Cluster 2 (n = 15)        B    14
21          Strongly disagree  Cluster 1 (n = 9)        C     0
22          Strongly disagree Cluster 2 (n = 15)        C     0
23          Somewhat disagree  Cluster 1 (n = 9)        C     0
24          Somewhat disagree Cluster 2 (n = 15)        C     0
25 Neither agree nor disagree  Cluster 1 (n = 9)        C     3
26 Neither agree nor disagree Cluster 2 (n = 15)        C     0
27             Somewhat agree  Cluster 1 (n = 9)        C     1
28             Somewhat agree Cluster 2 (n = 15)        C     3
29             Strongly agree  Cluster 1 (n = 9)        C     5
30             Strongly agree Cluster 2 (n = 15)        C    12

I originally plotted it like so using ggplot2 to display the count of responses:

( p5 <- ggplot(q5, aes(x = Var1, y = value, fill = variable)) +
    geom_bar(stat = "identity", width = 0.5, position=position_dodge2(reverse = TRUE)) +
    coord_flip() +
    theme(plot.title = element_text(size = 16), axis.text.x = element_text(size = 16),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    legend.text=element_text(size=16),
    legend.title=element_text(size=16),
    strip.text.x = element_text(size = 16)) +
    ylim(0,20) +
    scale_x_discrete(limits=c("Strongly disagree", "Somewhat disagree", "Neither agree nor disagree", "Somewhat agree", "Strongly agree")) +
    labs(x = "", y = "# of Responses", fill = "Question") +
    facet_grid(. ~ by) )

which gave me this:

However, I want to display the data as a percentage rather than count.

Following this post, I changed the code accordingly to:

( p5 <- ggplot(q5, aes(x = Var1, group = by, fill = variable)) +
    stat_count(mapping = aes(y = ..prop..)) +
    coord_flip() +
    theme(plot.title = element_text(size = 16), axis.text.x = element_text(size = 16),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    legend.text=element_text(size=16),
    legend.title=element_text(size=16),
    strip.text.x = element_text(size = 16)) +
    scale_y_continuous(limits = c(0,1),labels = scales::percent_format(accuracy = 5L)) +
    scale_x_discrete(limits=c("Strongly disagree", "Somewhat disagree", "Neither agree nor disagree", "Somewhat agree", "Strongly agree")) +
    labs(x = "", y = "% of Responses", fill = "Question") +
    facet_grid(. ~ by) )

However, this gives me this plot:

It seems like the plot is not recognizing my fill argument or the ..prop.. argument for y.

How can I fix this?

Body:
I have problems copying-pasting the data so I make an example like your data:

set.seed(111)
df = expand.grid(Var1=c("strong disagree","disagree","strong agree","agree","neither"),
by=1:2,variable=LETTERS[1:3])
df$value=rnbinom(nrow(df),mu=5,size=0.5)
df$value[df$Var1=="disagree" & df$by==1]=0

The error you have above is trying to do stat_count with on its own group. The easier solution i think is to count the proportions first and just plot:

library(ggplot2)
library(tidyr)
library(dplyr)

df %>% group_by(by,variable) %>%
mutate(value=replace_na(value/sum(value),0)) %>%
ggplot(aes(x=Var1,y=value,fill=variable)) +
geom_col(position="dodge") + facet_wrap(~by) +
scale_y_continuous(labels = scales::percent_format()) +
coord_flip()