问:
Dynamically created labels won't display on the screen pyqt5
I am making a basic GUI application using PyQt5, and need to create labels dynamically after user input. Now, the problem is they won't show on the screen, although the objects themselves are created. This function is getting called on button press after user finishes input:

```<code>def set_result_labels(self):
        font = QtGui.QFont()
        font.setPointSize(15)
        for i in range(len(self.text_parties_names)):
            label = QtWidgets.QLabel(self.centralwidget)
            setattr(self, f"label_{i+5}", label)
            label.setGeometry(QtCore.QRect(700, (100+4*i), 50, 50))
            label.setFont(font)
            label.setText(self.text_parties_names[i])
            label.setObjectName(f"label_{i+5}")
</code>```

But, if I "explicitly" create them, like this:

```<code>        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(600, 400, 171, 40))
        self.label_5.setFont(font)
        self.label_5.setText(self.text_parties_names[0])
        self.label_5.setObjectName("label_25")
</code>```

It works with no issues. I do not understand why.

答:
as an option, you can insert the label in the layout, for example like this:

```<code>import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        button = QtWidgets.QPushButton("Button")
        button.clicked.connect(self.set_result_labels)

        scrollArea = QtWidgets.QScrollArea()
        widget = QtWidgets.QWidget()
        scrollArea.setMinimumWidth(200)
        scrollArea.setMinimumHeight(200)
        scrollArea.setWidget(widget)
        scrollArea.setWidgetResizable(True)
        scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll_box = QtWidgets.QVBoxLayout(widget)

        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(scrollArea)
        layout.addStretch(1)
        layout.addWidget(button)

        self.text_parties_names = '12345'

    def set_result_labels(self):
        font = QtGui.QFont()
        font.setPointSize(15)
        for i in range(len(self.text_parties_names)):
            label = QtWidgets.QLabel()
            setattr(self, f"label_{i+5}", label)
#            label.setGeometry(QtCore.QRect(700, (100+4*i), 50, 50))
            label.setFont(font)
            label.setText(self.text_parties_names[i])
            label.setObjectName(f"label_{i+5}")

            self.scroll_box.addWidget(label)                                # <<<---

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

Body:
I am making a basic GUI application using PyQt5, and need to create labels dynamically after user input. Now, the problem is they won't show on the screen, although the objects themselves are created. This function is getting called on button press after user finishes input:

def set_result_labels(self):
        font = QtGui.QFont()
        font.setPointSize(15)
        for i in range(len(self.text_parties_names)):
            label = QtWidgets.QLabel(self.centralwidget)
            setattr(self, f"label_{i+5}", label)
            label.setGeometry(QtCore.QRect(700, (100+4*i), 50, 50))
            label.setFont(font)
            label.setText(self.text_parties_names[i])
            label.setObjectName(f"label_{i+5}")

But, if I "explicitly" create them, like this:

        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(600, 400, 171, 40))
        self.label_5.setFont(font)
        self.label_5.setText(self.text_parties_names[0])
        self.label_5.setObjectName("label_25")

It works with no issues. I do not understand why.

Body:
as an option, you can insert the label in the layout, for example like this:

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        button = QtWidgets.QPushButton("Button")
        button.clicked.connect(self.set_result_labels)

        scrollArea = QtWidgets.QScrollArea()
        widget = QtWidgets.QWidget()
        scrollArea.setMinimumWidth(200)
        scrollArea.setMinimumHeight(200)
        scrollArea.setWidget(widget)
        scrollArea.setWidgetResizable(True)
        scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll_box = QtWidgets.QVBoxLayout(widget)

        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(scrollArea)
        layout.addStretch(1)
        layout.addWidget(button)

        self.text_parties_names = '12345'

    def set_result_labels(self):
        font = QtGui.QFont()
        font.setPointSize(15)
        for i in range(len(self.text_parties_names)):
            label = QtWidgets.QLabel()
            setattr(self, f"label_{i+5}", label)
#            label.setGeometry(QtCore.QRect(700, (100+4*i), 50, 50))
            label.setFont(font)
            label.setText(self.text_parties_names[i])
            label.setObjectName(f"label_{i+5}")

            self.scroll_box.addWidget(label)                                # <<<---

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
Clear cairo text in gtk_window
I'm have a trouble with a cairo text.
I write some lines in a gtk_window:

```<code>cr = gdk_cairo_create(window->window);
        cairo_set_source_rgb(cr, 255, 255, 255);
        cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
        cairo_set_font_size(cr, 14.0);

        cairo_move_to(cr, 90.0, 85.0);
        cairo_show_text(cr, "Terror");
        cairo_set_font_size(cr, 12.0);
        cairo_set_source_rgb(cr, 30, 254, 145);
        cairo_move_to(cr, 90.0, 105.0);
        cairo_show_text(cr, "Underdogs");
        cairo_move_to(cr, 90.0, 120.0);
        cairo_show_text(cr, "Disziplin");
        cairo_destroy(cr);
</code>```

The problem is that this text should be dynamic, but if I call more than one time the function that writes the text, lines is overlapped.

Is there any method that flushes the previous text?

Thanks!

答:
From the Cairo FAQ:

If you want to clear your surface to a uniform, opaque color then it
is quite straightforward:

/* Set surface to opaque color (r, g, b) */
cairo_set_source_rgb (cr, r, g, b);
cairo_paint (cr);
```
<p>However, what if you want to clear the surface to something other than
an opaque color. Simply modifying the above code to use
<code>cairo_set_source_rgba (cr, 0, 0, 0, 0);</code> will not work since Cairo
uses the <code>OVER</code> compositing operator by default, and blending something
entirely transparent OVER something else has no effect at all.
Instead, you can use the <code>SOURCE</code> operator which copies both color and
alpha values directly from the source to the destination instead of
blending:</p>
<pre class="lang-c prettyprint-override"><code>/* Set surface to translucent color (r, g, b, a) */
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);
</code>```

Of course, you won't want to forget to set the default
CAIRO_OPERATOR_OVER again when you're finished. And the most
convenient habit for doing that is to just use
cairo_save/cairo_restore around the whole block:

/* Set surface to translucent color (r, g, b, a) without disturbing graphics state. */
cairo_save (cr);
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);
cairo_restore (cr);
```

Finally, to clear a surface to all transparent, one could simply use
CAIRO_OPERATOR_CLEAR instead of CAIRO_OPERATOR_SOURCE, in which case
the call to cairo_set_source_rgba would not be needed at all, (the
CLEAR operator always sets the destination to 0 in every channel
regardless of what the source pattern contains). But the above
approach with CAIRO_OPERATOR_SOURCE is a more general way to clear the
surface since it allows for "clearing" to a translucent color such as
50% red rather than just clearing to entirely transparent.

ContentLicense: CC BY-SA 2.5

Title: Clear cairo text in gtk_window

Body:
I'm have a trouble with a cairo text.
I write some lines in a gtk_window:

cr = gdk_cairo_create(window->window);
        cairo_set_source_rgb(cr, 255, 255, 255);
        cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
        cairo_set_font_size(cr, 14.0);

        cairo_move_to(cr, 90.0, 85.0);
        cairo_show_text(cr, "Terror");
        cairo_set_font_size(cr, 12.0);
        cairo_set_source_rgb(cr, 30, 254, 145);
        cairo_move_to(cr, 90.0, 105.0);
        cairo_show_text(cr, "Underdogs");
        cairo_move_to(cr, 90.0, 120.0);
        cairo_show_text(cr, "Disziplin");
        cairo_destroy(cr);

The problem is that this text should be dynamic, but if I call more than one time the function that writes the text, lines is overlapped.

Is there any method that flushes the previous text?

Thanks!

Body:
From the Cairo FAQ:

If you want to clear your surface to a uniform, opaque color then it
is quite straightforward:

/* Set surface to opaque color (r, g, b) */
cairo_set_source_rgb (cr, r, g, b);
cairo_paint (cr);

However, what if you want to clear the surface to something other than
an opaque color. Simply modifying the above code to use
cairo_set_source_rgba (cr, 0, 0, 0, 0); will not work since Cairo
uses the OVER compositing operator by default, and blending something
entirely transparent OVER something else has no effect at all.
Instead, you can use the SOURCE operator which copies both color and
alpha values directly from the source to the destination instead of
blending:

/* Set surface to translucent color (r, g, b, a) */
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);

Of course, you won't want to forget to set the default
CAIRO_OPERATOR_OVER again when you're finished. And the most
convenient habit for doing that is to just use
cairo_save/cairo_restore around the whole block:

/* Set surface to translucent color (r, g, b, a) without disturbing graphics state. */
cairo_save (cr);
cairo_set_source_rgba (cr, r, g, b, a);
cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
cairo_paint (cr);
cairo_restore (cr);

Finally, to clear a surface to all transparent, one could simply use
CAIRO_OPERATOR_CLEAR instead of CAIRO_OPERATOR_SOURCE, in which case
the call to cairo_set_source_rgba would not be needed at all, (the
CLEAR operator always sets the destination to 0 in every channel
regardless of what the source pattern contains). But the above
approach with CAIRO_OPERATOR_SOURCE is a more general way to clear the
surface since it allows for "clearing" to a translucent color such as
50% red rather than just clearing to entirely transparent.

ContentLicense: CC BY-SA 4.0


问:
How to convert List of Double to List of String?
This just might be too easy for all of you, but I am just learning and implementing Java in a project and am stuck with this.

How to convert List of Double  to List String?

答:
There are many ways to do this but here are two styles for you to choose from:

```<code>List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = new ArrayList<String>();
for (Double d : ds) {
    // Apply formatting to the string if necessary
    strings.add(d.toString());
}
</code>```

But a cooler way to do this is to use a modern collections API (my favourite is Guava) and do this in a more functional style:

```<code>List<String> strings = Lists.transform(ds, new Function<Double, String>() {
        @Override
        public String apply(Double from) {
            return from.toString();
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are many ways to do this but here are two styles for you to choose from:

List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = new ArrayList<String>();
for (Double d : ds) {
    // Apply formatting to the string if necessary
    strings.add(d.toString());
}

But a cooler way to do this is to use a modern collections API (my favourite is Guava) and do this in a more functional style:

List<String> strings = Lists.transform(ds, new Function<Double, String>() {
        @Override
        public String apply(Double from) {
            return from.toString();
        }
    });


问:
Setting Tikz Boarder Globally | Latex
With the following Code I am able to set the boarder for current page, but how can I make the boarder available to all pages without explicitly setting it on every page.

% !TeX TS-program = xelatex % | xelatex %

\documentclass[12pt, a4paper]{article}
\usepackage[left=3.3cm,right=2.3cm,top=2.3cm,bottom=2.3cm, footskip=42pt]{geometry}

\usepackage{fontspec}
\setmainfont{Times New Roman}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

    \begin{tikzpicture}[remember picture, overlay]
        \draw[line width=3pt] ($(current page.north west)+(2.5cm,-1.5cm)$) rectangle ($(current page.south east)+(-1.5cm,1.5cm)$);
        \draw[line width=1pt] ($(current page.north west)+(2.6cm,-1.6cm)$) rectangle ($(current page.south east)+(-1.6cm,1.6cm)$);
        \fill[red] (current page.center) circle (0.1);
        \node[font=\Large\bfseries, text width=5cm,align=center] at (current page.center) {
            \uppercase{Note -- 1}

            \vspace{24pt}

            \uppercase{Data analysis}
        };
    \end{tikzpicture}

    \newpage

    test

\end{document}

```

答:
One possibility is to use the eso-pic package:

```<code>% !TeX TS-program = xelatex % | xelatex %

\documentclass[12pt, a4paper]{article}
\usepackage[left=3.3cm,right=2.3cm,top=2.3cm,bottom=2.3cm, footskip=42pt]{geometry}

\usepackage{fontspec}
\setmainfont{Times New Roman}

\usepackage{tikz}
\usetikzlibrary{calc}

\usepackage{eso-pic}
\AddToShipoutPictureBG{%
\begin{tikzpicture}[remember picture, overlay]
  \draw[line width=3pt] ($(current page.north west)+(2.5cm,-1.5cm)$) rectangle ($(current page.south east)+(-1.5cm,1.5cm)$);
  \draw[line width=1pt] ($(current page.north west)+(2.6cm,-1.6cm)$) rectangle ($(current page.south east)+(-1.6cm,1.6cm)$);
\end{tikzpicture}%
}

\begin{document}

    \begin{tikzpicture}[remember picture, overlay]
        \fill[red] (current page.center) circle (0.1);
        \node[font=\Large\bfseries, text width=5cm,align=center] at (current page.center) {
            \uppercase{Note -- 1}

            \vspace{24pt}

            \uppercase{Data analysis}
        };
    \end{tikzpicture}

    \newpage

    test

\end{document}
</code>```

Title: Setting Tikz Boarder Globally | Latex

Body:
One possibility is to use the eso-pic package:

% !TeX TS-program = xelatex % | xelatex %

\documentclass[12pt, a4paper]{article}
\usepackage[left=3.3cm,right=2.3cm,top=2.3cm,bottom=2.3cm, footskip=42pt]{geometry}

\usepackage{fontspec}
\setmainfont{Times New Roman}

\usepackage{tikz}
\usetikzlibrary{calc}

\usepackage{eso-pic}
\AddToShipoutPictureBG{%
\begin{tikzpicture}[remember picture, overlay]
  \draw[line width=3pt] ($(current page.north west)+(2.5cm,-1.5cm)$) rectangle ($(current page.south east)+(-1.5cm,1.5cm)$);
  \draw[line width=1pt] ($(current page.north west)+(2.6cm,-1.6cm)$) rectangle ($(current page.south east)+(-1.6cm,1.6cm)$);
\end{tikzpicture}%
}

\begin{document}

    \begin{tikzpicture}[remember picture, overlay]
        \fill[red] (current page.center) circle (0.1);
        \node[font=\Large\bfseries, text width=5cm,align=center] at (current page.center) {
            \uppercase{Note -- 1}

            \vspace{24pt}

            \uppercase{Data analysis}
        };
    \end{tikzpicture}

    \newpage

    test

\end{document}


答:
The simplest way i can imagine doing this is converting your dataframe to a dataset and apply a map operation and then back to dataframe,

//  Define a case class

case class MyType(colId:Int,path:String,timestamp:Int) // they need to match the column names

dataframe.as[MyType].map(x=> <<Your Transformation code>>).toDf()

```

Title: Logic to manipulate dataframe in spark scala [Spark]

Body:
Take for example the following dataFrame:
x.show(false)

+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|colId|hdfsPath                                                                                |timestamp    |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|11    |hdfs://novus-nameservice/a/b/c/done/compiled-20200218050518-1-0-0-1582020318751.snappy|1662157400000|
|12    |hdfs://novus-nameservice/a/b/c/done/compiled-20200219060507-1-0-0-1582023907108.snappy|1662158000000|
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+

Now I am trying to update the existing DF to create a new DF based based on the column hdfsPath

The new DF should look like the following:

+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|colId|hdfsPath                                                                                |timestamp    |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+
|11    |hdfs://novus-nameservice/a/b/c/target/20200218/11/compiled-20200218050518-1-0-0-1582020318751.snappy|1662157400000|
|12    |hdfs://novus-nameservice/a/b/c/target/20200219/12/compiled-20200219060507-1-0-0-1582023907108.snappy|1662158000000|
+-------+--------------------------------------------------------------------------------------------------------------------------------------------+-------------+

So the path done changes to target and then from the compiled-20200218050518-1-0-0-1582020318751.snappy portion I get the date 20200218 and then colID 11 and then finally the snappy file. What would be the easiest and most efficient way to achieve this?

It's not a hard requirement to create a newDF, I can update the existing DF with a new column.

To summarize:
Current hdfsPath:

hdfs://novus-nameservice/a/b/c/done/compiled-20200218050518-1-0-0-1582020318751.snappy

Expected hdfsPath:

hdfs://novus-nameservice/a/b/c/target/20200218/11/compiled-20200218050518-1-0-0-1582020318751.snappy

Based on colID.


问:
Pass prop from Consumer -> Provider context and access it outside of Provider render?
I have a component called "Home," which is the home page for my website. This Home component uses a context called "ProductContext" in order to access all the products in a data.js file. The thing is, I'm going to have multiple *data.js files for each page of my website, so I went to tell the context file which page "I'm on" so it accesses the corresponding *data.js file.

"Home" component:

```<code>class Home extends Component {
  state = {
    page: "Home",
  };

  componentDidMount() {}

  render() {
    return (
      <React.Fragment>
        <div className="py-2">
          <div className="container-fluid">
            <Title title="PRODUCTS" className="pl-5" />
            <div
              className="row no-gutters "
              style={{ justifyContent: "center" }}
            >
              <ProductConsumer page={"Home"}>
                {(value) => {
                  console.log(value);
                  return value.products.map((product) => {
                    return <Product key={product.id} product={product} />;
                  });
                }}
              </ProductConsumer>
            </div>
          </div>
        </div>
      </React.Fragment>
    );
  }
}

export default Home;
</code>```

ProductContext:

```<code>render() {
    return (
      <ProductContext.Provider
        value={{
          ...this.state,
          handleDetail: this.handleDetail,
          addToCart: this.addToCart,
          openModal: this.openModal,
          closeModal: this.closeModal,
          increment: this.increment,
          decrement: this.decrement,
          removeItem: this.removeItem,
          clearCart: this.clearCart,
          setPage: this.setPage,
        }}
      >
        {this.props.children}
      </ProductContext.Provider>
    );
  }
}
</code>```

You can tell I tried a few things like passing it through props or through a function in the context. I'm sure I'm close but I can't figure out exactly how to do it. I've seen other examples where you call a Provider function, most commonly with "onClick" but this needs to happen when either the Home component or ProductContext is constructed or mounted so the Page component can pull the right data. What I mean:

```<code>//In Home Component

componentDidMount() {
   let context = this.context;
   context.setPage("Home");

}
</code>```

Except of course this isn't working.

答:
I had a very limited understanding of how contexts work. From this experience I guess I learned that contexts should really be looked as something that provides data, not something that takes data.

I resolved this issue by first sorting the data in the context into different arrays, and then passing the corresponding array to each page.

Body:
I have a component called "Home," which is the home page for my website. This Home component uses a context called "ProductContext" in order to access all the products in a data.js file. The thing is, I'm going to have multiple *data.js files for each page of my website, so I went to tell the context file which page "I'm on" so it accesses the corresponding *data.js file.

"Home" component:

class Home extends Component {
  state = {
    page: "Home",
  };

  componentDidMount() {}

  render() {
    return (
      <React.Fragment>

            <Title title="PRODUCTS" className="pl-5" />

              <ProductConsumer page={"Home"}>
                {(value) => {
                  console.log(value);
                  return value.products.map((product) => {
                    return <Product key={product.id} product={product} />;
                  });
                }}
              </ProductConsumer>

      </React.Fragment>
    );
  }
}

export default Home;

ProductContext:

render() {
    return (
      <ProductContext.Provider
        value={{
          ...this.state,
          handleDetail: this.handleDetail,
          addToCart: this.addToCart,
          openModal: this.openModal,
          closeModal: this.closeModal,
          increment: this.increment,
          decrement: this.decrement,
          removeItem: this.removeItem,
          clearCart: this.clearCart,
          setPage: this.setPage,
        }}
      >
        {this.props.children}
      </ProductContext.Provider>
    );
  }
}

You can tell I tried a few things like passing it through props or through a function in the context. I'm sure I'm close but I can't figure out exactly how to do it. I've seen other examples where you call a Provider function, most commonly with "onClick" but this needs to happen when either the Home component or ProductContext is constructed or mounted so the Page component can pull the right data. What I mean:

//In Home Component

componentDidMount() {
   let context = this.context;
   context.setPage("Home");

}

Except of course this isn't working.


问:
can't display data in the table (angular 9)
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>==>> Html
     <table *ngIf="universites" class="table table-striped">
                    <tr>
                        <th>
                            Code
                        </th>
                        <th>
                            Nom
                        </th>
                        <th>
                            Adresse
                        </th><th></th>
                        <tr *ngFor="let c of universites">
                            <td>
                                {{c.code_UNV}}
                            </td>
                            <td>
                                {{c.nom_UNV}}
                            </td>
                            <td>
                                {{c.adresse_site_UNV}}
                            </td>
                        </tr>
                </table></code>```

答:
Can you please close your first tr tag in html ? Hopefully this will work</p>

```<code><table *ngIf="universites" class="table table-striped">
<tr>
<th> Code </th>
<th> Nom </th>
<th> Adresse </th>
</tr>
<tr *ngFor="let c of universites"> <td> {{c.code_UNV}} </td> <td> {{c.nom_UNV}} </td> <td> {{c.adresse_site_UNV}} </td> </tr> </table>
</code>```

Body:
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }

==>> Html

                            Code

                            Nom

                            Adresse

                                {{c.code_UNV}}

                                {{c.nom_UNV}}

                                {{c.adresse_site_UNV}}

Body:
Can you please close your first tr tag in html ? Hopefully this will work

<table *ngIf="universites" class="table table-striped">
<tr>
<th> Code </th>
<th> Nom </th>
<th> Adresse </th>
</tr>
<tr *ngFor="let c of universites"> <td> {{c.code_UNV}} </td> <td> {{c.nom_UNV}} </td> <td> {{c.adresse_site_UNV}} </td> </tr> </table>


问:
Entity Framework and Application Intent parameter
I have a stored proc that uses a synonym to pull data from another SQL Server 2016 database.

This is the connection string that EF is using:

```<code><add name="ConnectionString_CSAdminEF_RO" connectionString="Data Source=myserver;initial catalog=csadmin;user=tcrpAdminTool;password=XXXX;applicationintent=readonly" providerName="System.Data.SqlClient" />
</code>```

It throws this error:

The OLE DB provider "SQLNCLI11" for linked server "MYSERVER.CORP.COMPANY.COM" does not contain the table "otherserver"."dbo"."mysynonym"". The table either does not exist or the current user does not have permissions on that table.

When I try it in ADO.NET it throws this error:

Procedure usp_get_Data has no parameters and arguments were supplied.

Here is the synonym:

```<code>CREATE SYNONYM [dbo].[mysynonym] FOR [OTHERSERVER.CORP.COMPANY.COM].[mydb].[dbo].[eDocsEntity]
</code>```

The problem only started when I added applicationintent=readonly. This additional parameter works fine when no parameter is involved.

Any ideas as to what could be causing this? I've seen nothing in the forums about it

Thanks

Carl

答:
From our DBA:

I was working on a linked server on primary not realizing that when you read only route to secondary you have to check the secondary servers linked server and in secondary which is a DMS primary they are using a server which did not have read rights to the database referenced by the synonym

I gave it read permissions and that's it

Body:
I have a stored proc that uses a synonym to pull data from another SQL Server 2016 database.

This is the connection string that EF is using:

<add name="ConnectionString_CSAdminEF_RO" connectionString="Data Source=myserver;initial catalog=csadmin;user=tcrpAdminTool;password=XXXX;applicationintent=readonly" providerName="System.Data.SqlClient" />

It throws this error:

The OLE DB provider "SQLNCLI11" for linked server "MYSERVER.CORP.COMPANY.COM" does not contain the table "otherserver"."dbo"."mysynonym"". The table either does not exist or the current user does not have permissions on that table.

When I try it in ADO.NET it throws this error:

Procedure usp_get_Data has no parameters and arguments were supplied.

Here is the synonym:

CREATE SYNONYM [dbo].[mysynonym] FOR [OTHERSERVER.CORP.COMPANY.COM].[mydb].[dbo].[eDocsEntity]

The problem only started when I added applicationintent=readonly. This additional parameter works fine when no parameter is involved.

Any ideas as to what could be causing this? I've seen nothing in the forums about it

Thanks

Carl


问:
Converting Strings in Excel to Dates
We imported a bunch of data into cells.  But when you click on the cell, their is an apostrophe before the data, so it thinks its a string. By removing the apostrophe, the data gets recognized as dates. How do I avoid doing this by hand?</p>

答:
I don't think the find and replce would would and the apostrophe is not part of the text, but a excel "feature". depending on how many you have to change - e.g. number of columns the simplist way I can think of without writing a macro would be.

Assuming your dates are in column A.

In a blank column put the following

```<code>=VALUE(A1)
</code>```

This will store the date as a number. replicate the formulae down the column and then copy the values over the original dates. Apply cell formatting to short/long date if needed.

Hope this helps

Title: Converting Strings in Excel to Dates

Body:
I don't think the find and replce would would and the apostrophe is not part of the text, but a excel "feature". depending on how many you have to change - e.g. number of columns the simplist way I can think of without writing a macro would be.

Assuming your dates are in column A.

In a blank column put the following

=VALUE(A1)

This will store the date as a number. replicate the formulae down the column and then copy the values over the original dates. Apply cell formatting to short/long date if needed.

Hope this helps


问:
Why does old value not passed to vue component?
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>```
</div>
</div>
</p>

<p>my code from vue component</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">
        <div class="panel-footer" v-if="results.length">
            <ul class="list-group select-region">
                <li class="list-group-item list-region" v-for="result in results" v-on:click="selectRegion(result)">
                    {{ result.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                results: [],
                query: '',
            }
        },
        methods: {
            autoComplete() {
                this.results = [];
                if(this.query.length > 2){
                    axios.get('/api/regions',{params: {_limit: 2, query: this.query}}).then(response => {
                        this.results = response.data;
                    });
                }
            },
            selectRegion(result) {
                let inputWithRegionName = document.querySelector('.js-region-name');
                let inputWithRegionId = document.querySelector('.js-region-id');
                let listRegions = document.querySelector('.panel-footer');

                inputWithRegionName.value = result.name;
                inputWithRegionId.value = result.id;
                listRegions.hidden = true;
            }
        }
    }
</script></code>```

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

答:
When you create a component (like you have with <autocomplete-region-component>, if you want to pass values to it from it's parent, you have to define the prop at the component level. So in your script, add a props property like so:

```<code>    props: [
        'query',
    ],
</code>```

Now in your autocomplete-region-component component, you can use the value of query as this.query as you would expect.

In your component tag, you don't use mustache tags to pass the value, you would just pass normal javascript. I'd also recommend not encoding the json at that point. You could always encode it within the component if you needed to.

```<code><autocomplete-region-component :query="old('regionName')">
</autocomplete-region-component>
</code>```

Body:
why does old value not passed to vue component?

passed old value here

<autocomplete-region-component :query="old('regionName')"></autocomplete-region-component>

my code from vue component

<template>

        <input
            type="text"
            autocomplete="off"
            v-model="query"
            v-on:keyup="autoComplete"
            class="form-control js-region-name"
            name="regionName"
            value=""
        >
        <input
            type="hidden"
            class="form-control js-region-id"
            name="regionId"
            value="enteredRegion">

                    {{ result.name }}

</template>

console not have mistakes

Please help with a detailed answer since I am a beginner and really need your help. thanks

UPDATE

Body:
When you create a component (like you have with <autocomplete-region-component>, if you want to pass values to it from it's parent, you have to define the prop at the component level. So in your script, add a props property like so:

    props: [
        'query',
    ],

Now in your autocomplete-region-component component, you can use the value of query as this.query as you would expect.

In your component tag, you don't use mustache tags to pass the value, you would just pass normal javascript. I'd also recommend not encoding the json at that point. You could always encode it within the component if you needed to.

<autocomplete-region-component :query="old('regionName')">
</autocomplete-region-component>


问:
How to properly implement serverless SSR with Next.js using `target: "serverless"` in version 8.0
Next.js 8.0 just introduced a new target: "serverless" config setting, described on this blog post. I set up a basic hello world app (here) to test it out. Copy-pasted the output of .next/serverless/pages/index.js to a Google Cloud Function (their equivalent of AWS Lambda) and had it call render() as outlined in the above blog post.

The problem I run into is that the page itself renders fine, but then it tries to fetch static assets (script files) at the same domain as the lambda, which of course doesn't work because there's nothing there but the lambda script.

You can see this happening here:

The idea I was going for was to use this new feature of Next.js to implement a micro-frontend architecture. Each page in pages/ could have its own development team / lifecycle, and be scaled accordingly on the backend. That is one of the main selling points of this feature, right?

What is the standard way of solving this? Do I need to set up a separate server for the static assets? Then put both behind a load balancer or router of some sort? If so, doesn't that defeat the purpose of using this to develop micro-frontends, since the static assets would include "index.js", "about.js", and script files for each page, and would need to be redeployed any time any page is updated?

Hope what I'm saying makes sense. Any help appreciated!

答:
In order for next.js to work with your google cloud functions, you need to create a next.config.js (I assume you already did) and add the assetprefix

```<code>const isProd = process.env.NODE_ENV === 'production'
module.exports = {
    target: 'serverless',
    assetPrefix: isProd ? 'https://yourRegion-projectId.cloudfunctions.net/functionName' : '',
}
</code>```

after this, npm build and deploy again.

Google Cloud functions free invocations is 2,000,000.
Firebase is 125,000.

Update - Firebase free invocation is now 2,000,000/month

Body:
In order for next.js to work with your google cloud functions, you need to create a next.config.js (I assume you already did) and add the assetprefix

const isProd = process.env.NODE_ENV === 'production'
module.exports = {
    target: 'serverless',
    assetPrefix: isProd ? 'https://yourRegion-projectId.cloudfunctions.net/functionName' : '',
}

after this, npm build and deploy again.

Google Cloud functions free invocations is 2,000,000.
Firebase is 125,000.

Update - Firebase free invocation is now 2,000,000/month


问:
Python Dataframe index as a tuple of XY Coordinates
My function collectHUC takes XY coordinates and builds a dictionary of HUC codes named stationsXY  for 1000 stations. The keys are tuples like ('41.462605 ', '-74.387089') with values like 0202000600. This process takes time, so I convert stationsXY to a DataFrame and save it as follows for later use:

```<code>xy = pd.DataFrame.from_dict(stationsXY, orient='index')
xy.to_csv('xy_huc.csv', index=False)
</code>```

Here is the issue, when reading back the file xy_huc.csv with

```<code>xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)
</code>```

The DataFrame xy_coor has 2 columns, column 0 for the XY coordinates and column 1 for HUC codes, by setting column 0 as the index, the index format is string now and not tuple. I have tried these so far:

Read the csv file, setting the index as a multi-index from the column

```<code>xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)
xy = pd.DataFrame(xy_coor, index=pd.MultiIndex.from_tuples(xy_coor.index))
</code>```

but I have got this error

```<code>TypeError: Expected tuple, got str
</code>```

Read the csv with index_col=False, set the index to column zero

```<code>xy_coor = pd.read_csv('xy_huc.csv', index_col=False, header=None)
xy = pd.DataFrame(stations_xy, index=pd.MultiIndex.from_tuples(xy_coor[0]))
</code>```

but xy indexes are in this form

xy DataFrame for point 2

I am willing to retrieve the file in the same format it was saved on. Any suggestions/recommendations are appreciated.

Thanks

答:
There are multiple ways to do this but I think the easiest way would be to save x and y as separate columns.

Another way would be to parse the tuple string for example:

```<code>def back_to_tuple(input_string):
    # remove punctuation but not comma
    punctuation = "(/')"
    for punc in punctuation:
        input_string = input_string.replace(punc, '')

    # split on comma -> list
    input_string = input_string.split(',')

    # split on comma -> list
    input_string = input_string.split(',')

    return input_string

</code>```

You could as well save the xy tuple as a string separated with ';':

```<code>def tuple_to_string(input_tuple)
    return ';'.join(input_tuple)
</code>```

And than retrieve it like so:

```<code>def back_to_tuple(input_string):
    return tuple(input_string.split(';'))
</code>```

Body:
My function collectHUC takes XY coordinates and builds a dictionary of HUC codes named stationsXY  for 1000 stations. The keys are tuples like ('41.462605 ', '-74.387089') with values like 0202000600. This process takes time, so I convert stationsXY to a DataFrame and save it as follows for later use:

xy = pd.DataFrame.from_dict(stationsXY, orient='index')
xy.to_csv('xy_huc.csv', index=False)

Here is the issue, when reading back the file xy_huc.csv with

xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)

The DataFrame xy_coor has 2 columns, column 0 for the XY coordinates and column 1 for HUC codes, by setting column 0 as the index, the index format is string now and not tuple. I have tried these so far:

Read the csv file, setting the index as a multi-index from the column

xy_coor = pd.read_csv('xy_huc.csv', index_col=0, header=None)
xy = pd.DataFrame(xy_coor, index=pd.MultiIndex.from_tuples(xy_coor.index))

but I have got this error

TypeError: Expected tuple, got str

Read the csv with index_col=False, set the index to column zero

xy_coor = pd.read_csv('xy_huc.csv', index_col=False, header=None)
xy = pd.DataFrame(stations_xy, index=pd.MultiIndex.from_tuples(xy_coor[0]))

but xy indexes are in this form

xy DataFrame for point 2

I am willing to retrieve the file in the same format it was saved on. Any suggestions/recommendations are appreciated.

Thanks

Body:
There are multiple ways to do this but I think the easiest way would be to save x and y as separate columns.

Another way would be to parse the tuple string for example:

def back_to_tuple(input_string):
    # remove punctuation but not comma
    punctuation = "(/')"
    for punc in punctuation:
        input_string = input_string.replace(punc, '')

    # split on comma -> list
    input_string = input_string.split(',')

    # split on comma -> list
    input_string = input_string.split(',')

    return input_string

You could as well save the xy tuple as a string separated with ';':

def tuple_to_string(input_tuple)
    return ';'.join(input_tuple)

And than retrieve it like so:

def back_to_tuple(input_string):
    return tuple(input_string.split(';'))


问:
How to use AutoMapper?
First time using AutoMapper and I'm have a hard time figuring out how to use it.
I'm trying to map a ViewModel to my Database Tables.

My ViewModel looks like this...

```<code>public class AddressEditViewModel
{
    public AddressEdit GetOneAddressByDistrictGuid { get; private set; }
    public IEnumerable<ZipCodeFind> GetZipCodes { get; private set; }

    public AddressEditViewModel(AddressEdit editAddress, IEnumerable<ZipCodeFind> Zips)
    {
        this.GetOneAddressByDistrictGuid = editAddress;
        this.GetZipCodes = Zips;
    }
}
</code>```

The Mapping I'm trying to use is...

```<code>CreateMap<Address, AddressEditViewModel>();
</code>```

When I run this test...

```<code>public void Should_map_dtos()
{
    AutoMapperConfiguration.Configure();
    Mapper.AssertConfigurationIsValid();
}
</code>```

I get this error...

AutoMapper.AutoMapperConfigurationException: The following 2 properties on JCIMS_MVC2.DomainModel.ViewModels.AddressEditViewModel
  are not mapped:
  GetOneAddressByDistrictGuid
  GetZipCodes
  Add a custom mapping expression, ignore, or rename the property on JCIMS_MVC2.DomainModel.Address.

I'm not sure how I am supposed to map those 2 properties. I would appreciate any direction.  Thanks

Mark

答:
Ok so I can see a few things you are doing that probably won't help.

Firstly this AutoMapper is used to copy Properties in one object to Properties in a diff object. Along the way it might interrogate or manipulate them to get the end result viewmodel in the correct state.

The properties are named 'Get...' which sounds more like a method to me.

The setters on your properties are private so AutoSetter won't be able to find them. Change these to minimum internal.

Use of a parametrized constructor is no longer needed when you use AutoMapper - as you are converting directly from one object to another. The parametised constructor is there mainly to show what is explicitly required by this object.

```<code>CreateMap<Address, AddressEditViewModel>()
         .ForMember( x => x.GetOneAddressByDistrictGuid ,
                          o => o.MapFrom( m => m."GetOneAddressByDistrictGuid") )
         .ForMember( x => x.GetZipCodes,
                          o => o.MapFrom( m => m."GetZipCodes" ) );
</code>```

What Automapper is really good for is copying from DataObjects into POCO objects, or View Model objects.

```<code>    public class AddressViewModel
    {
              public string FullAddress{get;set;}
    }

    public class Address
    {
              public string Street{get;set;}
              public string Suburb{get;set;}
              public string City{get;set;}
    }

    CreateMap<Address, AddressViewModel>()
             .ForMember( x => x.FullAddress,
                              o => o.MapFrom( m => String.Format("{0},{1},{2}"), m.Street, m.Suburb, m.City  ) );

    Address address = new Address(){
        Street = "My Street";
        Suburb= "My Suburb";
        City= "My City";
    };

    AddressViewModel addressViewModel = Mapper.Map(address, Address, AddressViewModel);
</code>```

Title: How to use AutoMapper?

Body:
First time using AutoMapper and I'm have a hard time figuring out how to use it.
I'm trying to map a ViewModel to my Database Tables.

My ViewModel looks like this...

public class AddressEditViewModel
{
    public AddressEdit GetOneAddressByDistrictGuid { get; private set; }
    public IEnumerable<ZipCodeFind> GetZipCodes { get; private set; }

    public AddressEditViewModel(AddressEdit editAddress, IEnumerable<ZipCodeFind> Zips)
    {
        this.GetOneAddressByDistrictGuid = editAddress;
        this.GetZipCodes = Zips;
    }
}

The Mapping I'm trying to use is...

CreateMap<Address, AddressEditViewModel>();

When I run this test...

public void Should_map_dtos()
{
    AutoMapperConfiguration.Configure();
    Mapper.AssertConfigurationIsValid();
}

I get this error...

AutoMapper.AutoMapperConfigurationException: The following 2 properties on JCIMS_MVC2.DomainModel.ViewModels.AddressEditViewModel
  are not mapped:
  GetOneAddressByDistrictGuid
  GetZipCodes
  Add a custom mapping expression, ignore, or rename the property on JCIMS_MVC2.DomainModel.Address.

I'm not sure how I am supposed to map those 2 properties. I would appreciate any direction.  Thanks

Mark

Body:
Ok so I can see a few things you are doing that probably won't help.

Firstly this AutoMapper is used to copy Properties in one object to Properties in a diff object. Along the way it might interrogate or manipulate them to get the end result viewmodel in the correct state.

The properties are named 'Get...' which sounds more like a method to me.

The setters on your properties are private so AutoSetter won't be able to find them. Change these to minimum internal.

Use of a parametrized constructor is no longer needed when you use AutoMapper - as you are converting directly from one object to another. The parametised constructor is there mainly to show what is explicitly required by this object.

CreateMap<Address, AddressEditViewModel>()
         .ForMember( x => x.GetOneAddressByDistrictGuid ,
                          o => o.MapFrom( m => m."GetOneAddressByDistrictGuid") )
         .ForMember( x => x.GetZipCodes,
                          o => o.MapFrom( m => m."GetZipCodes" ) );

What Automapper is really good for is copying from DataObjects into POCO objects, or View Model objects.

    public class AddressViewModel
    {
              public string FullAddress{get;set;}
    }

    public class Address
    {
              public string Street{get;set;}
              public string Suburb{get;set;}
              public string City{get;set;}
    }

    CreateMap<Address, AddressViewModel>()
             .ForMember( x => x.FullAddress,
                              o => o.MapFrom( m => String.Format("{0},{1},{2}"), m.Street, m.Suburb, m.City  ) );

    Address address = new Address(){
        Street = "My Street";
        Suburb= "My Suburb";
        City= "My City";
    };

    AddressViewModel addressViewModel = Mapper.Map(address, Address, AddressViewModel);


问:
multiple AND conditions for a single column in where clause
I have a table with column ID, datatype Integer, now my requirement is to select data from table that matches certain values like

```<code>ID
1
2
3
4
</code>```

Possible conditons:

if ID = 1 and ID = 2 then retrive the dataset, if ID = 1 and ID = 5 then don't return result set.

now here is the whole issue:

I am not sure how to write this condition with And clause

If I write

```<code>select ID where ID = 1 and ID =2
</code>```

this doesn't return any rows.

Not sure how to write query for this particular condition, Also I can't use OR because my requirement is table should contain both the values then return the result set.

答:
A column cannot have two values in the same row, so you will never have ID=1 AND ID=2 in the same row. This is why you're not seeing any data returned. Your condition will always be false.

You need to say something like this:

```<code>select id where id=1 OR id=2;
</code>```

or like this:

```<code>select id where id in (1,2);
</code>```

Body:
I have a table with column ID, datatype Integer, now my requirement is to select data from table that matches certain values like

ID
1
2
3
4

Possible conditons:

if ID = 1 and ID = 2 then retrive the dataset, if ID = 1 and ID = 5 then don't return result set.

now here is the whole issue:

I am not sure how to write this condition with And clause

If I write

select ID where ID = 1 and ID =2

this doesn't return any rows.

Not sure how to write query for this particular condition, Also I can't use OR because my requirement is table should contain both the values then return the result set.

Body:
A column cannot have two values in the same row, so you will never have ID=1 AND ID=2 in the same row. This is why you're not seeing any data returned. Your condition will always be false.

You need to say something like this:

select id where id=1 OR id=2;

or like this:

select id where id in (1,2);


问:
How can I pass a variable value from a "page" to "layout" in Nuxt JS?
I'm a beginner in VUE and donnow this one is the correct syntax. I need the variable {{name}} to be set from a page. Which means I need to change the value of the variable page to page. How can I achieve that? Help me guys.

My "Layout" Code is like below -

```<code><template>
  <div class="login-page">
    <div class="col1">{{ name }}</div>
    <div class="col2">
      <div class="content-box">
        <nuxt />
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: ['name']
}
</script>
</code>```

And my "Page" code is following -

```<code><template>
  <div>Welcome</div>
</template>

<script>
export default {
  layout: 'login',
  data: function() {
    return {
      name: 'Victor'
    }
  }
}
</script>
</code>```

答:
this can be achieved by using the vuex module. The layout have access to the vuex store, so once a page is open, you can call a mutation to set the page name and listen the name state in the layout component.

First the Vuex module, we can add a module by creating a file in the store folder,
in this case we are creating the page module:

```<code>// page.js file in the store folder
const state = {
  name: ''
}

const mutations = {
    setName(state, name) {
    state.name = name
  }
}

const getters = {
  getName: (state) => state.name
}

export default {
  state,
  mutations,
  getters
}
</code>```

Now we can use the setPageName mutation to set the pageName value once a page reach the created hook (also can be the mounted hook):

```<code>// Page.vue page
<template>
  <div>Welcome</div>
</template>
<script>
  export default {
    layout: 'login',
    created() {
      this.$store.commit('page/setName', 'Hello')
    },
  }
</script>
</code>```

And in the layout component we have the computed property pageName (or name if we want):

```<code><template>
  <div class="login-page">
    <div class="col1">{{ name }}</div>
    <div class="col2">
      <div class="content-box">
        <nuxt />
      </div>
    </div>
  </div>
</template>
<script>
export default {
  computed: {
    name() {
      return this.$store.getters['page/getName']
    }
  }
}
</script>
</code>```

And it's done!

Answer to your question in the commets:

The idea behind modules is keep the related information to some functionality in one place. I.e Let's say you want to have name, title and subtitle for each page, so the page module state variable will be:

```<code>const state = { name: '', title: '', subtitle: ''}
</code>```

Each variable can be updated with a mutation, declaring:

```<code>const mutations = {
  setName(state, name) {
    state.name = name
  },
  setPageTitle(state, title) {
    state.title = title
  },
  setPageSubtitle(state, subtitle) {
    state.subtitle = subtitle
  },
}
</code>```

And their values can be updated from any page with:

```<code>this.$store.commit('page/setPageTitle', 'A page title')
</code>```

The same if you want to read the value:

```<code>computed: {
  title() {
    // you can get the variable state without a getter
    // ['page'] is the module name, nuxt create the module name
    // using the file name page.js
    return this.$store.state['page'].title
  }
}
</code>```

The getters are good for format or filter information.

A new module can be added anytime if required, the idea behind vuex and the modules is to have a place with the information that is required in many places through the application, in one place. I.e. the application theme information, if the user select the light or dark theme, maybe the colors can be changed. You can read more about vuex with nuxt here: https://nuxtjs.org/guide/vuex-store/ and https://vuex.vuejs.org/

Body:
I'm a beginner in VUE and donnow this one is the correct syntax. I need the variable {{name}} to be set from a page. Which means I need to change the value of the variable page to page. How can I achieve that? Help me guys.

My "Layout" Code is like below -

<template>

{{ name }}

        <nuxt />

</template>

And my "Page" code is following -

<template>

Welcome

</template>

Body:
this can be achieved by using the vuex module. The layout have access to the vuex store, so once a page is open, you can call a mutation to set the page name and listen the name state in the layout component.

First the Vuex module, we can add a module by creating a file in the store folder,
in this case we are creating the page module:

// page.js file in the store folder
const state = {
  name: ''
}

const mutations = {
    setName(state, name) {
    state.name = name
  }
}

const getters = {
  getName: (state) => state.name
}

export default {
  state,
  mutations,
  getters
}

Now we can use the setPageName mutation to set the pageName value once a page reach the created hook (also can be the mounted hook):

// Page.vue page
<template>
  <div>Welcome</div>
</template>
<script>
  export default {
    layout: 'login',
    created() {
      this.$store.commit('page/setName', 'Hello')
    },
  }
</script>

And in the layout component we have the computed property pageName (or name if we want):

<template>
  <div class="login-page">
    <div class="col1">{{ name }}</div>
    <div class="col2">
      <div class="content-box">
        <nuxt />
      </div>
    </div>
  </div>
</template>
<script>
export default {
  computed: {
    name() {
      return this.$store.getters['page/getName']
    }
  }
}
</script>

And it's done!

Answer to your question in the commets:

The idea behind modules is keep the related information to some functionality in one place. I.e Let's say you want to have name, title and subtitle for each page, so the page module state variable will be:

const state = { name: '', title: '', subtitle: ''}

Each variable can be updated with a mutation, declaring:

const mutations = {
  setName(state, name) {
    state.name = name
  },
  setPageTitle(state, title) {
    state.title = title
  },
  setPageSubtitle(state, subtitle) {
    state.subtitle = subtitle
  },
}

And their values can be updated from any page with:

this.$store.commit('page/setPageTitle', 'A page title')

The same if you want to read the value:

computed: {
  title() {
    // you can get the variable state without a getter
    // ['page'] is the module name, nuxt create the module name
    // using the file name page.js
    return this.$store.state['page'].title
  }
}

The getters are good for format or filter information.

A new module can be added anytime if required, the idea behind vuex and the modules is to have a place with the information that is required in many places through the application, in one place. I.e. the application theme information, if the user select the light or dark theme, maybe the colors can be changed. You can read more about vuex with nuxt here: https://nuxtjs.org/guide/vuex-store/ and https://vuex.vuejs.org/


问:
Spring Crontab pattern: every weekday at specific times
Here is the documentation for the Spring Crontab syntax.

I want to run a task every weekday at 14:40, 14:45, 14:50, 14:55, and 15:00, but I can't figure out how to express this with a Crontab pattern. The closest I've come up with so far is:

```<code>0 40/5 14 * * MON-FRI
</code>```

But this doesn't run at 15:00.

Is this possible to express with a Crontab pattern at all?

答:
You need to split it into two expressions :

```<code>0 40-55/5 14 * * MON-FRI
0 0 15 * * MON-FRI
</code>```

If you only want to have one expression and you are okay with the last trigger time in a day run one minute before, you can use :

```<code>0 40-55/5,59 14 * * MON-FRI
</code>```

Spring internally use CronSequenceGenerator to generate the next trigger time for a cron expression. You can use it to verify a cron expression.

For example , to verify the next several trigger times of 0 40-55/5,59 14 * * MON-FRI:

```<code>CronSequenceGenerator generator = new CronSequenceGenerator("0 40-55/5,59 14 * * MON-FRI");

Date d = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
for (int i = 0; i < 10; i++) {
    d = generator.next(d);
    System.out.println(d);
}
</code>```

which will print out :

```<code>Tue Jun 02 14:40:00 HKT 2020
Tue Jun 02 14:45:00 HKT 2020
Tue Jun 02 14:50:00 HKT 2020
Tue Jun 02 14:55:00 HKT 2020
Tue Jun 02 14:59:00 HKT 2020
Wed Jun 03 14:40:00 HKT 2020
Wed Jun 03 14:45:00 HKT 2020
Wed Jun 03 14:50:00 HKT 2020
Wed Jun 03 14:55:00 HKT 2020
Wed Jun 03 14:59:00 HKT 2020
</code>```

Body:
Here is the documentation for the Spring Crontab syntax.

I want to run a task every weekday at 14:40, 14:45, 14:50, 14:55, and 15:00, but I can't figure out how to express this with a Crontab pattern. The closest I've come up with so far is:

0 40/5 14 * * MON-FRI

But this doesn't run at 15:00.

Is this possible to express with a Crontab pattern at all?

Body:
You need to split it into two expressions :

0 40-55/5 14 * * MON-FRI
0 0 15 * * MON-FRI

If you only want to have one expression and you are okay with the last trigger time in a day run one minute before, you can use :

0 40-55/5,59 14 * * MON-FRI

Spring internally use CronSequenceGenerator to generate the next trigger time for a cron expression. You can use it to verify a cron expression.

For example , to verify the next several trigger times of 0 40-55/5,59 14 * * MON-FRI:

CronSequenceGenerator generator = new CronSequenceGenerator("0 40-55/5,59 14 * * MON-FRI");

Date d = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
for (int i = 0; i < 10; i++) {
    d = generator.next(d);
    System.out.println(d);
}

which will print out :

Tue Jun 02 14:40:00 HKT 2020
Tue Jun 02 14:45:00 HKT 2020
Tue Jun 02 14:50:00 HKT 2020
Tue Jun 02 14:55:00 HKT 2020
Tue Jun 02 14:59:00 HKT 2020
Wed Jun 03 14:40:00 HKT 2020
Wed Jun 03 14:45:00 HKT 2020
Wed Jun 03 14:50:00 HKT 2020
Wed Jun 03 14:55:00 HKT 2020
Wed Jun 03 14:59:00 HKT 2020


问:
Extracting first line from a file if condition matches in a block
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

```<code>host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0
</code>```

So, the output should be host1, host4. I have tried the below code:

```<code>awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt
</code>```

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

答:
could you please try following.

```<code>awk '
BEGIN{
  FS=":"
}
/host/{
  ho=$1
  next
}
ho && /Failed: 0/{
  total=(total?total",":"")ho
  ho=""
}
END{
  if(total){
    print total
  }
}
'  Input_file
</code>```

Explanation: Adding detailed explanation for above.

```<code>awk '                                ##Starting awk program from here.
BEGIN{                               ##Starting BEGIN section from here.
  FS=":"                             ##Setting field sep as : here.
}
/host/{                              ##Checking condition if host is in line.
  ho=$1                              ##Setting ho variable to $1 here.
  next                               ##next will skip all further statements from here.
}
ho && /Failed: 0/{                   ##Checking if ho is SET and Failed: 0 is found in line.
  total=(total?total",":"")ho        ##Creating total variable and keep on adding values in it.
  ho=""                              ##Nullifying ho here.
}
END{                                 ##Starting END block of this specific progra here.
  if(total){                         ##Checking if total is NOT NULL.
    print total                      ##Printing total variable here.
  }
}
'  Input_file                        ##Mentioning Input_file name here.
</code>```

As per OP request additional one liner form of above:

```<code>awk 'BEGIN{FS=":"} {gsub(/\r/,"")} /host/{ho=$1;next} ho && /Failed: 0/{total=(total?total",":"")ho;ho=""} END{if(total){print total}}'  Input_file
</code>```

Body:
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0

So, the output should be host1, host4. I have tried the below code:

awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

Body:
could you please try following.

awk '
BEGIN{
  FS=":"
}
/host/{
  ho=$1
  next
}
ho && /Failed: 0/{
  total=(total?total",":"")ho
  ho=""
}
END{
  if(total){
    print total
  }
}
'  Input_file

Explanation: Adding detailed explanation for above.

awk '                                ##Starting awk program from here.
BEGIN{                               ##Starting BEGIN section from here.
  FS=":"                             ##Setting field sep as : here.
}
/host/{                              ##Checking condition if host is in line.
  ho=$1                              ##Setting ho variable to $1 here.
  next                               ##next will skip all further statements from here.
}
ho && /Failed: 0/{                   ##Checking if ho is SET and Failed: 0 is found in line.
  total=(total?total",":"")ho        ##Creating total variable and keep on adding values in it.
  ho=""                              ##Nullifying ho here.
}
END{                                 ##Starting END block of this specific progra here.
  if(total){                         ##Checking if total is NOT NULL.
    print total                      ##Printing total variable here.
  }
}
'  Input_file                        ##Mentioning Input_file name here.

As per OP request additional one liner form of above:

awk 'BEGIN{FS=":"} {gsub(/\r/,"")} /host/{ho=$1;next} ho && /Failed: 0/{total=(total?total",":"")ho;ho=""} END{if(total){print total}}'  Input_file


问:
How to display the AirPlay Menu SwiftUI
Thanks to the airplay audio systemName emoji I made a nice icon

```<code>Button(action: {
        showAirplay()
}, label: {
    Image(systemName: "airplayaudio")
        .imageScale(.large)
})

func showAirplay() {
       ???
}
</code>```

But I have no idea how to display the famous menu :

答:
Wrapping the AirPlay UIView for SwiftUI seems to be the best and simplest solution.

```<code>struct AirPlayView: UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {

        let routePickerView = AVRoutePickerView()
        routePickerView.backgroundColor = UIColor.clear
        routePickerView.activeTintColor = UIColor.red
        routePickerView.tintColor = UIColor.white

        return routePickerView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
    }
}
</code>```

Usage :

```<code>VStack {
  AirPlayView()
}
</code>```

Title: How to display the AirPlay Menu SwiftUI

Body:
Thanks to the airplay audio systemName emoji I made a nice icon

Button(action: {
        showAirplay()
}, label: {
    Image(systemName: "airplayaudio")
        .imageScale(.large)
})

func showAirplay() {
       ???
}

But I have no idea how to display the famous menu :

Body:
Wrapping the AirPlay UIView for SwiftUI seems to be the best and simplest solution.

struct AirPlayView: UIViewRepresentable {

    func makeUIView(context: Context) -> UIView {

        let routePickerView = AVRoutePickerView()
        routePickerView.backgroundColor = UIColor.clear
        routePickerView.activeTintColor = UIColor.red
        routePickerView.tintColor = UIColor.white

        return routePickerView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
    }
}

Usage :

VStack {
  AirPlayView()
}


问:
Work with an Amazon S3 response stream after response has been disposed
I'm using the Amazon SDK and I have a method that returns a Stream for an object stored in Amazon S3 service.

It contains something like this:

```<code>var request = new GetObjectRequest().WithBucketName(bucketName).WithKey(keyName);
using (var response = client.GetObject(request))
{
    return response.ResponseStream;
}
</code>```

Obviously, when doing this, the stream is not readable from the calling method because the request object has been disposed and when this is done, it closes the stream.

I don't want to download the file to a MemoryStream or a FileStream.

If I don't use the using clause, the garbage collector will dispose the request object at some point so I can't just not use it.

What I'm asking is, is there a way to wrap or copy the Stream into another Stream and then return it without having to download the file?

I'm using .NET 3.5.

Edit: The method is inherited from an abstract class and the caller method doesn't know it is working with Amazon. So it HAS to return a Stream.

答: If your function returns the response object (without using the using statement), and the caller assigns it to a variable, there will still be a reference to the response object.  Thus it won't be eligible garbage collected.

Body:
I'm using the Amazon SDK and I have a method that returns a Stream for an object stored in Amazon S3 service.

It contains something like this:

var request = new GetObjectRequest().WithBucketName(bucketName).WithKey(keyName);
using (var response = client.GetObject(request))
{
    return response.ResponseStream;
}

Obviously, when doing this, the stream is not readable from the calling method because the request object has been disposed and when this is done, it closes the stream.

I don't want to download the file to a MemoryStream or a FileStream.

If I don't use the using clause, the garbage collector will dispose the request object at some point so I can't just not use it.

What I'm asking is, is there a way to wrap or copy the Stream into another Stream and then return it without having to download the file?

I'm using .NET 3.5.

Edit: The method is inherited from an abstract class and the caller method doesn't know it is working with Amazon. So it HAS to return a Stream.


问:
how I can choose which on as element and which one is attribute
the following is the problem for employee
I have to design the dtd, xml, xsl table for my final project

For each Employee you have the following features:

EMP_ID (1 occurrence, required)

Name (1 occurrence, required)

Salary (0 or 1 occurrence, optional)

DNO (1 occurrence, required)

According  to the above problem EMP_ID, Name, Salary, DNO can be the Employee element or attribute. regarding to occurrence which one I choose as attribute or Element can anyone tell me how to solve this problem thanks a lot for helping.

答:
thanks for reply Mr. Daniel Haley I have built my. dtd like this is this correct or need any changes.</p>

```<code><!ELEMENT Project (employee*,Department*)>
<!ELEMENT employee (EMPID,EName,Salary?,DNO)>
<!ELEMENT EMPID (#PCDATA)>
<!ELEMENT EName (#PCDATA)>
<!ELEMENT Salary (#PCDATA)>
<!ELEMENT DNO (#PCDATA)>

<!ATTLIST EMPID empId CDATA #REQUIRED>
<!ATTLIST EName empName CDATA #REQUIRED>
<!ATTLIST Salary empSalary CDATA #IMPLIED>
<!ATTLIST DNO depNo CDATA #REQUIRED>

<!ELEMENT Department (DEP_ID,DName,Location)>
<!ELEMENT DEP_ID (#PCDATA)>
<!ELEMENT DName (#PCDATA)>
<!ELEMENT Location (#PCDATA)>
<!ATTLIST DEP_ID depId CDATA #REQUIRED>
<!ATTLIST DName depName CDATA #REQUIRED>
<!ATTLIST Location dep CDATA #IMPLIED>`
</code>```

Body:
thanks for reply Mr. Daniel Haley I have built my. dtd like this is this correct or need any changes.

<!ELEMENT Project (employee*,Department*)>
<!ELEMENT employee (EMPID,EName,Salary?,DNO)>
<!ELEMENT EMPID (#PCDATA)>
<!ELEMENT EName (#PCDATA)>
<!ELEMENT Salary (#PCDATA)>
<!ELEMENT DNO (#PCDATA)>

<!ATTLIST EMPID empId CDATA #REQUIRED>
<!ATTLIST EName empName CDATA #REQUIRED>
<!ATTLIST Salary empSalary CDATA #IMPLIED>
<!ATTLIST DNO depNo CDATA #REQUIRED>

<!ELEMENT Department (DEP_ID,DName,Location)>
<!ELEMENT DEP_ID (#PCDATA)>
<!ELEMENT DName (#PCDATA)>
<!ELEMENT Location (#PCDATA)>
<!ATTLIST DEP_ID depId CDATA #REQUIRED>
<!ATTLIST DName depName CDATA #REQUIRED>
<!ATTLIST Location dep CDATA #IMPLIED>`


问:
Decrypting using AES returning blank string
```<code>import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Arrays;

import java.util.*;

public class AES {

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your 16 character key here:");
        String EncryptionKey = input.next();
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        KeyGen.init(128);

        Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
        System.out.println("Enter text to encrypt or decrypt:");
        String Text = input.next();

        System.out.println("Do you want to encrypt or decrypt (e/d)");
        String answer = input.next();
        if (answer.equalsIgnoreCase("e")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            byte[] byteCipherText = AesCipher.doFinal(byteText);

            System.out.println(byteCipherText);

        } else if (answer.equalsIgnoreCase("d")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            String decryptKeyString = input.nextLine();
            Charset charset = StandardCharsets.UTF_16;
            byte[] cipherText = decryptKeyString.getBytes(charset);

            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            //byte[] bytePlainText = AesCipher.doFinal(cipherText);
            String plaintext = new String(AesCipher.doFinal(cipherText), "UTF-8");
            //Files.write(Paths.get(FileName2), bytePlainText);
            System.out.println(plaintext);
        }
    }

}
</code>```

TERMINAL OUTPUT:

```<code>Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
helloworld
Do you want to encrypt or decrypt (e/d)
e
[B@504bae78
//SECOND RUN OF PROGRAM
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
[B@504bae78
Do you want to encrypt or decrypt (e/d)
d
</code>```

This code is largely repurposed from other code on StackExchange, I just wanted to adapt the code to not use files but to use the console instead. For some reason decryption always returns empty for me though.

If you could help me out with what specific line I have wrong that would be greatly appreciated. Thanks so much.

答:
When you want to print an array in Java, you should use Arrays.toString to convert it to string first:

```<code>System.out.println(Arrays.toString(byteCipherText));
</code>```

instead of:

```<code>System.out.println(byteCipherText);
</code>```

See this question for more ways to print an array in Java.

Body:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Arrays;

import java.util.*;

public class AES {

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your 16 character key here:");
        String EncryptionKey = input.next();
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        KeyGen.init(128);

        Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
        System.out.println("Enter text to encrypt or decrypt:");
        String Text = input.next();

        System.out.println("Do you want to encrypt or decrypt (e/d)");
        String answer = input.next();
        if (answer.equalsIgnoreCase("e")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            byte[] byteCipherText = AesCipher.doFinal(byteText);

            System.out.println(byteCipherText);

        } else if (answer.equalsIgnoreCase("d")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            String decryptKeyString = input.nextLine();
            Charset charset = StandardCharsets.UTF_16;
            byte[] cipherText = decryptKeyString.getBytes(charset);

            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            //byte[] bytePlainText = AesCipher.doFinal(cipherText);
            String plaintext = new String(AesCipher.doFinal(cipherText), "UTF-8");
            //Files.write(Paths.get(FileName2), bytePlainText);
            System.out.println(plaintext);
        }
    }

}

TERMINAL OUTPUT:

Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
helloworld
Do you want to encrypt or decrypt (e/d)
e
[B@504bae78
//SECOND RUN OF PROGRAM
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
[B@504bae78
Do you want to encrypt or decrypt (e/d)
d

This code is largely repurposed from other code on StackExchange, I just wanted to adapt the code to not use files but to use the console instead. For some reason decryption always returns empty for me though.

If you could help me out with what specific line I have wrong that would be greatly appreciated. Thanks so much.

Body:
When you want to print an array in Java, you should use Arrays.toString to convert it to string first:

System.out.println(Arrays.toString(byteCipherText));

instead of:

System.out.println(byteCipherText);

See this question for more ways to print an array in Java.


问:
How would I make projectiles rain from the sky infinitely in Unity2D?
I'm currently trying to make a simple game in Unity where the player can move and dodge falling projectiles randomly. However, I am not totally sure how to implement something like this into my game.

Any help would be greatly appreciated!

答:
You could make a rain prefab with the tag such as "rain" and instantiate it at a random position. The problem with this is if you want a lot of raindrops this will be very slow, but you could make the raindrops near the player the prefab I was talking about and all the raindrops the player is unable to touch particles to give the illusion of acid rain.

Just an idea not sure how good this solution is, hope it helps!


问:
Why does my array become undefined as soon as the function is over?
Okay, I'm just doing a function that moves everything from one list to another, and as soon as that's finished, it spontaneously becomes undefined. There is no good reason for it to do that but what's the bad reason?

Here, look,

```<code>function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    var listOne=[0, 1, 2, 3];//we have a list
    var listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;
//these are mandatory, without this, even with the function below script,
//you have Uncaught ReferenceError: list(One and Two) is not defined
moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW UNDEFINED??? What??????
</code>```

Just why? I literally just defined it in my function. What's wrong with you (literally, I don't see)?

答:
You have two separate listTwo variables. One is global, while the other is local to the function moveList. The two occurrences have nothing to do with each other. Same goes for listOne.

So your code is equivalent to the following code, where I have changed the names to be clearer:

function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    var localListOne=[0, 1, 2, 3];//we have a list
    var localListTwo=[];//now we have an empty list
    var length = localListOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        localListTwo.push(localListOne[0]);//it just copies the first entry from the first list to the second
        localListOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + localListTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + localListOne);//this tells us what the original list is, which is empty
}
var globalListOne;
var globalListTwo;
//these are mandatory, without this, even with the function below script,
//you have Uncaught ReferenceError: list(One and Two) is not defined
moveList();//now we do the function, and then,
console.log("listTwo: " + globalListTwo); // Obviously globalListTwo has never been given a value, so it is undefined.
```

Body:
Okay, I'm just doing a function that moves everything from one list to another, and as soon as that's finished, it spontaneously becomes undefined. There is no good reason for it to do that but what's the bad reason?

Here, look,

function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    var listOne=[0, 1, 2, 3];//we have a list
    var listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;
//these are mandatory, without this, even with the function below script,
//you have Uncaught ReferenceError: list(One and Two) is not defined
moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW UNDEFINED??? What??????

Just why? I literally just defined it in my function. What's wrong with you (literally, I don't see)?


问:
How to send a multiple emails at a time in cakephp
I need to send multiple emails at a time, can any one have example? or any idea ?
I need to send mail to all my site users at a time (Mail content is same for all)

Currently i using following code in a for loop

```<code>        $this->Email->from     = '<no-reply@noreply.com>';
        $this->Email->to       =  $email;
        $this->Email->subject  =   $subject ;
        $this->Email->sendAs   = 'html';
</code>```

答:
I think you have 2 possibilities:

foreach

Let's assume you have a function mail_users within your UsersController

```<code>function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    foreach ($users as $user) {
        $this->Email->reset();
        $this->Email->from     = '<no-reply@noreply.com>';
        $this->Email->to       =  $user['email'];
        $this->Email->subject  =  $subject ;
        $this->Email->sendAs   = 'html';
        $this->Email->send('Your message body');
    }
}
</code>```

In this function the $this->Email->reset() is important.

using BCC

```<code>function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    $bcc = '';
    foreach ($users as $user) {
        $bcc .= $user['email'].',';
    }
    $this->Email->from     = '<no-reply@noreply.com>';
    $this->Email->bcc      = $bcc;
    $this->Email->subject  = $subject;
    $this->Email->sendAs   = 'html';
    $this->Email->send('Your message body');
}
</code>```

Now you can just call this method with a link to /users/mail_users/subject

For more information be sure to read the manual on the Email Component.

Body:
I need to send multiple emails at a time, can any one have example? or any idea ?
I need to send mail to all my site users at a time (Mail content is same for all)

Currently i using following code in a for loop

        $this->Email->from     = '<no-reply@noreply.com>';
        $this->Email->to       =  $email;
        $this->Email->subject  =   $subject ;
        $this->Email->sendAs   = 'html';

Body:
I think you have 2 possibilities:

foreach

Let's assume you have a function mail_users within your UsersController

function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    foreach ($users as $user) {
        $this->Email->reset();
        $this->Email->from     = '<no-reply@noreply.com>';
        $this->Email->to       =  $user['email'];
        $this->Email->subject  =  $subject ;
        $this->Email->sendAs   = 'html';
        $this->Email->send('Your message body');
    }
}

In this function the $this->Email->reset() is important.

using BCC

function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    $bcc = '';
    foreach ($users as $user) {
        $bcc .= $user['email'].',';
    }
    $this->Email->from     = '<no-reply@noreply.com>';
    $this->Email->bcc      = $bcc;
    $this->Email->subject  = $subject;
    $this->Email->sendAs   = 'html';
    $this->Email->send('Your message body');
}

Now you can just call this method with a link to /users/mail_users/subject

For more information be sure to read the manual on the Email Component.


答:
The reason is that you initialize TWO lists with the name listTwo in different scopes! One in the global scope, which you don't give it a value, so it stays undefined, and another one inside the function, and that cannot be reached from outside the function as there is another variable with the same name already!

For your code to work you should use the variables inside the function without declaring them.

```<code>function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    listOne=[0, 1, 2, 3];//we have a list
    listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;

moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW NOT UNDEFINED ;)
</code>```

The same applies for listOne variable as well.

Title: Why does my array become undefined as soon as the function is over?

Body:
The reason is that you initialize TWO lists with the name listTwo in different scopes! One in the global scope, which you don't give it a value, so it stays undefined, and another one inside the function, and that cannot be reached from outside the function as there is another variable with the same name already!

For your code to work you should use the variables inside the function without declaring them.

function moveList(){//in my real program it actually shuffles the list, this one just transfers the contents
    listOne=[0, 1, 2, 3];//we have a list
    listTwo=[];//now we have an empty list
    var length = listOne.length//and now we have the list length
    for (run = 0; run < length; run++) {
        listTwo.push(listOne[0]);//it just copies the first entry from the first list to the second
        listOne.splice(0, 1,)//and deletes it from the first list
    }//this does it for an entry in the list, it's length amount of times
    console.log("listTwo: " + listTwo);//this tells us what the new list now is, and it works
    console.log("listOne: " + listOne);//this tells us what the original list is, which is empty
}
var listOne;
var listTwo;

moveList();//now we do the function, and then,
console.log("listTwo: " + listTwo);//THE LIST IS NOW NOT UNDEFINED ;)

The same applies for listOne variable as well.


问:
Alert if Label goes missing from a metric
I have a metric
DS_Info{desc="GOT",index="312",name="EC80",exported_namespace="s905"}

Is there anyway I can alert if any one of these labels go missing. Not the metric, just one of the labels.

Thanks

答:
What you want is to alert if any of the label is missing (empty): meaning if it is different from regex .+.

If you want to exclude the case where the metric itself is missing, you can use the UNLESS operator in the following way:

```<code>- alert: MissingLabelInInfoMetric
  rule: DS_Info UNLESS DS_Info{desc=~".+",index=~".+",name=~".+",exported_namespace=~".+"}
</code>```

Which reads as "alert if DS_Info exists unless mentioned labels are not empty".

Body:
What you want is to alert if any of the label is missing (empty): meaning if it is different from regex .+.

If you want to exclude the case where the metric itself is missing, you can use the UNLESS operator in the following way:

- alert: MissingLabelInInfoMetric
  rule: DS_Info UNLESS DS_Info{desc=~".+",index=~".+",name=~".+",exported_namespace=~".+"}

Which reads as "alert if DS_Info exists unless mentioned labels are not empty".


问:
How do I manipulate a GET response in Angular 8?
I have a .Net core Api:

  var response = new
            {
                Data = data,
                TotalPages = totalPages
            };
            return Ok(response);
        }
```

<p>Data is an IEnumerable of Orders and total pages is an int.
I want to give this response in my Angular app so I have a service</p>

<pre class="lang-js prettyprint-override"><code>interface Response {
  totalPages: number;
  data: any;
}

@Injectable({
  providedIn: 'root'
})

export class OrderDataService {

  constructor(private http: HttpClient) {}

  getOrder(pageNumber: number, pageSize: number): Observable<any> {

    return this.http.get<Response>('http://localhost:5001/api/order/' + pageNumber + '/' + pageSize).pipe(
      map(res => res ),
      );
  }

}
</code>```

My component looks like this:

  constructor(private orderData: OrderDataService) { }

  orders: Order [];
  page = 1;
  pageSize = 10;
  total = 0;

  ngOnInit() {
    this.getOrders();
  }

  getOrders(): void {
    this.orderData.getOrder(this.page, this.pageSize)
    .subscribe(res => {
      this.orders = X;
      this.total = Y;

    });

  }

```

I want this.orders to contain the Data part of the response and this.total to contain the totalPages.

答:
You already have the answer, you just need to assign it in the subscription:

```<code>this.order = res.data;
this.total = res.totalPages;
</code>```

Also try to use typescript at it's best utilizing types, you can change your return type of getOrder to Observable<Response>.

Also change your interface declaration to:

```<code>interface Response {
  totalPages: number;
  data: Order[];
}
</code>```

Also I couldn't understand the purpose of the map in the getOrder function, I think it should look like this:

```<code> return this.http.get<Response>(`http://localhost:5001/api/order/${pageNumber}/${pageSize});
</code>```

Body:
I have a .Net core Api:

  var response = new
            {
                Data = data,
                TotalPages = totalPages
            };
            return Ok(response);
        }

Data is an IEnumerable of Orders and total pages is an int.
I want to give this response in my Angular app so I have a service

interface Response {
  totalPages: number;
  data: any;
}

@Injectable({
  providedIn: 'root'
})

export class OrderDataService {

  constructor(private http: HttpClient) {}

  getOrder(pageNumber: number, pageSize: number): Observable<any> {

    return this.http.get<Response>('http://localhost:5001/api/order/' + pageNumber + '/' + pageSize).pipe(
      map(res => res ),
      );
  }

}

My component looks like this:

  constructor(private orderData: OrderDataService) { }

  orders: Order [];
  page = 1;
  pageSize = 10;
  total = 0;

  ngOnInit() {
    this.getOrders();
  }

  getOrders(): void {
    this.orderData.getOrder(this.page, this.pageSize)
    .subscribe(res => {
      this.orders = X;
      this.total = Y;

    });

  }

I want this.orders to contain the Data part of the response and this.total to contain the totalPages.

Body:
You already have the answer, you just need to assign it in the subscription:

this.order = res.data;
this.total = res.totalPages;

Also try to use typescript at it's best utilizing types, you can change your return type of getOrder to Observable<Response>.

Also change your interface declaration to:

interface Response {
  totalPages: number;
  data: Order[];
}

Also I couldn't understand the purpose of the map in the getOrder function, I think it should look like this:

 return this.http.get<Response>(`http://localhost:5001/api/order/${pageNumber}/${pageSize});


问:
How to instantiate a Room object called room1 and print with string representation of room1 in python?
I am doing a question where it is telling me to instantiate a Room object called room1 with size = 132, view = 'City', type = 'Double', and basicRates = 120. Then, I have to print a string representation of room1. How should I do this?

答:
Like this?

```<code>class Room():
    size = 0
    view = ""
    type_ = ""
    basic_rates = 0

    def __str__(self):
        return 'Size: ' + str(self.size) + '\n' + 'View: ' + self.view + '\n' + \
            'Type: ' + self.type_ + '\n' + \
            'Basic Rates: ' + str(self.basic_rates)

room1 = Room()
room1.size = 132
room1.view = 'City'
room1.type_ = 'Double'
room1.basic_rates = 120

print(room1.__str__())
</code>```

Also, you should read about Python Classes

Body:
Like this?

class Room():
    size = 0
    view = ""
    type_ = ""
    basic_rates = 0

    def __str__(self):
        return 'Size: ' + str(self.size) + '\n' + 'View: ' + self.view + '\n' + \
            'Type: ' + self.type_ + '\n' + \
            'Basic Rates: ' + str(self.basic_rates)

room1 = Room()
room1.size = 132
room1.view = 'City'
room1.type_ = 'Double'
room1.basic_rates = 120

print(room1.__str__())

Also, you should read about Python Classes


问:
is it possible to call out Verilog function in a VHDL code by using Quartus
I'm currently reviewing 2 types of code (VHDL and Verilog).
I trying to combine some function from Verilog into VHDL code by using Quartus.
Is it possible to do it directly in Quartus?
Or any recommend free Verilog2VHDL converter?</p>

答:
There's no way to call a Verilog function from VHDL directly.

What you'll have to do is wrap the function in an module so that the function gets called whenever the inputs change, and make an assignment to the output.

```<code>module wrap_function(input arg1,arg2, output arg3);

function Vfunction(input arg1, arg2);
   begin
   // whatever
   Vfunction = ...;
   end
endfunction

assign arg3 = Vfunction(arg1,arg2);
endmodule
</code>```

Then you can instantiate this module in a similar VHDL entity wrapper that has a procedure the modifies the input and captures the outputs.

Body:
There's no way to call a Verilog function from VHDL directly.

What you'll have to do is wrap the function in an module so that the function gets called whenever the inputs change, and make an assignment to the output.

module wrap_function(input arg1,arg2, output arg3);

function Vfunction(input arg1, arg2);
   begin
   // whatever
   Vfunction = ...;
   end
endfunction

assign arg3 = Vfunction(arg1,arg2);
endmodule

Then you can instantiate this module in a similar VHDL entity wrapper that has a procedure the modifies the input and captures the outputs.