问:
keras - Difference between model predict function and model API function
I am trying to obtain the outputs and the final hidden states from a SimpleRNN layer in my model. The model has structure:

```<code>inp= Input(shape= (input_length,))
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False)(inp)
rnn_out, rnn_state= SimpleRNN(200,  return_state= True)(emb_out)
#out= Dense(1, activation= 'sigmoid')(rnn_out)
model = Model(inputs=inp, outputs=[rnn_out, rnn_state])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_7 (InputLayer)         [(None, 1403)]            0
_________________________________________________________________
embedding_10 (Embedding)     (None, 1403, 100)         4348900
_________________________________________________________________
simple_rnn_9 (SimpleRNN)     [(None, 200), (None, 200) 60200
=================================================================

</code>```

I notice that the shape of outputs are different when I use the model to predict test data model.predict(xte),
and model(xte) when I fit the test data to the model API. I would like some help interpreting the difference of the 2 operations and what the returned objects refer to.

```<code># 1.
all_outs, fin_states= model.predict(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)
>> Test data shape: (2400, 1403)
(2400, 200) (2400, 200)

# 2.
outs= model(xte_pad)
print('Test data shape:', xte_pad.shape)
print(outs.shape)
>> Test data shape: (2400, 1403)
(2400, 1403, 200)
</code>```

答:
When doing outs= model(xte_pad), you will get a list of outputs and a list does not have the property shape. The outputs are actually identical:

import tensorflow as tf

input_length = 1403
inp= tf.keras.layers.Input(shape= (input_length,))
emb_out= tf.keras.layers.Embedding(500, 100, input_length= input_length, trainable= False)(inp)
rnn_out, rnn_state= tf.keras.layers.SimpleRNN(200,  return_state= True)(emb_out)

model = tf.keras.Model(inputs=inp, outputs=[rnn_out, rnn_state])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model.summary()

xte_pad = tf.random.uniform((10, 1403), maxval=500, dtype=tf.int32)
all_outs, fin_states= model.predict(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)

all_outs, fin_states = model(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)
```
```Test data shape: (10, 1403)
(10, 200) (10, 200)
Test data shape: (10, 1403)
(10, 200) (10, 200)
```

Body:
I am trying to obtain the outputs and the final hidden states from a SimpleRNN layer in my model. The model has structure:

inp= Input(shape= (input_length,))
emb_out= Embedding(input_dim, output_dim, input_length= input_length,
                         weights= [Emat], trainable= False)(inp)
rnn_out, rnn_state= SimpleRNN(200,  return_state= True)(emb_out)
#out= Dense(1, activation= 'sigmoid')(rnn_out)
model = Model(inputs=inp, outputs=[rnn_out, rnn_state])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_7 (InputLayer)         [(None, 1403)]            0
_________________________________________________________________
embedding_10 (Embedding)     (None, 1403, 100)         4348900
_________________________________________________________________
simple_rnn_9 (SimpleRNN)     [(None, 200), (None, 200) 60200
=================================================================

I notice that the shape of outputs are different when I use the model to predict test data model.predict(xte),
and model(xte) when I fit the test data to the model API. I would like some help interpreting the difference of the 2 operations and what the returned objects refer to.

# 1.
all_outs, fin_states= model.predict(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)
>> Test data shape: (2400, 1403)
(2400, 200) (2400, 200)

# 2.
outs= model(xte_pad)
print('Test data shape:', xte_pad.shape)
print(outs.shape)
>> Test data shape: (2400, 1403)
(2400, 1403, 200)

Body:
When doing outs= model(xte_pad), you will get a list of outputs and a list does not have the property shape. The outputs are actually identical:

import tensorflow as tf

input_length = 1403
inp= tf.keras.layers.Input(shape= (input_length,))
emb_out= tf.keras.layers.Embedding(500, 100, input_length= input_length, trainable= False)(inp)
rnn_out, rnn_state= tf.keras.layers.SimpleRNN(200,  return_state= True)(emb_out)

model = tf.keras.Model(inputs=inp, outputs=[rnn_out, rnn_state])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
model.summary()

xte_pad = tf.random.uniform((10, 1403), maxval=500, dtype=tf.int32)
all_outs, fin_states= model.predict(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)

all_outs, fin_states = model(xte_pad)
print('Test data shape:', xte_pad.shape)
print(all_outs.shape, fin_states.shape)

Test data shape: (10, 1403)
(10, 200) (10, 200)
Test data shape: (10, 1403)
(10, 200) (10, 200)


来源: stackexchange

问:
catplot() in seaborn doesn't work with subplot()
I cannot subplot catplot. Here is my code:

```<code>import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1,2)
sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
sns.catplot(x='species', y='sepal_width', data=df , kind='violin')
</code>```

And here is the output:
How can I fix it?
Thank you.

答:
catplot creates its own new figure. You can either use catplot on a "long form dataframe" (using pd.melt()), or create individual sns.violinplots on each ax.

Using subplots with violinplot:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
fig, axes = plt.subplots(1, 2)
sns.violinplot(x='species', y='sepal_length', data=df, ax=axes[0])
sns.violinplot(x='species', y='sepal_width', data=df, ax=axes[1])
plt.tight_layout()
plt.show()
```
<p>Using <code>catplot</code> with long form dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
df_long = df.melt(id_vars='species', value_vars=['sepal_length', 'sepal_width'])

sns.catplot(x='species', y='value', col='variable', data=df_long, kind='violin')
plt.tight_layout()
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I cannot subplot catplot. Here is my code:

import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1,2)
sns.catplot(x='species', y='sepal_length', data=df , kind='violin')
sns.catplot(x='species', y='sepal_width', data=df , kind='violin')

And here is the output:
How can I fix it?
Thank you.

Body:
catplot creates its own new figure. You can either use catplot on a "long form dataframe" (using pd.melt()), or create individual sns.violinplots on each ax.

Using subplots with violinplot:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
fig, axes = plt.subplots(1, 2)
sns.violinplot(x='species', y='sepal_length', data=df, ax=axes[0])
sns.violinplot(x='species', y='sepal_width', data=df, ax=axes[1])
plt.tight_layout()
plt.show()

Using catplot with long form dataframe:

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
df_long = df.melt(id_vars='species', value_vars=['sepal_length', 'sepal_width'])

sns.catplot(x='species', y='value', col='variable', data=df_long, kind='violin')
plt.tight_layout()
plt.show()


问:
"NOT IN"/"NOT EXISTS" for pairwise column comparison not working in Redshift
I would like to rewrite the below statement in redshift. Redshift does not support IN/NOT IN for multiple column comparison. I get the following error when I try the same query with NOT EXISTS as well:

Invalid operation: This type of correlated subquery pattern is not supported due to internal error;

```<code>select count(distinct item) from tbl1
where (item,store) not in (
select distint item, store form tbl1
where *store changed* -- some filters
)
</code>```

答:
Your version of Redshift does not support this tuple syntax.  You may rephrase as follows:</p>
```<code>SELECT COUNT(DISTINCT item) AS cnt
FROM tbl1 t1
WHERE NOT EXISTS (
    SELECT 1
    FROM tbl1 t2
    WHERE t2.item = t1.item AND
          t2.store = t1.store AND
          (other filters here...)
);
</code>```

Body:
I would like to rewrite the below statement in redshift. Redshift does not support IN/NOT IN for multiple column comparison. I get the following error when I try the same query with NOT EXISTS as well:

Invalid operation: This type of correlated subquery pattern is not supported due to internal error;

select count(distinct item) from tbl1
where (item,store) not in (
select distint item, store form tbl1
where *store changed* -- some filters
)

Body:
Your version of Redshift does not support this tuple syntax.  You may rephrase as follows:

SELECT COUNT(DISTINCT item) AS cnt
FROM tbl1 t1
WHERE NOT EXISTS (
    SELECT 1
    FROM tbl1 t2
    WHERE t2.item = t1.item AND
          t2.store = t1.store AND
          (other filters here...)
);


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
Well.. since your projected database size is so small, a quick & dirty solution (more quick than dirty IMHO) would be to maintain your data in XML  (or serialize/deserialize object collections to XML) and query with LINQ.   It's fast and it works.  plus there's no DB engine to distribute with your app.

DISCLAIMER: Keep in mind that's IFF your data requirements remain small (and assuming its single user).  Once you have multiple users hitting your data concurrently, or data size increases, or you need functions that are most efficient when using some kind of RDBMS, this quick and dirty solution goes out the window and soon your app will collapse under the weight of all the extra code you will need to bake in to make it all work. =)

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: NoCarrier

LastEditorDisplayName: NoCarrier


问:
Hibernate JoinColumn annotation not restricting on named query where clause
I am playing around with hibernate and I have downloaded the following test DB https://dev.mysql.com/doc/employee/en/sakila-structure.html

I have a named query on the employee class of:

```<code>@NamedNativeQuery(
        name="complexQuery",
        query="select * from employees inner join salaries on employees.emp_no=salaries.emp_no where salaries.from_date < 19870101 " +
                "AND employees.emp_no = 10064;",
        resultClass=Employee.class
)
</code>```

I have mapped the employees to salaries via:

```<code>@OneToMany(
        cascade = CascadeType.ALL,
        fetch = FetchType.EAGER
)
@JoinColumn(name = "emp_no", nullable = false, insertable=false, updatable=false)
private Set<Salary> salaries = new HashSet<>();
</code>```

I expected that the following hibernate queries would include the where statement of

salaries.from_date < 19870101

however I noticed that actually the hibernate query for the salaries selects all rows for that employee id:

```<code>Hibernate:
    select
        *
    from
        employees
    inner join
        salaries
            on employees.emp_no=salaries.emp_no
    where
        salaries.from_date < 19870101
        AND employees.emp_no = 10064;
Hibernate:
    select
        salaries0_.emp_no as emp_no1_4_0_,
        salaries0_.from_date as from_dat2_4_0_,
        salaries0_.emp_no as emp_no1_4_1_,
        salaries0_.from_date as from_dat2_4_1_,
        salaries0_.salary as salary3_4_1_,
        salaries0_.to_date as to_date4_4_1_
    from
        salaries salaries0_
    where
        salaries0_.emp_no=?
</code>```

Is there anyway to have the auto generated salaries query also include

```<code>where
            salaries0_.from_date < ?
            AND salaries0_.emp_no=?
</code>```

EDIT: I am also getting the issue for a named query:

```<code>@NamedQuery(
        name="complexQuery",
        query="select e " +
                "from Employee e, Salary s " +
                "where e.id = 10064 " +
                "AND s.id.fromDate < 19900101" +
                "AND s.id.empNo = 10064"
                )
</code>```

答:
You are not joining Employee and Salary!

That's the correct statement

```<code>@NamedQuery(
    name="complexQuery",
    query="select e " +
            "from Employee e join e.salaries s " +
            "where e.id = 10064 " +
            "AND s.id.fromDate < 19900101"
            )
</code>```

Body:
I am playing around with hibernate and I have downloaded the following test DB https://dev.mysql.com/doc/employee/en/sakila-structure.html

I have a named query on the employee class of:

@NamedNativeQuery(
        name="complexQuery",
        query="select * from employees inner join salaries on employees.emp_no=salaries.emp_no where salaries.from_date < 19870101 " +
                "AND employees.emp_no = 10064;",
        resultClass=Employee.class
)

I have mapped the employees to salaries via:

@OneToMany(
        cascade = CascadeType.ALL,
        fetch = FetchType.EAGER
)
@JoinColumn(name = "emp_no", nullable = false, insertable=false, updatable=false)
private Set<Salary> salaries = new HashSet<>();

I expected that the following hibernate queries would include the where statement of

salaries.from_date < 19870101

however I noticed that actually the hibernate query for the salaries selects all rows for that employee id:

Hibernate:
    select
        *
    from
        employees
    inner join
        salaries
            on employees.emp_no=salaries.emp_no
    where
        salaries.from_date < 19870101
        AND employees.emp_no = 10064;
Hibernate:
    select
        salaries0_.emp_no as emp_no1_4_0_,
        salaries0_.from_date as from_dat2_4_0_,
        salaries0_.emp_no as emp_no1_4_1_,
        salaries0_.from_date as from_dat2_4_1_,
        salaries0_.salary as salary3_4_1_,
        salaries0_.to_date as to_date4_4_1_
    from
        salaries salaries0_
    where
        salaries0_.emp_no=?

Is there anyway to have the auto generated salaries query also include

where
            salaries0_.from_date < ?
            AND salaries0_.emp_no=?

EDIT: I am also getting the issue for a named query:

@NamedQuery(
        name="complexQuery",
        query="select e " +
                "from Employee e, Salary s " +
                "where e.id = 10064 " +
                "AND s.id.fromDate < 19900101" +
                "AND s.id.empNo = 10064"
                )

Body:
You are not joining Employee and Salary!

That's the correct statement

@NamedQuery(
    name="complexQuery",
    query="select e " +
            "from Employee e join e.salaries s " +
            "where e.id = 10064 " +
            "AND s.id.fromDate < 19900101"
            )


问:
How to reactively extract column of values from tibble for plotting?
I have an App that allows the user to stratify data, and select the point-in-time to stratify. A function (stratData(...)) in the below reproducible code generates the data table, and the output stratified table is correctly reactive, updating as the user changes the point-in-time.

However I want the user to also have the option the view the data as a bar plot. Below I comment with "# <<" my attempts to "tap" a data table (tibble) column for plotting. However, the plot as currently drafted doesn't reactively update to user changes in point-in-time the way the data table does.

How can column values be efficiently, and reactively, extracted from the data table? For reactive plotting, consistent with the data table?

Images at the bottom also show the issue, in lieu of "using words".

Reproducible code:

```<code>library(shiny)
library(tidyverse)
library(shinyWidgets)

ui <-
  fluidPage(
    uiOutput("stratPeriod"),
    radioButtons(
      inputId = 'stratsView',
      label = NULL,
      choices = list("Table view" = 1,"Plot view" = 2),
      selected = 1,
      inline = TRUE
    ),
    conditionalPanel(condition = "input.stratsView == 1",
                     h5(strong("Stratified data:")), tableOutput("stratData")
    ),
    conditionalPanel(condition = "input.stratsView == 2",
                     h5(strong("Stratified data:")), plotOutput("stratPlot")
    )
  )

server <- function(input, output, session) {
  dat <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3,3),
      Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
      Values_1 = c(-6, 26, 36, 46, 56, 86, 100, 10, 20, 30)
    )
  })

  output$stratPeriod <- renderUI({
    chc <- unique(na.omit(dat()[[2]]))
    selectInput(inputId = "stratPeriod",
                label = "Choose point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  stratData <- function(){
    req(input$stratPeriod)
    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))
    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})
    breaks <- seq(min(dat_1()[["Values_1"]]), max(dat_1()[["Values_1"]]), length.out = 6)
    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym("Values_1"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range)
    tmp <- tmp %>%
      summarise(Count = n(),Values = sum(!!sym("Values_1"))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
      Count <- tmp %>% pull(Count) # << my attempt to pull column of tibble data
    tmp
  }

  output$stratData <- renderTable({stratData()})
  output$stratPlot <- renderPlot({barplot(Count[-length(Count)])}) # << plot attempt, removing last value from vector
}

shinyApp(ui, server)
</code>```

答:
The issue is that your function stratData returns only the dataframe tmp. To make your code work you could

Return both the dataframe tmp and the vector Count as a named list, e.g. list(data = tmp, Count = Count) and use stratData()$data or stratData()$Count in renderPlot/Table

or as a second option:

Pull the Count column via a separate function or reactive, i.e. do Count <- reactive({ stratData() %>% pull(Count) }) and call it via Count() in renderPlot.

Reproducible code for the first approach:

library(shiny)
library(tidyverse)
library(shinyWidgets)

ui <-
  fluidPage(
    uiOutput("stratPeriod"),
    radioButtons(
      inputId = 'stratsView',
      label = NULL,
      choices = list("Table view" = 1,"Plot view" = 2),
      selected = 1,
      inline = TRUE
    ),
    conditionalPanel(condition = "input.stratsView == 1",
                     h5(strong("Stratified data:")), tableOutput("stratData")
    ),
    conditionalPanel(condition = "input.stratsView == 2",
                     h5(strong("Stratified data:")), plotOutput("stratPlot")
    )
  )

server <- function(input, output, session) {
  dat <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3,3),
      Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
      Values_1 = c(-6, 26, 36, 46, 56, 86, 100, 10, 20, 30)
    )
  })

  output$stratPeriod <- renderUI({
    chc <- unique(na.omit(dat()[[2]]))
    selectInput(inputId = "stratPeriod",
                label = "Choose point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  stratData <- function(){
    req(input$stratPeriod)
    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))
    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})
    breaks <- seq(min(dat_1()[["Values_1"]]), max(dat_1()[["Values_1"]]), length.out = 6)
    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym("Values_1"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range)
    tmp <- tmp %>%
      summarise(Count = n(),Values = sum(!!sym("Values_1"))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
    Count <- tmp %>% pull(Count)

    list(data = tmp, Count = Count)

  }

  output$stratData <- renderTable({stratData()$data})
  output$stratPlot <- renderPlot({barplot(stratData()$Count[-length(stratData()$Count)])})
}

shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:3019
```

Body:
I have an App that allows the user to stratify data, and select the point-in-time to stratify. A function (stratData(...)) in the below reproducible code generates the data table, and the output stratified table is correctly reactive, updating as the user changes the point-in-time.

However I want the user to also have the option the view the data as a bar plot. Below I comment with "# <<" my attempts to "tap" a data table (tibble) column for plotting. However, the plot as currently drafted doesn't reactively update to user changes in point-in-time the way the data table does.

How can column values be efficiently, and reactively, extracted from the data table? For reactive plotting, consistent with the data table?

Images at the bottom also show the issue, in lieu of "using words".

Reproducible code:

library(shiny)
library(tidyverse)
library(shinyWidgets)

ui <-
  fluidPage(
    uiOutput("stratPeriod"),
    radioButtons(
      inputId = 'stratsView',
      label = NULL,
      choices = list("Table view" = 1,"Plot view" = 2),
      selected = 1,
      inline = TRUE
    ),
    conditionalPanel(condition = "input.stratsView == 1",
                     h5(strong("Stratified data:")), tableOutput("stratData")
    ),
    conditionalPanel(condition = "input.stratsView == 2",
                     h5(strong("Stratified data:")), plotOutput("stratPlot")
    )
  )

server <- function(input, output, session) {
  dat <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3,3),
      Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04"),
      Values_1 = c(-6, 26, 36, 46, 56, 86, 100, 10, 20, 30)
    )
  })

  output$stratPeriod <- renderUI({
    chc <- unique(na.omit(dat()[[2]]))
    selectInput(inputId = "stratPeriod",
                label = "Choose point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  stratData <- function(){
    req(input$stratPeriod)
    filter_exp1 <- parse(text=paste0("Period",  "==", "'",input$stratPeriod, "'"))
    dat_1 <- reactive({dat() %>% filter(eval(filter_exp1))})
    breaks <- seq(min(dat_1()[["Values_1"]]), max(dat_1()[["Values_1"]]), length.out = 6)
    tmp <- dat() %>%
      filter(eval(filter_exp1)) %>%
      mutate(Range = cut(!!sym("Values_1"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(Range)
    tmp <- tmp %>%
      summarise(Count = n(),Values = sum(!!sym("Values_1"))) %>%
      complete(Range, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct) %>%
      bind_rows(summarise_all(., ~(if(is.numeric(.)) sum(.) else "Total")))
      Count <- tmp %>% pull(Count) # << my attempt to pull column of tibble data
    tmp
  }

  output$stratData <- renderTable({stratData()})
  output$stratPlot <- renderPlot({barplot(Count[-length(Count)])}) # << plot attempt, removing last value from vector
}

shinyApp(ui, server)


问:
check and count occurrence of particular key in list of dictionaries in python
Question:
Below is response body from GET call of REST API.
I need to check occurrence of status and gender in response body and count how many Male active, Male inactive, Female active and Female Inactive are present.

Given Input:

```<code>[
{"id":3627,
"name":"Arnesh Patil",
"email":"patil_arnesh@moen-mitchell.com",
"gender":"male",
"status":"active"},
{"id":3626,
"name":"Digambara Ahuja",
"email":"digambara_ahuja@monahan.com",
"gender":"male",
"status":"inactive"},
{"id":3625,
"name":"Smriti Sharma Esq.",
"email":"smriti_sharma_esq@wehner-homenick.com",
"gender":"female",
"status":"inactive"},{"id":3624,
"name":"Vedanga Ganaka PhD",
"email":"phd_ganaka_vedanga@medhurst.name",
"gender":"male",
"status":"active"}
]
</code>```

After that we need to store output in below nested dictionary format:

Expected Ouptut

```<code>{
'active':
    {  'male': 2,
       'female': 0
    },
'inactive':
    { 'male': 1,
      'female': 1
    }
}
</code>```

how to parse List of dictionary and get output as shown above?

答:
You can do it with standard dicts:</p>
```<code>result = {"active":{}, "inactive" ={}}
for i in data:
    result.get(i.get("status"))[i.get("gender")] = result.get(i.get("status")).get(i.get("gender"),0)+1
</code>```

Body:
Question:
Below is response body from GET call of REST API.
I need to check occurrence of status and gender in response body and count how many Male active, Male inactive, Female active and Female Inactive are present.

Given Input:

[
{"id":3627,
"name":"Arnesh Patil",
"email":"patil_arnesh@moen-mitchell.com",
"gender":"male",
"status":"active"},
{"id":3626,
"name":"Digambara Ahuja",
"email":"digambara_ahuja@monahan.com",
"gender":"male",
"status":"inactive"},
{"id":3625,
"name":"Smriti Sharma Esq.",
"email":"smriti_sharma_esq@wehner-homenick.com",
"gender":"female",
"status":"inactive"},{"id":3624,
"name":"Vedanga Ganaka PhD",
"email":"phd_ganaka_vedanga@medhurst.name",
"gender":"male",
"status":"active"}
]

After that we need to store output in below nested dictionary format:

Expected Ouptut

{
'active':
    {  'male': 2,
       'female': 0
    },
'inactive':
    { 'male': 1,
      'female': 1
    }
}

how to parse List of dictionary and get output as shown above?

Body:
You can do it with standard dicts:

result = {"active":{}, "inactive" ={}}
for i in data:
    result.get(i.get("status"))[i.get("gender")] = result.get(i.get("status")).get(i.get("gender"),0)+1


问:
Singleton Design "not being able to resolve to a type"
I'm trying to instantiate the Scanner using the Singleton design, but when I try to get my main method to instantiate the Scanner, I get an error saying that "Singleton.getInstance() can't be resolved to a type.

```<code>package exercise;
import java.util.Scanner;
public class NestedLoop {

    public static void main(String[] args) {
        stars();
        numbs();
}

public static void stars() {

    Singleton scanner=new Singleton.getInstance();
    int input=scanner.intScan();

    for(int row=0;row<input;row++) {
        for(int column=0;column<6;column++) {
        System.out.print("*");
        }
    System.out.println();
    }
    System.out.println(System.identityHashCode(scanner));
}

public static void numbs() {
    Singleton scanner=new Singleton.getInstance();
    int input=scanner.intScan();
    for(int row=0;row<input;row++) {
        for(int column=0;column<=row;column++) {
            System.out.printf("%d ",column+1);
        }
    System.out.println();
    }
    scanner.closeScan();
    System.out.println(System.identityHashCode(scanner));
}
}
</code>```

As for the Singleton class:

```<code>package exercise;
import java.util.Scanner;

public class Singleton {

    private static Singleton callScan=null;
    private Scanner input=new Scanner(System.in);
    private Singleton(){};

    public static Singleton getInstance() {
        if(callScan==null) {
            callScan=new Singleton();
        }
        return callScan;
    }

    public int intScan() {
        int val= input.nextInt();
        return val;
    }

    public void closeScan() {
        input.close();
    }

}
</code>```

Kind of stumped! Any help would be greatly appreciated!

答:
Replace

```<code>Singleton scanner = new Singleton.getInstance();
</code>```

with

```<code>Singleton scanner = Singleton.getInstance(); // Singleton.getInstance() is already an instance.
</code>```

Body:
I'm trying to instantiate the Scanner using the Singleton design, but when I try to get my main method to instantiate the Scanner, I get an error saying that "Singleton.getInstance() can't be resolved to a type.

package exercise;
import java.util.Scanner;
public class NestedLoop {

    public static void main(String[] args) {
        stars();
        numbs();
}

public static void stars() {

    Singleton scanner=new Singleton.getInstance();
    int input=scanner.intScan();

    for(int row=0;row<input;row++) {
        for(int column=0;column<6;column++) {
        System.out.print("*");
        }
    System.out.println();
    }
    System.out.println(System.identityHashCode(scanner));
}

public static void numbs() {
    Singleton scanner=new Singleton.getInstance();
    int input=scanner.intScan();
    for(int row=0;row<input;row++) {
        for(int column=0;column<=row;column++) {
            System.out.printf("%d ",column+1);
        }
    System.out.println();
    }
    scanner.closeScan();
    System.out.println(System.identityHashCode(scanner));
}
}

As for the Singleton class:

package exercise;
import java.util.Scanner;

public class Singleton {

    private static Singleton callScan=null;
    private Scanner input=new Scanner(System.in);
    private Singleton(){};

    public static Singleton getInstance() {
        if(callScan==null) {
            callScan=new Singleton();
        }
        return callScan;
    }

    public int intScan() {
        int val= input.nextInt();
        return val;
    }

    public void closeScan() {
        input.close();
    }

}

Kind of stumped! Any help would be greatly appreciated!

Body:
Replace

Singleton scanner = new Singleton.getInstance();

with

Singleton scanner = Singleton.getInstance(); // Singleton.getInstance() is already an instance.


问:
Deploy django to GAE standard from cloud build
I run following bash commands from my local machine to deploy django project to App engine.

```<code>python manage.py migrate
python manage.py collectstatic --noinput
gsutil rsync -R static/ gs://xyz4/static
gcloud config set project project_name_1
gcloud app deploy --quiet
</code>```

I would like to set it up on cloud build. I have enabled PUSH triggers on cloud build. Need help in creating cloudbuild.yaml file

答:
Cloud Build support to run on custom VPC with worker pools.

You can create a worker pool to access resources in VPC. If you will access when building you must click "Assign external IPs" in your worker pool settings and you mus use below code in your cloudbuild yaml:

```<code>options:
  pool:
    name: "projects/${PROJECT_ID}/locations/${_REGION}/workerPools/${_WORKER_POOL}"

substitutions:
  _REGION: 'your_region'
  _WORKER_POOL: 'your_pool_name'
</code>```

If you need to know your outbound ip you can access it from Cloud Nat and if you have firewall rules for outbound you have to assign a dedicated ip.

Body:
I run following bash commands from my local machine to deploy django project to App engine.

python manage.py migrate
python manage.py collectstatic --noinput
gsutil rsync -R static/ gs://xyz4/static
gcloud config set project project_name_1
gcloud app deploy --quiet

I would like to set it up on cloud build. I have enabled PUSH triggers on cloud build. Need help in creating cloudbuild.yaml file

Body:
Cloud Build support to run on custom VPC with worker pools.

You can create a worker pool to access resources in VPC. If you will access when building you must click "Assign external IPs" in your worker pool settings and you mus use below code in your cloudbuild yaml:

options:
  pool:
    name: "projects/${PROJECT_ID}/locations/${_REGION}/workerPools/${_WORKER_POOL}"

substitutions:
  _REGION: 'your_region'
  _WORKER_POOL: 'your_pool_name'

If you need to know your outbound ip you can access it from Cloud Nat and if you have firewall rules for outbound you have to assign a dedicated ip.


问:
I'm trying to learn Slim 4 and how to add Twig to it using PHP-DI but not able to figure it out
So I'm using a skeleton I found online....

The "boostrap.php" looks like

```<code>
use DI\ContainerBuilder;
use Slim\App;

require_once __DIR__ . '/../vendor/autoload.php';

$containerBuilder = new ContainerBuilder();

// Add DI container definitions
$containerBuilder->addDefinitions(__DIR__ . '/container.php');

// Create DI container instance
$container = $containerBuilder->build();

// Create Slim App instance
$app = $container->get(App::class);

// Register routes
(require __DIR__ . '/routes.php')($app);

// Register middleware
(require __DIR__ . '/middleware.php')($app);

return $app;
</code>```

In the container I'm adding TWIG I think correctly...

```<code>return [
    'settings' => function () {
        return require __DIR__ . '/settings.php';
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);

        return AppFactory::create();
    },

    ErrorMiddleware::class => function (ContainerInterface $container) {
        $app = $container->get(App::class);
        $settings = $container->get('settings')['error'];

        return new ErrorMiddleware(
            $app->getCallableResolver(),
            $app->getResponseFactory(),
            (bool)$settings['display_error_details'],
            (bool)$settings['log_errors'],
            (bool)$settings['log_error_details']
        );
    },

    Twig:class => function (ContainerInterface $container){
        return new Twig(__DIR__.'/../views',[
            'cache' => __DIR__ . '/../cache',
            'auto_reload' => true
        ]);
    },
     TwigMiddleware::class => function (ContainerInterface $container){
        return TwigMiddleware::createFromContainer($container->get(App::class));
    },

 etc etc etc
</code>```

So I'm thinking this is correct however I also need to setup the middleware for the Twig and also be able to use it in the Classes/Controller/Routes....

In my Middleware

```<code><?php

use Selective\BasePath\BasePathMiddleware;
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\TwigMiddleware;
use Slim\Views\Twig;

return function (App $app) {
    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();
    $app->add(TwigMiddleware::class));

    // Add the Slim built-in routing middleware
    $app->addRoutingMiddleware();

    $app->add(BasePathMiddleware::class);

    // Handle exceptions
    $app->add(ErrorMiddleware::class);
};

</code>```

The Current error is

```<code>Message: The specified container key does not exist: view
File: /home/webuser/testsite/genapp/vendor/slim/twig-view/src/TwigMiddleware.php
</code>```

So I'm not sure how to set the key I guess of for Twig instance/class.

I'm new to this format of DI so I'm unsure how to add the middleware and then use it throughout the app...

Thanks

答:
I guess you have installed the slim/twig-view component.

I would change the DI container TwigStart::class to Twig::class.

Instead of creating the Twig instance manually, better use the Twig::create method to build it.

Then you could also add a DI container definition for \Slim\Views\TwigMiddleware\TwigMiddleware::class that uses the TwigMiddleware::createFromContainer method to create and return the middleware instance.

This allows you to load the middlware only when its realy needed (lazy).

```<code>use Slim\Views\TwigMiddleware;
// ...

$app->add(TwigMiddleware::class);
</code>```

Body:
So I'm using a skeleton I found online....

The "boostrap.php" looks like

use DI\ContainerBuilder;
use Slim\App;

require_once __DIR__ . '/../vendor/autoload.php';

$containerBuilder = new ContainerBuilder();

// Add DI container definitions
$containerBuilder->addDefinitions(__DIR__ . '/container.php');

// Create DI container instance
$container = $containerBuilder->build();

// Create Slim App instance
$app = $container->get(App::class);

// Register routes
(require __DIR__ . '/routes.php')($app);

// Register middleware
(require __DIR__ . '/middleware.php')($app);

return $app;

In the container I'm adding TWIG I think correctly...

return [
    'settings' => function () {
        return require __DIR__ . '/settings.php';
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);

        return AppFactory::create();
    },

    ErrorMiddleware::class => function (ContainerInterface $container) {
        $app = $container->get(App::class);
        $settings = $container->get('settings')['error'];

        return new ErrorMiddleware(
            $app->getCallableResolver(),
            $app->getResponseFactory(),
            (bool)$settings['display_error_details'],
            (bool)$settings['log_errors'],
            (bool)$settings['log_error_details']
        );
    },

    Twig:class => function (ContainerInterface $container){
        return new Twig(__DIR__.'/../views',[
            'cache' => __DIR__ . '/../cache',
            'auto_reload' => true
        ]);
    },
     TwigMiddleware::class => function (ContainerInterface $container){
        return TwigMiddleware::createFromContainer($container->get(App::class));
    },

 etc etc etc

So I'm thinking this is correct however I also need to setup the middleware for the Twig and also be able to use it in the Classes/Controller/Routes....

In my Middleware

<?php

use Selective\BasePath\BasePathMiddleware;
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\TwigMiddleware;
use Slim\Views\Twig;

return function (App $app) {
    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();
    $app->add(TwigMiddleware::class));

    // Add the Slim built-in routing middleware
    $app->addRoutingMiddleware();

    $app->add(BasePathMiddleware::class);

    // Handle exceptions
    $app->add(ErrorMiddleware::class);
};

The Current error is

Message: The specified container key does not exist: view
File: /home/webuser/testsite/genapp/vendor/slim/twig-view/src/TwigMiddleware.php

So I'm not sure how to set the key I guess of for Twig instance/class.

I'm new to this format of DI so I'm unsure how to add the middleware and then use it throughout the app...

Thanks

Body:
I guess you have installed the slim/twig-view component.

I would change the DI container TwigStart::class to Twig::class.

Instead of creating the Twig instance manually, better use the Twig::create method to build it.

Then you could also add a DI container definition for \Slim\Views\TwigMiddleware\TwigMiddleware::class that uses the TwigMiddleware::createFromContainer method to create and return the middleware instance.

This allows you to load the middlware only when its realy needed (lazy).

use Slim\Views\TwigMiddleware;
// ...

$app->add(TwigMiddleware::class);


问:
OnPress for React Native Google Places Autocomplete doesn't work due to its parent components
I'm trying to use the react-native-google-places-autocomplete library within my React Native app, but I'm having an issue clicking on the suggested list.  Whenever I click on the Google suggested address, the list disappears and onPress doesn't grab the address. If I use the library in a component by itself without the parent components, it works perfectly fine, but only when I place the component within keyboardavoidingview or KeyboardAwareScrollView, it does not work:

This GooglePlacesInput.js component is just the standard library from the original repository:

       <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2} // minimum length of text to search
            autoFocus={false}
            returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
            keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
            listViewDisplayed={false}   // true/false/undefined
            fetchDetails={true}
            renderDescription={row => row.description} // custom description render
            onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
                console.log(data, details);
            }}
            textInputProps={{
                onBlur,
            }}
            getDefaultValue={() => ''}

            query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: googleAPIKeyForAutocomplete,
                language: 'en', // language of the results
                region: "CA",
                // types: '(cities)' // default: 'geocode'
                types: '',
            }}

            styles={{
                listView: {
                    position: 'absolute',
                    top: 60,
                    left: 10,
                    right: 10,
                    backgroundColor: 'white',
                    borderRadius: 5,
                    flex: 1,
                    elevation: 3,
                    zIndex: 100,
                },
                textInputContainer: {
                    backgroundColor: 'transparent',
                    margin: 0,
                    width: '100%',
                    padding: 0,
                    borderTopWidth: 0,
                    borderBottomWidth: 0
                },
                textInput: {
                    backgroundColor: '#F9F5F4',
                    borderRadius: 50,
                    width: "100%",
                    height: height / 15,
                    padding: 20,
                },
                description: {
                    // color: '#ac879a',
                    fontWeight: '300'
                },
                predefinedPlacesDescription: {
                    color: '#1faadb'
                }
            }}

            currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
            currentLocationLabel="Current location"
            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
            GoogleReverseGeocodingQuery={{
                // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
            }}
            GooglePlacesSearchQuery={{
                // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                rankby: 'distance',
                type: 'food'
            }}

            GooglePlacesDetailsQuery={{
                // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
                fields: 'formatted_address',
            }}

            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
            predefinedPlaces={[]}
            enablePoweredByContainer={false}
            debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
            renderLeftButton={() => { }}
            renderRightButton={() => { }}
        />
```

<p>I'm using <code>Formik</code> for its parent component <code>Form.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>        <View style={styles.container} >
            <Formik
                initialValues={initialValues}
                onSubmit={(value, action) => submitHandler(value, action)}
                validationSchema={yup.object().shape({
                    address: yup
                        .string()
                        .min(5)
                        .required(),
                })}
            >
                {({
                    values,
                    handleChange,
                    errors,
                    setFieldTouched,
                    touched,
                    isValid,
                    handleSubmit,
                    resetForm,
                    isSubmitting,
                    }) => (
                        <View style={styles.form}>

                            <Animated.View
                                style={[styles.fieldset, addressStyle]}
                                onLayout={e => {
                                    if (addressHeight !== e.nativeEvent.layout.y) {
                                        setAddressHeight(e.nativeEvent.layout.y)
                                    }
                                }}
                            >
                                <Text style={{ marginLeft: 40, marginVertical: 5 }}>
                                    <Text style={{ color: '#FF5D4E' }}>* </Text>
                                    Address
                                    </Text>
                                <View style={styles.autoComplete}>
                                    <GooglePlacesInput
                                        onBlur={() => onBlurProps('address', setFieldTouched)}
                                    />
                                </View>
                            </Animated.View>
                            {touched.address && errors.address &&
                                <Animated.Text style={{ fontSize: 10, color: 'red' }}>{errors.address}</Animated.Text>
                            }
                            <TouchableOpacity
                                disabled={!isValid || loading || isSubmitting}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity>
                        </View>
                    )}
            </Formik>
        </View>
</code>```

handleChange still has to be passed, but I want to first figure out the onPress situation first.

And finally, the most parent component:

        <KeyboardAwareScrollView>
            <SafeAreaView style={styles.container} >
                <ScrollView
                    keyboardShouldPersistTaps={'always'}
                    contentContainerStyle={styles.container}
                    style={{ flexGrow: 1 }}
                    showsVerticalScrollIndicator={false}
                    onLayout={e => {
                        if (heightPosition !== e.nativeEvent.layout.y) {
                            setHeightPosition(e.nativeEvent.layout.y)
                        }
                    }}
                >

                    <View style={styles.form}>
                        <Form
                            submitHandler={submitHandler}
                            loading={loading}
                            heightPosition={heightPosition}
                        />
                    </View>
                </ ScrollView>
            </SafeAreaView>
        </KeyboardAwareScrollView>
```

答: Include this property keepResultsAfterBlur={true}.

Body:
I'm trying to use the react-native-google-places-autocomplete library within my React Native app, but I'm having an issue clicking on the suggested list.  Whenever I click on the Google suggested address, the list disappears and onPress doesn't grab the address. If I use the library in a component by itself without the parent components, it works perfectly fine, but only when I place the component within keyboardavoidingview or KeyboardAwareScrollView, it does not work:

This GooglePlacesInput.js component is just the standard library from the original repository:

       <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2} // minimum length of text to search
            autoFocus={false}
            returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
            keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
            listViewDisplayed={false}   // true/false/undefined
            fetchDetails={true}
            renderDescription={row => row.description} // custom description render
            onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
                console.log(data, details);
            }}
            textInputProps={{
                onBlur,
            }}
            getDefaultValue={() => ''}

            query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: googleAPIKeyForAutocomplete,
                language: 'en', // language of the results
                region: "CA",
                // types: '(cities)' // default: 'geocode'
                types: '',
            }}

            styles={{
                listView: {
                    position: 'absolute',
                    top: 60,
                    left: 10,
                    right: 10,
                    backgroundColor: 'white',
                    borderRadius: 5,
                    flex: 1,
                    elevation: 3,
                    zIndex: 100,
                },
                textInputContainer: {
                    backgroundColor: 'transparent',
                    margin: 0,
                    width: '100%',
                    padding: 0,
                    borderTopWidth: 0,
                    borderBottomWidth: 0
                },
                textInput: {
                    backgroundColor: '#F9F5F4',
                    borderRadius: 50,
                    width: "100%",
                    height: height / 15,
                    padding: 20,
                },
                description: {
                    // color: '#ac879a',
                    fontWeight: '300'
                },
                predefinedPlacesDescription: {
                    color: '#1faadb'
                }
            }}

            currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
            currentLocationLabel="Current location"
            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
            GoogleReverseGeocodingQuery={{
                // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
            }}
            GooglePlacesSearchQuery={{
                // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                rankby: 'distance',
                type: 'food'
            }}

            GooglePlacesDetailsQuery={{
                // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
                fields: 'formatted_address',
            }}

            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
            predefinedPlaces={[]}
            enablePoweredByContainer={false}
            debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
            renderLeftButton={() => { }}
            renderRightButton={() => { }}
        />

I'm using Formik for its parent component Form.js:

        <View style={styles.container} >
            <Formik
                initialValues={initialValues}
                onSubmit={(value, action) => submitHandler(value, action)}
                validationSchema={yup.object().shape({
                    address: yup
                        .string()
                        .min(5)
                        .required(),
                })}
            >
                {({
                    values,
                    handleChange,
                    errors,
                    setFieldTouched,
                    touched,
                    isValid,
                    handleSubmit,
                    resetForm,
                    isSubmitting,
                    }) => (
                        <View style={styles.form}>

                            <Animated.View
                                style={[styles.fieldset, addressStyle]}
                                onLayout={e => {
                                    if (addressHeight !== e.nativeEvent.layout.y) {
                                        setAddressHeight(e.nativeEvent.layout.y)
                                    }
                                }}
                            >
                                <Text style={{ marginLeft: 40, marginVertical: 5 }}>
                                    <Text style={{ color: '#FF5D4E' }}>* </Text>
                                    Address
                                    </Text>
                                <View style={styles.autoComplete}>
                                    <GooglePlacesInput
                                        onBlur={() => onBlurProps('address', setFieldTouched)}
                                    />
                                </View>
                            </Animated.View>
                            {touched.address && errors.address &&
                                <Animated.Text style={{ fontSize: 10, color: 'red' }}>{errors.address}</Animated.Text>
                            }
                            <TouchableOpacity
                                disabled={!isValid || loading || isSubmitting}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity>
                        </View>
                    )}
            </Formik>
        </View>

handleChange still has to be passed, but I want to first figure out the onPress situation first.

And finally, the most parent component:

        <KeyboardAwareScrollView>
            <SafeAreaView style={styles.container} >
                <ScrollView
                    keyboardShouldPersistTaps={'always'}
                    contentContainerStyle={styles.container}
                    style={{ flexGrow: 1 }}
                    showsVerticalScrollIndicator={false}
                    onLayout={e => {
                        if (heightPosition !== e.nativeEvent.layout.y) {
                            setHeightPosition(e.nativeEvent.layout.y)
                        }
                    }}
                >

                    <View style={styles.form}>
                        <Form
                            submitHandler={submitHandler}
                            loading={loading}
                            heightPosition={heightPosition}
                        />
                    </View>
                </ ScrollView>
            </SafeAreaView>
        </KeyboardAwareScrollView>


问:
How do I avoid duplicate action dispatches caused by to a delay in redux store update/propagation of redux state to connected components?
I'm working on a React app that uses React-Router and Redux.

This app has certain routes that require authentication, in this case I'm redirecting the user to a login page as follows.

```<code>return <Redirect
  to={{
    pathname: '/login',
    search: `?ret=${encodeURIComponent(location.pathname)}`
}}
</code>```

The login page is rendered using a Login component, which is connected to the redux store and checks a boolean isSignedIn. When isSignedIn === true, I redirect the user to the path specified in the ret query param. The relevant code is below.

```<code>const Login = (props) => {
    if (!props.isSignedIn) {
        // show a message and CTA asking the user to log in
    }

    const queryParams =  qs.parse(props.location.search, { ignoreQueryPrefix: true });
    const ret = queryParams.ret || '/';

    return <Redirect to={ret} />
}
</code>```

I'm using google oAuth2 in the app, and after the user signs in via Google, I dispatch a SIGN_IN action which updates isSignedIn to true. The oAuth flow is handled by a GoogleAuth component, which checks whether a user is signed in each time a page is rendered, and also handles the sign in/sign out click events. This component renders on every page of the app.

```<code>class GoogleAuth extends React.Component {
    componentDidMount() {
        window.gapi.load('client:auth2', () => {
            window.gapi.client.init({
                clientId: 'someclientid',
                scope: 'email'
            }).then(() => {
                this.auth = window.gapi.auth2.getAuthInstance();
                // initial check to see if user is signed in
                this.onAuthChange(this.auth.isSignedIn.get());
                // listens for change in google oAuth status
                this.auth.isSignedIn.listen(this.onAuthChange);
            })
        });
    };

    onAuthChange = async (isGoogleSignedIn) => {
        if (!this.props.isSignedIn && isGoogleSignedIn){
            await this.props.signIn(this.auth.currentUser.get().getId());
        } else if (this.props.isSignedIn && !isGoogleSignedIn) {
            await this.props.signOut();
        }
    }

    handleSignIn = () => {
        this.auth.signIn();
    }

    handleSignOut = () => {
        this.auth.signOut();
    }
</code>```

The issue I'm facing is that the SIGN_IN action (dispatched by calling this.props.signIn()) is getting called multiple times when I log in from the '/login' page, and get redirected.

It appears that the redirect occurs before the redux store has properly updated the value of isSignedIn and this results in a duplicate SIGN_IN action dispatch.

How can I prevent this? I considered adding a short delay before the redirect, but I'm not sure that's the right way.

EDIT:
I found out that this is happening because I'm rendering the GoogleAuth component twice on the login page (once in the header, and once on the page itself). This resulted in the action getting dispatched twice. Both GoogleAuth components detected the change in authentication status, and as a result both dispatched a SIGN_IN action. There was no delay in propagation of redux store data to the connected component, at least in this scenario.

答:
Ok, figured this out.

I'm rendering the GoogleAuth component twice on the login page - once in the header, and once within the main content. That's why the action was getting dispatched twice.

Both GoogleAuth components detected the change in authentication status, and as a result both dispatched a SIGN_IN action.

Body:
I'm working on a React app that uses React-Router and Redux.

This app has certain routes that require authentication, in this case I'm redirecting the user to a login page as follows.

return <Redirect
  to={{
    pathname: '/login',
    search: `?ret=${encodeURIComponent(location.pathname)}`
}}

The login page is rendered using a Login component, which is connected to the redux store and checks a boolean isSignedIn. When isSignedIn === true, I redirect the user to the path specified in the ret query param. The relevant code is below.

const Login = (props) => {
    if (!props.isSignedIn) {
        // show a message and CTA asking the user to log in
    }

    const queryParams =  qs.parse(props.location.search, { ignoreQueryPrefix: true });
    const ret = queryParams.ret || '/';

    return <Redirect to={ret} />
}

I'm using google oAuth2 in the app, and after the user signs in via Google, I dispatch a SIGN_IN action which updates isSignedIn to true. The oAuth flow is handled by a GoogleAuth component, which checks whether a user is signed in each time a page is rendered, and also handles the sign in/sign out click events. This component renders on every page of the app.

class GoogleAuth extends React.Component {
    componentDidMount() {
        window.gapi.load('client:auth2', () => {
            window.gapi.client.init({
                clientId: 'someclientid',
                scope: 'email'
            }).then(() => {
                this.auth = window.gapi.auth2.getAuthInstance();
                // initial check to see if user is signed in
                this.onAuthChange(this.auth.isSignedIn.get());
                // listens for change in google oAuth status
                this.auth.isSignedIn.listen(this.onAuthChange);
            })
        });
    };

    onAuthChange = async (isGoogleSignedIn) => {
        if (!this.props.isSignedIn && isGoogleSignedIn){
            await this.props.signIn(this.auth.currentUser.get().getId());
        } else if (this.props.isSignedIn && !isGoogleSignedIn) {
            await this.props.signOut();
        }
    }

    handleSignIn = () => {
        this.auth.signIn();
    }

    handleSignOut = () => {
        this.auth.signOut();
    }

The issue I'm facing is that the SIGN_IN action (dispatched by calling this.props.signIn()) is getting called multiple times when I log in from the '/login' page, and get redirected.

It appears that the redirect occurs before the redux store has properly updated the value of isSignedIn and this results in a duplicate SIGN_IN action dispatch.

How can I prevent this? I considered adding a short delay before the redirect, but I'm not sure that's the right way.

EDIT:
I found out that this is happening because I'm rendering the GoogleAuth component twice on the login page (once in the header, and once on the page itself). This resulted in the action getting dispatched twice. Both GoogleAuth components detected the change in authentication status, and as a result both dispatched a SIGN_IN action. There was no delay in propagation of redux store data to the connected component, at least in this scenario.


问:
Change img via css if it is out the container
I've got a container for image and img inside.

Is there some way to change the img content if it's width becomes bigger than the container width via css? Maby image-set?

nav{;
    width: 100%;
    padding: 0;
    height:70px;
    display: flex;
    position: relative;
    border-bottom: 1px solid #b8bbc0;
}

.logo-container{
    display: inline-block;
    overflow: hidden;
    max-width: 25%;
    flex: 0 0  25%;
    -ms-flex: 0 0  25%;
    padding: 5px 0;
    margin: 5px 5px 5px 0;
    position: absolute;
    left: 5px;
}
.logo-helper{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.logo-container img{
    max-height:40px;
    margin: 5px;
    display: inline-block;
    content:   url(https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <nav>
    <div class="logo-container">
        <span class="helper"></span>
        <img>
    </div>
    </nav></code>```

答:
It is a little tricky to change your code since you for some reason decided to use the content  - it is normally used for pseudo elements.

Here I use just src instead

const img = new Image()
img.addEventListener("load",function() {
  const w = this.width, h=this.height;
  const container = document.querySelector(".logo-container");
  const style = window.getComputedStyle(container)
  const sW = parseFloat(style.width)
  const img = container.querySelector("img")
  console.log(w,sW)
  if (w > sW) this.src='https://via.placeholder.com/150?text=150px'
  img.src=this.src
})

img.src="https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png"```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  ;
  width: 100%;
  padding: 0;
  height: 70px;
  display: flex;
  position: relative;
  border-bottom: 1px solid #b8bbc0;
}

.logo-container {
  display: inline-block;
  overflow: hidden;
  width: 25%;
  max-width: 25%;
  flex: 0 0 25%;
  -ms-flex: 0 0 25%;
  padding: 5px 0;
  margin: 5px 5px 5px 0;
  position: absolute;
  left: 5px;
  border: 1px solid black;
}

.logo-helper {
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.logo-container img {
  max-height: 40px;
  margin: 5px;
  display: inline-block;
}</code>```

```

Body:
It is a little tricky to change your code since you for some reason decided to use the content  - it is normally used for pseudo elements.

Here I use just src instead

const img = new Image()
img.addEventListener("load",function() {
  const w = this.width, h=this.height;
  const container = document.querySelector(".logo-container");
  const style = window.getComputedStyle(container)
  const sW = parseFloat(style.width)
  const img = container.querySelector("img")
  console.log(w,sW)
  if (w > sW) this.src='https://via.placeholder.com/150?text=150px'
  img.src=this.src
})

img.src="https://wilcity.com/wp-content/uploads/2018/12/sample-logo-design-png-3.png"

nav {
  ;
  width: 100%;
  padding: 0;
  height: 70px;
  display: flex;
  position: relative;
  border-bottom: 1px solid #b8bbc0;
}

.logo-container {
  display: inline-block;
  overflow: hidden;
  width: 25%;
  max-width: 25%;
  flex: 0 0 25%;
  -ms-flex: 0 0 25%;
  padding: 5px 0;
  margin: 5px 5px 5px 0;
  position: absolute;
  left: 5px;
  border: 1px solid black;
}

.logo-helper {
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.logo-container img {
  max-height: 40px;
  margin: 5px;
  display: inline-block;
}

<nav>
  <div class="logo-container">
    <span class="helper"></span>
    <img>
  </div>
</nav>


问:
How can I push the local repo changes to remote repo and remote has already updated files which I don't have?
How can I push the local repo changes to remote repo and remote has already updated files which I don't have? We are working in a team so continuously there are changes that need to be pulled first but unfortunately, my code gets disappeared when I pull it.

I am using the following commands:
In order to PUSH

```<code>git add .
git commit -m 'msg'
git push -u origin development
! [rejected]        development -> development (fetch first)

error: failed to push some refs to 'https://github.com/gsesltd/metis_maza.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

In order to PULL:

```<code>git pull origin development
</code>```

My files get updated and all my written code is gone now. Thanks to git reset that I have my code.

Can somebody please tell me how can I push the code without force push + I want to have all the remote updates too? How can I do that?

答:
In order to minimize any "code disappearance" on pull, do a rebase instead: that would replay your own local commits on top of fetched commits from the remote repository.

Since Git 2.6 (Q3 2015), type:

git config --global pull.rebase true
git config --global rebase.autoStash true
```

Then a simple git pull will at least put your commits on top.

Body:
How can I push the local repo changes to remote repo and remote has already updated files which I don't have? We are working in a team so continuously there are changes that need to be pulled first but unfortunately, my code gets disappeared when I pull it.

I am using the following commands:
In order to PUSH

git add .
git commit -m 'msg'
git push -u origin development
! [rejected]        development -> development (fetch first)

error: failed to push some refs to 'https://github.com/gsesltd/metis_maza.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

In order to PULL:

git pull origin development

My files get updated and all my written code is gone now. Thanks to git reset that I have my code.

Can somebody please tell me how can I push the code without force push + I want to have all the remote updates too? How can I do that?

Body:
In order to minimize any "code disappearance" on pull, do a rebase instead: that would replay your own local commits on top of fetched commits from the remote repository.

Since Git 2.6 (Q3 2015), type:

git config --global pull.rebase true
git config --global rebase.autoStash true

Then a simple git pull will at least put your commits on top.


问:
flutter problem: how to manage height in tabbar

I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.

I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
this is my cwctv page.

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.black),
        automaticallyImplyLeading: true,
        backgroundColor: Colors.white,
        elevation: 0.5,      ),
      drawer: Drawer(
        child: SideBar(),
      ),
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(top: 18.0),
        child: Container(
          height: 80,
          width: 80,
          child: FittedBox(
            child: FloatingActionButton(
              focusColor: Colors.transparent,
              backgroundColor: selectBlueColor,
              onPressed: () {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => HomePage()));
              },
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              child: Image.asset(
                'assets/home_icon.png',
              ),
              elevation: 1.0,
              highlightElevation: 2,
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: Container(
          // height: MediaQuery.of(context).size.height * (10 / 100),
          child: BottomNavBarTV()),
      body: Stack(
        children: [
          Padding(
              padding: const EdgeInsets.only(left: 16.0,right: 16,bottom: 4,top: 0),
              child: SizedBox(
                  height: 60,
                  child:  TextField( keyboardType: TextInputType.text,
                          onChanged: (value) {
                            setState(() {
                              print("tab on cwctv page $cwcTvTab");
                            });
                          },
                          // controller: cwcTvTab == 3 ?searchImageQuery : cwcTvTab == 2 ?searchPdfQuery : cwcTvTab == 1 ? searchAudioQuery : searchVideoQuery,
                          controller: searchQuery,
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                              borderSide: BorderSide.none,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF1F2F6),
                            hintText: 'Search for Wellness Tips & Tricks',
                            suffixIcon: const Icon(
                              Icons.search_outlined,
                              color: Color(0xFF444444),
                            ),
                          ),
                        )
                     )),
          Padding(
            padding: EdgeInsets.only(top: 70.0),
            child: TestScreen(widget.selectTab),
          ),

          // CwcTVPageChanger(),
          // VideoComponent(),
        ],
      ),
    );
  }
</code>```

This is my tab screen page.

```<code>import 'package:cwc/constants/constants.dart';
import 'package:cwc/ui/CwcTv/components/images/image_document.dart';
import 'package:cwc/ui/CwcTv/components/podcast/podcast_list.dart';
import 'package:cwc/ui/CwcTv/components/slides/slide_component.dart';
import 'package:cwc/ui/CwcTv/components/videos/video_component.dart';
import 'package:cwc/ui/CwcTv/cwc_tv.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:cwc/constants/constant_functions.dart';

class TestScreen extends StatefulWidget {
  int selectedPage;

  TestScreen(this.selectedPage);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  void _handleTabSelection() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        // _tabSection(context, widget.selectedPage,controller!),
        _tabSection(context, widget.selectedPage),
      ],
    );
  }
}

Widget _tabSection(BuildContext context, var selectedPage) {
  return DefaultTabController(
    initialIndex: selectedPage,
    length: 4,
    child: SafeArea(
      child: Column(
        // mainAxisSize: MainAxisSize.min,
        children: [
          TabBar(
            indicatorColor: Colors.black,
            onTap: (v) {

              cwcTvTab = v;

            },
            isScrollable: true,
            // physics: NeverScrollableScrollPhysics(),
            labelColor: Colors.black,
            tabs: [
              Tab(
                child: Text(
                  'Video',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Podcast',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Documents',
                  style: GoogleFonts.poppins(
                    color: Colors.black,
                  ),
                ),
              ),
              Tab(
                child: Text(
                  'Images',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
            ],
          ),
          Container(
            height: MediaQuery.of(context).size.height - 282,
            // height: MediaQuery.of(context).size.height - 205,
            // height: double.infinity,
            child:
                TabBarView( physics: NeverScrollableScrollPhysics(),
                    children: [
              VideoComponent(),
              PodcastList(),
              SlideComponent(),
              ImageDocument(),
            ]),
          ),
        ],
      ),
    ),
  );
}

</code>```

this is my android Device's screenshot.

this is my IOS Device's screenshot.

答:
There is 2 options you can use, first try with indicator like this one:

```<code>TabBar(
        indicator: UnderlineTabIndicator(
          borderSide: BorderSide(width: 5.0),
          insets: EdgeInsets.symmetric(horizontal:16.0)
        ),
        indicatorColor: Colors.black,
        onTap: (v) {

          cwcTvTab = v;

        },
        isScrollable: true,
        // physics: NeverScrollableScrollPhysics(),
        labelColor: Colors.black,
        tabs: [
          Tab(
            child: Text(
              'Video',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Podcast',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Documents',
              style: GoogleFonts.poppins(
                color: Colors.black,
              ),
            ),
          ),
          Tab(
            child: Text(
              'Images',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
        ],
      ),
</code>```

Or you can just wrap it with a container.

```<code>    PreferredSize(
      preferredSize: const Size.fromHeight(10),
      child: Container(
        height: 50,
        child: TabBar(
          indicatorColor: Colors.black,
          isScrollable: true,
          labelColor: Colors.black,
          tabs: [
            Tab(
              child: Text(
                'Video',
              ),
            ),
            Tab(
              child: Text(
                'Podcast',
              ),
            ),
            Tab(
              child: Text(
                'Documents',
              ),
            ),
            Tab(
              child: Text(
                'Images',
              ),
            ),
          ],
        ),
      ),
    ),
</code>```

Body:
I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.

I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
I have a problem this that in my android device cwctv page is working but in IOS Device giving height error,so how to set height for every device.
this is my cwctv page.

@override
  Widget build(BuildContext context) {
    return Scaffold(backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.black),
        automaticallyImplyLeading: true,
        backgroundColor: Colors.white,
        elevation: 0.5,      ),
      drawer: Drawer(
        child: SideBar(),
      ),
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(top: 18.0),
        child: Container(
          height: 80,
          width: 80,
          child: FittedBox(
            child: FloatingActionButton(
              focusColor: Colors.transparent,
              backgroundColor: selectBlueColor,
              onPressed: () {
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => HomePage()));
              },
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              child: Image.asset(
                'assets/home_icon.png',
              ),
              elevation: 1.0,
              highlightElevation: 2,
            ),
          ),
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: Container(
          // height: MediaQuery.of(context).size.height * (10 / 100),
          child: BottomNavBarTV()),
      body: Stack(
        children: [
          Padding(
              padding: const EdgeInsets.only(left: 16.0,right: 16,bottom: 4,top: 0),
              child: SizedBox(
                  height: 60,
                  child:  TextField( keyboardType: TextInputType.text,
                          onChanged: (value) {
                            setState(() {
                              print("tab on cwctv page $cwcTvTab");
                            });
                          },
                          // controller: cwcTvTab == 3 ?searchImageQuery : cwcTvTab == 2 ?searchPdfQuery : cwcTvTab == 1 ? searchAudioQuery : searchVideoQuery,
                          controller: searchQuery,
                          decoration: InputDecoration(
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10.0),
                              borderSide: BorderSide.none,
                            ),
                            filled: true,
                            fillColor: const Color(0xFFF1F2F6),
                            hintText: 'Search for Wellness Tips & Tricks',
                            suffixIcon: const Icon(
                              Icons.search_outlined,
                              color: Color(0xFF444444),
                            ),
                          ),
                        )
                     )),
          Padding(
            padding: EdgeInsets.only(top: 70.0),
            child: TestScreen(widget.selectTab),
          ),

          // CwcTVPageChanger(),
          // VideoComponent(),
        ],
      ),
    );
  }

This is my tab screen page.

import 'package:cwc/constants/constants.dart';
import 'package:cwc/ui/CwcTv/components/images/image_document.dart';
import 'package:cwc/ui/CwcTv/components/podcast/podcast_list.dart';
import 'package:cwc/ui/CwcTv/components/slides/slide_component.dart';
import 'package:cwc/ui/CwcTv/components/videos/video_component.dart';
import 'package:cwc/ui/CwcTv/cwc_tv.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:cwc/constants/constant_functions.dart';

class TestScreen extends StatefulWidget {
  int selectedPage;

  TestScreen(this.selectedPage);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  void _handleTabSelection() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        // _tabSection(context, widget.selectedPage,controller!),
        _tabSection(context, widget.selectedPage),
      ],
    );
  }
}

Widget _tabSection(BuildContext context, var selectedPage) {
  return DefaultTabController(
    initialIndex: selectedPage,
    length: 4,
    child: SafeArea(
      child: Column(
        // mainAxisSize: MainAxisSize.min,
        children: [
          TabBar(
            indicatorColor: Colors.black,
            onTap: (v) {

              cwcTvTab = v;

            },
            isScrollable: true,
            // physics: NeverScrollableScrollPhysics(),
            labelColor: Colors.black,
            tabs: [
              Tab(
                child: Text(
                  'Video',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Podcast',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
              Tab(
                child: Text(
                  'Documents',
                  style: GoogleFonts.poppins(
                    color: Colors.black,
                  ),
                ),
              ),
              Tab(
                child: Text(
                  'Images',
                  style: GoogleFonts.poppins(color: Colors.black),
                ),
              ),
            ],
          ),
          Container(
            height: MediaQuery.of(context).size.height - 282,
            // height: MediaQuery.of(context).size.height - 205,
            // height: double.infinity,
            child:
                TabBarView( physics: NeverScrollableScrollPhysics(),
                    children: [
              VideoComponent(),
              PodcastList(),
              SlideComponent(),
              ImageDocument(),
            ]),
          ),
        ],
      ),
    ),
  );
}

this is my android Device's screenshot.

this is my IOS Device's screenshot.

Body:
There is 2 options you can use, first try with indicator like this one:

TabBar(
        indicator: UnderlineTabIndicator(
          borderSide: BorderSide(width: 5.0),
          insets: EdgeInsets.symmetric(horizontal:16.0)
        ),
        indicatorColor: Colors.black,
        onTap: (v) {

          cwcTvTab = v;

        },
        isScrollable: true,
        // physics: NeverScrollableScrollPhysics(),
        labelColor: Colors.black,
        tabs: [
          Tab(
            child: Text(
              'Video',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Podcast',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
          Tab(
            child: Text(
              'Documents',
              style: GoogleFonts.poppins(
                color: Colors.black,
              ),
            ),
          ),
          Tab(
            child: Text(
              'Images',
              style: GoogleFonts.poppins(color: Colors.black),
            ),
          ),
        ],
      ),

Or you can just wrap it with a container.

    PreferredSize(
      preferredSize: const Size.fromHeight(10),
      child: Container(
        height: 50,
        child: TabBar(
          indicatorColor: Colors.black,
          isScrollable: true,
          labelColor: Colors.black,
          tabs: [
            Tab(
              child: Text(
                'Video',
              ),
            ),
            Tab(
              child: Text(
                'Podcast',
              ),
            ),
            Tab(
              child: Text(
                'Documents',
              ),
            ),
            Tab(
              child: Text(
                'Images',
              ),
            ),
          ],
        ),
      ),
    ),


问:
Multiple substring replacement in bash
I'm working in an HPC cluster which has a lot of partitions ($HOME, $SCRATCH, $WORKDIR, $SHARED,...) and was trying to find a way to clearly identify which partition I'm at the moment.

After some digging, I found that

```<code>export PS1="\e[33;1m\u@\h: \e[31m\w\e[0m\$ "
</code>```

would show me what I'm looking for. However, the path becomes really cumbersome since all of these partitions have a really long pwd output.

I found out that this command,

```<code>aaa@bbb: ~$ echo $PROMPT_COMMAND
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" ${PWD/#$HOME/~}"
</code>```

mainly the ${PWD/#$HOME/~} part, might be why the $HOME directory appears simply with ~.

Is there a way to change this environment variable (or any other alternative) for me to have something like:

```<code>aaa@bbb: ~/foo/bar$          # when I'm working in $HOME
aaa@bbb: scratch/foo/bar$    # when I'm working in $SCRATCH
aaa@bbb: shared/foo/bar$     # when I'm working in $SHARED
</code>```

答:
Set PROMPT_COMMAND to command, which will set a variable with truncated path value.

Replace \w in PS1 with the variable name.

My example:

```<code>export PROMPT_COMMAND='export CURDIR=$( pwd | sed "s|$HOME|~|;s|/var/lib/postgresql|pg|;s|/opt|stuff|" )'
export PS1='\[\033]0;\u@\h:\w\007\]\[\033[01;32m\]\u@\h\[\033[01;34m\] $CURDIR \$\[\033[00m\] '
</code>```

Title: Multiple substring replacement in bash

Body:
I'm working in an HPC cluster which has a lot of partitions ($HOME, $SCRATCH, $WORKDIR, $SHARED,...) and was trying to find a way to clearly identify which partition I'm at the moment.

After some digging, I found that

export PS1="\e[33;1m\u@\h: \e[31m\w\e[0m\$ "

would show me what I'm looking for. However, the path becomes really cumbersome since all of these partitions have a really long pwd output.

I found out that this command,

aaa@bbb: ~$ echo $PROMPT_COMMAND
printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" ${PWD/#$HOME/~}"

mainly the ${PWD/#$HOME/~} part, might be why the $HOME directory appears simply with ~.

Is there a way to change this environment variable (or any other alternative) for me to have something like:

aaa@bbb: ~/foo/bar$          # when I'm working in $HOME
aaa@bbb: scratch/foo/bar$    # when I'm working in $SCRATCH
aaa@bbb: shared/foo/bar$     # when I'm working in $SHARED

Body:
Set PROMPT_COMMAND to command, which will set a variable with truncated path value.

Replace \w in PS1 with the variable name.

My example:

export PROMPT_COMMAND='export CURDIR=$( pwd | sed "s|$HOME|~|;s|/var/lib/postgresql|pg|;s|/opt|stuff|" )'
export PS1='\[\033]0;\u@\h:\w\007\]\[\033[01;32m\]\u@\h\[\033[01;34m\] $CURDIR \$\[\033[00m\] '


问:
help with bm25 explanation. Rare words in a small index/common words in a small index
I need a little help in understanding the bm25 relevance ranking (im using sphinx). When there is a small index (very small lets say), does this negatively influence relevance on common words that appear alot in a document? Lets say you have 4 articles total in the index (very small, yes)....titled: "norway", "canada stocks rebound again", "canada", "vietnam". The fields specified are title, and body. Lets say the query is : "canada". Basically, "canada" appears alot in (descending order)...i. "canada" ii. "canada stocks rebound again" iii. "norway" (it does in this article). Doesn't bm25 take into account word frequency? I read that words that appear very frequently in the index and the document actually take down the ranking. By the way, when I search in sphinx using proximity_bm25....."canada stocks rebound again" is ranked slightly higher than "canada"....curious :p</p>

答: There is some specific information on the Sphinx implementation of BM25 on their blog.  Note that that explanation begins "BM25 ... depends on frequencies of the matched keywords only."  The measure itself is primarily based on TF (Term Frequency) and IDF (Inverse Document Frequency); i.e. the frequency of the term across the entire corpus and the (inverse) number of documents containing that term.  The formulae is given in the referenced link.

ContentLicense: CC BY-SA 3.0


问:
Compare given date with today
I have following

```<code>$var = "2010-01-21 00:00:00.0"
</code>```

I'd like to compare this date against today's date (i.e. I'd like to know if this $var is  before today or equals today or not)

What function would I need to use?

答:
Try this:</p>
```<code>if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
    echo "ok";
} else {
    echo "not";
}
</code>```

Title: Compare given date with today

Body:
I have following

$var = "2010-01-21 00:00:00.0"

I'd like to compare this date against today's date (i.e. I'd like to know if this $var is  before today or equals today or not)

What function would I need to use?

Body:
Try this:

if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
    echo "ok";
} else {
    echo "not";
}


问:
JavaScript - img caption to appear/disappear onclick event
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

```<code><div id="section1" >
        <h1>Pictures from my vacation</h1>`enter code here`
        <figure style="float: left;" >
            <img src="Photos/p1.jpg" title="Beach" value="hide/show" onclick="showOrHide()">
            <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
        </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>
</code>```

JS

function showOrHide() {

```<code>if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}
</code>```

}

答:
A few things to get you on your way:

I wouldn't use onxyz-attribute-style event handlers. They can only call global functions, passing parameters to them is difficult because of handling text inside JavaScript code inside an HTML attribute, and various other things. I'd use modern event handling like addEventListener.

But if you did want to use an onclick attribute for this, I'd use onclick="showOrHide(this)" (this will refer to the image that this click was on) and then accept an img parameter in the function, rather than using an id to do the lookup.

Boolean values like true and false don't go in quotes.

You don't seem to have declared your show variable anywhere.

I'd use a class rather than directly modifying the style of the element.

So with all that in mind:

"use strict";

document.addEventListener("click", event => {
    const img = event.target.closest(".toggle-image");
    if (img && img.nextElementSibling.tagName === "FIGCAPTION") {
        img.nextElementSibling.classList.toggle("hidden");
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
    visibility: hidden;
}</code>```

Pictures from my vacation
`enter code here`

Waterton Beach

Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.

```

That code uses event delegation by hooking click on the document as a whole and then, when the click occurs, seeing if the click was on an .image-toggle element (or passed through when bubbling). If it did, it looks at the next element after the img to see if it's a figcaption and, if so, toggles a hidden class in the element's class list element to show/hide the caption.

(Those links are to MDN, which is an excellent resource for web programming information.)

Body:
I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on  the forum.

HTML

Pictures from my vacation
`enter code here`

Waterton Beach

Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.

JS

function showOrHide() {

if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";

}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}

}

Body:
A few things to get you on your way:

I wouldn't use onxyz-attribute-style event handlers. They can only call global functions, passing parameters to them is difficult because of handling text inside JavaScript code inside an HTML attribute, and various other things. I'd use modern event handling like addEventListener.

But if you did want to use an onclick attribute for this, I'd use onclick="showOrHide(this)" (this will refer to the image that this click was on) and then accept an img parameter in the function, rather than using an id to do the lookup.

Boolean values like true and false don't go in quotes.

You don't seem to have declared your show variable anywhere.

I'd use a class rather than directly modifying the style of the element.

So with all that in mind:

"use strict";

document.addEventListener("click", event => {
    const img = event.target.closest(".toggle-image");
    if (img && img.nextElementSibling.tagName === "FIGCAPTION") {
        img.nextElementSibling.classList.toggle("hidden");
    }
});

.hidden {
    visibility: hidden;
}

<div id="section1">
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;">
        <img src="Photos/p1.jpg" class="toggle-image" title="Beach" value="hide/show">
        <figcaption class="hidden">Waterton Beach</figcaption>
    </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>

That code uses event delegation by hooking click on the document as a whole and then, when the click occurs, seeing if the click was on an .image-toggle element (or passed through when bubbling). If it did, it looks at the next element after the img to see if it's a figcaption and, if so, toggles a hidden class in the element's class list element to show/hide the caption.

(Those links are to MDN, which is an excellent resource for web programming information.)