问:
How to create a “add tab“button in JAVAFX？
I want to create a button ,which will create a new tab to tabPane when clicking,and on the right of all tab alltime. I'll appreciate if there has any example how to do it.</p>

答:
Your code should look similar to the code below.
This example uses a button above the TabPane.

public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        VBox layout = new VBox(10); // VBox with spacing of 10. Button sits above TabPane
        layout.getChildren().addAll(newTabButton(tabPane), tabPane); // Adding button and TabPane to VBox

        stage.setScene(new Scene(layout));
        stage.show();
    }

    // Button that adds a new tab and selects it
    private Button newTabButton(TabPane tabPane) {
        Button addTab = new Button("Create Tab");
        addTab.setOnAction(event -> {
            tabPane.getTabs().add(new Tab("New Tab")); // Adding new tab at the end, so behind all the other tabs
            tabPane.getSelectionModel().selectLast(); // Selecting the last tab, which is the newly created one
        });
        return addTab;
    }
}
```

<p>If you want it to be like in a browser, this code should do it.
This uses the an empty tab at the end, which acts like a button. You can add an icon like + instead of the text in the tab label.</p>

<pre class="lang-java prettyprint-override"><code>public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        tabPane.getTabs().add(newTabButton(tabPane));

        stage.setScene(new Scene(tabPane));
        stage.show();
    }

    // Tab that acts as a button and adds a new tab and selects it
    private Tab newTabButton(TabPane tabPane) {
        Tab addTab = new Tab("Create Tab"); // You can replace the text with an icon
        addTab.setClosable(false);
        tabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
            if(newTab == addTab) {
                tabPane.getTabs().add(tabPane.getTabs().size() - 1, new Tab("New Tab")); // Adding new tab before the "button" tab
                tabPane.getSelectionModel().select(tabPane.getTabs().size() - 2); // Selecting the tab before the button, which is the newly created one
            }
        });
        return addTab;
    }
}
</code>```

Body:
Your code should look similar to the code below.
This example uses a button above the TabPane.

public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        VBox layout = new VBox(10); // VBox with spacing of 10. Button sits above TabPane
        layout.getChildren().addAll(newTabButton(tabPane), tabPane); // Adding button and TabPane to VBox

        stage.setScene(new Scene(layout));
        stage.show();
    }

    // Button that adds a new tab and selects it
    private Button newTabButton(TabPane tabPane) {
        Button addTab = new Button("Create Tab");
        addTab.setOnAction(event -> {
            tabPane.getTabs().add(new Tab("New Tab")); // Adding new tab at the end, so behind all the other tabs
            tabPane.getSelectionModel().selectLast(); // Selecting the last tab, which is the newly created one
        });
        return addTab;
    }
}

If you want it to be like in a browser, this code should do it.
This uses the an empty tab at the end, which acts like a button. You can add an icon like + instead of the text in the tab label.

public class TabPaneSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TabPane tabPane = new TabPane();

        tabPane.getTabs().add(newTabButton(tabPane));

        stage.setScene(new Scene(tabPane));
        stage.show();
    }

    // Tab that acts as a button and adds a new tab and selects it
    private Tab newTabButton(TabPane tabPane) {
        Tab addTab = new Tab("Create Tab"); // You can replace the text with an icon
        addTab.setClosable(false);
        tabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
            if(newTab == addTab) {
                tabPane.getTabs().add(tabPane.getTabs().size() - 1, new Tab("New Tab")); // Adding new tab before the "button" tab
                tabPane.getSelectionModel().select(tabPane.getTabs().size() - 2); // Selecting the tab before the button, which is the newly created one
            }
        });
        return addTab;
    }
}


来源: stackexchange

问:
How to add action from redux connect to component props typescript
I want to declare props in my react component. Here is code:

```<code>interface HeaderProps {
  getUserData: typeof _getUserData;
}

const Header: React.FC<HeaderProps> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return <div>Test</div>;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

export default connect(() => ({}), mapDispatchToProps)(Header);

</code>```

But TS is throwing error. I have tried to rewrite connect like this
connect<{}, HeaderProps>(() => ({}), mapDispatchToProps)(Header);
But it have not worked.
I have tried to look for answer in the web, but was not ably to find any.
TS Error:

```<code>rgument of type 'FC<HeaderProps>' is not assignable to parameter of type 'ComponentType<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
  Type 'FunctionComponent<HeaderProps>' is not assignable to type 'FunctionComponent<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
    Types of property 'propTypes' are incompatible.
      Type 'WeakValidationMap<HeaderProps> | undefined' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>> | undefined'.
        Type 'WeakValidationMap<HeaderProps>' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
          Types of property 'getUserData' are incompatible.
            Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>> | undefined' is not assignable to type 'Validator<() => Promise<void>> | undefined'.
              Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>>' is not assignable to type 'Validator<() => Promise<void>>'.
                Type '() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>' is not assignable to type '() => Promise<void>'.ts(2345)

</code>```

答:
Your mapDispatchToProps needs to be function, passing in dispatch and wrapping your action

```<code>const mapDispatchToProps = (dispatch: any) => {
    return {
       getUserData: bindActionCreators<any, any>(_getUserData, dispatch)
    }
}
</code>```

Also if you're not passing any props through on the mapStateToProps function you can just pass through a null.

```<code>export default connect(null, mapDispatchToProps)(Header);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to declare props in my react component. Here is code:

interface HeaderProps {
  getUserData: typeof _getUserData;
}

const Header: React.FC<HeaderProps> = ({ getUserData }) => {
  useEffect(() => {
    getUserData();
  }, []);

  return
Test
;
};

const mapDispatchToProps = {
  getUserData: _getUserData,
};

export default connect(() => ({}), mapDispatchToProps)(Header);

But TS is throwing error. I have tried to rewrite connect like this
connect<{}, HeaderProps>(() => ({}), mapDispatchToProps)(Header);
But it have not worked.
I have tried to look for answer in the web, but was not ably to find any.
TS Error:

rgument of type 'FC<HeaderProps>' is not assignable to parameter of type 'ComponentType<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
  Type 'FunctionComponent<HeaderProps>' is not assignable to type 'FunctionComponent<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
    Types of property 'propTypes' are incompatible.
      Type 'WeakValidationMap<HeaderProps> | undefined' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>> | undefined'.
        Type 'WeakValidationMap<HeaderProps>' is not assignable to type 'WeakValidationMap<Matching<{ getUserData: () => Promise<void>; }, HeaderProps>>'.
          Types of property 'getUserData' are incompatible.
            Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>> | undefined' is not assignable to type 'Validator<() => Promise<void>> | undefined'.
              Type 'Validator<() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>>' is not assignable to type 'Validator<() => Promise<void>>'.
                Type '() => (dispatch: Dispatch<AnyAction>, getState: () => {}, api: AxiosStatic) => Promise<void>' is not assignable to type '() => Promise<void>'.ts(2345)

Body:
Your mapDispatchToProps needs to be function, passing in dispatch and wrapping your action

const mapDispatchToProps = (dispatch: any) => {
    return {
       getUserData: bindActionCreators<any, any>(_getUserData, dispatch)
    }
}

Also if you're not passing any props through on the mapStateToProps function you can just pass through a null.

export default connect(null, mapDispatchToProps)(Header);


问:
vue js select (vuetify) + axios population
I have a stack with vue js (vuetify) + laravel + axios.
I am trying to populate a dropdown select using axios.
I have setup an API route on laravel so I can pull data from database table "Categories".
The api return the following:

```<code>[
{
    "id": 1,
    "category_name": "Electronics",
    "category_synonym": "Computer Accessories",
    "created_at": "2020-05-31T20:11:56.000000Z",
    "updated_at": "2020-05-31T20:11:56.000000Z"
},
{
    "id": 2,
    "category_name": "Hardware",
    "category_synonym": "hardware",
    "created_at": "2020-05-31T20:17:13.000000Z",
    "updated_at": "2020-05-31T20:17:13.000000Z"
},
{
    "id": 3,
    "category_name": "Kitchenware",
    "category_synonym": null,
    "created_at": "2020-05-31T20:49:32.000000Z",
    "updated_at": "2020-05-31T20:49:32.000000Z"
},
{
    "id": 4,
    "category_name": "Textile",
    "category_synonym": null,
    "created_at": "2020-05-31T21:29:30.000000Z",
    "updated_at": "2020-05-31T21:29:30.000000Z"
}
</code>```

]

I would like to put the category_name into a vue js dropdown contained into a foram.
How to make it simply ?

答:
Vuetify select has item-text and item-value. You can use these props:

```<code><v-select
  label="Category"
  :items="categories"
  item-text="category_name"
  item-value="id"
/>
</code>```

Body:
I have a stack with vue js (vuetify) + laravel + axios.
I am trying to populate a dropdown select using axios.
I have setup an API route on laravel so I can pull data from database table "Categories".
The api return the following:

[
{
    "id": 1,
    "category_name": "Electronics",
    "category_synonym": "Computer Accessories",
    "created_at": "2020-05-31T20:11:56.000000Z",
    "updated_at": "2020-05-31T20:11:56.000000Z"
},
{
    "id": 2,
    "category_name": "Hardware",
    "category_synonym": "hardware",
    "created_at": "2020-05-31T20:17:13.000000Z",
    "updated_at": "2020-05-31T20:17:13.000000Z"
},
{
    "id": 3,
    "category_name": "Kitchenware",
    "category_synonym": null,
    "created_at": "2020-05-31T20:49:32.000000Z",
    "updated_at": "2020-05-31T20:49:32.000000Z"
},
{
    "id": 4,
    "category_name": "Textile",
    "category_synonym": null,
    "created_at": "2020-05-31T21:29:30.000000Z",
    "updated_at": "2020-05-31T21:29:30.000000Z"
}

]

I would like to put the category_name into a vue js dropdown contained into a foram.
How to make it simply ?

Body:
Vuetify select has item-text and item-value. You can use these props:

<v-select
  label="Category"
  :items="categories"
  item-text="category_name"
  item-value="id"
/>


问:
Sum rows in one column between 2 time range
Is there a way to sum values in a column between two different time. The two different hrs are different for different start and end calculation. The formula i used is =SUMIFS(Period,time,">="&Time Range,time,  Range,"<="&Time Range) , but the formula returns only the first hour value but the expected result should be between total of start calc and end cal value

```<code>time          period  Cal stat    Time Range       Expected Result
6:37:02 AM      1     start calc  6:37:02 AM     4
6:37:03 AM      1     no action     0
6:37:04 AM      2     End Calc    6:37:04 AM
6:37:06 AM      1     Start Calc  6:37:06 AM     6
6:37:07 AM      1     no action     0
6:37:08 AM      2     no action     0
6:37:10 AM      1     no action     0
6:37:11 AM      1     End Calc    6:37:11 AM
6:37:12 AM      2     Start Calc   6:37:12 AM     3
6:37:14 AM      1     End Calc     6:37:14 AM
6:37:15 AM      1     no action     0
6:37:16 AM      1     no action     0
6:37:17 AM      2     no action     0
6:37:19 AM      2     no action     0
</code>```

答:
I don't know about doing it with SUMIFS.

However, with INDEX(MATCH(…, you can construct a formula that will sum from the current row to the next "end Calc", and use an IF(… to only show results in the start calc rows.

```<code>E2: =IF(C2="start calc", SUM( INDEX(B2:$B$15,1):  INDEX(B2:$B$15,MATCH(TRUE,C2:$C$15="end Calc",0))),"")
</code>```

Fill the formula down as far as needed

The $15 row numbers in the formula can be changed to any row that is at least as large as your expected table, but be sure it remains an absolute address.

e.g: =IF(C2="start calc", SUM( INDEX(B2:$B$1500,1):  INDEX(B2:$B$1500,MATCH(TRUE,C2:$C$1500="end Calc",0))),"")

Body:
Is there a way to sum values in a column between two different time. The two different hrs are different for different start and end calculation. The formula i used is =SUMIFS(Period,time,">="&Time Range,time,  Range,"<="&Time Range) , but the formula returns only the first hour value but the expected result should be between total of start calc and end cal value

time          period  Cal stat    Time Range       Expected Result
6:37:02 AM      1     start calc  6:37:02 AM     4
6:37:03 AM      1     no action     0
6:37:04 AM      2     End Calc    6:37:04 AM
6:37:06 AM      1     Start Calc  6:37:06 AM     6
6:37:07 AM      1     no action     0
6:37:08 AM      2     no action     0
6:37:10 AM      1     no action     0
6:37:11 AM      1     End Calc    6:37:11 AM
6:37:12 AM      2     Start Calc   6:37:12 AM     3
6:37:14 AM      1     End Calc     6:37:14 AM
6:37:15 AM      1     no action     0
6:37:16 AM      1     no action     0
6:37:17 AM      2     no action     0
6:37:19 AM      2     no action     0

Body:
I don't know about doing it with SUMIFS.

However, with INDEX(MATCH(…, you can construct a formula that will sum from the current row to the next "end Calc", and use an IF(… to only show results in the start calc rows.

E2: =IF(C2="start calc", SUM( INDEX(B2:$B$15,1):  INDEX(B2:$B$15,MATCH(TRUE,C2:$C$15="end Calc",0))),"")

Fill the formula down as far as needed

The $15 row numbers in the formula can be changed to any row that is at least as large as your expected table, but be sure it remains an absolute address.

e.g: =IF(C2="start calc", SUM( INDEX(B2:$B$1500,1):  INDEX(B2:$B$1500,MATCH(TRUE,C2:$C$1500="end Calc",0))),"")


问:
How to create and send a table by grouping rows by email addresses - GoogleSheets
I need help to create a table, from column [B] to column [I] if the emails from the managers of column [J] are the same:

Example_01
The yellow lines have the same manager in column [J]: "rafalmfei@gmail.com", so I need to set up a single email with a table, for the manager (Column [J2] and [J3]) with a copy for o Partner E-mail "rafaalmeida_feitoa@yahoo.com.br" (column k 2 and k 3) with lines 2 and 3.

Example_02
And an email with another separate table for the manager "rafaalmeida_feitoa@yahoo.com.br", (column [4] and column [5]) with a copy for Partner E-mail "rafalmfei@gmail.com" (column k [4] and k [5]) with lines 4 and 5.

Example_03
Currently, I have the email ready with the code below, but I receive the lines in separate emails, I need it to be in a single email in table format:

```<code>    function enviarEmailJornada(){
  // Linka a planilha de controle ao script e pega todas as colunas existentes
  var planilha = SpreadsheetApp.getActive();
  var sheet = planilha.getSheetByName("Analise_Maio");
  var linhas = sheet.getRange(1, 1, 156).getValues();
  var colunas;

  // Cria as variáveis necessárias para enviar o e-mail
  var toEmail;
  var ccEmail;
  var subject = "[URGENTE] Análise imediata de projetos sem ETC";
  var message;

  // Percorre as linhas da tabela e busca os dados de cada coluna
  for(var i = 0; i < linhas.length; i++){
    colunas = sheet.getRange(i+1,1,1,sheet.getLastColumn()).getValues()[0];
    toEmail = colunas[9];
    ccEmail = colunas[10];
    if(colunas[0] == "1"){
      message = "Caro(a), <br><br>";
      message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome. <br><br>";
      message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores. <br><br>";
      message += "<br>————————————<br><br> " + " "+ colunas[1] +" " + colunas[2] + " " + colunas[3] + " " + colunas[4] + " "  + colunas[5] + " " + colunas[6] + " " + colunas[7] + " " + colunas[8] + " " +"<br><br><br>";
      message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências. <br><br>";
      message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.<br><br>";
      message += "Conto com a sua pronta atuação. <br><br>";
      message += "Rafaela Feitosa <br><br>";
      GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
    }
  }
}
</code>```

Thank you!

答:
You can do the following

Retrieve all managers from the sheet

Use ...new Set() to retrieve unique values of managers

For each distinct manager retrieve the relevant sheet values and push them into an html table

Send an email after iterating through all rows and retrieving all data for particular manager

SAMPLE

```<code>function enviarEmailJornada(){
  // Linka a planilha de controle ao script e pega todas as colunas existentes
  var planilha = SpreadsheetApp.getActive();
  var sheet = planilha.getSheetByName("Analise_Maio");
  // Cria as variáveis necessárias para enviar o e-mail
  var subject = "[URGENTE] Análise imediata de projetos sem ETC";
  var message;

  var colunas = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getValues();

  var managers =  sheet.getRange(1, 8, sheet.getLastRow()).getValues().flat();
  Logger.log(managers);
  var uniqueManagers = [...new Set(managers)];
  Logger.log(uniqueManagers);
  uniqueManagers.forEach(myFunction);

  function myFunction(manager) {
    var table = "<table>"
    var toEmail = "";
    var ccEmail = "";
    // Percorre as linhas da tabela e busca os dados de cada coluna
    for(var i = 0; i < colunas.length; i++){
      if(colunas[i][7] == manager && colunas[i][0] == "1"){
        toEmail = colunas[i][9];
        ccEmail = colunas[i][10];
        table += "<tr><td>"+ colunas[i][1] +"</td><td>" + colunas[i][2] + "</td><td>" + colunas[i][3] + "</td><td>" + colunas[i][4] + "</td><td>"  + colunas[i][5] + "</td><td>" + colunas[i][6] + "</td><td>" + colunas[i][7] + "</td><td>" + colunas[i][8] + " " +"</td></tr>";
      }
    }
    Logger.log("table"+ table);
    if(toEmail != ""){
      message = "Caro(a), <br><br>";
      message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome. <br><br>";
      message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores. <br><br>";
      message += "<br>————————————<br><br> "
      message += table + "</table>";
      message += "<br><br><br>";
      message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências. <br><br>";
      message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.<br><br>";
      message += "Conto com a sua pronta atuação. <br><br>";
      message += "Rafaela Feitosa <br><br>";
      GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
    }
  }
}
</code>```

References:

flat()

Set()

Spread

Body:
I need help to create a table, from column [B] to column [I] if the emails from the managers of column [J] are the same:

Example_01
The yellow lines have the same manager in column [J]: "rafalmfei@gmail.com", so I need to set up a single email with a table, for the manager (Column [J2] and [J3]) with a copy for o Partner E-mail "rafaalmeida_feitoa@yahoo.com.br" (column k 2 and k 3) with lines 2 and 3.

Example_02
And an email with another separate table for the manager "rafaalmeida_feitoa@yahoo.com.br", (column [4] and column [5]) with a copy for Partner E-mail "rafalmfei@gmail.com" (column k [4] and k [5]) with lines 4 and 5.

Example_03
Currently, I have the email ready with the code below, but I receive the lines in separate emails, I need it to be in a single email in table format:

    function enviarEmailJornada(){
  // Linka a planilha de controle ao script e pega todas as colunas existentes
  var planilha = SpreadsheetApp.getActive();
  var sheet = planilha.getSheetByName("Analise_Maio");
  var linhas = sheet.getRange(1, 1, 156).getValues();
  var colunas;

  // Cria as variáveis necessárias para enviar o e-mail
  var toEmail;
  var ccEmail;
  var subject = "[URGENTE] Análise imediata de projetos sem ETC";
  var message;

  // Percorre as linhas da tabela e busca os dados de cada coluna
  for(var i = 0; i < linhas.length; i++){
    colunas = sheet.getRange(i+1,1,1,sheet.getLastColumn()).getValues()[0];
    toEmail = colunas[9];
    ccEmail = colunas[10];
    if(colunas[0] == "1"){
      message = "Caro(a),

";
      message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome.

";
      message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores.

";
      message += "
————————————

 " + " "+ colunas[1] +" " + colunas[2] + " " + colunas[3] + " " + colunas[4] + " "  + colunas[5] + " " + colunas[6] + " " + colunas[7] + " " + colunas[8] + " " +"

";
      message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências.

";
      message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.

";
      message += "Conto com a sua pronta atuação.

";
      message += "Rafaela Feitosa

";
      GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
    }
  }
}

Thank you!

Body:
You can do the following

Retrieve all managers from the sheet

Use ...new Set() to retrieve unique values of managers

For each distinct manager retrieve the relevant sheet values and push them into an html table

Send an email after iterating through all rows and retrieving all data for particular manager

SAMPLE

function enviarEmailJornada(){
  // Linka a planilha de controle ao script e pega todas as colunas existentes
  var planilha = SpreadsheetApp.getActive();
  var sheet = planilha.getSheetByName("Analise_Maio");
  // Cria as variáveis necessárias para enviar o e-mail
  var subject = "[URGENTE] Análise imediata de projetos sem ETC";
  var message;

  var colunas = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getValues();

  var managers =  sheet.getRange(1, 8, sheet.getLastRow()).getValues().flat();
  Logger.log(managers);
  var uniqueManagers = [...new Set(managers)];
  Logger.log(uniqueManagers);
  uniqueManagers.forEach(myFunction);

  function myFunction(manager) {
    var table = "<table>"
    var toEmail = "";
    var ccEmail = "";
    // Percorre as linhas da tabela e busca os dados de cada coluna
    for(var i = 0; i < colunas.length; i++){
      if(colunas[i][7] == manager && colunas[i][0] == "1"){
        toEmail = colunas[i][9];
        ccEmail = colunas[i][10];
        table += "<tr><td>"+ colunas[i][1] +"</td><td>" + colunas[i][2] + "</td><td>" + colunas[i][3] + "</td><td>" + colunas[i][4] + "</td><td>"  + colunas[i][5] + "</td><td>" + colunas[i][6] + "</td><td>" + colunas[i][7] + "</td><td>" + colunas[i][8] + " " +"</td></tr>";
      }
    }
    Logger.log("table"+ table);
    if(toEmail != ""){
      message = "Caro(a), <br><br>";
      message += "Identificamos que os projetos abaixo apresentam ETC zero e estão em seu nome. <br><br>";
      message += "Adicionalmente, elencamos projetos que estão com ETC Zerado e que o valor faturado é inferior a 0% da última valorização do WIP, o que pode indicar um risco em relação à realização destes valores. <br><br>";
      message += "<br>————————————<br><br> "
      message += table + "</table>";
      message += "<br><br><br>";
      message += "Peço a gentileza de que efetuem a imediata análise, reportando diretamente aos sócios dos projetos, a razão destas inconsistências. <br><br>";
      message += " Adicionalmente, como já diversas vezes solicitado, peço que efetuem imediatamente as baixas dos projetos cujo trabalho já foi concluído (ETC Zero) e valores faturados.<br><br>";
      message += "Conto com a sua pronta atuação. <br><br>";
      message += "Rafaela Feitosa <br><br>";
      GmailApp.sendEmail(toEmail,subject,"",{cc: ccEmail, htmlBody: message, name: "Análise imediata de projetos sem ETC"});
    }
  }
}

References:

flat()

Set()

Spread


问:
WebDriverException: Message: invalid argument: can't kill an exited process with GeckoDriver, Selenium and Python on RaspberryPi3
Server: Raspberry Pi 3

OS: Dietpi - version 159

Geckodriver version: 0.22 for arm

Firefox version: 52.9.0

Python version: 3.5

Selenium version: 3.14.1

Gecko is executable, and is located in /usr/local/bin/

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.set_headless(headless=True)
driver = webdriver.Firefox(firefox_options=options)

print('Need your login credential')
username = input('What is your username?:\n')
password = input('What is your password?:\n')
...
...
</code>```

Output:

```<code>root@RPi3:~# python3.5 ITE-bot.py
Traceback (most recent call last):
  File "ITE-bot.py", line 12, in <module>
    driver = webdriver.Firefox(firefox_options=options)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
    keep_alive=True)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process
</code>```

Any idea what is wrong? I've tried google without luck.

答:
As there can be many different underlying causes for this error it is best to find the root cause setting selenium to use debug level logging. In my case, for Ruby with capybara I needed to set: Selenium::WebDriver.logger.level = :debug. And voilà, running the same spec I could see in the logs that a dependency was missing, in my case:

```<code>libdbus-glib-1.so.2: cannot open shared object file: No such file or directory
Couldn't load XPCOM.
</code>```

After installing it all worked fine.

Body:
Server: Raspberry Pi 3

OS: Dietpi - version 159

Geckodriver version: 0.22 for arm

Firefox version: 52.9.0

Python version: 3.5

Selenium version: 3.14.1

Gecko is executable, and is located in /usr/local/bin/

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time

options = Options()
options.set_headless(headless=True)
driver = webdriver.Firefox(firefox_options=options)

print('Need your login credential')
username = input('What is your username?:\n')
password = input('What is your password?:\n')
...
...

Output:

root@RPi3:~# python3.5 ITE-bot.py
Traceback (most recent call last):
  File "ITE-bot.py", line 12, in <module>
    driver = webdriver.Firefox(firefox_options=options)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
    keep_alive=True)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process

Any idea what is wrong? I've tried google without luck.

Body:
As there can be many different underlying causes for this error it is best to find the root cause setting selenium to use debug level logging. In my case, for Ruby with capybara I needed to set: Selenium::WebDriver.logger.level = :debug. And voilà, running the same spec I could see in the logs that a dependency was missing, in my case:

libdbus-glib-1.so.2: cannot open shared object file: No such file or directory
Couldn't load XPCOM.

After installing it all worked fine.


问:
Functional API Linking Feed-Forward Networks and Convolutional neural network
Right now I have two networks f and g, the first trained on task 1 and the second on task 2.  I labelled my data as either beloning to task 1 or to task 2.  How can I build the following (trainable) custom architecture:

x -> decide if 1 or 2 -> pass to f or g accordingly?

I've never used such a branched architecture before...

答:
I tried to demonstrate what you need with a Sample Code shown below. Please let me know if this is not what you are looking for and give more details, and I will be Happy to help you.

As per the question, we are trying to achieve 2 Tasks, Task 1 --> Regression (Feedforward Neural Networks) and Task 2 --> CNN. We shall form 2 Datasets from the existing Dataset based on the Label, whether it belongs to Task 1 --> Data_T1 and Task 2 --> Data_T2.

Then using Functional API, we can pass Multiple Inputs and we can get Multiple Outputs.

Code is shown below:

```<code>from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, Dense, Flatten
import pandas as pd

F1 = [1,2,3,4,5,6,7,8,9,10]
F2 = [1,2,3,4,5,6,7,8,9,10]
F3 = [1,2,3,4,5,6,7,8,9,10]
Task = ['t1', 't1', 't2', 't1', 't2', 't2', 't2', 't1', 't1', 't2']

Dict = {'F1': F1, 'F2':F2, 'F3':F3, 'Task':Task} # Column Task tells us whether the Data belongs to Task1 or Task2

Data = pd.DataFrame(Dict) #Create a Dummy Data Frame

Data_T1 = Data[Data['Task']=='t1']
Data_T1 = Data_T1.drop(columns = ['Task'])

Data_T2 = Data[Data['Task']=='t2']
Data_T2 = Data_T2.drop(columns = ['Task'])

Input1 = ...
Input2 = ...

Number_Of_Classes = 3
# Regression Model
D1 = Dense(10, activation = 'relu')(Input1)
Out_Task1 = Dense(1, activation = 'linear')
# CNN Model
Conv1 = Conv2D(16, (3,3), activation = 'relu')(Input2)
Conv2 = Conv2D(32, (3,3, activation = 'relu'))(Conv1)
Flatten = Flatten()(Conv2)
D2_1 = Dense(10, activation = 'relu')
Out_Task2 = Dense(Number_Of_Classes, activation = 'softmax')

model = Model(inputs = [Input1, Input2], outputs = [Out_Task1, Out_Task2])

model.compile....

model.fit([Data_T1, Data_T2], .....)
</code>```

Body:
I tried to demonstrate what you need with a Sample Code shown below. Please let me know if this is not what you are looking for and give more details, and I will be Happy to help you.

As per the question, we are trying to achieve 2 Tasks, Task 1 --> Regression (Feedforward Neural Networks) and Task 2 --> CNN. We shall form 2 Datasets from the existing Dataset based on the Label, whether it belongs to Task 1 --> Data_T1 and Task 2 --> Data_T2.

Then using Functional API, we can pass Multiple Inputs and we can get Multiple Outputs.

Code is shown below:

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, Dense, Flatten
import pandas as pd

F1 = [1,2,3,4,5,6,7,8,9,10]
F2 = [1,2,3,4,5,6,7,8,9,10]
F3 = [1,2,3,4,5,6,7,8,9,10]
Task = ['t1', 't1', 't2', 't1', 't2', 't2', 't2', 't1', 't1', 't2']

Dict = {'F1': F1, 'F2':F2, 'F3':F3, 'Task':Task} # Column Task tells us whether the Data belongs to Task1 or Task2

Data = pd.DataFrame(Dict) #Create a Dummy Data Frame

Data_T1 = Data[Data['Task']=='t1']
Data_T1 = Data_T1.drop(columns = ['Task'])

Data_T2 = Data[Data['Task']=='t2']
Data_T2 = Data_T2.drop(columns = ['Task'])

Input1 = ...
Input2 = ...

Number_Of_Classes = 3
# Regression Model
D1 = Dense(10, activation = 'relu')(Input1)
Out_Task1 = Dense(1, activation = 'linear')
# CNN Model
Conv1 = Conv2D(16, (3,3), activation = 'relu')(Input2)
Conv2 = Conv2D(32, (3,3, activation = 'relu'))(Conv1)
Flatten = Flatten()(Conv2)
D2_1 = Dense(10, activation = 'relu')
Out_Task2 = Dense(Number_Of_Classes, activation = 'softmax')

model = Model(inputs = [Input1, Input2], outputs = [Out_Task1, Out_Task2])

model.compile....

model.fit([Data_T1, Data_T2], .....)


问:
Super class method and submethods for subclasses in runtime
I have method with super class as argument in main class.

```<code>public class MainClass() {
...
    public void myMethod(MyClass class)
...
</code>```

In runtime this object can be any of its subclasses and it should call different method depending on subclasses in same main class

```<code>public class MainClass() {
...
    public void mySubMethod(MySubClass1 class)

    public void mySubMethod(MuySubClass2 class)
...
</code>```

Of course, I can use instanceOf or Static Factory Pattern with Enum but still it will be (pseudo code)

```<code>public void myMethod(MyClass class) {
if (instanceOf == MySubclass1) mySubMethod((MySubClass1)subClass1Object)
if (instanceOf == MySubclass2) mySubMethod((MySubClass2)subClass2Object)
}
</code>```

In runtime jvm knows which subclass exactly object is and knows for each sub-method argument should be. I don't have control over MyClass, MySubclass1 and MySubclass2,...

But is there any elegant way to achive this?

答:
One solution to this is to use HandlerFactories

```<code>public class HandlerRegistry {
  public void registerHandler(Class classToHandle, HandlerFactory handler)
  // returns the proper handler (via the HandlerFactory) for the registered class
  public Handler getHandlerFor(Class classToHandle)
}
</code>```

You can make the methods in this class static or use the Singleton pattern to make the HandlerRgistry accessible everywhere
    }

Body:
I have method with super class as argument in main class.

public class MainClass() {
...
    public void myMethod(MyClass class)
...

In runtime this object can be any of its subclasses and it should call different method depending on subclasses in same main class

public class MainClass() {
...
    public void mySubMethod(MySubClass1 class)

    public void mySubMethod(MuySubClass2 class)
...

Of course, I can use instanceOf or Static Factory Pattern with Enum but still it will be (pseudo code)

public void myMethod(MyClass class) {
if (instanceOf == MySubclass1) mySubMethod((MySubClass1)subClass1Object)
if (instanceOf == MySubclass2) mySubMethod((MySubClass2)subClass2Object)
}

In runtime jvm knows which subclass exactly object is and knows for each sub-method argument should be. I don't have control over MyClass, MySubclass1 and MySubclass2,...

But is there any elegant way to achive this?

Body:
One solution to this is to use HandlerFactories

public class HandlerRegistry {
  public void registerHandler(Class classToHandle, HandlerFactory handler)
  // returns the proper handler (via the HandlerFactory) for the registered class
  public Handler getHandlerFor(Class classToHandle)
}

You can make the methods in this class static or use the Singleton pattern to make the HandlerRgistry accessible everywhere
    }


问:
How to handle CSV files in this Python script
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data, without turning it into a dictionary. How do I skip over the header record with the field names?

import os
import csv

# Create a file with data in it
def create_file(filename):
    with open(filename, "w") as file:
        file.write("name,color,type\n")
        file.write("carnation,pink,annual\n")
        file.write("daffodil,yellow,perennial\n")
        file.write("iris,blue,perennial\n")
        file.write("poinsettia,red,perennial\n")
        file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
    return_string = ""
    # Call the function to create the file
    create_file(filename)

    # Open the file
    with open(filename) as file:
        # Read the rows of the file
        rows = csv.reader(file)
        rows = list(rows)
        # Process each row
        for row in rows:
            name, color, ty = row
            # Format the return string for data rows only
            if row != rows[0]:
                return_string += "a {} {} is {}\n".format(name, color, ty)
    return return_string

#Call the function
print(contents_of_file("flowers.csv"))
```

<p>After submitting my answer, the following message is shown:</p>

```Not quite, contents_of_file returned:
a carnation pink is
annual
a daffodil yellow is perennial
a iris blue is
perennial
a poinsettia red is perennial
a sunflower yellow
is annual

The output should be:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a
red poinsettia is perennial
a yellow sunflower is annual
```

How can I correct this problem?

答:
To address the question of " How do I skip over the header record with the field names?". One can use next():</p>

```<code>with open('my_file.csv', 'r') as f:
    headers = next(f)
    # do something with rest of the lines
</code>```

Body:
Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data, without turning it into a dictionary. How do I skip over the header record with the field names?

import os
import csv

# Create a file with data in it
def create_file(filename):
    with open(filename, "w") as file:
        file.write("name,color,type\n")
        file.write("carnation,pink,annual\n")
        file.write("daffodil,yellow,perennial\n")
        file.write("iris,blue,perennial\n")
        file.write("poinsettia,red,perennial\n")
        file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
    return_string = ""
    # Call the function to create the file
    create_file(filename)

    # Open the file
    with open(filename) as file:
        # Read the rows of the file
        rows = csv.reader(file)
        rows = list(rows)
        # Process each row
        for row in rows:
            name, color, ty = row
            # Format the return string for data rows only
            if row != rows[0]:
                return_string += "a {} {} is {}\n".format(name, color, ty)
    return return_string

#Call the function
print(contents_of_file("flowers.csv"))

After submitting my answer, the following message is shown:

Not quite, contents_of_file returned:
a carnation pink is
annual
a daffodil yellow is perennial
a iris blue is
perennial
a poinsettia red is perennial
a sunflower yellow
is annual

The output should be:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a
red poinsettia is perennial
a yellow sunflower is annual

How can I correct this problem?

Body:
To address the question of " How do I skip over the header record with the field names?". One can use next():

with open('my_file.csv', 'r') as f:
    headers = next(f)
    # do something with rest of the lines


问:
Angular - How to open a virtual scroll centered on the clicked image?
After a couple of days of research and experiments, I can't seem to be able to replicate the following typical Instagram behavior in Angular 8, using Angular Material's cdk-virtual-scroll-viewport.

Click on an image from the profile's grid of images

Open an infinite scroll of images, centered on the clicked image, while having the previous and next images loaded below and above it.

The problem specifically lies on opening the virtual scroll centered on the clicked image.

My setup:

the Profile Component loads the image grid with an *ngFor="let post of posts"

On click, a new Timeline Component is initiated, receiving the above posts array as a state with [state]='{ data: posts }', along with the clicked post's array position.

Everything works, the feed (timeline, as I call it) is loaded, but although I can make it scroll to the clicked post position with this.viewPort.scrollToIndex(index), I can't make it load on this position directly.

Why don't I want it to simply scroll there although it is almost instant? Because all the HD images that precede the clicked post will be pulled from the server in order to be loaded as the feed scrolls it's way there. Imagine if the clicked post has 20 other image posts before it.

What else have i tried:

I've tried cutting the posts array right before the clicked post, loading that second part of the array (which starts with he clicked post) with a *cdkVirtualFor="let post of posts", and then pushing the first part of the array in the beginning of posts so that it will load above the fold. But, when the first part of the array is prepended in posts, the view navigates to the top of the page (first post) instead of loading the prepended posts above the fold, which is what I want.

Any ideas on how to make this sorcery work will be highly appreciated.

答:
I still haven't found a way to start rendering from the clicked post, but the best workaround I found was the following.

It turns out that using this.viewPort.scrollToIndex(scrollIndex, "auto") - pay attention to the auto parameter - does not actually scroll through the page but practically teleports directly to the desired index. Which means that, if you call the method soon enough, no other items between the beginning of the page and the index you land on will be loaded from the server. You can check this experiment in this StackBlitz with the Network tab on chrome dev tools open.

Now, trying to run the above command the way it was intended, like so:

```<code>  ngAfterViewInit() {
    this.viewPort.scrollToIndex(i);
  }
</code>```

you will probably figure out that it doesn't work. Two solutions to this bug has been offered here. They both work, but calling setTimeout() is visibly slower as you actually see the "snap" to the new index when the page loads. Thus, the best way to handle this is to run the scrollToIndex() method in an ngAfterViewChecked() hook instead of an ngAfterViewInit(), like so:

```<code>  ngAfterViewChecked() {
    this.viewPort.scrollToIndex(i);
  }
</code>```

It is not a perfect solution but it does practically replicate the desired experience to the end user.

Body:
I still haven't found a way to start rendering from the clicked post, but the best workaround I found was the following.

It turns out that using this.viewPort.scrollToIndex(scrollIndex, "auto") - pay attention to the auto parameter - does not actually scroll through the page but practically teleports directly to the desired index. Which means that, if you call the method soon enough, no other items between the beginning of the page and the index you land on will be loaded from the server. You can check this experiment in this StackBlitz with the Network tab on chrome dev tools open.

Now, trying to run the above command the way it was intended, like so:

  ngAfterViewInit() {
    this.viewPort.scrollToIndex(i);
  }

you will probably figure out that it doesn't work. Two solutions to this bug has been offered here. They both work, but calling setTimeout() is visibly slower as you actually see the "snap" to the new index when the page loads. Thus, the best way to handle this is to run the scrollToIndex() method in an ngAfterViewChecked() hook instead of an ngAfterViewInit(), like so:

  ngAfterViewChecked() {
    this.viewPort.scrollToIndex(i);
  }

It is not a perfect solution but it does practically replicate the desired experience to the end user.


问:
Get language in a tpl file
I want to write a code in different languages using an

if (language = en || lenguage=es) {// code } (For example)

in a tpl file. How can I know what language the user is using?

Thanks!

答:
In Prestashop 1.7 it seems that the correct way to read the iso code of the current language is

```<code>{$language.iso_code}
</code>```

To find out all the properties of the object:

```<code>{$language|@var_dump}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get language in a tpl file

Body:
In Prestashop 1.7 it seems that the correct way to read the iso code of the current language is

{$language.iso_code}

To find out all the properties of the object:

{$language|@var_dump}


问:
What is the use of 'did' attribute of string.xml in android studio?
I found some similar usages like followings:

```<code><string name="add_button_tts_enabled" did="BODY_P1SS_P2SS">%1$s %2$s </string>
</code>```

I just want to learn what 'did' attribute does here.

答: That should be a custom attribute defined above. Check the complete code from start.</p>

Body:
I found some similar usages like followings:

<string name="add_button_tts_enabled" did="BODY_P1SS_P2SS">%1$s %2$s </string>

I just want to learn what 'did' attribute does here.


问:
Issue @import angular_components material css in AngularDart
I am having an issue importing the anugular_components material.scss package.  For some reason Sass is not able to locate the scss files in the angular_components package.

The error is:

```<code>/* Error: Can't find stylesheet to import.
 *   ,
 * 1 | @import 'package:angular_components/css/material/material';
 *   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *   '
 *   wakeup_component.scss 1:9  root stylesheet */
</code>```

My pubspec.yaml file looks like this:

```<code>name: ct
description: A web app for CasaTunes using Angular Dart and Material Design
# version: 1.0.0
# homepage: https://www.casatunes.com

environment:
  sdk: '>=2.7.0 <3.0.0'

dependencies:
  angular: ^6.0.0-alpha+1
  angular_components: ^0.14.0-alpha+1
  angular_router: ^2.0.0-alpha+24

dev_dependencies:
  angular_test: ^2.3.0
  build_runner: ^1.6.0
  build_test: ^0.10.8
  build_web_compilers: ^2.3.0
  pedantic: ^1.8.0
  test: ^1.6.0
  sass_builder: ^2.1.2
  casatunes_rest:
    path: /Users/davidkrinker/Development/CasaTunes REST API/dart/api
</code>```

I am using Sass version: 1.26.5
Using WebStorm

答: The fix was to disable WebStorm's file watching to automatically build the .css files from the .scss files.</p>

Body:
I am having an issue importing the anugular_components material.scss package.  For some reason Sass is not able to locate the scss files in the angular_components package.

The error is:

/* Error: Can't find stylesheet to import.
 *   ,
 * 1 | @import 'package:angular_components/css/material/material';
 *   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *   '
 *   wakeup_component.scss 1:9  root stylesheet */

My pubspec.yaml file looks like this:

name: ct
description: A web app for CasaTunes using Angular Dart and Material Design
# version: 1.0.0
# homepage: https://www.casatunes.com

environment:
  sdk: '>=2.7.0 <3.0.0'

dependencies:
  angular: ^6.0.0-alpha+1
  angular_components: ^0.14.0-alpha+1
  angular_router: ^2.0.0-alpha+24

dev_dependencies:
  angular_test: ^2.3.0
  build_runner: ^1.6.0
  build_test: ^0.10.8
  build_web_compilers: ^2.3.0
  pedantic: ^1.8.0
  test: ^1.6.0
  sass_builder: ^2.1.2
  casatunes_rest:
    path: /Users/davidkrinker/Development/CasaTunes REST API/dart/api

I am using Sass version: 1.26.5
Using WebStorm


问:
string manipulation: partly convert to lowercase
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

```<code>>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2
</code>```

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

```<code>>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee
</code>```

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

答:
You can replace your regex check with</p>

```<code>if ss.lower().startswith('formatdate'):
</code>```

Body:
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). For the first example, I came up something like this:

>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
...   SS = ss.split('(')
...   SS[0] = SS[0].lower()
...   ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2

Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!

Update:

I probably didn't say it very clearly: it's not always formatdate(), sometimes it's startdate() or enddate() along with UserName==JohnDee and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's script.

>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
...   if fdt.search(sX):
...     p1,p2 = sX.split('(',1)
...     sX = "%s(%s" % (p1.lower(), p2)
...   else: sX = sX.lower()
...   return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee

This is exactly what I wanted. Thanks everyone for helping. Cheers!!

Body:
You can replace your regex check with

if ss.lower().startswith('formatdate'):


问:
Stepwise subsetting of a list in Python
My current solution looks like:

```<code>import numpy as np

chunksize = 10
l = list(np.arange(0,99))

while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    l.pop(0)
    print(l_subset)
</code>```

This doesn't look like a very efficient solution, since .pop requires traversing the list. What are fast ways to do that?

答:
Using numpy is the fastest solution I've found:</p>

```<code>import numpy as np
import time
chunksize = 10
arr = np.arange(0,99999)
l = list(arr)

start = time.time()
while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    l.pop(0)
runTime = time.time()-start
print(runTime) #0.8397529125213623s

l = list(arr)
start = time.time()
while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    del l[0]
 runTime = time.time()-start
 print(runTime) #0.879807710647583s

 start = time.time()
 lower = 0
 upper = chunksize
 n_subset = int(len(arr)/chunksize)
 for i in range(n_subset):
     arr[lower:upper]
     lower = lower + 1
     upper = upper + 1
runTime = time.time()-start
print(runTime) # 0.002997159957885742s
</code>```

Title: Stepwise subsetting of a list in Python

Body:
My current solution looks like:

import numpy as np

chunksize = 10
l = list(np.arange(0,99))

while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    l.pop(0)
    print(l_subset)

This doesn't look like a very efficient solution, since .pop requires traversing the list. What are fast ways to do that?

Body:
Using numpy is the fastest solution I've found:

import numpy as np
import time
chunksize = 10
arr = np.arange(0,99999)
l = list(arr)

start = time.time()
while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    l.pop(0)
runTime = time.time()-start
print(runTime) #0.8397529125213623s

l = list(arr)
start = time.time()
while len(l) > chunksize:
    l_subset = l
    l_subset = l_subset[0:chunksize]
    del l[0]
 runTime = time.time()-start
 print(runTime) #0.879807710647583s

 start = time.time()
 lower = 0
 upper = chunksize
 n_subset = int(len(arr)/chunksize)
 for i in range(n_subset):
     arr[lower:upper]
     lower = lower + 1
     upper = upper + 1
runTime = time.time()-start
print(runTime) # 0.002997159957885742s


问:
Range slider value
I have this simple countdown which goes from 5 to 0 every 1 second:

```<code><html>
 <head>
  <meta charset="utf-8"/>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js">
  </script>
 </head>
 <body>
<button id="start">START</button>
COUNTDOWN:<span id="countdown"></span>
<input id="time_delay" type="range" min="1000" max="10000" value="1000" step="1000">
<span id="time_delay">1000</span>
  <script>
    let start = document.getElementById('start');
    let start_click = rxjs.fromEvent(start, 'click');
    start_click.subscribe(x => console.log('click'));

start_click.pipe(rxjs.operators.tap()).subscribe(
  ()=> {
    let time = rxjs.timer(0, 1000).pipe(
      rxjs.operators.skip(0)
    , rxjs.operators.take(6)
    , rxjs.operators.map(x => 5-x)
      );

    time.subscribe(x => console.log('instant', x));
    let countdown = document.getElementById('countdown');
    time.subscribe(x => countdown.innerText = x);
    start.disabled = true;

    let end = time.pipe(
    rxjs.operators.last()
    , rxjs.operators.repeatWhen(() => start_click)
    );

    end.subscribe(x=>start.disabled = false);
    start_click.subscribe(x => start.disabled = true);
    });
  </script>
 </body>
</html>
</code>```

I'd like to learn how to change a value with my range slider. For example, when I change the slider, the let time = rxjs.timer(0, 1000) change to let time = rxjs.timer(0, 5000)

答:
you can try something like:

const timeDelay = document.querySelector('#time_delay');
const timeDelayView = document.querySelector('#time_delay_view');
rxjs.fromEvent(timeDelay, 'change').subscribe(() => {
  timeDelayView.innerText = timeDelay.value;
});

let start = document.getElementById('start');
let start_click = rxjs.fromEvent(start, 'click');
start_click.subscribe(x => console.log('click'));

start_click.pipe(rxjs.operators.tap()).subscribe(
  ()=> {
    let time = rxjs.timer(0, timeDelay.value).pipe(
      rxjs.operators.skip(0)
    , rxjs.operators.take(6)
    , rxjs.operators.map(x => 5-x)
      );

    time.subscribe(x => console.log('instant', x));
    let countdown = document.getElementById('countdown');
    time.subscribe(x => countdown.innerText = x);
    start.disabled = true;

    let end = time.pipe(
    rxjs.operators.last()
    , rxjs.operators.repeatWhen(() => start_click)
    );

    end.subscribe(x=>start.disabled = false);
    start_click.subscribe(x => start.disabled = true);
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

<button id="start">START</button>
COUNTDOWN:<span id="countdown"></span>

<br>
<input id="time_delay" type="range" min="1000" max="10000" value="1000" step="1000">
<span id="time_delay_view">1000</span></code>```

please also note, that in you code there are 2 elements with the same id time_delay, the id should be unique per page, so I changed span's id to time_delay_view

Title: Range slider value

Body:
I have this simple countdown which goes from 5 to 0 every 1 second:

  <meta charset="utf-8"/>

<button id="start">START</button>
COUNTDOWN:
<input id="time_delay" type="range" min="1000" max="10000" value="1000" step="1000">
1000

I'd like to learn how to change a value with my range slider. For example, when I change the slider, the let time = rxjs.timer(0, 1000) change to let time = rxjs.timer(0, 5000)

Body:
you can try something like:

const timeDelay = document.querySelector('#time_delay');
const timeDelayView = document.querySelector('#time_delay_view');
rxjs.fromEvent(timeDelay, 'change').subscribe(() => {
  timeDelayView.innerText = timeDelay.value;
});

let start = document.getElementById('start');
let start_click = rxjs.fromEvent(start, 'click');
start_click.subscribe(x => console.log('click'));

start_click.pipe(rxjs.operators.tap()).subscribe(
  ()=> {
    let time = rxjs.timer(0, timeDelay.value).pipe(
      rxjs.operators.skip(0)
    , rxjs.operators.take(6)
    , rxjs.operators.map(x => 5-x)
      );

    time.subscribe(x => console.log('instant', x));
    let countdown = document.getElementById('countdown');
    time.subscribe(x => countdown.innerText = x);
    start.disabled = true;

    let end = time.pipe(
    rxjs.operators.last()
    , rxjs.operators.repeatWhen(() => start_click)
    );

    end.subscribe(x=>start.disabled = false);
    start_click.subscribe(x => start.disabled = true);
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

<button id="start">START</button>
COUNTDOWN:<span id="countdown"></span>

<br>
<input id="time_delay" type="range" min="1000" max="10000" value="1000" step="1000">
<span id="time_delay_view">1000</span>

please also note, that in you code there are 2 elements with the same id time_delay, the id should be unique per page, so I changed span's id to time_delay_view


问:
I want to call api with orderid when order is placed?

Here Is My code

```<code>add_action( 'woocommerce_payment_complete', 'my_api_call');
function my_api_call( $order_id ){

    // Order Setup Via WooCommerce

    $order = new WC_Order( $order_id );

    // Iterate Through Items

    $items = $order->get_items();

    $url = "http://Example.com/Api/WooCommerceApi/SaveSubscriptionAndZoomData?".$order;
 }
</code>```

Please help me with your knowledge.
Thanks

答:
You are not sending the URL anywhere at the moment.

You should use curl to post this URL with any variables you need. However, you are also trying to post a full order which will not work at all.

I am not sure what your API/system requires from your website but if you want to send only the order ID then this should look something like this:

```<code>add_action( 'woocommerce_payment_complete', 'my_api_call');
function my_api_call( $order_id ){

// Order Setup Via WooCommerce

$order = new WC_Order( $order_id );

// Iterate Through Items

$items = $order->get_items();

$url = "http://example.com/Api/WooCommerceApi/SaveSubscriptionAndZoomData";

$orderid = "OrderId=".$order_id;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $orderid);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

 }
</code>```

The $response should give you a message. Important: this code is untested but you should be able to get the solution from here.

Source: POST data to a URL in PHP

Body:
Here Is My code

add_action( 'woocommerce_payment_complete', 'my_api_call');
function my_api_call( $order_id ){

    // Order Setup Via WooCommerce

    $order = new WC_Order( $order_id );

    // Iterate Through Items

    $items = $order->get_items();

    $url = "http://Example.com/Api/WooCommerceApi/SaveSubscriptionAndZoomData?".$order;
 }

Please help me with your knowledge.
Thanks

Body:
You are not sending the URL anywhere at the moment.

You should use curl to post this URL with any variables you need. However, you are also trying to post a full order which will not work at all.

I am not sure what your API/system requires from your website but if you want to send only the order ID then this should look something like this:

add_action( 'woocommerce_payment_complete', 'my_api_call');
function my_api_call( $order_id ){

// Order Setup Via WooCommerce

$order = new WC_Order( $order_id );

// Iterate Through Items

$items = $order->get_items();

$url = "http://example.com/Api/WooCommerceApi/SaveSubscriptionAndZoomData";

$orderid = "OrderId=".$order_id;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $orderid);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

 }

The $response should give you a message. Important: this code is untested but you should be able to get the solution from here.

Source: POST data to a URL in PHP


问:
AJAX data not displayed in page
To sum up what I'm trying to achieve here:

Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>

This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data

The PHP page is displayed inside a div on the page

Here is the function, using jQuery:

```<code>function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      console.log(data);
    }
  });

  $('#my-div').load('target.php');
}
</code>```

To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>

When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:

Notice: Undefined index: value

Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.

答:
Please try this.
and you need to return the result from target.php page

```<code>function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      $('#my-div').html(data);
    }
  });

}
</code>```

Title: AJAX data not displayed in page

Body:
To sum up what I'm trying to achieve here:

Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>

This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data

The PHP page is displayed inside a div on the page

Here is the function, using jQuery:

function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      console.log(data);
    }
  });

  $('#my-div').load('target.php');
}

To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>

When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:

Notice: Undefined index: value

Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.

Body:
Please try this.
and you need to return the result from target.php page

function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      $('#my-div').html(data);
    }
  });

}


问:
The mysqli_connect not working
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

```<code>$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
</code>```

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

答:
Try this:</p>

```<code>$dbc = @ mysql_connect('localhost', 'root', '') or exit('Not connecting.');
</code>```

Title: The mysqli_connect not working

Body:
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

Body:
Try this:

$dbc = @ mysql_connect('localhost', 'root', '') or exit('Not connecting.');


问:
NullPointerException when using FirebaseUI and RecyclerView
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

```<code>public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}
</code>```

Activity code:

```<code>recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }
</code>```

xml of recycler_view_row:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

errors:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)
</code>```

答:
You have defined the Textview inside the function. Define it as </p>

```<code>private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;
        TextView textView;
        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            textView = view.findViewById(R.id.editName);
        }

        void setFoodName(String foodName) {

            textView.setText(foodName);
        }
    }
</code>```

Body:
I followed this guide How to display data from Firestore in a RecyclerView with Android?, but am facing a NullPointerException in the setter in the ViewHolder. I'm also actually very unsure of what to do in the setter in the ViewHolder...

![database]https://imgur.com/a/wquZ08f

Model:

public class FoodModel {
    private String foodName;
    private String foodType;
    private String foodQty;
    private String foodExpDate;

    public FoodModel() {}

    public FoodModel(String name, String type, String qty, String expDate) {
        this.foodName = name;
        this.foodType = type;
        this.foodQty = qty;
        this.foodExpDate = expDate;
    }

    public String getFoodName() {return foodName;}
    public void setFoodName(String name) {foodName = name;}

    public String getFoodType() {return foodType;}
    public void setFoodType(String type) {foodType = type;}

    public String getFoodQty() {return foodQty;}
    public void setFoodQty(String qty) {foodQty = qty;}

    public String getFoodExpDate() {return foodExpDate;}
    public void setFoodExpDate(String expDate) {foodExpDate = expDate;}
}

Activity code:

recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        Query foodQuery = db.collection("Food")
                .orderBy("food_name", Query.Direction.ASCENDING);

        FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>()
                .setQuery(foodQuery, FoodModel.class)
                .build();

        adapter = new FirestoreRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FoodViewHolder holder, int position, @NonNull FoodModel model) {
                holder.setFoodName(model.getFoodName());
            }
            @NonNull
            @Override
            public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup group, int viewType) {
                View view = LayoutInflater.from(group.getContext()).inflate(R.layout.recycler_view_row, group, false);
                return new FoodViewHolder(view);
            }
        };
        recyclerView.setAdapter(adapter);
    }
    private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;

        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
        }

        void setFoodName(String foodName) {
            TextView textView = view.findViewById(R.id.editName);
            textView.setText(foodName);
        }
    }

xml of recycler_view_row:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/foodListRow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

errors:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.qremind, PID: 17735
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.qremind.FoodList$FoodViewHolder.setFoodName(FoodList.java:91)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:70)
        at com.example.qremind.FoodList$1.onBindViewHolder(FoodList.java:67)
        at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:158)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:878)
        at android.view.Choreographer.doCallbacks(Choreographer.java:690)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:864)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:185)
        at android.app.ActivityThread.main(ActivityThread.java:6473)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:916)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:806)

Body:
You have defined the Textview inside the function. Define it as

private class FoodViewHolder extends RecyclerView.ViewHolder {
        private View view;
        TextView textView;
        FoodViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            textView = view.findViewById(R.id.editName);
        }

        void setFoodName(String foodName) {

            textView.setText(foodName);
        }
    }


问:
Delete 5 years old records from a table and its dependencies i.e. parent and child tables both in Oracle using query or procedure
How to 5 years old records from a table and its dependencies i.e. parent and child tables both in Oracle using query or procedure.

I tried using the dateadd command of oracle but it only delete records from main table and not from its child table.
Assume table A is main table and B&C are child tables. How can we delete records from A as well as B&C that are 5 yrs old.

答:
You have to first delete child tables by joining the child tables with parent table

Once child table is deleted, delete the parent table

You can either have a procedure or you can also delete using simple queries.


答:
If you use .load() your browser will make another GET request to target.php and display it, so your $_POST will be empty.
You can use $('#my-div').html(data) inside success: of ajax or you can use $_GET instead of $_POST in your php and pass variable in url like this

$('#my-div').load('target.php?value='str.value);

Title: AJAX data not displayed in page


问:
How to render the values in a parent child relationship in Django
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like.

```<code>class Category(models.Model):
    title = models.CharField(max_length=30)
    slug = models.SlugField(unique=True)

class Meta:
    ordering = ['title']

def __str__(self):
    return self.title

class SafariPackages(models.Model):
    image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False)
    title = models.CharField(max_length=200)
    cost = models.FloatField(null=False)
    days = models.FloatField(blank=False, null=False)
    nights = models.FloatField(blank=False, null=False)
    category = models.ManyToManyField(Category)
    exodus = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    telegram = models.TextField(max_length=140, null=False)
    description = models.TextField(null=False)
    slug = models.SlugField(max_length=200, unique=True)

objects = EntryQuerySet.as_manager()

def __str__(self):
    return self.title

class Meta:
    verbose_name = 'Safari Package Entry'
    verbose_name_plural = 'Safari Package Entries'

class DayNumber(models.Model):
    daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE)
    day_number = models.CharField( max_length=10, null=True, blank=True)
    image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1)
    day_description = models.TextField()
</code>```

The views that I have so far look like this

```<code>def safaripackages_view(request, *args,**kwargs):
    print (args, kwargs)
    print (request.user)

    all_safaripackages = SafariPackages.objects.all()

#Paginator
paginator = Paginator(all_safaripackages, 8)
page = request.GET.get('page')
try:
    all_safaripackages = paginator.page(page)
except PageNotAnInteger:
    all_safaripackages = paginator.page(1)
except EmptyPage:
    all_safaripackages = paginator.page(paginator.num_pages)

context = {
'all_safaripackages': all_safaripackages,
}

return render (request, "safaripackages.html", context)

def single_safaripackage(request, post_id):
    safaripackage = SafariPackages.objects.get(pk=post_id)
    return render (request, 'single_safaripackage.html', {'safaripackage':safaripackage,})
</code>```

How do I include the values of the DayNumber model in the single_safaripackage view?

答:
In accordance to my understanding,you are trying to render the day numbers of the packages from the child model.

The trick is:

"the parent model"."the child model"_set.all()
eg: parent.child_set.all()

*the child model to be lower case all through regardless of its original form in the model.py

Here is the solution to dynamically render a specific package to the browser:

```<code>def safaripackages_view(request,pk):
    safaripackage = SafariPackages.objects.get(name=pk_test)
    days = safaripackage.daynumber_set.all()
    context = {"days":days,"safaripackage":safaripackage}
    return render(request,'main/single_safaripackage.html',context)
</code>```

Here is the solution to render all packages:

```<code>def safaripackages_view(request):
    safaripackage = SafariPackages.objects.all()
    days = safaripackage.daynumber_set.all()
    context = {"days":days,"safaripackage":safaripackage}
    return render(request,'main/single_safaripackage.html',context)
</code>```

In your template you can have like a table to render

```<code><table>
          <tr>
            <th>Day Details</th>
            <th>Day Number</th>
            <th>Day Description</th>
          </tr>
{% for day in days %}
          <tr>
              <th>{{day.daydetails}}</th>
              <th>   {{day.day_number}}</td>
              <td>{{day.day_description}}</td>
<td><img src="{% url 'day.image.url' %}" class="templates" alt=""> <td/>
              <tr/>
          {% endfor %}

        </table>
</code>```

Body:
I am creating a django app where the admin can add travel packages. To add the explicit details of the package I created a child that will handle those values. Here is how the code looks like.

class Category(models.Model):
    title = models.CharField(max_length=30)
    slug = models.SlugField(unique=True)

class Meta:
    ordering = ['title']

def __str__(self):
    return self.title

class SafariPackages(models.Model):
    image = models.ImageField(upload_to='SafariPackages/%Y/%m/%d', null=False)
    title = models.CharField(max_length=200)
    cost = models.FloatField(null=False)
    days = models.FloatField(blank=False, null=False)
    nights = models.FloatField(blank=False, null=False)
    category = models.ManyToManyField(Category)
    exodus = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    telegram = models.TextField(max_length=140, null=False)
    description = models.TextField(null=False)
    slug = models.SlugField(max_length=200, unique=True)

objects = EntryQuerySet.as_manager()

def __str__(self):
    return self.title

class Meta:
    verbose_name = 'Safari Package Entry'
    verbose_name_plural = 'Safari Package Entries'

class DayNumber(models.Model):
    daydetails = models.ForeignKey(SafariPackages, related_name='daydetails', default=1, on_delete=models.CASCADE)
    day_number = models.CharField( max_length=10, null=True, blank=True)
    image = models.ImageField (upload_to='SafariPackagesDetails/%Y/%m/%d', null=False, default=1)
    day_description = models.TextField()

The views that I have so far look like this

def safaripackages_view(request, *args,**kwargs):
    print (args, kwargs)
    print (request.user)

    all_safaripackages = SafariPackages.objects.all()

#Paginator
paginator = Paginator(all_safaripackages, 8)
page = request.GET.get('page')
try:
    all_safaripackages = paginator.page(page)
except PageNotAnInteger:
    all_safaripackages = paginator.page(1)
except EmptyPage:
    all_safaripackages = paginator.page(paginator.num_pages)

context = {
'all_safaripackages': all_safaripackages,
}

return render (request, "safaripackages.html", context)

def single_safaripackage(request, post_id):
    safaripackage = SafariPackages.objects.get(pk=post_id)
    return render (request, 'single_safaripackage.html', {'safaripackage':safaripackage,})

How do I include the values of the DayNumber model in the single_safaripackage view?

Body:
In accordance to my understanding,you are trying to render the day numbers of the packages from the child model.

The trick is:

"the parent model"."the child model"_set.all()
eg: parent.child_set.all()

*the child model to be lower case all through regardless of its original form in the model.py

Here is the solution to dynamically render a specific package to the browser:

def safaripackages_view(request,pk):
    safaripackage = SafariPackages.objects.get(name=pk_test)
    days = safaripackage.daynumber_set.all()
    context = {"days":days,"safaripackage":safaripackage}
    return render(request,'main/single_safaripackage.html',context)

Here is the solution to render all packages:

def safaripackages_view(request):
    safaripackage = SafariPackages.objects.all()
    days = safaripackage.daynumber_set.all()
    context = {"days":days,"safaripackage":safaripackage}
    return render(request,'main/single_safaripackage.html',context)

In your template you can have like a table to render

<table>
          <tr>
            <th>Day Details</th>
            <th>Day Number</th>
            <th>Day Description</th>
          </tr>
{% for day in days %}
          <tr>
              <th>{{day.daydetails}}</th>
              <th>   {{day.day_number}}</td>
              <td>{{day.day_description}}</td>
<td><img src="{% url 'day.image.url' %}" class="templates" alt=""> <td/>
              <tr/>
          {% endfor %}

        </table>


问:
Snowflake Credit Calculation during scale up when clusters running in parallel for overlapping period
How does credit consumed gets calculated during scale up and scale down when queries running on old size cluster as well new queries on new size cluster during the change over.
e.g.  There were 4 queries running on X-Small size taking 12 mins to execute. While these queries running in their 2nd minute, I scaled up warehouse to Small Size and new 2 queries running on Small size for 4 mins and I scale down warehouse again for X-Small size. I have setup 5 mins as auto suspend time. Will the idle time before Auto suspend, charged for X-Small size or Small size ?  How the idle time before auto suspend get charged ? </p>

答:
It should be charged for x-small for 1 min of provisioning plus 5 mins of auto-suspend time - given there is no query executed.
or
It should be charged for x-small for query time(provisioning time & query time) plus 5 mins - given that no additional query was running </p>