问:
Modifying Response of Graphql before sent out
I am looking for a way to modify the response object of a graphql query or mutation before it gets sent out.

Basically in addition the the data object, I want to have extra fields like code and message.

At the moment I am solving this by adding the fields directly into my GQL schemas take this type definition for example:

```<code>type Query {
  myItems: myItemResponse
}

type myItemResponse {
  myItem: Item
  code: String!
  success: Boolean!
  message: String!
}
</code>```

The response itself would be look like that:

```<code>{
   data: {
      myItems: {
         myItem: [ ... fancy Items ... ],
         message: 'successfully retrieved fancy Items',
         code: <CODE_FOR_SUCCESSFUL_QUERY>
      }
   }
}
</code>```

I find that solution not nice because it overcomplicates things in my FrontEnd.

I would prefer a solution where message code and other Metadata are seperated from the actual data, so something like this:

```<code>{
   data: {
      myItems: [ ... fancy Items ... ],
   },
   message: 'successfully retrieved fancy Items',
   code: <CODE_FOR_SUCCESSFUL_QUERY>
}
</code>```

With apollo-server I already tried the formatResponse object in the constructor:

```<code>const server = new ApolloServer({
   ...
   formatResponse({ data }) {
     return {
        data,
        test: 'Property to test if shown in the FrontEnd',
     }
   }
   ...
}
</code>```

unfortunately that doesn't have the desired effect. Before I use express middlewares I want to ask if there is a possibility to do this via apollo-server out of the box or if I am maybe just missing something in the formatResponse function.

答:
from graphql.org:
A response to a GraphQL operation must be a map.

If the operation encountered any errors, the response map must contain an entry with key errors. The value of this entry is described in the “Errors” section. If the operation completed without encountering any errors, this entry must not be present.

If the operation included execution, the response map must contain an entry with key data. The value of this entry is described in the “Data” section. If the operation failed before execution, due to a syntax error, missing information, or validation error, this entry must not be present.

The response map may also contain an entry with key extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

To ensure future changes to the protocol do not break existing servers and clients, the top level response map must not contain any entries other than the three described above.

Body:
I am looking for a way to modify the response object of a graphql query or mutation before it gets sent out.

Basically in addition the the data object, I want to have extra fields like code and message.

At the moment I am solving this by adding the fields directly into my GQL schemas take this type definition for example:

type Query {
  myItems: myItemResponse
}

type myItemResponse {
  myItem: Item
  code: String!
  success: Boolean!
  message: String!
}

The response itself would be look like that:

{
   data: {
      myItems: {
         myItem: [ ... fancy Items ... ],
         message: 'successfully retrieved fancy Items',
         code: <CODE_FOR_SUCCESSFUL_QUERY>
      }
   }
}

I find that solution not nice because it overcomplicates things in my FrontEnd.

I would prefer a solution where message code and other Metadata are seperated from the actual data, so something like this:

{
   data: {
      myItems: [ ... fancy Items ... ],
   },
   message: 'successfully retrieved fancy Items',
   code: <CODE_FOR_SUCCESSFUL_QUERY>
}

With apollo-server I already tried the formatResponse object in the constructor:

const server = new ApolloServer({
   ...
   formatResponse({ data }) {
     return {
        data,
        test: 'Property to test if shown in the FrontEnd',
     }
   }
   ...
}

unfortunately that doesn't have the desired effect. Before I use express middlewares I want to ask if there is a possibility to do this via apollo-server out of the box or if I am maybe just missing something in the formatResponse function.


来源: stackexchange

问:
Aligning QGridLayouts
I'm trying to create a 'table' where the headers and row labels remain visible. Kind of like the Frozen Column Example, but using a QGridLayout.

My approach is to put three QGridLayouts into aligned QScrollAreas, where the main table contains RxC rows and columns and is scrollable in any direction, and the column and row headers are contained in 1xC and Rx1 cells, respectively. Then I can just get the different QScrollAreas to track each other.

I've got this working (though I haven't touched the matched-scrolling bit yet), but I'm having a lot of trouble getting the three different QGridLayouts to have the same size cells (in width or height).

Part of the problem is that the table cells can be variously sized, meaning that each row and column is not the same height/width as all of the others. But I also can't figure out how to get the heights/widths of the rows of the different QGridLayouts to match.

As you can see in the image above, there are three rows and two columns. I want the Row Headers to line up with the three rows, and the Column Headers to line up with the two columns.

Here's a minimal example. There's a lot still for me to figure out and get working, but this first step is an important one.

```<code>import PyQt5.QtGui
import PyQt5.QtWidgets
import PyQt5.QtCore

class MainBuyerWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(PyQt5.QtWidgets.QMainWindow, self).__init__(*args, **kwargs)

        (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        ) = self.setup_table()

        self.columns_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.rows_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.table_scroll_widget = PyQt5.QtWidgets.QScrollArea()

        self.columns_scroll_widget.setWidget(columns_widget)
        self.rows_scroll_widget.setWidget(rows_widget)
        self.table_scroll_widget.setWidget(table_widget)

        central_layout = PyQt5.QtWidgets.QGridLayout()
        central_layout.addWidget(self.columns_scroll_widget, 0, 1, 1, 5)
        central_layout.addWidget(   self.rows_scroll_widget, 1, 0, 5, 1)
        central_layout.addWidget(  self.table_scroll_widget, 1, 1, 5, 5)

        central_widget = PyQt5.QtWidgets.QWidget()
        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)
        self.show()

    def setup_table(self):
        columns_layout = PyQt5.QtWidgets.QGridLayout()
        rows_layout = PyQt5.QtWidgets.QGridLayout()
        table_layout = PyQt5.QtWidgets.QGridLayout()

        columns_widget = PyQt5.QtWidgets.QWidget()
        columns_widget.setLayout(columns_layout)

        rows_widget = PyQt5.QtWidgets.QWidget()
        rows_widget.setLayout(rows_layout)

        table_widget = PyQt5.QtWidgets.QWidget()
        table_widget.setLayout(table_layout)

        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell\nis a\ntall one"),      0, 0)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell is shorter"),           1, 0)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell is of\nmedium height"), 2, 0)

        table_layout.addWidget(PyQt5.QtWidgets.QLabel("Also notice that widths of columns are not all the same"), 0, 1)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("Though that doesn't matter"),  1, 1)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("(In this example anyway)"),    2, 1)

        columns_layout.addWidget(PyQt5.QtWidgets.QLabel("Column Header 1"), 0, 0)
        columns_layout.addWidget(PyQt5.QtWidgets.QLabel("Column Header 2"), 0, 1)

        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 1"), 0, 0)
        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 2"), 1, 0)
        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 3"), 2, 0)

        return (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        )

######################################################################

if __name__ == "__main__":

    app = PyQt5.QtWidgets.QApplication([])
    window = MainBuyerWindow()
    app.exec_()
</code>```

I think my main problem is I don't understand Qt well enough, so I'm not sure what to look at. What I tried was calling the show() (or activate()) method to get the geometries all worked out, and then going through the first row and column of the table_layout to get their dimensions using cellRect, and then calling columnMinimumWidth and rowMinimumHeight on the corresponding row/column of rows_layout and columns_layout.

This is the same idea used in this (almost identical) question, but when I implement it here it also doesn't seem to work. (Essentially just adding the following lines)

```<code>        table_layout.activate()

        for i in range(table_layout.columnCount()):
            w = table_layout.columnMinimumWidth(i)
            columns_layout.setColumnMinimumWidth(i, w)

        for i in range(table_layout.rowCount()):
            h = table_layout.rowMinimumHeight(i)
            rows_layout.setRowMinimumHeight(i, h)
</code>```

Can someone help me out here? Thank you so much!

答:
I would set a fixed height to each row header label based on the height of that row in the table (and similarly a fixed width to each column header label based on the width of that column in the table), which fixes the layout alignment but also makes it simple to match up the scrolling.

```<code>class MainBuyerWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(PyQt5.QtWidgets.QMainWindow, self).__init__(*args, **kwargs)

        (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        ) = self.setup_table()

        self.columns_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.rows_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.table_scroll_widget = PyQt5.QtWidgets.QScrollArea()

        self.columns_scroll_widget.setWidget(columns_widget)
        self.rows_scroll_widget.setWidget(rows_widget)
        self.table_scroll_widget.setWidget(table_widget)

        for i in range(rows_layout.count()):
            label = rows_layout.itemAt(i).widget()
            label.setFixedHeight(table_layout.cellRect(i, 0).height())
        for i in range(columns_layout.count()):
            label = columns_layout.itemAt(i).widget()
            label.setFixedWidth(table_layout.cellRect(0, i).width())
        ...
</code>```

Use QScrollArea.setWidgetResizable(True) so the scroll area can resize the widget as needed, and allow the header labels to take up the required amount of space to be aligned with the table.

```<code>        ...
        self.columns_scroll_widget.setWidgetResizable(True)
        self.rows_scroll_widget.setWidgetResizable(True)
        self.table_scroll_widget.setWidgetResizable(True)

        # Size policies to keep the row and column headers minimal/sufficient
        # and allow table_scroll_widget to get as much space as possible when resized
        self.columns_scroll_widget.setSizePolicy(PyQt5.QtWidgets.QSizePolicy.Preferred, PyQt5.QtWidgets.QSizePolicy.Minimum)
        self.rows_scroll_widget.setSizePolicy(PyQt5.QtWidgets.QSizePolicy.Minimum, PyQt5.QtWidgets.QSizePolicy.Preferred)
        ...
</code>```

QScrollBar inherits from QAbstractSlider so you can connect its valueChanged signal to the setValue slot of another scroll bar. These values will be consistent across the layouts now since their row heights and column widths are equal.

```<code>        ...
        # User scrolling in table will cause headers to scroll
        self.table_scroll_widget.horizontalScrollBar().valueChanged[int].connect(self.columns_scroll_widget.horizontalScrollBar().setValue)
        self.table_scroll_widget.verticalScrollBar().valueChanged[int].connect(self.rows_scroll_widget.verticalScrollBar().setValue)

        # User scrolling on headers will cause table to scroll
        self.columns_scroll_widget.horizontalScrollBar().valueChanged[int].connect(self.table_scroll_widget.horizontalScrollBar().setValue)
        self.rows_scroll_widget.verticalScrollBar().valueChanged[int].connect(self.table_scroll_widget.verticalScrollBar().setValue)

        central_layout = PyQt5.QtWidgets.QGridLayout()
        central_layout.addWidget(self.columns_scroll_widget, 0, 1, 1, 5)
        central_layout.addWidget(   self.rows_scroll_widget, 1, 0, 5, 1)
        central_layout.addWidget(  self.table_scroll_widget, 1, 1, 5, 5)

        central_widget = PyQt5.QtWidgets.QWidget()
        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)
        self.show()
</code>```

Outcome:

ContentLicense: CC BY-SA 4.0

Title: Aligning QGridLayouts

Body:
I'm trying to create a 'table' where the headers and row labels remain visible. Kind of like the Frozen Column Example, but using a QGridLayout.

My approach is to put three QGridLayouts into aligned QScrollAreas, where the main table contains RxC rows and columns and is scrollable in any direction, and the column and row headers are contained in 1xC and Rx1 cells, respectively. Then I can just get the different QScrollAreas to track each other.

I've got this working (though I haven't touched the matched-scrolling bit yet), but I'm having a lot of trouble getting the three different QGridLayouts to have the same size cells (in width or height).

Part of the problem is that the table cells can be variously sized, meaning that each row and column is not the same height/width as all of the others. But I also can't figure out how to get the heights/widths of the rows of the different QGridLayouts to match.

As you can see in the image above, there are three rows and two columns. I want the Row Headers to line up with the three rows, and the Column Headers to line up with the two columns.

Here's a minimal example. There's a lot still for me to figure out and get working, but this first step is an important one.

import PyQt5.QtGui
import PyQt5.QtWidgets
import PyQt5.QtCore

class MainBuyerWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(PyQt5.QtWidgets.QMainWindow, self).__init__(*args, **kwargs)

        (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        ) = self.setup_table()

        self.columns_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.rows_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.table_scroll_widget = PyQt5.QtWidgets.QScrollArea()

        self.columns_scroll_widget.setWidget(columns_widget)
        self.rows_scroll_widget.setWidget(rows_widget)
        self.table_scroll_widget.setWidget(table_widget)

        central_layout = PyQt5.QtWidgets.QGridLayout()
        central_layout.addWidget(self.columns_scroll_widget, 0, 1, 1, 5)
        central_layout.addWidget(   self.rows_scroll_widget, 1, 0, 5, 1)
        central_layout.addWidget(  self.table_scroll_widget, 1, 1, 5, 5)

        central_widget = PyQt5.QtWidgets.QWidget()
        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)
        self.show()

    def setup_table(self):
        columns_layout = PyQt5.QtWidgets.QGridLayout()
        rows_layout = PyQt5.QtWidgets.QGridLayout()
        table_layout = PyQt5.QtWidgets.QGridLayout()

        columns_widget = PyQt5.QtWidgets.QWidget()
        columns_widget.setLayout(columns_layout)

        rows_widget = PyQt5.QtWidgets.QWidget()
        rows_widget.setLayout(rows_layout)

        table_widget = PyQt5.QtWidgets.QWidget()
        table_widget.setLayout(table_layout)

        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell\nis a\ntall one"),      0, 0)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell is shorter"),           1, 0)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("This cell is of\nmedium height"), 2, 0)

        table_layout.addWidget(PyQt5.QtWidgets.QLabel("Also notice that widths of columns are not all the same"), 0, 1)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("Though that doesn't matter"),  1, 1)
        table_layout.addWidget(PyQt5.QtWidgets.QLabel("(In this example anyway)"),    2, 1)

        columns_layout.addWidget(PyQt5.QtWidgets.QLabel("Column Header 1"), 0, 0)
        columns_layout.addWidget(PyQt5.QtWidgets.QLabel("Column Header 2"), 0, 1)

        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 1"), 0, 0)
        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 2"), 1, 0)
        rows_layout.addWidget(PyQt5.QtWidgets.QLabel("Row Header 3"), 2, 0)

        return (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        )

######################################################################

if __name__ == "__main__":

    app = PyQt5.QtWidgets.QApplication([])
    window = MainBuyerWindow()
    app.exec_()

I think my main problem is I don't understand Qt well enough, so I'm not sure what to look at. What I tried was calling the show() (or activate()) method to get the geometries all worked out, and then going through the first row and column of the table_layout to get their dimensions using cellRect, and then calling columnMinimumWidth and rowMinimumHeight on the corresponding row/column of rows_layout and columns_layout.

This is the same idea used in this (almost identical) question, but when I implement it here it also doesn't seem to work. (Essentially just adding the following lines)

        table_layout.activate()

        for i in range(table_layout.columnCount()):
            w = table_layout.columnMinimumWidth(i)
            columns_layout.setColumnMinimumWidth(i, w)

        for i in range(table_layout.rowCount()):
            h = table_layout.rowMinimumHeight(i)
            rows_layout.setRowMinimumHeight(i, h)

Can someone help me out here? Thank you so much!

Body:
I would set a fixed height to each row header label based on the height of that row in the table (and similarly a fixed width to each column header label based on the width of that column in the table), which fixes the layout alignment but also makes it simple to match up the scrolling.

class MainBuyerWindow(PyQt5.QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(PyQt5.QtWidgets.QMainWindow, self).__init__(*args, **kwargs)

        (
            columns_widget, rows_widget, table_widget,
            columns_layout, rows_layout, table_layout,
        ) = self.setup_table()

        self.columns_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.rows_scroll_widget = PyQt5.QtWidgets.QScrollArea()
        self.table_scroll_widget = PyQt5.QtWidgets.QScrollArea()

        self.columns_scroll_widget.setWidget(columns_widget)
        self.rows_scroll_widget.setWidget(rows_widget)
        self.table_scroll_widget.setWidget(table_widget)

        for i in range(rows_layout.count()):
            label = rows_layout.itemAt(i).widget()
            label.setFixedHeight(table_layout.cellRect(i, 0).height())
        for i in range(columns_layout.count()):
            label = columns_layout.itemAt(i).widget()
            label.setFixedWidth(table_layout.cellRect(0, i).width())
        ...

Use QScrollArea.setWidgetResizable(True) so the scroll area can resize the widget as needed, and allow the header labels to take up the required amount of space to be aligned with the table.

        ...
        self.columns_scroll_widget.setWidgetResizable(True)
        self.rows_scroll_widget.setWidgetResizable(True)
        self.table_scroll_widget.setWidgetResizable(True)

        # Size policies to keep the row and column headers minimal/sufficient
        # and allow table_scroll_widget to get as much space as possible when resized
        self.columns_scroll_widget.setSizePolicy(PyQt5.QtWidgets.QSizePolicy.Preferred, PyQt5.QtWidgets.QSizePolicy.Minimum)
        self.rows_scroll_widget.setSizePolicy(PyQt5.QtWidgets.QSizePolicy.Minimum, PyQt5.QtWidgets.QSizePolicy.Preferred)
        ...

QScrollBar inherits from QAbstractSlider so you can connect its valueChanged signal to the setValue slot of another scroll bar. These values will be consistent across the layouts now since their row heights and column widths are equal.

        ...
        # User scrolling in table will cause headers to scroll
        self.table_scroll_widget.horizontalScrollBar().valueChanged[int].connect(self.columns_scroll_widget.horizontalScrollBar().setValue)
        self.table_scroll_widget.verticalScrollBar().valueChanged[int].connect(self.rows_scroll_widget.verticalScrollBar().setValue)

        # User scrolling on headers will cause table to scroll
        self.columns_scroll_widget.horizontalScrollBar().valueChanged[int].connect(self.table_scroll_widget.horizontalScrollBar().setValue)
        self.rows_scroll_widget.verticalScrollBar().valueChanged[int].connect(self.table_scroll_widget.verticalScrollBar().setValue)

        central_layout = PyQt5.QtWidgets.QGridLayout()
        central_layout.addWidget(self.columns_scroll_widget, 0, 1, 1, 5)
        central_layout.addWidget(   self.rows_scroll_widget, 1, 0, 5, 1)
        central_layout.addWidget(  self.table_scroll_widget, 1, 1, 5, 5)

        central_widget = PyQt5.QtWidgets.QWidget()
        central_widget.setLayout(central_layout)
        self.setCentralWidget(central_widget)
        self.show()

Outcome:


问:
Create target directory outside project directory with sbt
The structure of my project is:

```<code>└───current-working-dir
    ├───my-project
        ├───src
</code>```

When I run sbt compile in current-working-dir where .sbt file looks like:

```<code>lazy val root = (project in file("my-project"))
  .settings(
    name := "my-project",
    settings,
    libraryDependencies ++= commonDependencies
  )
</code>```

then it generates target in the project directory:

```<code>└───current-working-dir
    ├───my-project
        ├───src
        ├───target
</code>```

Is it possible to make sbt to create target outside the project directory? For instance:

```<code>└───current-working-dir
    ├───my-project
        ├───src
    ├───target
</code>```

or

```<code>└───current-working-dir
    ├───my-project
        ├───src
    ├───my-project-compilation
        ├───target
</code>```

答:
Actually, I guess correct is

```<code>lazy val root = (project in file("my-project"))
  .settings(
    name := "my-project",
    settings,
    libraryDependencies ++= commonDependencies,
    target := baseDirectory.value / ".." / "my-project-compilation" / "target"
  )
</code>```

You can check that if you place file as current-working-dir/my-project/src/main/scala/App.scala then compiled class appears as current-working-dir/my-project-compilation/target/scala-2.13/classes/App.class.

Body:
The structure of my project is:

└───current-working-dir
    ├───my-project
        ├───src

When I run sbt compile in current-working-dir where .sbt file looks like:

lazy val root = (project in file("my-project"))
  .settings(
    name := "my-project",
    settings,
    libraryDependencies ++= commonDependencies
  )

then it generates target in the project directory:

└───current-working-dir
    ├───my-project
        ├───src
        ├───target

Is it possible to make sbt to create target outside the project directory? For instance:

└───current-working-dir
    ├───my-project
        ├───src
    ├───target

or

└───current-working-dir
    ├───my-project
        ├───src
    ├───my-project-compilation
        ├───target

Body:
Actually, I guess correct is

lazy val root = (project in file("my-project"))
  .settings(
    name := "my-project",
    settings,
    libraryDependencies ++= commonDependencies,
    target := baseDirectory.value / ".." / "my-project-compilation" / "target"
  )

You can check that if you place file as current-working-dir/my-project/src/main/scala/App.scala then compiled class appears as current-working-dir/my-project-compilation/target/scala-2.13/classes/App.class.


问:
Amazon AWS S3 Glacier: is there a file hierarchy
Does Amazon AWS S3 Glacier support some semblance of file hierarchy inside a Vault for Archives?

For example, in AWS S3, objects are given hierarchy via /.  For example: all_logs/some_sub_category/log.txt

I am storing multiple .tar.gz files, and would like:

All files in the same Vault

Within the Vault, files are grouped into several categories (as opposed to flat structure)

I could not find how to do this documented anywhere.  If file hierarchy inside S3 Glacier is possible, can you provide brief instructions for how to do so?

答:
Does Amazon AWS S3 Glacier support some semblance of file hierarchy inside a Vault for Archives?

No, there's no hierarchy other than "archives exist inside a vault".

For example, in AWS S3, objects are given hierarchy via /. For example: all_logs/some_sub_category/log.txt

This is actually incorrect.

S3 doesn't have any inherent hierarchy. The character / is absolutely no different than any other character valid for the key of an S3 Object.

The S3 Console — and most S3 client tools, including AWS's CLI — treat the / character in a special way. But notice that it is a client-side thing. The client will make sure that listing happens in such a way that a / behaves as most people would expect, that is, as a "hierarchy separator".

If file hierarchy inside S3 Glacier is possible, can you provide brief instructions for how to do so?

You need to keep track of your hierarchy separately. For example, when you store an archive in Glacier, you could write metadata about that archive in a database (RDS, DynamoDB, etc).

As a side note, be careful about .tar.gz in Glacier, especially if you're talking about (1) a very large archive (2) that is composed of a large number of small individual files (3) which you may want to access individually.

If those conditions are met (and in my experience they often are in real-world scenarios), then using .tar.gz will often lead to excessive costs when retrieving data.

The reason is because you pay per number of requests as well as per size of request. So while having one huge .tar.gz file may reduce your costs in terms of number of requests, the fact that gzip uses DEFLATE, which is a non-splittable compression algorithm, means that you'll have to retrieve the entire .tar.gz archive, decompress it, and finally get the one file that you actually want.

An alternative approach that solves the problem I described above — and that, at the same time, relates back to your question and my answer — is to actually first gzip the individual files, and then tar them together. The reason this solves the problem is that when you tar the files together, the individual files actually have clear bounds inside the tarball. And then, when you request a retrieval from glacier, you can request only a range of the archive. E.g., you could say, "Glacier, give me bytes between 105MB and 115MB of archive X". That way you can (1) reduce the total number of requests (since you have a single tar file), and (2) reduce the total size of the requests and storage (since you have compressed data).

Now, to know which range you need to retrieve, you'll need to store metadata somewhere — usually the same place where you will keep your hierarchy! (like I mentioned above, RDS, DynamoDB, Elasticsearch, etc).

Anyways, just an optimization that could save a tremendous amount of money in the future (and I've worked with a ton of customers who wasted a lot of money because they didn't know about this).


问:
How to incorporate multiple orders of integration into my Integrator class?
I have a working Integrator class that will compute the definite Integral of basic functions of a single variable. I have tested the integrations of some basic functions and it appears to be working correctly.

I'm now at the point where I would like to expand this class to be able to perform multiple Integrals of the same function... and this is where I've hit a roadblock...

Here is my Integrator Class and some basic usage examples:

Integrator.h

```<code>#pragma once

#include <algorithm>
#include <utility>
#include <functional>

struct Limits {
    double lower;
    double upper;

    Limits() : lower{ 0 }, upper{ 0 } {}
    Limits(double a, double b) : lower{ a }, upper{ b } {
        if (a > b) std::swap(lower, upper);
    }

    void applyLimits(double a, double b) {
        lower = a;
        upper = b;
        if (a > b) std::swap(lower, upper);
    }
};

class Integrator {
private:
    Limits limits_;
    std::function<double(double)> integrand_;

    double dx_;
    double dy_;
    double integral_;
    int step_size_;

public:
    Integrator(Limits limits, int stepSize, std::function<double(double)> integrand, double dy = 0)
        : limits_{ limits },
        step_size_{ stepSize },
        integrand_{ integrand },
        dx_{ 0 }, dy_{ 0 }
    {}
    ~Integrator() = default;

    constexpr double dx() const { return this->dx_; }
    constexpr double dy() const { return this->dy_; }
    constexpr double integral() const { return this->integral_; }

    Limits limits() const { return limits_; }
    std::function<double(double)>* integrand() { return &this->integrand_; }

    // This is always a 1st order of integration!
    constexpr double evaluate() {
        double distance = limits_.upper - limits_.lower;      // Distance is defined as X0 to XN. (upperLimit - lowerLimit)
        dx_ = distance / step_size_;                          // Calculate the amount of iterations by dividing
                                                              // the x-distance by the dx stepsize
        integral_ = 0;                                        // Initialize area to zero
        for (auto i = 0; i < step_size_; i++) {               // For each dx step or iteration calculate the area at Xi
            dy_ = integrand_(limits_.lower + i * dx_);
            double area = dy_ * dx_;                          // Where the width along x is defines as dxStepSize*i
            integral_ += area;                                // and height(dy) is f(x) at Xi. Sum all of the results
        }

        return integral_;
    }
};
</code>```

main.cpp

```<code>#include <iostream>
#include <exception>
#include <cmath>

#include "Integrator.h"

constexpr double PI = 3.14159265358979;

constexpr double funcA(double x) {
    return x;
}

constexpr double funcB(double x) {
    return (x*x);
}

constexpr double funcC(double x) {
    return ((0.5*(x*x)) + (3*x) - (1/x));
}

double funcD(double x) {
    return sin(x);
}

int main() {
    try {
        std::cout << "Integration of f(x) = x from a=3.0 to b=5.0\nwith an expected output of 8\n";
        Integrator integratorA(Limits(3.0, 5.0), 10000, &funcA);
        std::cout << integratorA.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = x^2 from a=2.0 to b=20.0\nwith an expected output of 2664\n";
        Integrator integratorB(Limits(2.0, 20.0), 10000, &funcB);
        std::cout << integratorB.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = (1\\2)x^2 + 3x - (1\\x) from a=1.0 to b=10.0\nwith an expected output of 312.6974\n";
        Integrator integratorC(Limits(1.0, 10.0), 10000, &funcC);
        std::cout << integratorC.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = sin(x) from a=0.0 to b=" <<PI<< "\nwith an expected output of 2\n";
        Integrator integratorD(Limits(0.0, PI), 10000, &funcD);
        std::cout << integratorD.evaluate() << '\n';

    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
</code>```

Output

```<code>Integration of f(x) = x from a=3.0 to b=5.0
with an expected output of 8
7.9998

Integration of f(x) = x^2 from a=2.0 to b=20.0
with an expected output of 2664
2663.64

Integration of f(x) = (1\2)x^2 + 3x - (1\x) from a=1.0 to b=10.0
with an expected output of 312.6974
312.663

Integration of f(x) = sin(x) from a=0.0 to b=3.14159
with an expected output of 2
2
</code>```

I was thinking of adding another function to this class similar to its evaluate() function... It currently looks something like this:

```<code>double integrate(Limits limits, double dy) {
    double total = 0;
    dy_ = dy;

    for (int i = 0; i < step_size_; i++) {
        double yi = limits_.lower*i*dy_;
        double dx = static_cast<double>(yi - limits.lower) / stepSize;
        double innerArea = 0;

        for (int j = 0; j < step_size_; j++) {
            Integrator inner(limits, step_size_, integrand_, dy_);
            innerArea += inner.evaluate();
        }
        double outerArea = innerArea * dy_;
        total += outerArea;
    }

    integral_ = total;
    return integral_;
}
</code>```

And this is where I'm getting confused or stumped... I'm not sure how to implement this function properly when it comes to the limits of integration with respect to the inner and outer integrals.

Take for example the following integral below:

The inner integral's upper limit is based on y for each iteration of computation... This has to be done dynamically. The outer integral is straight forward as it goes from [3,5] as opposed to [1,y].

I think I'm on the right track, but something in the above approach is totally off... I'm getting completely wrong values from expected or intended values...

Any and all suggestions and or tips are highly welcomed!

Edit - Note - I supplied the wrong image above, that has been updated...

The expected output should be: 65.582 with the correctly supplied function f(x) = 1/2x^2 + 3x - (1/x). And when I try to compute the double integral I end up getting this...

And here is the added code to the driver program or main.cpp...

```<code>std::cout << "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n";
Integrator integratorE(Limits(3, 5), 1000, &funcC);
double dy = integratorE.limits().upper - integratorE.limits().lower;
integratorE.integrate(Limits(1, integratorE.integral()), dy);
std::cout << integratorE.integral() << '\n';
</code>```

However, it is not printing anything to the console...

Edit

I wasn't getting output for I wasn't waiting long enough. The iterations were defined as 1000 by the step_size. This will end up generating 1000^1000 total iterations... I had overlooked this in the construction of the Integrator object. I had changed this in my code to have a step_size of 100. And now my application is outputting a value of 2.68306e+189 which is clearly wrong! When I increase the step_size to 500 it is giving me something on the order of 6.62804e+190 which is still wrong.

答:
After going back and watching the video again... I started to break down the double looping structure in my class's integrate() function.

I removed some unneeded parameters from both the constructor and this function's signature. I removed the dependency of passing in the dy since I'm able to calculate and store this value internally.

I had done a minor overhaul of my integrate member function. I'm now calculating both the dy and dx at the appropriate times using the appropriate limits of integration with respect to the step_size.

Instead of creating an instance of an Integrator within this function and using that instance's evaluate() function. I completely removed this behavior since I don't need to do this as this class stores an instance of the function of integration called integrand where this is an std::function<T> object. With this, I can just calculate the current y by passing in the xi into that integrand. Then I can use that to calculate the inner area for the summation.

My updated function looks like this:

```<code>double integrate(double lower = 0.0, double upper = 0.0) {
    // Since we are not using the inner upper limit directly
    // make sure that it is still greater than the lower limit
    if (upper <= lower) {
        upper = lower + 1;
    }
    Limits limits(lower, upper);

    double outerSum = 0;
    dy_ = static_cast<double>(limits_.upper - limits_.lower) / step_size_;

    for (int i = 0; i < step_size_; i++) {
        double yi = limits_.lower+i*dy_;
        double dx_ = static_cast<double>(yi - limits.lower) / step_size_;
        double innerSum = 0;

        for (int j = 0; j < step_size_; j++) {
            double xi = limits.lower + dx_ * j;
            double fx = integrand_(xi);
            double innerArea = fx*dx_;
            innerSum += innerArea;
        }
        double outerArea = innerSum * dy_;
        outerSum += outerArea;
    }

    integral_ = outerSum;
    return integral_;
}
</code>```

And here is the usage of this function within my main class:

```<code>std::cout << "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n";
Integrator integratorE(Limits(3, 5), 100, &funcC);
//double dy = integratorE.limits().upper - integratorE.limits().lower;
integratorE.integrate(1);
std::cout << integratorE.integral() << '\n';
</code>```

And this is giving me an output of:

```<code>Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y]
with an expected output of 65.582
64.6426
</code>```

With a step_size of 100 iterations and an output of:

```<code>Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y]
with an expected output of 65.582
65.3933
</code>```

With a step_size of 500 iterations.

So as this class now stands, I can use evaluate() to perform a single definite integration of a single variable and I can use integrate(lower,upper) to perform at least a double definite integration of a single variable.

Body:
I have a working Integrator class that will compute the definite Integral of basic functions of a single variable. I have tested the integrations of some basic functions and it appears to be working correctly.

I'm now at the point where I would like to expand this class to be able to perform multiple Integrals of the same function... and this is where I've hit a roadblock...

Here is my Integrator Class and some basic usage examples:

Integrator.h

#pragma once

#include <algorithm>
#include <utility>
#include <functional>

struct Limits {
    double lower;
    double upper;

    Limits() : lower{ 0 }, upper{ 0 } {}
    Limits(double a, double b) : lower{ a }, upper{ b } {
        if (a > b) std::swap(lower, upper);
    }

    void applyLimits(double a, double b) {
        lower = a;
        upper = b;
        if (a > b) std::swap(lower, upper);
    }
};

class Integrator {
private:
    Limits limits_;
    std::function<double(double)> integrand_;

    double dx_;
    double dy_;
    double integral_;
    int step_size_;

public:
    Integrator(Limits limits, int stepSize, std::function<double(double)> integrand, double dy = 0)
        : limits_{ limits },
        step_size_{ stepSize },
        integrand_{ integrand },
        dx_{ 0 }, dy_{ 0 }
    {}
    ~Integrator() = default;

    constexpr double dx() const { return this->dx_; }
    constexpr double dy() const { return this->dy_; }
    constexpr double integral() const { return this->integral_; }

    Limits limits() const { return limits_; }
    std::function<double(double)>* integrand() { return &this->integrand_; }

    // This is always a 1st order of integration!
    constexpr double evaluate() {
        double distance = limits_.upper - limits_.lower;      // Distance is defined as X0 to XN. (upperLimit - lowerLimit)
        dx_ = distance / step_size_;                          // Calculate the amount of iterations by dividing
                                                              // the x-distance by the dx stepsize
        integral_ = 0;                                        // Initialize area to zero
        for (auto i = 0; i < step_size_; i++) {               // For each dx step or iteration calculate the area at Xi
            dy_ = integrand_(limits_.lower + i * dx_);
            double area = dy_ * dx_;                          // Where the width along x is defines as dxStepSize*i
            integral_ += area;                                // and height(dy) is f(x) at Xi. Sum all of the results
        }

        return integral_;
    }
};

main.cpp

#include <iostream>
#include <exception>
#include <cmath>

#include "Integrator.h"

constexpr double PI = 3.14159265358979;

constexpr double funcA(double x) {
    return x;
}

constexpr double funcB(double x) {
    return (x*x);
}

constexpr double funcC(double x) {
    return ((0.5*(x*x)) + (3*x) - (1/x));
}

double funcD(double x) {
    return sin(x);
}

int main() {
    try {
        std::cout << "Integration of f(x) = x from a=3.0 to b=5.0\nwith an expected output of 8\n";
        Integrator integratorA(Limits(3.0, 5.0), 10000, &funcA);
        std::cout << integratorA.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = x^2 from a=2.0 to b=20.0\nwith an expected output of 2664\n";
        Integrator integratorB(Limits(2.0, 20.0), 10000, &funcB);
        std::cout << integratorB.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = (1\\2)x^2 + 3x - (1\\x) from a=1.0 to b=10.0\nwith an expected output of 312.6974\n";
        Integrator integratorC(Limits(1.0, 10.0), 10000, &funcC);
        std::cout << integratorC.evaluate() << '\n';

        std::cout << "\n\nIntegration of f(x) = sin(x) from a=0.0 to b=" <<PI<< "\nwith an expected output of 2\n";
        Integrator integratorD(Limits(0.0, PI), 10000, &funcD);
        std::cout << integratorD.evaluate() << '\n';

    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Output

Integration of f(x) = x from a=3.0 to b=5.0
with an expected output of 8
7.9998

Integration of f(x) = x^2 from a=2.0 to b=20.0
with an expected output of 2664
2663.64

Integration of f(x) = (1\2)x^2 + 3x - (1\x) from a=1.0 to b=10.0
with an expected output of 312.6974
312.663

Integration of f(x) = sin(x) from a=0.0 to b=3.14159
with an expected output of 2
2

I was thinking of adding another function to this class similar to its evaluate() function... It currently looks something like this:

double integrate(Limits limits, double dy) {
    double total = 0;
    dy_ = dy;

    for (int i = 0; i < step_size_; i++) {
        double yi = limits_.lower*i*dy_;
        double dx = static_cast<double>(yi - limits.lower) / stepSize;
        double innerArea = 0;

        for (int j = 0; j < step_size_; j++) {
            Integrator inner(limits, step_size_, integrand_, dy_);
            innerArea += inner.evaluate();
        }
        double outerArea = innerArea * dy_;
        total += outerArea;
    }

    integral_ = total;
    return integral_;
}

And this is where I'm getting confused or stumped... I'm not sure how to implement this function properly when it comes to the limits of integration with respect to the inner and outer integrals.

Take for example the following integral below:

The inner integral's upper limit is based on y for each iteration of computation... This has to be done dynamically. The outer integral is straight forward as it goes from [3,5] as opposed to [1,y].

I think I'm on the right track, but something in the above approach is totally off... I'm getting completely wrong values from expected or intended values...

Any and all suggestions and or tips are highly welcomed!

Edit - Note - I supplied the wrong image above, that has been updated...

The expected output should be: 65.582 with the correctly supplied function f(x) = 1/2x^2 + 3x - (1/x). And when I try to compute the double integral I end up getting this...

And here is the added code to the driver program or main.cpp...

std::cout << "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n";
Integrator integratorE(Limits(3, 5), 1000, &funcC);
double dy = integratorE.limits().upper - integratorE.limits().lower;
integratorE.integrate(Limits(1, integratorE.integral()), dy);
std::cout << integratorE.integral() << '\n';

However, it is not printing anything to the console...

Edit

I wasn't getting output for I wasn't waiting long enough. The iterations were defined as 1000 by the step_size. This will end up generating 1000^1000 total iterations... I had overlooked this in the construction of the Integrator object. I had changed this in my code to have a step_size of 100. And now my application is outputting a value of 2.68306e+189 which is clearly wrong! When I increase the step_size to 500 it is giving me something on the order of 6.62804e+190 which is still wrong.

Body:
After going back and watching the video again... I started to break down the double looping structure in my class's integrate() function.

I removed some unneeded parameters from both the constructor and this function's signature. I removed the dependency of passing in the dy since I'm able to calculate and store this value internally.

I had done a minor overhaul of my integrate member function. I'm now calculating both the dy and dx at the appropriate times using the appropriate limits of integration with respect to the step_size.

Instead of creating an instance of an Integrator within this function and using that instance's evaluate() function. I completely removed this behavior since I don't need to do this as this class stores an instance of the function of integration called integrand where this is an std::function<T> object. With this, I can just calculate the current y by passing in the xi into that integrand. Then I can use that to calculate the inner area for the summation.

My updated function looks like this:

double integrate(double lower = 0.0, double upper = 0.0) {
    // Since we are not using the inner upper limit directly
    // make sure that it is still greater than the lower limit
    if (upper <= lower) {
        upper = lower + 1;
    }
    Limits limits(lower, upper);

    double outerSum = 0;
    dy_ = static_cast<double>(limits_.upper - limits_.lower) / step_size_;

    for (int i = 0; i < step_size_; i++) {
        double yi = limits_.lower+i*dy_;
        double dx_ = static_cast<double>(yi - limits.lower) / step_size_;
        double innerSum = 0;

        for (int j = 0; j < step_size_; j++) {
            double xi = limits.lower + dx_ * j;
            double fx = integrand_(xi);
            double innerArea = fx*dx_;
            innerSum += innerArea;
        }
        double outerArea = innerSum * dy_;
        outerSum += outerArea;
    }

    integral_ = outerSum;
    return integral_;
}

And here is the usage of this function within my main class:

std::cout << "\n\nTesting Double Integration of f(x) = (1\\2)x^2 + 3x - (1\\x) from [3,5] and [1,y]\nwith an expected output of 65.582\n";
Integrator integratorE(Limits(3, 5), 100, &funcC);
//double dy = integratorE.limits().upper - integratorE.limits().lower;
integratorE.integrate(1);
std::cout << integratorE.integral() << '\n';

And this is giving me an output of:

Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y]
with an expected output of 65.582
64.6426

With a step_size of 100 iterations and an output of:

Testing Double Integration of f(x) = (1\2)x^2 + 3x - (1\x) from [3,5] and [1,y]
with an expected output of 65.582
65.3933

With a step_size of 500 iterations.

So as this class now stands, I can use evaluate() to perform a single definite integration of a single variable and I can use integrate(lower,upper) to perform at least a double definite integration of a single variable.


问:
where is data stored?
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
</code>```

model class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}
</code>```

view.cshtml

```<code>@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            name
        </th>
        <th>
            fname
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.fname)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>
</code>```

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.

答:
it looks like its done through

private logindata db = new
  logindata();

Do you have that part in details?

ContentLicense: CC BY-SA 3.0

Title: where is data stored?

Body:
i am designing a project in .net 4.0 using mvc3. I am using two attribute name and fname(father name).

my controller class:

loginController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class loginController : Controller
    {
        private logindata db = new logindata();

        //
        // GET: /login/

        public ViewResult Index()
        {
            return View(db.loginobj.ToList());
        }

        //
        // GET: /login/Details/5

        public ViewResult Details(int id)
        {
          //  login login = db.loginobj.Find(id);
            login login = db.loginobj.Find(2) ;
            return View(login);
        }

        //
        // GET: /login/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /login/Create

        [HttpPost]
        public ActionResult Create(login login)
        {
            if (ModelState.IsValid)
            {
                db.loginobj.Add(login);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(login);
        }

        //
        // GET: /login/Edit/5

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

model class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
login.cs

namespace MvcMovie.Models
{
    public class login
    {
        public int ID { get; set; }
        public string name{get; set;}
        public string fname { get; set; }
    }
    public class logindata : DbContext
    {
        public DbSet<login> loginobj { get; set; }
    }
}

view.cshtml

@model IEnumerable<MvcMovie.Models.login>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            name

            fname

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.name)

            @Html.DisplayFor(modelItem => item.fname)

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

}

I want to ask that where is data stored which is created by me? means how can I see that table of entries which is done by me?

whenever i click of .sdf file then there is a problem occured as shown in following picture, what should i do to solve this problem. should i installed something. i installed visual studio 2010 and sql server 2008.


问:
Why does PySpark throw a JSONDecodeError when attempting to load a string from a Kafka topic to a dictionary?
I am using Spark Structured Streaming to read from a Kafka topic (records are in JSON format) with the intent of performing some transformations once I get the data into Spark. My first step is to read records from the topic as strings and then convert them to a dictionary (via the python json library) to perform transformations (I do not want to use the to_json capability within Spark because the format of the records in my Kafka topic may change and I do not want to use Spark Streaming which does not require a schema because there is no native functionality to write back to topics). I received a JSONDecodeError (below) when attempting to convert the strings.

Here are the components which produce my error:

I run the following PySpark Code locally:

from pyspark.sql.functions import udf
from pyspark.sql import SparkSession
import pyspark
import json
from pyspark.sql.types import StringType

def str_to_json(s):
    j = json.loads(s)
    return j

if __name__ == "__main__":
    spark = SparkSession.builder \
        .master("local") \
        .appName("App Name") \
        .getOrCreate()

    strToJson = udf(str_to_json, StringType())

    spark.udf.register("strToJson", strToJson)

    df = spark \
        .readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "first_topic") \
        .load() \
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

    df_transformed = df.withColumn('strToJson', strToJson('value'))

    query = df_transformed \
        .writeStream \
        .format("console") \
        .outputMode("update") \
        .start()
```

<p>I then write a record to my Kafka topic using the <code>kafka-console-producer</code> also from my local machine in the following format:</p>

```'{"name":"bob"}'
```

<p>The following error is then outputted to the console when Spark attempts to use the UDF to convert the value of a record (from the Kafka Topic) to a JSON/dictionary object within the PySpark job:</p>

```raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:452)
    at org.apache.spark.sql.execution.python.PythonUDFRunner$$anon$1.read(PythonUDFRunner.scala:81)
    at org.apache.spark.sql.execution.python.PythonUDFRunner$$anon$1.read(PythonUDFRunner.scala:64)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:406)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$13$$anon$1.hasNext(WholeStageCodegenExec.scala:636)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$$anonfun$run$3.apply(WriteToDataSourceV2Exec.scala:117)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$$anonfun$run$3.apply(WriteToDataSourceV2Exec.scala:116)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1394)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$.run(WriteToDataSourceV2Exec.scala:146)
    at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec$$anonfun$doExecute$2.apply(WriteToDataSourceV2Exec.scala:67)
    at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec$$anonfun$doExecute$2.apply(WriteToDataSourceV2Exec.scala:66)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
```

<p>I added a couple debugging print statements within the UDF to see what value is being passed in:</p>

```>>> type(s)
<class 'str'>

>>> print(s)
'{"name": "bob"}'
```

答:
Can you try below code to produce a json message to kafka console producer?

keep the json records in a file as below

```<code>[nsr@inlthome]$ cat > samplerecords.json
{"name": "bob"}
{"name": "john"}
</code>```

and run console producer

```<code>./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic first_topic < samplerecords.json
</code>```

I have tried running the program below:

Body:
I am using Spark Structured Streaming to read from a Kafka topic (records are in JSON format) with the intent of performing some transformations once I get the data into Spark. My first step is to read records from the topic as strings and then convert them to a dictionary (via the python json library) to perform transformations (I do not want to use the to_json capability within Spark because the format of the records in my Kafka topic may change and I do not want to use Spark Streaming which does not require a schema because there is no native functionality to write back to topics). I received a JSONDecodeError (below) when attempting to convert the strings.

Here are the components which produce my error:

I run the following PySpark Code locally:

from pyspark.sql.functions import udf
from pyspark.sql import SparkSession
import pyspark
import json
from pyspark.sql.types import StringType

def str_to_json(s):
    j = json.loads(s)
    return j

if __name__ == "__main__":
    spark = SparkSession.builder \
        .master("local") \
        .appName("App Name") \
        .getOrCreate()

    strToJson = udf(str_to_json, StringType())

    spark.udf.register("strToJson", strToJson)

    df = spark \
        .readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "first_topic") \
        .load() \
        .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")

    df_transformed = df.withColumn('strToJson', strToJson('value'))

    query = df_transformed \
        .writeStream \
        .format("console") \
        .outputMode("update") \
        .start()

I then write a record to my Kafka topic using the kafka-console-producer also from my local machine in the following format:

'{"name":"bob"}'

The following error is then outputted to the console when Spark attempts to use the UDF to convert the value of a record (from the Kafka Topic) to a JSON/dictionary object within the PySpark job:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:452)
    at org.apache.spark.sql.execution.python.PythonUDFRunner$$anon$1.read(PythonUDFRunner.scala:81)
    at org.apache.spark.sql.execution.python.PythonUDFRunner$$anon$1.read(PythonUDFRunner.scala:64)
    at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:406)
    at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage2.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$13$$anon$1.hasNext(WholeStageCodegenExec.scala:636)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$$anonfun$run$3.apply(WriteToDataSourceV2Exec.scala:117)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$$anonfun$run$3.apply(WriteToDataSourceV2Exec.scala:116)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1394)
    at org.apache.spark.sql.execution.datasources.v2.DataWritingSparkTask$.run(WriteToDataSourceV2Exec.scala:146)
    at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec$$anonfun$doExecute$2.apply(WriteToDataSourceV2Exec.scala:67)
    at org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2Exec$$anonfun$doExecute$2.apply(WriteToDataSourceV2Exec.scala:66)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I added a couple debugging print statements within the UDF to see what value is being passed in:

>>> type(s)
<class 'str'>

>>> print(s)
'{"name": "bob"}'

Body:
Can you try below code to produce a json message to kafka console producer?

keep the json records in a file as below

[nsr@inlthome]$ cat > samplerecords.json
{"name": "bob"}
{"name": "john"}

and run console producer

./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic first_topic < samplerecords.json

I have tried running the program below:


问:
Changes made to member of object, inside object, inside a vector, do not survive end of method. C++
Sorry for the title. I cannot made something more descriptive or clear than that..

I'm trying to do something that resembles a very basic auction.

To simplify things, I'm going to put here the essentials of every class.
I'm also translated everything from spanish to english, so if there is a typo, it's only here. The actual code compile fine.

There are four classes involved here:

```<code>class Person
{
private:
    std::string name;
}

class Offer
{
private:
    int amount;
    Person *bidder;
}

class Item
{
private:
    int itemNumber;
    std::string itemName;
    Offer *biggestBidder;

public:
    Item(int, std::string)
    void setbiggestBidder(Offer* const &); // I did this '* const &' thing while trying solutions
    Oferta *getBiggestBidder();
}

class Auction
{
private:
    std::vector<Item> itemCollection;
    int amountOfItems; // in above's collection
}

</code>```

I didn't put the getters, setters, and constructors/destructors here so it's not too long.
Inside Item.cpp I have:

```<code>Item::Item(int number, std::string name)
:itemNumber(number),
itemName(name),
biggestBidder(NULL)
{
    // this->itemNumber= number;
    // this->itemName= name;
    // this->biggestBidder= NULL;
}

void Item::setbiggestBidder(Offer* const &offer)
{
    if (biggestBidder== NULL || biggestBidder->getAmount() < offer->getAmount())
    {
        std::cout << "Address of offer in setbiggestBidder: " << offer << std::endl;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
        biggestBidder = offer;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
    }
    else
    {
    }
}

Oferta *Lote::getBiggestBidder()
{

    std::cout << "Address of biggestBidder in getBiggestBidder(): " << this->biggestBidder << std::endl;
    if (this->biggestBidder == nullptr)
    {
        std::cout << "biggestBidder IS NULL" << std::endl;
    }
    else
    {
        std::cout << "biggestBidder is NOT NULL" << std::endl;
    }

    return biggestBidder;
}

</code>```

Now, the main and the problem:

```<code>Item l1(111, "BANANA");
Item l2(222, "MESA"); // this number 222 is just an ID for the item. It does nothing
Person p1("TheDude");
Offer of1(100, &p1);

// now put the item inside a vector and create an auction instance
std::vector<Item> item1;
collect.push_back(banana);
Auction coleccion1(collect, collect.size());

/*
Now we are ready. If I do this..
*/

std::cout << "Test with item outside vector" << std::endl;

std::cout << "Bidding $" << of1.getAmount() << " for item number "
            << l2.getNumber() << ", " << l2.getItemName() << std::endl;

l2.setBiggestBidder(&of1); // amount 100
/*
If here I do

l2.setBiggestBidder(&of2); // amount 200
l2.setBiggestBidder(&of1); // amount 100

At the bottom of the output, we get 200. It's all good.
*/
std::cout << l2.getBiggestBidder()->getAmount() << std::endl;

/*
We get this output:
Test with item outside vector
Bidding $100 for item number 222, MESA
Address of offer in setbiggestBidder: 0x66fb20
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb20
Address of biggestBidder in getBiggestBidder(): 0x66fb20
biggestBidder is NOT NULL
200 <-- l2.getBiggestBidder()->getAmount()
*/

// But if we try with the item inside the vector:

std::cout << "Bidding $" << of1.getAmount() << " for item number "
                << coleccion1.getItemCollection().at(0).getNumber() << ", "
                    << coleccion1.getItemCollection().at(0).getItemName() << std::endl;

/*
We get:
Test with item in vector
Bidding $100 for item number 111, BANANA
Address of offer in setbiggestBidder: 0x66fb10
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb10
Address of biggestBidder in getBiggestBidder(): 0
biggestBidder IS NULL
0

and here is the issue.
*/
</code>```

I really do not like having to do a post so large for a problem that I'm sure is about something extremely basic, but I have looked everywhere and cannot find any solution to this problem.
It have been weeks since I stumbled upon this.

Why is that everything works fine if I put an item on the method setBiggestBidder, but the change does not survive the end of the method when I put an item that is inside of a vector? And how can I fix it?

答: collect.push_back(l2); creates a copy. l2 and coleccion1.getItemCollection().at(0) are two different objects. If you change l2 coleccion1.getItemCollection().at(0) won't be changed. You could store a pointer in the vector. You should remember that the object is destroyed at the end of the function and the vector contains a dangling pointer.

Body:
Sorry for the title. I cannot made something more descriptive or clear than that..

I'm trying to do something that resembles a very basic auction.

To simplify things, I'm going to put here the essentials of every class.
I'm also translated everything from spanish to english, so if there is a typo, it's only here. The actual code compile fine.

There are four classes involved here:

class Person
{
private:
    std::string name;
}

class Offer
{
private:
    int amount;
    Person *bidder;
}

class Item
{
private:
    int itemNumber;
    std::string itemName;
    Offer *biggestBidder;

public:
    Item(int, std::string)
    void setbiggestBidder(Offer* const &); // I did this '* const &' thing while trying solutions
    Oferta *getBiggestBidder();
}

class Auction
{
private:
    std::vector<Item> itemCollection;
    int amountOfItems; // in above's collection
}

I didn't put the getters, setters, and constructors/destructors here so it's not too long.
Inside Item.cpp I have:

Item::Item(int number, std::string name)
:itemNumber(number),
itemName(name),
biggestBidder(NULL)
{
    // this->itemNumber= number;
    // this->itemName= name;
    // this->biggestBidder= NULL;
}

void Item::setbiggestBidder(Offer* const &offer)
{
    if (biggestBidder== NULL || biggestBidder->getAmount() < offer->getAmount())
    {
        std::cout << "Address of offer in setbiggestBidder: " << offer << std::endl;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
        biggestBidder = offer;
        std::cout << "Address of biggestBidder in setbiggestBidder: " << (biggestBidder) << std::endl;
    }
    else
    {
    }
}

Oferta *Lote::getBiggestBidder()
{

    std::cout << "Address of biggestBidder in getBiggestBidder(): " << this->biggestBidder << std::endl;
    if (this->biggestBidder == nullptr)
    {
        std::cout << "biggestBidder IS NULL" << std::endl;
    }
    else
    {
        std::cout << "biggestBidder is NOT NULL" << std::endl;
    }

    return biggestBidder;
}

Now, the main and the problem:

Item l1(111, "BANANA");
Item l2(222, "MESA"); // this number 222 is just an ID for the item. It does nothing
Person p1("TheDude");
Offer of1(100, &p1);

// now put the item inside a vector and create an auction instance
std::vector<Item> item1;
collect.push_back(banana);
Auction coleccion1(collect, collect.size());

/*
Now we are ready. If I do this..
*/

std::cout << "Test with item outside vector" << std::endl;

std::cout << "Bidding $" << of1.getAmount() << " for item number "
            << l2.getNumber() << ", " << l2.getItemName() << std::endl;

l2.setBiggestBidder(&of1); // amount 100
/*
If here I do

l2.setBiggestBidder(&of2); // amount 200
l2.setBiggestBidder(&of1); // amount 100

At the bottom of the output, we get 200. It's all good.
*/
std::cout << l2.getBiggestBidder()->getAmount() << std::endl;

/*
We get this output:
Test with item outside vector
Bidding $100 for item number 222, MESA
Address of offer in setbiggestBidder: 0x66fb20
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb20
Address of biggestBidder in getBiggestBidder(): 0x66fb20
biggestBidder is NOT NULL
200 <-- l2.getBiggestBidder()->getAmount()
*/

// But if we try with the item inside the vector:

std::cout << "Bidding $" << of1.getAmount() << " for item number "
                << coleccion1.getItemCollection().at(0).getNumber() << ", "
                    << coleccion1.getItemCollection().at(0).getItemName() << std::endl;

/*
We get:
Test with item in vector
Bidding $100 for item number 111, BANANA
Address of offer in setbiggestBidder: 0x66fb10
Address of biggestBidder in setbiggestBidder: 0
Address of biggestBidder in setbiggestBidder: 0x66fb10
Address of biggestBidder in getBiggestBidder(): 0
biggestBidder IS NULL
0

and here is the issue.
*/

I really do not like having to do a post so large for a problem that I'm sure is about something extremely basic, but I have looked everywhere and cannot find any solution to this problem.
It have been weeks since I stumbled upon this.

Why is that everything works fine if I put an item on the method setBiggestBidder, but the change does not survive the end of the method when I put an item that is inside of a vector? And how can I fix it?


问:
ADB2C custom policy - redirect to source page once signed in
I have created a custom policy for signin and another for sign up. What I would like to do is send my users back to their original source page once they have hit the callback from the policy.

E.g. If they were on a blog page /some-article and hit signin, I would like them to end up back here, rather than just at the base callback url.

I couldn't see any clear way to send in data to a custom policy and return it so I can parse it at the call back. Or if there is a better way?

答: Azure AD B2C supports the state parameter. You can use this for whatever you want. I generally use it to save the last visited url via base64encoding. </p>


问:
npm install throws a bunch of errors in react project
I'm currently learning how to work with React and everytime I try to work on a course file and run npm install I get back a million errors and warning. On literally every file I try this on. I've made sure I'm inside the right directory and that there is a json file.

```<code>    gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.4.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/jessiematias/Downloads/hooks-videoplayer-starterfiles-master/react-hooks-videoplayer-START/node_modules/webpack-dev-server/node_modules/fsevents
gyp ERR! node -v v12.17.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
</code>```

I've already tried to reinstall node, update npm to latest version (i'm on 6.14.4) and run npm cache clean but none of those worked. The only  thing that worked once was to run a command that was something along the lines of npm install missing dependencies but that's not it, i can't remember it or find it anywhere online now.

答:
You are having a problem with the C compiler of node. Often, this module (node-gyp) is a dependency of one of your dependencies. The problem usually occurs, if not all settings are correctly set. Follow the official installation guide of node-gyp:

Windows: https://github.com/nodejs/node-gyp#on-windows

Mac OS: https://github.com/nodejs/node-gyp#on-macos

Body:
I'm currently learning how to work with React and everytime I try to work on a course file and run npm install I get back a million errors and warning. On literally every file I try this on. I've made sure I'm inside the right directory and that there is a json file.

    gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.4.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/jessiematias/Downloads/hooks-videoplayer-starterfiles-master/react-hooks-videoplayer-START/node_modules/webpack-dev-server/node_modules/fsevents
gyp ERR! node -v v12.17.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok

I've already tried to reinstall node, update npm to latest version (i'm on 6.14.4) and run npm cache clean but none of those worked. The only  thing that worked once was to run a command that was something along the lines of npm install missing dependencies but that's not it, i can't remember it or find it anywhere online now.


问:
Acrobat Dynamic Date Stamp with Dialogue Box Results not Displaying
I am completely a novice at this, and borrowed part of a script from a sample online.

I am working a stamp with a dialogue box prompting for the date, and defaulting to the current date if no response. I have gotten it to display the dialogue box and the default date. But, the results don't end up on the stamp. Could someone please assist on resolving the issues?

```<code>if(event.source.forReal && (event.source.stampName == "#2Nw2jMn7S5l9QIPW-WGOHB"))
{
   var rgEmpty = /^\s*$/;
   var cDate = null;
   var cDfltDate = null;
   if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
      cDfltDate = event.value;
   else
      cDfltDate = util.printd("mmm dd yyyy",new Date());
   while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
   {
       cDate = app.response({cQuestion:"Please Enter the Date",
                             cTitle:"Stamp Date Entry",
                             cDefault:cDfltDate ,
                             cLabel:"Date:"
                           });
       if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
       {
          app.alert("Please enter date as \"mmm dd yyyy\"\n\nEx: Apr 15 2020",1);
          if(cDate != null)
            cDfltDate = cDate;
       }
   }
}
</code>```

Also, I would like to distribute the final stamp to my coworkers as a template rather than them creating the script. Can I share the stamp pdf, and have them create one off my template without them having to modify the script?

Thank you!

答:
Thank you! I was able to solve the issue with assistance on another thread. Here is the last post there:

IT WORKS!!!

The date is required in oder to be official, and this specific format is also required. So, I think the exit of simply clicking OK is good enough because it gives a default date automatically.

Last thing to test is that an end user can just copy it directly into the stamps folder and start using it. I will test that out this morning when someone is available and follow up.

Thank you for your help!

Here is the code that worked:

```<code>

        console.println("Stamping:" + event.source.StampName);

        if(event.source.forReal && (event.source.stampName == "#StampTemplate"))
        {
           var rgEmpty = /^\s*$/;
           var cDate = null;
           var cDfltDate = null;
           if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
              cDfltDate = event.value;
           else
              cDfltDate = util.printd("mmm dd yyyy",new Date());
           while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
           {
               cDate = app.response({cQuestion:"Please enter date as \"mmm dd yyyy\"\n\nFor Example: Apr 15 2020",
                                     cTitle:"Stamp Date Entry",
                                     cDefault:cDfltDate ,
                                     cLabel:"Date:"
                                   });
               if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
               {
                  app.alert("Please enter date as \"mmm dd yyyy\"\n\nFor Example: Apr 15 2020",1)
               }
               else
                  event.value = cDate;
               }
        }

</code>```

Body:
I am completely a novice at this, and borrowed part of a script from a sample online.

I am working a stamp with a dialogue box prompting for the date, and defaulting to the current date if no response. I have gotten it to display the dialogue box and the default date. But, the results don't end up on the stamp. Could someone please assist on resolving the issues?

if(event.source.forReal && (event.source.stampName == "#2Nw2jMn7S5l9QIPW-WGOHB"))
{
   var rgEmpty = /^\s*$/;
   var cDate = null;
   var cDfltDate = null;
   if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
      cDfltDate = event.value;
   else
      cDfltDate = util.printd("mmm dd yyyy",new Date());
   while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
   {
       cDate = app.response({cQuestion:"Please Enter the Date",
                             cTitle:"Stamp Date Entry",
                             cDefault:cDfltDate ,
                             cLabel:"Date:"
                           });
       if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
       {
          app.alert("Please enter date as \"mmm dd yyyy\"\n\nEx: Apr 15 2020",1);
          if(cDate != null)
            cDfltDate = cDate;
       }
   }
}

Also, I would like to distribute the final stamp to my coworkers as a template rather than them creating the script. Can I share the stamp pdf, and have them create one off my template without them having to modify the script?

Thank you!

Body:
Thank you! I was able to solve the issue with assistance on another thread. Here is the last post there:

IT WORKS!!!

The date is required in oder to be official, and this specific format is also required. So, I think the exit of simply clicking OK is good enough because it gives a default date automatically.

Last thing to test is that an end user can just copy it directly into the stamps folder and start using it. I will test that out this morning when someone is available and follow up.

Thank you for your help!

Here is the code that worked:

        console.println("Stamping:" + event.source.StampName);

        if(event.source.forReal && (event.source.stampName == "#StampTemplate"))
        {
           var rgEmpty = /^\s*$/;
           var cDate = null;
           var cDfltDate = null;
           if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
              cDfltDate = event.value;
           else
              cDfltDate = util.printd("mmm dd yyyy",new Date());
           while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
           {
               cDate = app.response({cQuestion:"Please enter date as \"mmm dd yyyy\"\n\nFor Example: Apr 15 2020",
                                     cTitle:"Stamp Date Entry",
                                     cDefault:cDfltDate ,
                                     cLabel:"Date:"
                                   });
               if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
               {
                  app.alert("Please enter date as \"mmm dd yyyy\"\n\nFor Example: Apr 15 2020",1)
               }
               else
                  event.value = cDate;
               }
        }


问:
Refreshing List of MIDI Input Devices
I'm using pygame's MIDI module to collect a list of available MIDI input devices.

I'm using a method inside a custom-built class to generate this list like so:

```<code>def create_devices(self):
        pygame.midi.init()
        devices = []
        device_count = pygame.midi.get_count()
        for d in range(device_count):
            device = pygame.midi.get_device_info(d)
            device_name = device[1].decode()
            device_type = device[2]
            if device_type == 1:
                input_device = MidiDevice(d, device_name)
                devices.append(input_device)
        return devices
</code>```

I'm setting the list returned from this method to a property in my class in the constructor, and later on I'm rendering the inputs to the screen as buttons meant for selection.

I also have a refresh button that when clicked executes this function and sets the property in my class to the list returned again.

The problem I'm running into is that even if I add or remove MIDI inputs while the program is running, the refresh button always returns what was originally created in the class constructor.

Restarting the program after changing my inputs ends up displaying the inputs that are presently available.

I'd like for the refresh button to automatically find the new inputs, but I must be missing something.

I'm pretty new to pygame and python in general, so I'm eager to learn why this is behaving counter to how I expect.

Any help is super appreciated!

答:
SOLVED.

Turns out I needed to quit the pygame.midi module so that it could be reinitialized.

Here's the small change that fixed my issue:

```<code>    def create_devices(self):
        pygame.midi.init()
        devices = []
        device_count = pygame.midi.get_count()
        for d in range(device_count):
            device = pygame.midi.get_device_info(d)
            device_name = device[1].decode()
            device_type = device[2]
            if device_type == 1:
                input_device = MidiDevice(d, device_name)
                devices.append(input_device)
        pygame.midi.quit() # THIS LINE FIXED IT
        return devices
</code>```

Title: Refreshing List of MIDI Input Devices

Body:
I'm using pygame's MIDI module to collect a list of available MIDI input devices.

I'm using a method inside a custom-built class to generate this list like so:

def create_devices(self):
        pygame.midi.init()
        devices = []
        device_count = pygame.midi.get_count()
        for d in range(device_count):
            device = pygame.midi.get_device_info(d)
            device_name = device[1].decode()
            device_type = device[2]
            if device_type == 1:
                input_device = MidiDevice(d, device_name)
                devices.append(input_device)
        return devices

I'm setting the list returned from this method to a property in my class in the constructor, and later on I'm rendering the inputs to the screen as buttons meant for selection.

I also have a refresh button that when clicked executes this function and sets the property in my class to the list returned again.

The problem I'm running into is that even if I add or remove MIDI inputs while the program is running, the refresh button always returns what was originally created in the class constructor.

Restarting the program after changing my inputs ends up displaying the inputs that are presently available.

I'd like for the refresh button to automatically find the new inputs, but I must be missing something.

I'm pretty new to pygame and python in general, so I'm eager to learn why this is behaving counter to how I expect.

Any help is super appreciated!

Body:
SOLVED.

Turns out I needed to quit the pygame.midi module so that it could be reinitialized.

Here's the small change that fixed my issue:

    def create_devices(self):
        pygame.midi.init()
        devices = []
        device_count = pygame.midi.get_count()
        for d in range(device_count):
            device = pygame.midi.get_device_info(d)
            device_name = device[1].decode()
            device_type = device[2]
            if device_type == 1:
                input_device = MidiDevice(d, device_name)
                devices.append(input_device)
        pygame.midi.quit() # THIS LINE FIXED IT
        return devices


问:
Atlas with Mongoku
Can I connect my Atlas MongoDB account with Mongoku?</p>

答:
That is a resounding "Maybe"

The master branch of Mongoku lists the mongo node driver version 3.2.2 in its dependencies.  According to the folks a MongoDB, that is compatible with up to MongoDB 4.0: https://docs.mongodb.com/drivers/driver-compatibility-reference#id11

If your Atlas cluster is version 4.0 or earlier, that should work fine.

If the cluster is MongoDB version 4.2, it might work for most things, but you may need to rebuild Mongoku with version 3.3 or higher of the driver in order to be fully compatible.

Title: Atlas with Mongoku


问:
How to skip a before_filter for Devise's SessionsController?
I have a before_filter in my ApplicationController; that is, for every controller in my project.

How can I skip_before_filter for Devise's SessionsController create action ?

答:
 new answer

what about wrapping the before_filter in an unless block filtering by params[:controller]

```<code>def some_before_action
  unless params[:controller] == "sessions_controller_for_devise_name"
      ... #=> do the stuff here
  end
end
</code>```

 old answer

just authorize which actions should use the before filter

```<code>before_filter :action, :only => ...
</code>```

and authorize your others.

found this here

Body:
 new answer

what about wrapping the before_filter in an unless block filtering by params[:controller]

def some_before_action
  unless params[:controller] == "sessions_controller_for_devise_name"
      ... #=> do the stuff here
  end
end

 old answer

just authorize which actions should use the before filter

before_filter :action, :only => ...

and authorize your others.

found this here