问:
How to use --split-debug-info=/<project-name>/<directory>
In the command below, how to use --split-debug-info=/<project-name>/<directory>

```<code>flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>
</code>```

When I declare project-name &  directory path then the path contains nothing after build.

The --split-debug-info flag specifies the directory where Flutter can
  output debug files. This command generates a symbol map.

So the directory defined, but where are the resulted symbol maps?

答:
First of all, make sure you are using a version of Flutter framework >= 1.16.2, you can check it by running:

```<code>flutter --version
</code>```

And if it's not the case, you can upgrade the Flutter framework by running:

```<code>flutter upgrade
</code>```

Then, in order to generate the symbol map files when you run the flutter build command, you can use the command like this:

```<code> flutter build apk --obfuscate --split-debug-info=some_parent_directory/some_child_directory
</code>```

Note that some_parent_directory and some_child_directory are arbitrary names that you can replace for whatever you want.

Also note that there's no slash (/) symbol at the beggining of the right side of the equals (=) symbol of the --split-debug-info=some_parent_directory/some_child_directory part of the command.

For the example above, after the command finishes, you can find a some_parent_directory directory under your project's root directory, which contains another directory called some_child_directory which finally contains the symbol map files:

app.android-arm.symbols

app.android-arm64.symbols

app.android-x64.symbols

Body:
In the command below, how to use --split-debug-info=/<project-name>/<directory>

flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>

When I declare project-name &  directory path then the path contains nothing after build.

The --split-debug-info flag specifies the directory where Flutter can
  output debug files. This command generates a symbol map.

So the directory defined, but where are the resulted symbol maps?

Body:
First of all, make sure you are using a version of Flutter framework >= 1.16.2, you can check it by running:

flutter --version

And if it's not the case, you can upgrade the Flutter framework by running:

flutter upgrade

Then, in order to generate the symbol map files when you run the flutter build command, you can use the command like this:

 flutter build apk --obfuscate --split-debug-info=some_parent_directory/some_child_directory

Note that some_parent_directory and some_child_directory are arbitrary names that you can replace for whatever you want.

Also note that there's no slash (/) symbol at the beggining of the right side of the equals (=) symbol of the --split-debug-info=some_parent_directory/some_child_directory part of the command.

For the example above, after the command finishes, you can find a some_parent_directory directory under your project's root directory, which contains another directory called some_child_directory which finally contains the symbol map files:

app.android-arm.symbols

app.android-arm64.symbols

app.android-x64.symbols


来源: stackexchange

问:
Can Blob URLs be considered as a solution to prevent users from copying the images from inside the developers console?
As we all know, if we read the image (or video) files as a binary object and then make a URL to these objects, we can then display the files with these blob URLs inside the HTML which can not be accessed in another window or tab since it only exists in the current session. As a result, the user can not simply save the file (for example we can not simply download youtube videos since their video tags have blob URLs as their sources).

So can we say this is a way to prevent users from stealing the sensitive files using the developer's console? If so, why so many websites do not do that? I know many websites that have copy-righted images or sell wallpapers but you can simply download their files from the console.
Or is something wrong with this method?

答:
Not at all no. The file is on their computer already, and they can very well save it, be it an image or even a video, feeding the HTML element with a blob:// URL doesn't prevent any "save As" actions:

fetch( "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" )
  .then( resp => resp.blob() )
  .then( blob => {
    console.log( 'img loaded' );
    const elem = document.querySelector( 'img' );
    elem.src = URL.createObjectURL( blob );
  } );

fetch( "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm" )
  .then( resp => resp.blob() )
  .then( blob => {
    console.log( 'video loaded' );
    const elem = document.querySelector( 'video' );
    elem.src = URL.createObjectURL( blob );
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Try to right click "save As..." these two media:
<img>
<video controls></video></code>```

Revoking the blob:// URL once loaded could make it a bit harder, but even then, if you look at the Network Panel of your dev tools, you'll see the original request from which the Blob has been generated and from where your users will be able to scrape your data.

YouTube is not using a blob:// URL to prevent downloads

If they really did want to make it harder to download their videos, they'd protect it with DRMs and would be using the EME API, but they're not.

The blob:// URL you see in YouTube's video doesn't point to a Blob, but to a MediaSource object. They do use this API to be able to serve adaptive contents, i.e to be able to send a lower quality of the same media on the fly when the connection quality worsens.

It has absolutely nothing to do with any protection, and a quick search on the web will tell you it's quite simple to find back the original files YT is streaming.

ContentLicense: CC BY-SA 4.0

Body:
Not at all no. The file is on their computer already, and they can very well save it, be it an image or even a video, feeding the HTML element with a blob:// URL doesn't prevent any "save As" actions:

fetch( "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" )
  .then( resp => resp.blob() )
  .then( blob => {
    console.log( 'img loaded' );
    const elem = document.querySelector( 'img' );
    elem.src = URL.createObjectURL( blob );
  } );

fetch( "https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm" )
  .then( resp => resp.blob() )
  .then( blob => {
    console.log( 'video loaded' );
    const elem = document.querySelector( 'video' );
    elem.src = URL.createObjectURL( blob );
  } );

Try to right click "save As..." these two media:
<img>
<video controls></video>

Revoking the blob:// URL once loaded could make it a bit harder, but even then, if you look at the Network Panel of your dev tools, you'll see the original request from which the Blob has been generated and from where your users will be able to scrape your data.

YouTube is not using a blob:// URL to prevent downloads

If they really did want to make it harder to download their videos, they'd protect it with DRMs and would be using the EME API, but they're not.

The blob:// URL you see in YouTube's video doesn't point to a Blob, but to a MediaSource object. They do use this API to be able to serve adaptive contents, i.e to be able to send a lower quality of the same media on the fly when the connection quality worsens.

It has absolutely nothing to do with any protection, and a quick search on the web will tell you it's quite simple to find back the original files YT is streaming.


问:
change expanding space of nested layouts in pyqt
I want to seperate the widgets of the mainwindow into 3 layouts and add them into a mainlayout
the center layout contains a tablewidget and shoud have a bigger width then the left/right one. so far I did not found a way to use a grid layout and adjust each column width individualy.

therefore I tryed to use 3 vboxlayouts and insert them into an hboxlayout

what if read so far is that the widgets size are fixed so they expand at the same rate if stretched.

is there an easier way to make the center layout widht bigger with for example inserting an spacer without  changing  the SizePolicy of each widget ?

```<code>import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout)
        # self.qhboxlayout.addWidget(Separador)
        self.qhboxlayout.addLayout(center_voboxlayout)
        self.qhboxlayout.addLayout(rightvboxlayout)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())
</code>```

答:
Try this :

you will decide how much space allocate for each layout, by the following way :

```<code>    self.qhboxlayout.addLayout(left_vboxlayout,20)
    self.qhboxlayout.addLayout(center_voboxlayout,80)
    self.qhboxlayout.addLayout(rightvboxlayout,20)
</code>```

Your Code

```<code>import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout,20)
        self.qhboxlayout.addLayout(center_voboxlayout,80)
        self.qhboxlayout.addLayout(rightvboxlayout,20)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())
</code>```

Body:
I want to seperate the widgets of the mainwindow into 3 layouts and add them into a mainlayout
the center layout contains a tablewidget and shoud have a bigger width then the left/right one. so far I did not found a way to use a grid layout and adjust each column width individualy.

therefore I tryed to use 3 vboxlayouts and insert them into an hboxlayout

what if read so far is that the widgets size are fixed so they expand at the same rate if stretched.

is there an easier way to make the center layout widht bigger with for example inserting an spacer without  changing  the SizePolicy of each widget ?

import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout)
        # self.qhboxlayout.addWidget(Separador)
        self.qhboxlayout.addLayout(center_voboxlayout)
        self.qhboxlayout.addLayout(rightvboxlayout)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())

Body:
Try this :

you will decide how much space allocate for each layout, by the following way :

    self.qhboxlayout.addLayout(left_vboxlayout,20)
    self.qhboxlayout.addLayout(center_voboxlayout,80)
    self.qhboxlayout.addLayout(rightvboxlayout,20)

Your Code

import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg

class Stretchme(qtw.QWidget):
    def __init__(self):
        super().__init__()

        # # View
        table_widget = qtw.QTableWidget()

        # -----interface--widgets--------------------------#

        # -------- parameter_widgets------------#
        parameter_label = qtw.QLabel("Parameter")

        test_time_label = qtw.QLabel("Time")
        self.clocktime = qtw.QTimeEdit()
        test_date_label = qtw.QLabel("Date")
        self.date_time = qtw.QDateEdit()

        grob_fein_label = qtw.QLabel("Grobe")
        grob_fein_combo_box = qtw.QComboBox()

        vr_label = qtw.QLabel("Lame")
        self.vr_feuchte_input = qtw.QLineEdit()

        # leftvboxlayout
        left_vboxlayout = qtw.QVBoxLayout()

        left_vboxlayout.addStretch(1)

        left_vboxlayout.addWidget(test_time_label)
        left_vboxlayout.addWidget(self.clocktime)
        left_vboxlayout.addWidget(test_date_label)
        left_vboxlayout.addWidget(self.date_time)
        left_vboxlayout.addWidget(grob_fein_label)
        left_vboxlayout.addWidget(grob_fein_combo_box)
        left_vboxlayout.addWidget(vr_label)
        left_vboxlayout.addWidget(self.vr_feuchte_input)

        # centervboxlayout
        center_voboxlayout = qtw.QVBoxLayout()
        #
        # center_voboxlayout.addStretch()
        # center_voboxlayout.setStretchFactor()
        # center_voboxlayout.addSpacing()
        # center_voboxlayout.setStretchFactor()

        #
        # table_widget.setMinimumSize(90,80)

        center_voboxlayout.addWidget(table_widget)

        # righvobxlayout
        # buttons
        self.button_1 = qtw.QPushButton("Button 1")
        self.button_2 = qtw.QPushButton("Button 2")
        self.button_2 = qtw.QPushButton("Button 3")

        rightvboxlayout = qtw.QVBoxLayout()
        rightvboxlayout.addStretch(1)
        rightvboxlayout.addWidget(self.button_1)
        rightvboxlayout.addWidget(self.button_2)
        rightvboxlayout.addWidget(self.button_2)

        #
        #
        # Separador = qtw.QFrame()
        # # Separador.Shape(QFrame.HLine)
        # Separador.setFrameShape(qtw.QFrame.HLine)
        #
        # Separador.setSizePolicy(qtw.QSizePolicy.Minimum,qtw.QSizePolicy.Expanding)
        # Separador.setLineWidth(5)
        # # HPOUT1_layout = QVBoxLayout()
        # # HPOUT1_layout.addLayout(HPOUT1L_layout)
        # # HPOUT1_layout.addWidget(Separador)
        # # HPOUT1_layout.addLayout(HPOUT1R_layout)

        ## main layout
        self.qhboxlayout = qtw.QHBoxLayout()
        self.qhboxlayout.addLayout(left_vboxlayout,20)
        self.qhboxlayout.addLayout(center_voboxlayout,80)
        self.qhboxlayout.addLayout(rightvboxlayout,20)
        #
        # ### Main Grid

        # -------------------------------------------------- #
        selected_color = qtg.QColor(0,0,255)

        # self.setGeometry(300, 300, 1850, 950)
        self.setStyleSheet("background-color: {}")
        self.setLayout(self.qhboxlayout)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = Stretchme()
    sys.exit(app.exec_())


问:
create matrix with columns populated from vector values and row names from a different vector values
i have this data...

```<code>df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
               NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
               Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df
   year   NODCCODE Number
1: 2017 110040218    1
2: 2014 121053801    5
3: 2012 170281801    2
4: 2014 170281801    2
5: 2014 170281801    4
</code>```

I'd like to create this for a much larger data set

```<code>df3 <- structure(list(year = c(2012L, 2014L, 2017L),
               `110040218` = c(0L, 0L, 1L),
               `121053801` = c(2L, 5L, 0L),
               `170281801` = c(2L, 3L, 0L)),
          row.names = c(NA, -3L), class = c("data.table", "data.frame"))

df3
   year 110040218 121053801 170281801
1: 2012         0         2         2
2: 2014         0         5         3
3: 2017         1         0         0
</code>```

I made the second table manually so let me explain in case I screwed it up. I have the three starting vectors, which all have many repeated values. I want the column names to be the NODCCODE numbers iterated only once, so no repeats. The first column will by consecutive years populated from the year column, but also not repeating. To populate the matrix I want to use the Number values, but if the year and NODCCODE number match then it needs to take the average and put that in that cell of the matrix.

My starting data is number of fish caught per net. So I have many species (NODCCODE code) records for each year. My actual data can be found here:  https://drive.google.com/file/d/1LTxZhD00QvFbioLPiOJMLjm5MftOmbZt/view?usp=sharing  if that is more helpful. There are many nets set and the same species are caught in many of them each year.
The final matrix if using the whole data set, should have years 2008-2018 sequentially in the first column (only one row per year). And something like 136-138 NODCODES as the rest of the column names.

So in other words its going to be a very short but very wide matrix with year as column 1. the rest of the columns will be unique NODCCODE (species). The value for each one will be an average of all the values for that NODCCODE (species) and year combinations.

I've tried many ways to do this including group by and the following code:

```<code>test <- gather(test, NODCCODE, Number, -year) %>% arrange(year, NODCCODE)
</code>```

But I keep getting results that are not even close.

I've probably over complicated this so hopefully my example data helps. Thanks in advance!

答:
This should do it:

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

df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
                    NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
                    Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df <- df %>%
  pivot_wider(names_from = NODCCODE,
              values_from = Number,
              values_fn = list(Number = mean))

df[is.na(df)] <- 0
</code>```

Function gather has been retired in tidyr and has been replaced with pivot_wider. We need the argument values_fn as we otherwise would end up with nested vector for some of the list elements. values_fn allows us to apply a function to each element after changing shape.

With this output:

```<code>> df
# A tibble: 3 x 4
   year `110040218` `121053801` `170281801`
  <int>       <dbl>       <dbl>       <dbl>
1  2017           1           0           0
2  2014           0           5           3
3  2012           0           0           2
</code>```

UPDATE

pivot_wider comes with an argument to deal with missing values: values_fill:

```<code>df <- df %>%
  pivot_wider(names_from = NODCCODE,
              values_from = Number,
              values_fn = list(Number = mean),
              values_fill = list(Number = 0))
</code>```

Body:
i have this data...

df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
               NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
               Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df
   year   NODCCODE Number
1: 2017 110040218    1
2: 2014 121053801    5
3: 2012 170281801    2
4: 2014 170281801    2
5: 2014 170281801    4

I'd like to create this for a much larger data set

df3 <- structure(list(year = c(2012L, 2014L, 2017L),
               `110040218` = c(0L, 0L, 1L),
               `121053801` = c(2L, 5L, 0L),
               `170281801` = c(2L, 3L, 0L)),
          row.names = c(NA, -3L), class = c("data.table", "data.frame"))

df3
   year 110040218 121053801 170281801
1: 2012         0         2         2
2: 2014         0         5         3
3: 2017         1         0         0

I made the second table manually so let me explain in case I screwed it up. I have the three starting vectors, which all have many repeated values. I want the column names to be the NODCCODE numbers iterated only once, so no repeats. The first column will by consecutive years populated from the year column, but also not repeating. To populate the matrix I want to use the Number values, but if the year and NODCCODE number match then it needs to take the average and put that in that cell of the matrix.

My starting data is number of fish caught per net. So I have many species (NODCCODE code) records for each year. My actual data can be found here:  https://drive.google.com/file/d/1LTxZhD00QvFbioLPiOJMLjm5MftOmbZt/view?usp=sharing  if that is more helpful. There are many nets set and the same species are caught in many of them each year.
The final matrix if using the whole data set, should have years 2008-2018 sequentially in the first column (only one row per year). And something like 136-138 NODCODES as the rest of the column names.

So in other words its going to be a very short but very wide matrix with year as column 1. the rest of the columns will be unique NODCCODE (species). The value for each one will be an average of all the values for that NODCCODE (species) and year combinations.

I've tried many ways to do this including group by and the following code:

test <- gather(test, NODCCODE, Number, -year) %>% arrange(year, NODCCODE)

But I keep getting results that are not even close.

I've probably over complicated this so hopefully my example data helps. Thanks in advance!

Body:
This should do it:

library(dplyr)
library(tidyr)

df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
                    NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
                    Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df <- df %>%
  pivot_wider(names_from = NODCCODE,
              values_from = Number,
              values_fn = list(Number = mean))

df[is.na(df)] <- 0

Function gather has been retired in tidyr and has been replaced with pivot_wider. We need the argument values_fn as we otherwise would end up with nested vector for some of the list elements. values_fn allows us to apply a function to each element after changing shape.

With this output:

> df
# A tibble: 3 x 4
   year `110040218` `121053801` `170281801`
  <int>       <dbl>       <dbl>       <dbl>
1  2017           1           0           0
2  2014           0           5           3
3  2012           0           0           2

UPDATE

pivot_wider comes with an argument to deal with missing values: values_fill:

df <- df %>%
  pivot_wider(names_from = NODCCODE,
              values_from = Number,
              values_fn = list(Number = mean),
              values_fill = list(Number = 0))


问:
How to properly resize an image?
I am a starter for the CNN DL.
During CNN code I faced this error:

Negative dimension size caused by subtracting 3 from 1 for
  'conv2d_3/convolution' (op: 'Conv2D') with input shapes: [?,19,1,64],
  [3,3,64,64]

My image data show 300(w), 855(h) pixels size.

For the np array transformation, I applied below.

```<code>(width,height = 28)->>
img = cv2.resize(img, None, fx = img_width/img.shape[0], fy = img_height/img.shape[1])
                x.append(img/256)
                y.append(label)
</code>```

And then, I tried CNN by using this:

```<code>model.add(Convolution2D(16,(3,3), border_mode='same', activation='relu', input_shape=x_train.shape[1:]))

x_train.shape[1:] = (80,10,3)
</code>```

Please help to fix this error.
Thank you for read.

答:
you have an input with the shape (19x1x64) where 64 is the number of channels. That's why your 3x3 convolution operation cannot be performed. What probably is happening:

- you are resizing your image in a wrong way (hence the 19x1x64 dimension as opposed to the 28x28x3 you potentially intended to achieve).

How to solve this? check out your resizing again and print your image shape after resize, see if this is what you aimed for.

Title: How to properly resize an image?

Body:
I am a starter for the CNN DL.
During CNN code I faced this error:

Negative dimension size caused by subtracting 3 from 1 for
  'conv2d_3/convolution' (op: 'Conv2D') with input shapes: [?,19,1,64],
  [3,3,64,64]

My image data show 300(w), 855(h) pixels size.

For the np array transformation, I applied below.

(width,height = 28)->>
img = cv2.resize(img, None, fx = img_width/img.shape[0], fy = img_height/img.shape[1])
                x.append(img/256)
                y.append(label)

And then, I tried CNN by using this:

model.add(Convolution2D(16,(3,3), border_mode='same', activation='relu', input_shape=x_train.shape[1:]))

x_train.shape[1:] = (80,10,3)

Please help to fix this error.
Thank you for read.


问:
DatePicker on Mac not saving date until return key is pressed
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

```<code>class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}
</code>```

答:
How about using DatePicker for the date part, and the following textfields for the time input part.</p>

```<code>import SwiftUI
import Combine

struct ContentView: View {
@State var date = Date()
var body: some View {
    NavigationView {
        NavigationLink(destination: DateHMPicker(date: self.$date)) {
            VStack {
                Text("Show time")
                Text("\(self.date)")
            }
        }
    }.navigationViewStyle(StackNavigationViewStyle())
}
}

struct DateHMPicker: View {
@State var labelText = ""
@Binding var date: Date

var body: some View {
    HStack {
        Spacer()
        DatePicker(labelText, selection: self.$date, displayedComponents: .date)
        Spacer()
        HoursMinutesPicker(date: self.$date).frame(width: 90)
    }.fixedSize()
}
}

struct TextFieldTime: View {
let range: ClosedRange<Int>
@Binding var value: Int
var handler: () -> Void

@State private var isGood = false
@State private var textValue = ""
@State private var digits = 2

var body: some View {
    TextField("", text: $textValue)
        .font(Font.body.monospacedDigit())
        .onReceive(Just(textValue)) { txt in
            // must be numbers
            var newTxt = txt.filter {"0123456789".contains($0)}
            if newTxt == txt {
                // restrict the digits
                if newTxt.count > self.digits {
                    newTxt = String(newTxt.dropLast())
                }
                // check the number
                self.isGood = false
                if let number = NumberFormatter().number(from: newTxt) {
                    if self.range.contains(number.intValue) {
                        self.textValue = newTxt
                        self.value = number.intValue
                        self.isGood = true
                    } else {
                        self.textValue = self.textValue.count == 1
                            ? String(self.range.lowerBound) : String(self.textValue.dropLast())
                    }
                }
                if self.value >= 0 && self.isGood {
                    self.handler()
                }
            } else {
                self.textValue = newTxt.isEmpty ? String(self.range.lowerBound) : newTxt
            }

    }.onAppear(perform: {
        self.textValue = String(self.value)
        self.digits = String(self.range.upperBound).count
    })
        .fixedSize()
}
}

struct HoursMinutesPicker: View {
@Binding var date: Date
@State var separator = ":"

@State var hours: Int = 0
@State var minutes: Int = 0

var body: some View {
    HStack (spacing: 1) {
        TextFieldTime(range: 0...23, value: self.$hours, handler: self.update)
        Text(separator)
        TextFieldTime(range: 0...59, value: self.$minutes, handler: self.update)
    }.onAppear(perform: loadData).padding(5)
}

func loadData() {
    self.hours = Calendar.current.component(.hour, from: date)
    self.minutes = Calendar.current.component(.minute, from: date)
}

func update() {
    let baseDate = Calendar.current.dateComponents([.year, .month, .day], from: date)
    var dc = DateComponents()
    dc.year = baseDate.year
    dc.month = baseDate.month
    dc.day = baseDate.day
    dc.hour = self.hours
    dc.minute = self.minutes
    if let newDate = Calendar.current.date(from: dc), date != newDate {
        date = newDate
    }
}
}
</code>```

Body:
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}

Body:
How about using DatePicker for the date part, and the following textfields for the time input part.

import SwiftUI
import Combine

struct ContentView: View {
@State var date = Date()
var body: some View {
    NavigationView {
        NavigationLink(destination: DateHMPicker(date: self.$date)) {
            VStack {
                Text("Show time")
                Text("\(self.date)")
            }
        }
    }.navigationViewStyle(StackNavigationViewStyle())
}
}

struct DateHMPicker: View {
@State var labelText = ""
@Binding var date: Date

var body: some View {
    HStack {
        Spacer()
        DatePicker(labelText, selection: self.$date, displayedComponents: .date)
        Spacer()
        HoursMinutesPicker(date: self.$date).frame(width: 90)
    }.fixedSize()
}
}

struct TextFieldTime: View {
let range: ClosedRange<Int>
@Binding var value: Int
var handler: () -> Void

@State private var isGood = false
@State private var textValue = ""
@State private var digits = 2

var body: some View {
    TextField("", text: $textValue)
        .font(Font.body.monospacedDigit())
        .onReceive(Just(textValue)) { txt in
            // must be numbers
            var newTxt = txt.filter {"0123456789".contains($0)}
            if newTxt == txt {
                // restrict the digits
                if newTxt.count > self.digits {
                    newTxt = String(newTxt.dropLast())
                }
                // check the number
                self.isGood = false
                if let number = NumberFormatter().number(from: newTxt) {
                    if self.range.contains(number.intValue) {
                        self.textValue = newTxt
                        self.value = number.intValue
                        self.isGood = true
                    } else {
                        self.textValue = self.textValue.count == 1
                            ? String(self.range.lowerBound) : String(self.textValue.dropLast())
                    }
                }
                if self.value >= 0 && self.isGood {
                    self.handler()
                }
            } else {
                self.textValue = newTxt.isEmpty ? String(self.range.lowerBound) : newTxt
            }

    }.onAppear(perform: {
        self.textValue = String(self.value)
        self.digits = String(self.range.upperBound).count
    })
        .fixedSize()
}
}

struct HoursMinutesPicker: View {
@Binding var date: Date
@State var separator = ":"

@State var hours: Int = 0
@State var minutes: Int = 0

var body: some View {
    HStack (spacing: 1) {
        TextFieldTime(range: 0...23, value: self.$hours, handler: self.update)
        Text(separator)
        TextFieldTime(range: 0...59, value: self.$minutes, handler: self.update)
    }.onAppear(perform: loadData).padding(5)
}

func loadData() {
    self.hours = Calendar.current.component(.hour, from: date)
    self.minutes = Calendar.current.component(.minute, from: date)
}

func update() {
    let baseDate = Calendar.current.dateComponents([.year, .month, .day], from: date)
    var dc = DateComponents()
    dc.year = baseDate.year
    dc.month = baseDate.month
    dc.day = baseDate.day
    dc.hour = self.hours
    dc.minute = self.minutes
    if let newDate = Calendar.current.date(from: dc), date != newDate {
        date = newDate
    }
}
}


问:
c# constructor injection and constructor overloads
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

```<code>public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}
</code>```

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

```<code>public SomeConstructor(string name) : this(name, null)
{
}
</code>```

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.

答:
```<code>public void Save()
{
    if (_someObject == null)
        throw new InvalidOperationException();
}
</code>```

I guess that this is obvious. But you really can't create a contract in which the type is constructed differently unless you also change your SomeConstructor type to work like a decorator pattern. What the decorator pattern does is that it let's you build the inheritance hierarchy at run-time not compile-time.

You can then create different objects depending on what operations are allowed internally. This is some work for something which can easily be handled with a pre-condition for the Save method. But maybe this is what you need. And if you did it you could stipulate your contract in the constructor of SomeConstructor.

Here's an example:

```<code>interface ISomeConstructor
{
    void Save();
}

class SomeConstructor
{
    ISomeConstructor impl;

    public SomeConstructor(string name, object someObject)
    {
        impl = new StringAndObject(name, someObject);
    }

    public SomeConstructor(string name)
    {
        impl = new JustString(name);
    }

    public void Save()
    {
        impl.Save();
    }
}
</code>```

The types StringAndObject and JustString implements ISomeConstructor and they can handle the Save method as they see fit.

This is a slight variation of the decorator pattern as normally you'd expect ISomeConstructor to be passed as an argument to the constructor as well.

ContentLicense: CC BY-SA 3.0

Body:
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

public SomeConstructor(string name) : this(name, null)
{
}

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.

Body:
public void Save()
{
    if (_someObject == null)
        throw new InvalidOperationException();
}

I guess that this is obvious. But you really can't create a contract in which the type is constructed differently unless you also change your SomeConstructor type to work like a decorator pattern. What the decorator pattern does is that it let's you build the inheritance hierarchy at run-time not compile-time.

You can then create different objects depending on what operations are allowed internally. This is some work for something which can easily be handled with a pre-condition for the Save method. But maybe this is what you need. And if you did it you could stipulate your contract in the constructor of SomeConstructor.

Here's an example:

interface ISomeConstructor
{
    void Save();
}

class SomeConstructor
{
    ISomeConstructor impl;

    public SomeConstructor(string name, object someObject)
    {
        impl = new StringAndObject(name, someObject);
    }

    public SomeConstructor(string name)
    {
        impl = new JustString(name);
    }

    public void Save()
    {
        impl.Save();
    }
}

The types StringAndObject and JustString implements ISomeConstructor and they can handle the Save method as they see fit.

This is a slight variation of the decorator pattern as normally you'd expect ISomeConstructor to be passed as an argument to the constructor as well.


问:
I am receiving an infinite while loop when I run my code and enter the wrong input values. Does anyone know why, and how to fix it?
I receive an infinite while loop when I incorrectly enter the input for user_vendor or user_card. It works fine when I enter the correct values. card_check is set to the correct card value. The vendors I have listed are </p>

```<code>def user_vendor(vendor):

 while True:

    if vendor == 'Visa' or vendor == 'MasterCard' or vendor == 'American Express' or vendor == 'Discover':

        print("\nValid vendor, thank you!")
        break

    else:
        print("\nPlease enter a valid vendor.")
        continue

def user_card(card, card_check):

 while True:

    if card == card_check:

        print("\nCard matches, thank you!")
        break

    else:
        print("\nCard does not match!")
        continue

def main():

 card_check = 5412753456789010

 vendor = input("\nPlease enter your Vendor for your card (Visa, MasterCard, American Express, Discover): ")
 user_vendor(vendor)
 card = int(input("\nPlease enter your card number: "))
 user_card(card,card_check)

 return;

main()
</code>```

答:
The functions user_card and user_vendor are not updating the values of the card and vendor. Here is a better approach:

```<code>def user_vendor(vendor):

    if vendor == 'Visa' or vendor == 'MasterCard' or vendor == 'American Express' or vendor == 'Discover':
        return ("\nValid vendor, thank you!")
    else:
        return("\nPlease enter a valid vendor.")

def user_card(card, card_check):
    if card == card_check:
        return("\nCard matches, thank you!")
    else:
        return("\nCard does not match!")

def main():
    card_check = 5412753456789010
    while True:
        vendor = input("\nPlease enter your Vendor for your card (Visa, MasterCard, American Express, Discover): ")
        user_vendor_checkin = user_vendor(vendor)
        print(user_vendor_checkin)
        card = int(input("\nPlease enter your card number: "))
        user_card_checkin = user_card(card,card_check)
        print(user_card_checkin)

main()
</code>```

Of course, you can optimize more but it will works fine

Body:
I receive an infinite while loop when I incorrectly enter the input for user_vendor or user_card. It works fine when I enter the correct values. card_check is set to the correct card value. The vendors I have listed are

def user_vendor(vendor):

 while True:

    if vendor == 'Visa' or vendor == 'MasterCard' or vendor == 'American Express' or vendor == 'Discover':

        print("\nValid vendor, thank you!")
        break

    else:
        print("\nPlease enter a valid vendor.")
        continue

def user_card(card, card_check):

 while True:

    if card == card_check:

        print("\nCard matches, thank you!")
        break

    else:
        print("\nCard does not match!")
        continue

def main():

 card_check = 5412753456789010

 vendor = input("\nPlease enter your Vendor for your card (Visa, MasterCard, American Express, Discover): ")
 user_vendor(vendor)
 card = int(input("\nPlease enter your card number: "))
 user_card(card,card_check)

 return;

main()

Body:
The functions user_card and user_vendor are not updating the values of the card and vendor. Here is a better approach:

def user_vendor(vendor):

    if vendor == 'Visa' or vendor == 'MasterCard' or vendor == 'American Express' or vendor == 'Discover':
        return ("\nValid vendor, thank you!")
    else:
        return("\nPlease enter a valid vendor.")

def user_card(card, card_check):
    if card == card_check:
        return("\nCard matches, thank you!")
    else:
        return("\nCard does not match!")

def main():
    card_check = 5412753456789010
    while True:
        vendor = input("\nPlease enter your Vendor for your card (Visa, MasterCard, American Express, Discover): ")
        user_vendor_checkin = user_vendor(vendor)
        print(user_vendor_checkin)
        card = int(input("\nPlease enter your card number: "))
        user_card_checkin = user_card(card,card_check)
        print(user_card_checkin)

main()

Of course, you can optimize more but it will works fine


问:
SCRIPT errors with IE 11 when using Babel and Vue.js
We're having a problem with our Vue.js application on Windows 10 / IE 11.

The application was giving SCRIPT1003: Expected ':' until we updated out babel.config to the following:

```<code>module.exports = {
  presets: [
    [
      '@vue/cli-plugin-babel/preset',
      {
        targets: {
          'ie': '11'
        }
      }
    ]
  ]
}
</code>```

At which point the error is now SCRIPT1002: Synxax Error chunk-vendors.js (11365, 9311) which appears to relate to the vuelidate node module.

It appears that I need to exclude the above package, but I dont understand where the syntax should go.
It's also likely that there will be multiple packages that I need to exclude.

The base project was built using vue-cli 4.4.1 and the config files haven't moved far from the stock install

答:
Do you want to transpile the modules? You could use exclude property in webpack.config.js or babel.config.js to transpile modules.

You could change this line:

```<code>...
 exclude: /node_modules/,
...
</code>```

into this:

```<code>...
  exclude: /node_modules\/(?!name-of-untranspiled-module)/,
...
</code>```

If you need to exclude more than one module you can extend the exception list like so:

```<code>exclude: /node_modules\/(?![module1|module2])/
</code>```

For more information, you could refer to this link.

Body:
We're having a problem with our Vue.js application on Windows 10 / IE 11.

The application was giving SCRIPT1003: Expected ':' until we updated out babel.config to the following:

module.exports = {
  presets: [
    [
      '@vue/cli-plugin-babel/preset',
      {
        targets: {
          'ie': '11'
        }
      }
    ]
  ]
}

At which point the error is now SCRIPT1002: Synxax Error chunk-vendors.js (11365, 9311) which appears to relate to the vuelidate node module.

It appears that I need to exclude the above package, but I dont understand where the syntax should go.
It's also likely that there will be multiple packages that I need to exclude.

The base project was built using vue-cli 4.4.1 and the config files haven't moved far from the stock install

Body:
Do you want to transpile the modules? You could use exclude property in webpack.config.js or babel.config.js to transpile modules.

You could change this line:

...
 exclude: /node_modules/,
...

into this:

...
  exclude: /node_modules\/(?!name-of-untranspiled-module)/,
...

If you need to exclude more than one module you can extend the exception list like so:

exclude: /node_modules\/(?![module1|module2])/

For more information, you could refer to this link.


问:
how to to connect and use JDBCUtil
hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";

static {
    try {
        Class.forName("org.hsqldb.jdbcDriver");
    } catch (ClassNotFoundException ex) {
        System.err.println("Unable to load HSQL JDBC driver");
    }
}

public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(CONN_STR);
}
</code>```

}

but when I run it, I get the below Exception:

```<code>Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
    at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
    at ui.UI.main(UI.java:28)
</code>```

in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to  jdbc:hsqldb:hsql://localhost/?
thank U

答:
your String CONN_STR = "jdbc:hsqldb:hsql://localhost/"; should be

```<code>conn = DriverManager.getConnection(jdbc:hsqldb:hsql://localhost/xdb", "sa", "");
</code>```

In some circumstances, you may have to use the following line to get the driver.

Class.forName("org.hsqldb.jdbcDriver").newInstance();

Title: how to to connect and use JDBCUtil

Body:
hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";

static {
    try {
        Class.forName("org.hsqldb.jdbcDriver");
    } catch (ClassNotFoundException ex) {
        System.err.println("Unable to load HSQL JDBC driver");
    }
}

public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(CONN_STR);
}

}

but when I run it, I get the below Exception:

Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
    at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
    at ui.UI.main(UI.java:28)

in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to  jdbc:hsqldb:hsql://localhost/?
thank U

Body:
your String CONN_STR = "jdbc:hsqldb:hsql://localhost/"; should be

conn = DriverManager.getConnection(jdbc:hsqldb:hsql://localhost/xdb", "sa", "");

In some circumstances, you may have to use the following line to get the driver.

Class.forName("org.hsqldb.jdbcDriver").newInstance();


问:
How do I open a port for a remote Postgresql connection?
I am trying to set up a database on my computer that can be accessed remotely by others. I have modified my postgresql.conf by to listening_addresses = '*' and added host all all 0.0.0.0/0 md5to my pg_hba.conf file. When we try to connect to the database remotely, we get the error psql: could not connect to server: Connection refused Is the server running on host "MYIPADDRESS" and accepting CP/IP connections on port 5432? The port is 5432 is also closed when I got to https://www.yougetsignal.com/tools/open-ports/. How do we go about solving this problem? Let me know if I need to provide more code. Thanks in advance!

Update: Here is my log.

```<code>2020-06-01 12:00:09.385 EDT [13570] LOG:  listening on IPv6 address "::1", port 5432
2020-06-01 12:00:09.385 EDT [13570] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-06-01 12:00:09.386 EDT [13570] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
</code>```

答:
Are you sure so your database is running?

Do you see Postgres is process list? ps ax|grep postgres.

Do you see some interesting in Postgres log?

Postgres log should to contains:

```
serverlog          [----]  0 L:[  1+ 0   1/589] *(0   /50295b) 0050 0x032                                                                                [*][X]
2020-05-29 07:45:11.931 CEST [12960] LOG:  starting PostgreSQL 13beta1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 10.1.1 20200507 (Red Hat 10.1.1-1), 64-bit
2020-05-29 07:45:11.933 CEST [12960] LOG:  listening on IPv6 address "::1", port 5432
2020-05-29 07:45:11.933 CEST [12960] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-05-29 07:45:11.959 CEST [12960] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
```

If Postgres is running, then problem can be firewall. You should to open port 5432 for remote access.

Body:
I am trying to set up a database on my computer that can be accessed remotely by others. I have modified my postgresql.conf by to listening_addresses = '*' and added host all all 0.0.0.0/0 md5to my pg_hba.conf file. When we try to connect to the database remotely, we get the error psql: could not connect to server: Connection refused Is the server running on host "MYIPADDRESS" and accepting CP/IP connections on port 5432? The port is 5432 is also closed when I got to https://www.yougetsignal.com/tools/open-ports/. How do we go about solving this problem? Let me know if I need to provide more code. Thanks in advance!

Update: Here is my log.

2020-06-01 12:00:09.385 EDT [13570] LOG:  listening on IPv6 address "::1", port 5432
2020-06-01 12:00:09.385 EDT [13570] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-06-01 12:00:09.386 EDT [13570] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"

Body:
Are you sure so your database is running?

Do you see Postgres is process list? ps ax|grep postgres.

Do you see some interesting in Postgres log?

Postgres log should to contains:

serverlog          [----]  0 L:[  1+ 0   1/589] *(0   /50295b) 0050 0x032                                                                                [*][X]
2020-05-29 07:45:11.931 CEST [12960] LOG:  starting PostgreSQL 13beta1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 10.1.1 20200507 (Red Hat 10.1.1-1), 64-bit
2020-05-29 07:45:11.933 CEST [12960] LOG:  listening on IPv6 address "::1", port 5432
2020-05-29 07:45:11.933 CEST [12960] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-05-29 07:45:11.959 CEST [12960] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"

If Postgres is running, then problem can be firewall. You should to open port 5432 for remote access.


问:
How to find the starting and ending index of elements in list automatically in python
I would like to find the starting and ending index of all the userId in the list, I want to do this without specifying every single userId, because the dataset is large.

```<code>[1, 1, 1, 1, 1, 1, 1, 1, 1, 1.......213,213,213,213]
</code>```

I want the output to be

```<code>[{1: 0, 20},{2: 21, 40}.....{213: 29,703, 30,000}]
</code>```

Is there a package or function that can do this automatically in python?

答:
You can do this:

```<code>from collections import Counter

a = ...

a_counter = Counter(a)
a_indices = []

running_count = 0

for x, x_count in sorted(a_counter.items()):
   a_indices.append({x: (running_count, running_count + x_count - 1)})
   running_count += x_count
</code>```

For example, if a = [1, 1, 2, 2, 3, 3], a_indices = [{1: (0, 1)}, {2: (2, 3)}, {3: (4, 5)}] (closest to your output format, while being valid).

If you're willing to slightly change your output format, use:

```<code>a_indices = {}

running_count = 0

for x, x_count in sorted(a_counter.items()):
   a_indices[x] = (running_count, running_count + x_count - 1)
   running_count += x_count
</code>```

Now a_indices, for the a above, will be {1: (0, 1), 2: (2, 3), 3: (4, 5)}, a much nicer structure to work with.

Both of these solutions will make each end index for x inclusive. If you want to make it exclusive, replace running_count + x_count - 1 with running_count + x_count.

Body:
I would like to find the starting and ending index of all the userId in the list, I want to do this without specifying every single userId, because the dataset is large.

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1.......213,213,213,213]

I want the output to be

[{1: 0, 20},{2: 21, 40}.....{213: 29,703, 30,000}]

Is there a package or function that can do this automatically in python?

Body:
You can do this:

from collections import Counter

a = ...

a_counter = Counter(a)
a_indices = []

running_count = 0

for x, x_count in sorted(a_counter.items()):
   a_indices.append({x: (running_count, running_count + x_count - 1)})
   running_count += x_count

For example, if a = [1, 1, 2, 2, 3, 3], a_indices = [{1: (0, 1)}, {2: (2, 3)}, {3: (4, 5)}] (closest to your output format, while being valid).

If you're willing to slightly change your output format, use:

a_indices = {}

running_count = 0

for x, x_count in sorted(a_counter.items()):
   a_indices[x] = (running_count, running_count + x_count - 1)
   running_count += x_count

Now a_indices, for the a above, will be {1: (0, 1), 2: (2, 3), 3: (4, 5)}, a much nicer structure to work with.

Both of these solutions will make each end index for x inclusive. If you want to make it exclusive, replace running_count + x_count - 1 with running_count + x_count.


问:
Stripe Connection Error
I have the follow backend Node.js code to connect to my Stripe account to make a Charge. But I'm getting this error. I'm using Firebase Functions, and this functionality used to work before, so I doubt this is anything to do with Firebase access restrictions. Any ideas and help on this will be greatly appreciated!</p>

```<code>var functions = require('firebase-functions');
var stripe = require('stripe')('sk_test');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

exports.stripePay = functions.https.onRequest((request, response) => {
  if (request.method === 'POST') {
    var app = express();
    var router = express.Router();

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cors());

    var stripetoken = request.body.cardToken;
    var amountpayable = request.body.amount;

    var charge = stripe.charges.create({
      amount: amountpayable,
      currency: 'usd',
      source: stripetoken,
      description: 'Sample transaction'
    }, function (err, charge) {
      console.log("ST4");
      if (err) {
        response.send("Failed!");
      }
      else {
        response.send({ success: true });
      }
    })
  }

{ Error: An error occurred with our connection to Stripe
    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1020:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)   type: 'StripeConnectionError', stack: 'Error: An error occurred with our connection to Stripe\n    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)\n    at emitOne (events.js:96:13)\n    at ClientRequest.emit (events.js:188:7)\n    at TLSSocket.socketErrorListener (_http_client.js:310:9)\n    at emitOne (events.js:96:13)\n    at TLSSocket.emit (events.js:188:7)\n    at connectErrorNT (net.js:1020:8)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickDomainCallback (internal/process/next_tick.js:122:9)',   rawType: undefined,   code: undefined,   param: undefined,   message: 'An error occurred with our connection to Stripe',   detail:     { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
       at errnoException (dns.js:28:10)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'ENOTFOUND',
     errno: 'ENOTFOUND',
     syscall: 'getaddrinfo',
     hostname: 'api.stripe.com',
     host: 'api.stripe.com',
     port: '443' },   raw:     { message: 'An error occurred with our connection to Stripe',
     detail:
      { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
          at errnoException (dns.js:28:10)
          at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
        code: 'ENOTFOUND',
        errno: 'ENOTFOUND',
        syscall: 'getaddrinfo',
        hostname: 'api.stripe.com',
        host: 'api.stripe.com',
        port: '443' } },   requestId: undefined,   statusCode: undefined } Reply
</code>```

答: Dimitris answer is correct, in more layman's terms simply get on the blaze plan and you can make calls to stripe api from Firebase Functions.</p>

Title: Stripe Connection Error

Body:
I have the follow backend Node.js code to connect to my Stripe account to make a Charge. But I'm getting this error. I'm using Firebase Functions, and this functionality used to work before, so I doubt this is anything to do with Firebase access restrictions. Any ideas and help on this will be greatly appreciated!

var functions = require('firebase-functions');
var stripe = require('stripe')('sk_test');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

exports.stripePay = functions.https.onRequest((request, response) => {
  if (request.method === 'POST') {
    var app = express();
    var router = express.Router();

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cors());

    var stripetoken = request.body.cardToken;
    var amountpayable = request.body.amount;

    var charge = stripe.charges.create({
      amount: amountpayable,
      currency: 'usd',
      source: stripetoken,
      description: 'Sample transaction'
    }, function (err, charge) {
      console.log("ST4");
      if (err) {
        response.send("Failed!");
      }
      else {
        response.send({ success: true });
      }
    })
  }

{ Error: An error occurred with our connection to Stripe
    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1020:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)   type: 'StripeConnectionError', stack: 'Error: An error occurred with our connection to Stripe\n    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)\n    at emitOne (events.js:96:13)\n    at ClientRequest.emit (events.js:188:7)\n    at TLSSocket.socketErrorListener (_http_client.js:310:9)\n    at emitOne (events.js:96:13)\n    at TLSSocket.emit (events.js:188:7)\n    at connectErrorNT (net.js:1020:8)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickDomainCallback (internal/process/next_tick.js:122:9)',   rawType: undefined,   code: undefined,   param: undefined,   message: 'An error occurred with our connection to Stripe',   detail:     { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
       at errnoException (dns.js:28:10)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'ENOTFOUND',
     errno: 'ENOTFOUND',
     syscall: 'getaddrinfo',
     hostname: 'api.stripe.com',
     host: 'api.stripe.com',
     port: '443' },   raw:     { message: 'An error occurred with our connection to Stripe',
     detail:
      { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
          at errnoException (dns.js:28:10)
          at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
        code: 'ENOTFOUND',
        errno: 'ENOTFOUND',
        syscall: 'getaddrinfo',
        hostname: 'api.stripe.com',
        host: 'api.stripe.com',
        port: '443' } },   requestId: undefined,   statusCode: undefined } Reply


问:
Port Forwarded Python Socket Error (SERVER)
I am currently working on a Python project to control my PC remotely from across networks. Currently I have a portmap.io connection set up, (IP: 193.xxx.xxx.xx with port 1234, I’m using an OpenVPN)
When I run my Python script:

```<code>import socket
from os import system, name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = “193.xxx.xxx.xx”
PORT = 1234
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
s.send(b”Connection established”.encode(“utf-8”))
</code>```

When I run this Python script, I get this error:

OSError: [WinError 10049] The requested address is not valid in its context

I’m almost 85% sure this is because you can’t use bind() on an ip, so what should I do? The socket needs to go across networks.

答:
(SOLVED)
I used ngrok to create a tcp tunnel and used 0.0.0.0 as my local host, and used the provided details for the remote connection</p>

Body:
I am currently working on a Python project to control my PC remotely from across networks. Currently I have a portmap.io connection set up, (IP: 193.xxx.xxx.xx with port 1234, I’m using an OpenVPN)
When I run my Python script:

import socket
from os import system, name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = “193.xxx.xxx.xx”
PORT = 1234
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
s.send(b”Connection established”.encode(“utf-8”))

When I run this Python script, I get this error:

OSError: [WinError 10049] The requested address is not valid in its context

I’m almost 85% sure this is because you can’t use bind() on an ip, so what should I do? The socket needs to go across networks.


问:
Service Worker registration fails with firebase hosting and functions
Service Worker is not registered with an application builded by Nuxt.js (Universal) which is running on Firebase Functions.

I'm currently trying to build a prototype web application with Nuxt.js Universal mode and Firebase Functions.
The app uses service worker with nuxt official pwa-module to manage the session of logged in user, so that the client could send the request with authorization header to the server and server would verify the user session via Firebase Authentication.

I've already tried to run it on local server with yarn run build and yarn run start, and ensured the service worker have been correctly registered and worked perfectly.
However when I try to check the same operation with firebase serve, I receive following errors on the browser.

```<code>A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
dcbac67bb39a765db27a.js:1 Service worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
</code>```

I also found that the service worker does not send the session data to the server. Exactly same thing was reproduced when I deployed source into production with firebase deploy.

It even occurs when I completely clean project with yarn create nuxt-app, yarn run build and firebase serve. "sw.js" file indicates failed status on Chrome developer tool.

I'm not sure if it is concerned but my Firebase is on Spark plan.

My project tree.

```<code>.
├── firebase.json
├── firestore.indexes.json
├── firestore.rules
├── functions
│   ├── index.js
│   ├── nuxt
│   │   ├── App.js
│   │   ├── axios.js
│   │   ├── client.js
│   │   ├── components
│   │   ├── dist
│   │   ├── empty.js
│   │   ├── index.js
│   │   ├── loading.html
│   │   ├── middleware.js
│   │   ├── router.js
│   │   ├── server.js
│   │   ├── store.js
│   │   ├── sw.plugin.js
│   │   ├── sw.template.js
│   │   ├── utils.js
│   │   └── views
│   ├── package-lock.json
│   ├── package.json
│   └── yarn.lock
├── public
└── src
    ├── assets
    ├── components
    ├── jest.config.js
    ├── layouts
    ├── middleware
    ├── nuxt.config.js
    ├── package.json
    ├── pages
    ├── plugins
    ├── server
    ├── static
    │   └── sw.js
    ├── store
    └── test
    └── yarn.lock
</code>```

src/static/sw.js

```<code>importScripts('/_nuxt/workbox.4c4f5ca6.js')

workbox.precaching.precacheAndRoute([
  {
    "url": "/_nuxt/021e1640b53136b75c48.js",
    "revision": "2753e747206d803c793b59a324c1931b"
  },
  {
    "url": "/_nuxt/03c9e340d8692d1403a9.js",
    "revision": "2b882d73d20a0b2cfd318e9e05d3496e"
  },
  {
    "url": "/_nuxt/78bddfa6b6a4919b78d6.js",
    "revision": "70312f6623089e3b4aa6454120c1e177"
  },
  {
    "url": "/_nuxt/85c817abccdd40162004.js",
    "revision": "45448f8709d01af59bb125a1d06be23a"
  },
  {
    "url": "/_nuxt/8654a518d0f3e326c9a6.js",
    "revision": "a42426f5e7b458acc6fdf0e9e48c7d35"
  },
  {
    "url": "/_nuxt/95b421159066eff9e318.js",
    "revision": "efd1643042f804defa7212979867558a"
  },
  {
    "url": "/_nuxt/9b487bf2df1190b68565.js",
    "revision": "78837d0e624deccc85761b44f9ede9be"
  },
  {
    "url": "/_nuxt/ce59381752309c170d41.js",
    "revision": "d3e50bf27891c4efa6dff5076a0772a6"
  },
  {
    "url": "/_nuxt/d8fa6ae5ca14331879f6.js",
    "revision": "5da6698c9359df803243ecc44519b610"
  },
  {
    "url": "/_nuxt/dcbac67bb39a765db27a.js",
    "revision": "9505aa84ddb2a70b826d324433daff36"
  },
  {
    "url": "/_nuxt/dee89eef613849499c7f.js",
    "revision": "43117ed819efe3d00c963dd655894d5f"
  }
], {
  "cacheId": "justtest",
  "directoryIndex": "/",
  "cleanUrls": false
})

workbox.clientsClaim()
workbox.skipWaiting()

workbox.routing.registerRoute(new RegExp('/_nuxt/.*'), workbox.strategies.cacheFirst({}), 'GET')

workbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkFirst({}), 'GET')
</code>```

functions/index.js

```<code>const functions = require("firebase-functions")
const { Nuxt } = require("nuxt")
const express = require("express")
const app = express()

const nuxt = new Nuxt({ buildDir: "nuxt", dev: false })

function handleRequest(req, res) {
  res.setHeader('Cache-Control', 'private')
  return new Promise((resolve, reject) => {
    nuxt.render(req, res, promise => {
      promise.then(resolve).catch(reject)
    })
  })
}

app.use(handleRequest)

exports.ssr = functions.https.onRequest(app)
</code>```

Expected behavior is that sw.js working fine when I run the app with firebase serve and firebase deploy.

答:
Fellow Nuxt.js developers in 2020, Jun

If you are deploying Nuxt.js 2.12.2 project with SSR, you probably have .nuxt folder in your project directory.  Delete that, configure Workbox from nuxt.config.js if you need and run nuxt build, npm run build or yarn build.

If it works on local machine, you can try clearing caches on server to make sure all old .nuxt folders are gone and redeploy the project.

Hope this helps ✨

Body:
Service Worker is not registered with an application builded by Nuxt.js (Universal) which is running on Firebase Functions.

I'm currently trying to build a prototype web application with Nuxt.js Universal mode and Firebase Functions.
The app uses service worker with nuxt official pwa-module to manage the session of logged in user, so that the client could send the request with authorization header to the server and server would verify the user session via Firebase Authentication.

I've already tried to run it on local server with yarn run build and yarn run start, and ensured the service worker have been correctly registered and worked perfectly.
However when I try to check the same operation with firebase serve, I receive following errors on the browser.

A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE
dcbac67bb39a765db27a.js:1 Service worker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

I also found that the service worker does not send the session data to the server. Exactly same thing was reproduced when I deployed source into production with firebase deploy.

It even occurs when I completely clean project with yarn create nuxt-app, yarn run build and firebase serve. "sw.js" file indicates failed status on Chrome developer tool.

I'm not sure if it is concerned but my Firebase is on Spark plan.

My project tree.

.
├── firebase.json
├── firestore.indexes.json
├── firestore.rules
├── functions
│   ├── index.js
│   ├── nuxt
│   │   ├── App.js
│   │   ├── axios.js
│   │   ├── client.js
│   │   ├── components
│   │   ├── dist
│   │   ├── empty.js
│   │   ├── index.js
│   │   ├── loading.html
│   │   ├── middleware.js
│   │   ├── router.js
│   │   ├── server.js
│   │   ├── store.js
│   │   ├── sw.plugin.js
│   │   ├── sw.template.js
│   │   ├── utils.js
│   │   └── views
│   ├── package-lock.json
│   ├── package.json
│   └── yarn.lock
├── public
└── src
    ├── assets
    ├── components
    ├── jest.config.js
    ├── layouts
    ├── middleware
    ├── nuxt.config.js
    ├── package.json
    ├── pages
    ├── plugins
    ├── server
    ├── static
    │   └── sw.js
    ├── store
    └── test
    └── yarn.lock

src/static/sw.js

importScripts('/_nuxt/workbox.4c4f5ca6.js')

workbox.precaching.precacheAndRoute([
  {
    "url": "/_nuxt/021e1640b53136b75c48.js",
    "revision": "2753e747206d803c793b59a324c1931b"
  },
  {
    "url": "/_nuxt/03c9e340d8692d1403a9.js",
    "revision": "2b882d73d20a0b2cfd318e9e05d3496e"
  },
  {
    "url": "/_nuxt/78bddfa6b6a4919b78d6.js",
    "revision": "70312f6623089e3b4aa6454120c1e177"
  },
  {
    "url": "/_nuxt/85c817abccdd40162004.js",
    "revision": "45448f8709d01af59bb125a1d06be23a"
  },
  {
    "url": "/_nuxt/8654a518d0f3e326c9a6.js",
    "revision": "a42426f5e7b458acc6fdf0e9e48c7d35"
  },
  {
    "url": "/_nuxt/95b421159066eff9e318.js",
    "revision": "efd1643042f804defa7212979867558a"
  },
  {
    "url": "/_nuxt/9b487bf2df1190b68565.js",
    "revision": "78837d0e624deccc85761b44f9ede9be"
  },
  {
    "url": "/_nuxt/ce59381752309c170d41.js",
    "revision": "d3e50bf27891c4efa6dff5076a0772a6"
  },
  {
    "url": "/_nuxt/d8fa6ae5ca14331879f6.js",
    "revision": "5da6698c9359df803243ecc44519b610"
  },
  {
    "url": "/_nuxt/dcbac67bb39a765db27a.js",
    "revision": "9505aa84ddb2a70b826d324433daff36"
  },
  {
    "url": "/_nuxt/dee89eef613849499c7f.js",
    "revision": "43117ed819efe3d00c963dd655894d5f"
  }
], {
  "cacheId": "justtest",
  "directoryIndex": "/",
  "cleanUrls": false
})

workbox.clientsClaim()
workbox.skipWaiting()

workbox.routing.registerRoute(new RegExp('/_nuxt/.*'), workbox.strategies.cacheFirst({}), 'GET')

workbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkFirst({}), 'GET')

functions/index.js

const functions = require("firebase-functions")
const { Nuxt } = require("nuxt")
const express = require("express")
const app = express()

const nuxt = new Nuxt({ buildDir: "nuxt", dev: false })

function handleRequest(req, res) {
  res.setHeader('Cache-Control', 'private')
  return new Promise((resolve, reject) => {
    nuxt.render(req, res, promise => {
      promise.then(resolve).catch(reject)
    })
  })
}

app.use(handleRequest)

exports.ssr = functions.https.onRequest(app)

Expected behavior is that sw.js working fine when I run the app with firebase serve and firebase deploy.


问:
K8s init container restart itself
I have pod that includes one init container and one app container,
between them there is a volume with shared folder.

My issue is that once a day or even more, the init container run itself and therefore it delete the node modules from the volume, then the main app crash because of missing modules.
The app container is not making any restarts, only the init container.

is anyone familiar with this issue in k8s? why those restarts happens only in the init container?

Thanks :)

edit:
the deployment yaml file -

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "25"
  creationTimestamp: "2020-05-19T06:48:18Z"
  generation: 25
  labels:
    apps: ******
    commit: ******
  name: *******
  namespace: fleet
  resourceVersion: "24059934"
  selfLink: *******
  uid: *******
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: *******
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: *******
        commit: *******
        revision: *******
    spec:
      containers:
        image: XXXXXXXXXXXX
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /ping
            port: http
            scheme: HTTP
          initialDelaySeconds: 120
          periodSeconds: 30
          successThreshold: 1
          timeoutSeconds: 30
        name: *******
        ports:
        - containerPort: 1880
          name: http
          protocol: TCP
        readinessProbe:
          failureThreshold: 20
          httpGet:
            path: /ping
            port: http
            scheme: HTTP
          initialDelaySeconds: 20
          periodSeconds: 5
          successThreshold: 1
          timeoutSeconds: 30
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /opt/breeze
          name: workdir
      dnsPolicy: ClusterFirst
      imagePullSecrets:
      - name: flowregistrykey
      initContainers:
        image: XXXXXXXXXXXX
        imagePullPolicy: IfNotPresent
        name: get-flow-json
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /work-dir
          name: workdir
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - emptyDir: {}
        name: workdir
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2020-06-01T12:30:10Z"
    lastUpdateTime: "2020-06-01T12:30:10Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2020-05-19T06:48:18Z"
    lastUpdateTime: "2020-06-01T12:45:05Z"
    message: ReplicaSet "collection-associator.sandbox.services.collection-8784dcb9d"
      has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 25
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1
</code>```

and this image explain the problem-
the pod was created 7 days ago, but the files inside were created today, and there is no node_modules folder - because only the init container run again and not the app container so there was no mpm install

答:
the init container run itself and therefore it delete the node modules from the volume

initContainer is only run when a pod restart. Don't treat it as service or application. It should be a script, a job only for setup before your application.

then the main app crash because of missing modules.

node_modules is not dynamic loading. It's loaded when you npm start

You might want to try livenessProbe.

Many applications running for long periods of time eventually transition to broken states, and cannot recover except by being restarted. Kubernetes provides liveness probes to detect and remedy such situations.

initContainers:
  - name: set-delete-time
    command: ["/bin/sh","-c"]
    args:
      - |
        # Let's set 3600
        echo 3600 > deleteTime

...
containers:
  - name: node-app
    livenessProbe:
      exec:
        command:
        # If deleteTime > 0 exit 0
        # Else /tmp/deleteTime - $periodSeconds > /tmp/deleteTime
        - cat
        - /tmp/deleteTime
        - ...
      initialDelaySeconds: 5
      periodSeconds: 5
```

Title: K8s init container restart itself

Body:
I have pod that includes one init container and one app container,
between them there is a volume with shared folder.

My issue is that once a day or even more, the init container run itself and therefore it delete the node modules from the volume, then the main app crash because of missing modules.
The app container is not making any restarts, only the init container.

is anyone familiar with this issue in k8s? why those restarts happens only in the init container?

Thanks :)

edit:
the deployment yaml file -

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "25"
  creationTimestamp: "2020-05-19T06:48:18Z"
  generation: 25
  labels:
    apps: ******
    commit: ******
  name: *******
  namespace: fleet
  resourceVersion: "24059934"
  selfLink: *******
  uid: *******
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: *******
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: *******
        commit: *******
        revision: *******
    spec:
      containers:
        image: XXXXXXXXXXXX
        imagePullPolicy: IfNotPresent
        livenessProbe:
          failureThreshold: 3
          httpGet:
            path: /ping
            port: http
            scheme: HTTP
          initialDelaySeconds: 120
          periodSeconds: 30
          successThreshold: 1
          timeoutSeconds: 30
        name: *******
        ports:
        - containerPort: 1880
          name: http
          protocol: TCP
        readinessProbe:
          failureThreshold: 20
          httpGet:
            path: /ping
            port: http
            scheme: HTTP
          initialDelaySeconds: 20
          periodSeconds: 5
          successThreshold: 1
          timeoutSeconds: 30
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /opt/breeze
          name: workdir
      dnsPolicy: ClusterFirst
      imagePullSecrets:
      - name: flowregistrykey
      initContainers:
        image: XXXXXXXXXXXX
        imagePullPolicy: IfNotPresent
        name: get-flow-json
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /work-dir
          name: workdir
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - emptyDir: {}
        name: workdir
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2020-06-01T12:30:10Z"
    lastUpdateTime: "2020-06-01T12:30:10Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2020-05-19T06:48:18Z"
    lastUpdateTime: "2020-06-01T12:45:05Z"
    message: ReplicaSet "collection-associator.sandbox.services.collection-8784dcb9d"
      has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 25
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

and this image explain the problem-
the pod was created 7 days ago, but the files inside were created today, and there is no node_modules folder - because only the init container run again and not the app container so there was no mpm install


问:
Passing user provided docker build argument to python program
I am trying to take user input as build argument for Dockerfile and trying to pass the same to python program. Here is my use case :

```<code>Dockerfile :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t ${number}

app.py

import argparse
import time

def input():
    parser = argparse.ArgumentParser()
    parser.add_argument('number', help='take program number as input')
    args = parser.parse_args()
    return args

def root(args):
    for i in range(10):
        print("Hello World from : " + str(args.number))
        time.sleep(2)

if __name__ == "__main__":
    args = input()
    root(args)
</code>```

Docker build command :

docker build -t passarg:1 --build-arg number=1 .

Docker run command :

docker run passarg:1

Error :

usage: app.py [-h] number

app.py: error: the following arguments are required: number

答:
Build arguments go out of scope once the build is complete. As such, when the command is run (when you try to start the container), the argument has no value. Instead use an environment variable which maintains its value.
You can do something like this if you still want to use a build argument :</p>

```<code>FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
ENV num ${number}
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t $num
</code>```

Body:
I am trying to take user input as build argument for Dockerfile and trying to pass the same to python program. Here is my use case :

Dockerfile :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t ${number}

app.py

import argparse
import time

def input():
    parser = argparse.ArgumentParser()
    parser.add_argument('number', help='take program number as input')
    args = parser.parse_args()
    return args

def root(args):
    for i in range(10):
        print("Hello World from : " + str(args.number))
        time.sleep(2)

if __name__ == "__main__":
    args = input()
    root(args)

Docker build command :

docker build -t passarg:1 --build-arg number=1 .

Docker run command :

docker run passarg:1

Error :

usage: app.py [-h] number

app.py: error: the following arguments are required: number

Body:
Build arguments go out of scope once the build is complete. As such, when the command is run (when you try to start the container), the argument has no value. Instead use an environment variable which maintains its value.
You can do something like this if you still want to use a build argument :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
ENV num ${number}
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t $num


问:
How to rename a component in Angular CLI?
Is there any shortcut to rename a component with the Angular CLI other than manually editing all the component files such as folder name, .css, .ts, spec.ts and app.module.ts? </p>

答: In WebStorm, you can right click → Refactor → Rename on the name of the component in the TypeScript file and it will change the name everywhere.</p>