问:
How can I import functions from an other javascript file?
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

```<code>export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}
</code>```

--- main.js ---

```<code>import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();
</code>```

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.

答:
Okay, so I figured it out!

The main problem was that I haven't added the "type="module"" attribute to my main.js file in my HTML. After that I got an other error: "404- Not Found", and I could fix it by adding ".js" after my import. So the perfectly working code is:

--- index.html ---

```<code><script src="../static/js/main.js" type="module"></script>
<script src="../static/js/dataManager.js" type="module"></script>
</code>```

--- dataManager.js ---

```<code>export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText);
    };
    allPlanetsInfo.send();

}
</code>```

--- main.js ---

```<code>import { getAllPlanetDataFromAPI } from './dataManager.js';

getAllPlanetDataFromAPI();
</code>```

Thanks for all of the answers and comments, especially @yaswanth who moved me in the direction of the solution!

Body:
I'm pretty new in JS, and I have some trouble with importing.

I'm doing a Star Wars planet list application, where I'd like to import functions from an other JS file like this:

--- dataManager.js ---

export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText)
    };
    allPlanetsInfo.send();

}

--- main.js ---

import { getAllPlanetDataFromAPI } from './dataManager';

getAllPlanetDataFromAPI();

The error message I get is: "Uncaught SyntaxError: Unexpected token {"

Seems like the syntax is incorrect, but I have already checked all of the "import" articles on the web, and couldn't find what I'm doing wrong.

Body:
Okay, so I figured it out!

The main problem was that I haven't added the "type="module"" attribute to my main.js file in my HTML. After that I got an other error: "404- Not Found", and I could fix it by adding ".js" after my import. So the perfectly working code is:

--- index.html ---

<script src="../static/js/main.js" type="module"></script>
<script src="../static/js/dataManager.js" type="module"></script>

--- dataManager.js ---

export function getAllPlanetDataFromAPI() {

    let allPlanetsInfo = new XMLHttpRequest();
    allPlanetsInfo.open('GET', 'https://swapi.co/api/planets');
    allPlanetsInfo.onload = function () {
        console.log(allPlanetsInfo.responseText);
    };
    allPlanetsInfo.send();

}

--- main.js ---

import { getAllPlanetDataFromAPI } from './dataManager.js';

getAllPlanetDataFromAPI();

Thanks for all of the answers and comments, especially @yaswanth who moved me in the direction of the solution!


来源: stackexchange

问:
Auth0->Atlassian SAML SSO Problem (SP Entity and ACS URL)
So I'm trying to integrate single sign-on with Auth0 (being both the service provider and the identity provider) with the Atlassian stack.

Atlassian offer SAML single sign-on. However, it is telling me:

```<code>Your users won't be able to log in with SAML single sign-on until you've copied
the values for SP Entity ID and SP Assertion Consumer Service URL to your
identity provider.
</code>```

I've put the assertion consumer service URL in place of the callback URL, I've done some research and I'm almost certain this is correct.

However, the issue is with the Entity ID. Where does this go?

答:
I've not used Auth0 before, but I think you have to set it as audience in the settings, e.g. see https://auth0.com/docs/protocols/saml/saml-apps/heroku
IMHO but the configuration option is a bit misleading. Instead of using audience, using EntityID might be clearer, as this is also the term used in the SAML spec.

ContentLicense: CC BY-SA 4.0

Body:
So I'm trying to integrate single sign-on with Auth0 (being both the service provider and the identity provider) with the Atlassian stack.

Atlassian offer SAML single sign-on. However, it is telling me:

Your users won't be able to log in with SAML single sign-on until you've copied
the values for SP Entity ID and SP Assertion Consumer Service URL to your
identity provider.

I've put the assertion consumer service URL in place of the callback URL, I've done some research and I'm almost certain this is correct.

However, the issue is with the Entity ID. Where does this go?


问:
How to hide the x-axis values while subplotting with plotly
I'm using plotly to plot a large csv file (with a lot of data) and to subplot in line (which works actually) some charts.
The problem is that for each chart I get all of the date+time for each point on the x-axis resulting in a bad quality chart. How can I hide for the 5 first chart the values of the x-axis while keeping it for the last one to have a better vieaw of the charts ?

Here is my code : the problematic part start at line 125

import os
import pandas as pd
import plotly
import plotly.graph_objs as go
from tkinter import *

window = Tk()
window.title("Interface utilisateur")

consigne=Label(window, text="Merci de remplir les champs ci-dessous avant de cliquer sur start")
consigne.grid(column = 1,row=0)

consDateDEB=Label(window, text="Date de début de sélection (format JJMMAAAA)")
consDateDEB.grid(column=0,row=1)
DateDEB = Entry(window,width=25)
DateDEB.grid(column = 2,row=1)

consDateFIN=Label(window, text="Date de fin de sélection (format JJMMAAAA)")
consDateFIN.grid(column=0,row=2)
DateFIN = Entry(window,width=25)
DateFIN.grid(column = 2,row=2)

consPathIN=Label(window, text="Chemin d'accès aux fichiers (format C://user/dossier1/dossier2/)")
consPathIN.grid(column=0,row=3)
PathIN = Entry(window,width=50)
PathIN.grid(column = 2,row=3)

consPathOUT=Label(window, text="Chemin d'écriture des fichiers (format C://user/dossier1/dossier2/)")
consPathOUT.grid(column=0,row=4)
PathOUT = Entry(window,width=50)
PathOUT.grid(column = 2,row=4)

def click():
        pathIN = PathIN.get()
        pathOUT = PathOUT.get()
        DateDebut = DateDEB.get()
        DateFin = DateFIN.get()
        tracer(DateDebut,DateFin,pathIN,pathOUT)
btn = Button(window, text='Start',command=click,width=30,height=2,activebackground='red')
btn.grid(column = 1,row=5)

window.mainloop()

def tracer(DateDebut,DateFin,pathIN,pathOUT):
#    DateDebut=10052019
#    DateFin=12052019
#    pathIN='D://Clef64go/PJT/Logfiles/'
#    pathOUT='D://Clef64go/PJT/OUT/'
    Logfiles = os.listdir(pathIN)

    def conversion(Logfile_JJMMAAAA):
        nomFichierINT = int(Logfile_JJMMAAAA[12:16] + Logfile_JJMMAAAA[10:12] + Logfile_JJMMAAAA[8:10])
        return nomFichierINT

    def conversionInverse(AAAAMMJJ):
        AAAAMMJJ = str(AAAAMMJJ)
        nomFichierSTR = "Logfile_" + AAAAMMJJ[6:8] + AAAAMMJJ[4:6] + AAAAMMJJ[0:4]+".csv"
        return nomFichierSTR

    DateDebut = str(DateDebut)
    DateFin = str(DateFin)
    DebTempo = DateDebut[4:8]+DateDebut[2:4]+DateDebut[0:2]
    FinTempo = DateFin[4:8]+DateFin[2:4]+DateFin[0:2]
    DateDebut=int(DebTempo)
    DateFin=int(FinTempo)

    L_Selection=[]
    for fichier in Logfiles:
        Tempo=conversion(fichier)
        if Tempo >= DateDebut and Tempo <= DateFin :
            L_Selection.append(Tempo)

    L_Selection = sorted(L_Selection)
    L_Clean=[]

    for fichier in L_Selection :
        Tempo = conversionInverse(fichier)
        L_Clean.append(Tempo)

    #L_Log = os.listdir("D://Clef64go/PJT/TEST2/")
    dfList=[]
    colnames=['No.','Date','Time','Temp1','Unit','Temp2','Unit','Lux2','Unit','BP1','Humidité Relat','Unit','CO2','Unit','Présence','Temp1_EnO','Unit','Temp2_EnO','Unit','Temp3_EnO','Unit','RH3_EnO','Unit','Chauffage','test']
    for filename in L_Clean:
        filename = pathIN + filename
        typefile=type(filename)
        df=pd.read_csv(filename, sep = ';', error_bad_lines=False, encoding="ANSI")
        dfList.append(df)

    concatDf=pd.concat(dfList,axis=0)
    concatDf.columns=colnames
    pathOUT = pathOUT + "/" + str(DateDebut) +" a "+ str(DateFin) + ".csv"
    concatDf.to_csv(pathOUT, sep = ';',index=False)

    df = pd.read_csv(pathOUT,decimal=",",sep = ';', error_bad_lines=False, encoding="ANSI",names=colnames)
    df['Temp1'] = [x.replace(',', '.') for x in df['Temp1']]
    df['Temp2'] = [x.replace(',', '.') for x in df['Temp2']]
    df['Temp1_EnO'] = [x.replace(',', '.') for x in df['Temp1_EnO']]
    df['Temp2_EnO'] = [x.replace(',', '.') for x in df['Temp2_EnO']]
    df['Temp3_EnO'] = [x.replace(',', '.') for x in df['Temp3_EnO']]

    date = df['Date']+df['Time']
    y1 = df['Temp1']
    y2 = df['Temp2']
    y3 = df['Temp3_EnO']
    y4 = df['Humidité Relat']
    y5 = df['CO2']
    y6 = df['Présence']

    #plotly.offline.plot({
    #    "data": [go.Scatter(x=x, y=y)],
    #        "layout": go.Layout(title="Température 1 en fonction du temps")
    #   }, auto_open=True)

    temp1 = go.Scatter(
        x=date,
        y=y1,
        name="Température 1 (°C)"
    )
    temp2 = go.Scatter(
        x=date,
        y=y2,
        name="Température 2 (°C)"
    )
    temp3 = go.Scatter(
        x=date,
        y=y3,
        name="Température 3 (°C)"
    )
    Humidite = go.Scatter(
        x=date,
        y=y4,
        name="Humidité relative (%)"
    )
    dioxyde_de_carbone = go.Scatter(
        x=date,
        y=y5,
        name="Taux C02 (ppm)"
    )
    presence = go.Scatter(
        x=date,
        y=y6,
        name="Présence"
    )

    fig = plotly.tools.make_subplots(rows=6, cols=1)

    fig.append_trace(temp1, 1, 1)
    fig.append_trace(temp2, 2, 1)
    fig.append_trace(temp3, 3, 1)
    fig.append_trace(Humidite, 4, 1)
    fig.append_trace(dioxyde_de_carbone, 5, 1)
    fig.append_trace(presence, 6, 1)

    fig['layout'].update(title='Représentation graphique des données')
    plotly.offline.plot(fig, filename=str(DateDebut) +" a "+ str(DateFin) + ".csv", auto_open=True)
```

Here is what I get :

答:
I started from Andrews comment. But the relevant source is this one:

```<code>trace0 = go.Scatter(
  x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3],
  y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0]
)

trace1 = go.Scatter(
  x = [0,1,2,3],
  y = [1,2,4,8],
  yaxis = "y2"
)

layout = go.Layout(
    width = 800,
    height = 500,
    title = "fixed-ratio axes",
    xaxis = dict(
      nticks = 10,
      domain = [0, 0.45],
      title = "shared X axis"
    ),
    yaxis = dict(
      scaleanchor = "x",
      domain = [0, 0.45],
      title = "1:1"
    ),
    yaxis2 = dict(
      scaleanchor = "x",
      scaleratio = 0.2,
      domain = [0.55,1],
      title = "1:5"
    ))
</code>```

Explanation

You need to define the xaxis once. For every other subplot you set scaleanchor = "x", so that every subplot shares the same xaxis. All the plots that share one xasis are automatically plotted as subplots, so you coul get rid of your present structure.

Required Edit

```<code>    data = [temp1,temp2,temp3,Humidite, dioxyde_de_carbone, presence]

    layout = go.Layout(
        width = 800,
        height = 500,
        title = "fixed-ratio axes using 10 ticks",
        xaxis = dict(
        nticks = 10,
        title = "shared X axis showing DATE"
        ),
        yaxis = dict(
        scaleanchor = "x",
        title = "Temp"
        ),
        yaxis2 = dict(
        scaleanchor = "x",
        title = "Humidity"
        ),
        yaxis3 = dict(
        scaleanchor = "x",
        title = "ppm"
        ),
        yaxis4 = dict(
        scaleanchor = "x",
        title = "presence"
        ),
        showlegend= False
    )

    fig = go.Figure(data=data, layout=layout)
    plotly.offline.plot(fig, filename=str(DateDebut) +" a "+ str(DateFin) + ".csv", auto_open=True)
    fig = plotly.tools.make_subplots(rows=6, cols=1)
</code>```

Body:
I'm using plotly to plot a large csv file (with a lot of data) and to subplot in line (which works actually) some charts.
The problem is that for each chart I get all of the date+time for each point on the x-axis resulting in a bad quality chart. How can I hide for the 5 first chart the values of the x-axis while keeping it for the last one to have a better vieaw of the charts ?

Here is my code : the problematic part start at line 125

import os
import pandas as pd
import plotly
import plotly.graph_objs as go
from tkinter import *

window = Tk()
window.title("Interface utilisateur")

consigne=Label(window, text="Merci de remplir les champs ci-dessous avant de cliquer sur start")
consigne.grid(column = 1,row=0)

consDateDEB=Label(window, text="Date de début de sélection (format JJMMAAAA)")
consDateDEB.grid(column=0,row=1)
DateDEB = Entry(window,width=25)
DateDEB.grid(column = 2,row=1)

consDateFIN=Label(window, text="Date de fin de sélection (format JJMMAAAA)")
consDateFIN.grid(column=0,row=2)
DateFIN = Entry(window,width=25)
DateFIN.grid(column = 2,row=2)

consPathIN=Label(window, text="Chemin d'accès aux fichiers (format C://user/dossier1/dossier2/)")
consPathIN.grid(column=0,row=3)
PathIN = Entry(window,width=50)
PathIN.grid(column = 2,row=3)

consPathOUT=Label(window, text="Chemin d'écriture des fichiers (format C://user/dossier1/dossier2/)")
consPathOUT.grid(column=0,row=4)
PathOUT = Entry(window,width=50)
PathOUT.grid(column = 2,row=4)

def click():
        pathIN = PathIN.get()
        pathOUT = PathOUT.get()
        DateDebut = DateDEB.get()
        DateFin = DateFIN.get()
        tracer(DateDebut,DateFin,pathIN,pathOUT)
btn = Button(window, text='Start',command=click,width=30,height=2,activebackground='red')
btn.grid(column = 1,row=5)

window.mainloop()

def tracer(DateDebut,DateFin,pathIN,pathOUT):
#    DateDebut=10052019
#    DateFin=12052019
#    pathIN='D://Clef64go/PJT/Logfiles/'
#    pathOUT='D://Clef64go/PJT/OUT/'
    Logfiles = os.listdir(pathIN)

    def conversion(Logfile_JJMMAAAA):
        nomFichierINT = int(Logfile_JJMMAAAA[12:16] + Logfile_JJMMAAAA[10:12] + Logfile_JJMMAAAA[8:10])
        return nomFichierINT

    def conversionInverse(AAAAMMJJ):
        AAAAMMJJ = str(AAAAMMJJ)
        nomFichierSTR = "Logfile_" + AAAAMMJJ[6:8] + AAAAMMJJ[4:6] + AAAAMMJJ[0:4]+".csv"
        return nomFichierSTR

    DateDebut = str(DateDebut)
    DateFin = str(DateFin)
    DebTempo = DateDebut[4:8]+DateDebut[2:4]+DateDebut[0:2]
    FinTempo = DateFin[4:8]+DateFin[2:4]+DateFin[0:2]
    DateDebut=int(DebTempo)
    DateFin=int(FinTempo)

    L_Selection=[]
    for fichier in Logfiles:
        Tempo=conversion(fichier)
        if Tempo >= DateDebut and Tempo <= DateFin :
            L_Selection.append(Tempo)

    L_Selection = sorted(L_Selection)
    L_Clean=[]

    for fichier in L_Selection :
        Tempo = conversionInverse(fichier)
        L_Clean.append(Tempo)

    #L_Log = os.listdir("D://Clef64go/PJT/TEST2/")
    dfList=[]
    colnames=['No.','Date','Time','Temp1','Unit','Temp2','Unit','Lux2','Unit','BP1','Humidité Relat','Unit','CO2','Unit','Présence','Temp1_EnO','Unit','Temp2_EnO','Unit','Temp3_EnO','Unit','RH3_EnO','Unit','Chauffage','test']
    for filename in L_Clean:
        filename = pathIN + filename
        typefile=type(filename)
        df=pd.read_csv(filename, sep = ';', error_bad_lines=False, encoding="ANSI")
        dfList.append(df)

    concatDf=pd.concat(dfList,axis=0)
    concatDf.columns=colnames
    pathOUT = pathOUT + "/" + str(DateDebut) +" a "+ str(DateFin) + ".csv"
    concatDf.to_csv(pathOUT, sep = ';',index=False)

    df = pd.read_csv(pathOUT,decimal=",",sep = ';', error_bad_lines=False, encoding="ANSI",names=colnames)
    df['Temp1'] = [x.replace(',', '.') for x in df['Temp1']]
    df['Temp2'] = [x.replace(',', '.') for x in df['Temp2']]
    df['Temp1_EnO'] = [x.replace(',', '.') for x in df['Temp1_EnO']]
    df['Temp2_EnO'] = [x.replace(',', '.') for x in df['Temp2_EnO']]
    df['Temp3_EnO'] = [x.replace(',', '.') for x in df['Temp3_EnO']]

    date = df['Date']+df['Time']
    y1 = df['Temp1']
    y2 = df['Temp2']
    y3 = df['Temp3_EnO']
    y4 = df['Humidité Relat']
    y5 = df['CO2']
    y6 = df['Présence']

    #plotly.offline.plot({
    #    "data": [go.Scatter(x=x, y=y)],
    #        "layout": go.Layout(title="Température 1 en fonction du temps")
    #   }, auto_open=True)

    temp1 = go.Scatter(
        x=date,
        y=y1,
        name="Température 1 (°C)"
    )
    temp2 = go.Scatter(
        x=date,
        y=y2,
        name="Température 2 (°C)"
    )
    temp3 = go.Scatter(
        x=date,
        y=y3,
        name="Température 3 (°C)"
    )
    Humidite = go.Scatter(
        x=date,
        y=y4,
        name="Humidité relative (%)"
    )
    dioxyde_de_carbone = go.Scatter(
        x=date,
        y=y5,
        name="Taux C02 (ppm)"
    )
    presence = go.Scatter(
        x=date,
        y=y6,
        name="Présence"
    )

    fig = plotly.tools.make_subplots(rows=6, cols=1)

    fig.append_trace(temp1, 1, 1)
    fig.append_trace(temp2, 2, 1)
    fig.append_trace(temp3, 3, 1)
    fig.append_trace(Humidite, 4, 1)
    fig.append_trace(dioxyde_de_carbone, 5, 1)
    fig.append_trace(presence, 6, 1)

    fig['layout'].update(title='Représentation graphique des données')
    plotly.offline.plot(fig, filename=str(DateDebut) +" a "+ str(DateFin) + ".csv", auto_open=True)

Here is what I get :

Body:
I started from Andrews comment. But the relevant source is this one:

trace0 = go.Scatter(
  x = [0,1,1,0,0,1,1,2,2,3,3,2,2,3],
  y = [0,0,1,1,3,3,2,2,3,3,1,1,0,0]
)

trace1 = go.Scatter(
  x = [0,1,2,3],
  y = [1,2,4,8],
  yaxis = "y2"
)

layout = go.Layout(
    width = 800,
    height = 500,
    title = "fixed-ratio axes",
    xaxis = dict(
      nticks = 10,
      domain = [0, 0.45],
      title = "shared X axis"
    ),
    yaxis = dict(
      scaleanchor = "x",
      domain = [0, 0.45],
      title = "1:1"
    ),
    yaxis2 = dict(
      scaleanchor = "x",
      scaleratio = 0.2,
      domain = [0.55,1],
      title = "1:5"
    ))

Explanation

You need to define the xaxis once. For every other subplot you set scaleanchor = "x", so that every subplot shares the same xaxis. All the plots that share one xasis are automatically plotted as subplots, so you coul get rid of your present structure.

Required Edit

    data = [temp1,temp2,temp3,Humidite, dioxyde_de_carbone, presence]

    layout = go.Layout(
        width = 800,
        height = 500,
        title = "fixed-ratio axes using 10 ticks",
        xaxis = dict(
        nticks = 10,
        title = "shared X axis showing DATE"
        ),
        yaxis = dict(
        scaleanchor = "x",
        title = "Temp"
        ),
        yaxis2 = dict(
        scaleanchor = "x",
        title = "Humidity"
        ),
        yaxis3 = dict(
        scaleanchor = "x",
        title = "ppm"
        ),
        yaxis4 = dict(
        scaleanchor = "x",
        title = "presence"
        ),
        showlegend= False
    )

    fig = go.Figure(data=data, layout=layout)
    plotly.offline.plot(fig, filename=str(DateDebut) +" a "+ str(DateFin) + ".csv", auto_open=True)
    fig = plotly.tools.make_subplots(rows=6, cols=1)


问:
How can I maintain multiple versions of an applications on playstore?
I want to maintain multiple versions of an application ,so that EMM admin has a control where he can silently push different version to different devices using android management api.

Google play doesn't allow to maintain multiple versions of an application.

答:
It depends what you mean and what you want for different versions. There are a bunch of important questions:

would you ever want a user to change version from one version to another (and back again)?

would you ever want a user to have two versions installed at once?

If the answer to both of the above is yes, then you will need to use different package names for the versions. If the answer is no, then Google Play lets you have different versions using test channels.

But in general you are right. Google Play requires all users of an app to get the latest version.


问:
Regular Expression in .NET
I should write a regex pattern in c# that checks for input string whether it conains certain characters and does not conain another characters, for example:
I want that the string contain only a-z, not contain (d,b) and the length of all the string longer than 5, I write "[a-z]{5,}", how can I avoid that the input contain d and b?

Additional question: Can I have option to condition in the regex, in other words if whichever boolian var equals true check somthing and if it equals false not check it?

Thanks

答:
For the first question, why not simply try this: [ace-z]{5,} ?
For the second option, can't you format the regex string in some way based on the boolean variable before executing it ?
Or, if you want programmatically exclude some chars, you can create programmatically the regex by expliciting all the chars [abcdefgh....] without the exclusion.

ContentLicense: CC BY-SA 3.0

Title: Regular Expression in .NET


问:
Committee Methods (ensemble learners) Best Model
I have the following question and I seek your kind support:

You are given the choice of two types of base classifiers (models) to
  use in a (bagged) committee:

Classifier A: which is known to have an (error) variance of 40, but has been found to produce uncorrelated models under bagging

Classifier B: which is known to have an (error) variance of 30, but has been found to produce models with a pairwise covariance of 0.3
  under bagging

Assuming Classifiers A and B have equal error bias and a committee of
  size 10, which Classifier would you choose and why?

Personally, I would go for Classifier B because having a variance of 0.3 is better than having uncorrelated  models.

Am I right in this?

答: You are right. B is better for the reason you specified</p>


问:
write a sql stored procedure to delete the data from the table?
I have a simple application which stores the data into the sql server database table named student table .The design of the table is as follows 3 colums. name ,sex and registeredtime(datetime).In my WPF window i have three fields to insert the data into the table.Now i want to have the delete button based on the input given by the user(which is a datetimepicker).

How to delete the data from the table which is 7 days old compared to the date given by the user. ?

I want to have a stored procedure which i can call from the c# code.i am able to try some thing like this but Select * from studenttable where registereddate < GetDate()-7 but i am unable to achieve what i am supposed to ...

答:
```<code>-- =============================================
-- Author:      XXXX
-- Create date: xx-xx-xxxx
-- Description: Procedure for Deleting  From Table
-- =============================================

CREATE PROCEDURE [dbo].[SP_Employee_Delete]
(
@EmpCode bigint=null,
@Msg nvarchar(MAX)=null OUTPUT
)
AS
BEGIN TRY

DELETE FROM tbl_Employees
WHERE EmpCode=@EmpCode

SET @Msg='Employee Deleted Successfully.'

END TRY
BEGIN CATCH
SET @Msg=ERROR_MESSAGE()
END CATCH

GO
</code>```


问:
How can I paste data from one spreadsheet to the last column of another?
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

EDIT: Error occurs on this line:

```<code>Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
</code>```

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

```<code>Dest.Cells(1, colDest) = "Test"
</code>```

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

答:
Below are some guidelines on how to find last column an import value after last column.</p>

```<code>Option Explicit

Sub Test()

    Dim LastColumn As Long

        With ThisWorkbook.Worksheets("Sheet1")

            'Last Column using UsedRange (NOT A GOOD IDEA)
            LastColumn = .UsedRange.Columns(.UsedRange.Columns.Count).Column
            'Last Column using specific row 7
            LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column

            'Add a value in row 5 & after last column
            .Cells(5, LastColumn + 1).Value = ""

        End With

End Sub
</code>```

Body:
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

EDIT: Error occurs on this line:

Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

Dest.Cells(1, colDest) = "Test"

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

Body:
Below are some guidelines on how to find last column an import value after last column.

Option Explicit

Sub Test()

    Dim LastColumn As Long

        With ThisWorkbook.Worksheets("Sheet1")

            'Last Column using UsedRange (NOT A GOOD IDEA)
            LastColumn = .UsedRange.Columns(.UsedRange.Columns.Count).Column
            'Last Column using specific row 7
            LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column

            'Add a value in row 5 & after last column
            .Cells(5, LastColumn + 1).Value = ""

        End With

End Sub


问:
Division doesn't seem to work in Robotframework, what am I doing wrong?
I am trying to do division using the / operator.

The resulting Floating point number is way off the mark.  What did I miss?

This is the output from RF:

```<code>KEYWORD: BuiltIn.Log ${nearTermsAmount}
Documentation:

Logs the given message with the given level.
Start / End / Elapsed: 20190527 17:13:09.091 / 20190527 17:13:09.107 /
17:13:09.107   INFO   3,666.00
00:00:00.000 KEYWORD: BuiltIn.Log ${nearAllIn}
Documentation:
 Logs the given message with the given level.
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.107
17:13:09.107   INFO   1.607976
00:00:00.015 KEYWORD: ${calNearTerms/BaseAmount} = BuiltIn.Run Keyword If      ${isBase}, Calculate Terms Amount, ${nearBaseAmount}, ${nearAllIn}, ELSE, Calculate Base Amount, ${nearTermsAmount}, ${nearAllIn}
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.122 /   00:00:00.015
00:00:00.015 KEYWORD: rateTicketKeywords.Calculate Base Amount  ${nearTermsAmount}, ${nearAllIn}
Documentation:

Calculates the base amount out of the given rate
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.122 / 00:00:00.015
00:00:00.000 KEYWORD: ${baseAmount} = BuiltIn.Evaluate ${givenAmount} / ${givenRate}
00:00:00.015 KEYWORD: ${result} = rateTicketKeywords.Strip Numeric Commas ${baseAmount}
00:00:00.000 KEYWORD: ${result} = BuiltIn.Convert To Number ${result}, 5
17:13:09.122   INFO   ${calNearTerms/BaseAmount} = 3414.18529
00:00:00.016 KEYWORD: ${otherAmount} = BuiltIn.Run Keyword If ${isBase}, Strip Numeric Commas, ${nearTermsAmount}, ELSE, Strip Numeric Commas, ${nearBaseAmount}
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.122 / 20190527 17:13:09.138 / 00:00:00.016
00:00:00.016 KEYWORD: rateTicketKeywords.Strip Numeric Commas ${nearBaseAmount}
17:13:09.138   INFO   ${otherAmount} = 2279.88
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate ${calNearTerms/BaseAmount} - ${otherAmount}
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate abs(${diff})
Documentation:

Evaluates the given expression in Python and returns the results.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.138 / 00:00:00.000
17:13:09.138   INFO   ${diff} = 1134.30529
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate ${diff} / ${otherAmount}
Documentation:

Evaluates the given expression in Python and returns the results.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.138 / 00:00:00.000
17:13:09.138   INFO   ${diff} = 0.497528505886
00:00:00.000 KEYWORD: ${status} = BuiltIn.Evaluate ${diff} > 0.0006
00:00:00.015 KEYWORD: BuiltIn.Run Keyword If ${status}, FAIL, the   calculated near terms amount which was inserted in the trade ticked differ to  the near terms amount from the execution dialog, True
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.153 / 00:00:00.015
00:00:00.015 KEYWORD: BuiltIn.Fail the calculated near terms amount which was inserted in the trade ticked differ to the near terms amount from the  execution dialog, True
Documentation:

Fails the test with the given message and optionally alters its tags.

Source code:
Calculate Terms Amount
[Documentation]  Calculates the terms amount out of the given rate
[Arguments]  ${givenAmount}  ${givenRate}
log  ${givenAmount}
${givenAmount}=  Strip Numeric Commas  ${givenAmount}
#log  ${givenAmount}
${termsAmount}=  Evaluate  ${givenAmount} * ${givenRate}
${result}=  Strip Numeric Commas  ${termsAmount}
${result}=  Convert To Number  ${result}  5
[Return]  ${result}
</code>```

The code tests the math done by the system being tested.  The number pulled from the application is correct, my answer is way off.

答:
When I cut and paste the Calculate Base Amount Keyword, I noticed the '=' symbol was missing (see below).  I am not sure what this would do but either it is syntactically correct, or the syntax checker could use some work :).

This line:

```<code>${baseAmount}  Evaluate  ${givenAmount} / ${givenRate}
</code>```

Should be:

```<code>${baseAmount}=  Evaluate  ${givenAmount} / ${givenRate}
</code>```

Body:
I am trying to do division using the / operator.

The resulting Floating point number is way off the mark.  What did I miss?

This is the output from RF:

KEYWORD: BuiltIn.Log ${nearTermsAmount}
Documentation:

Logs the given message with the given level.
Start / End / Elapsed: 20190527 17:13:09.091 / 20190527 17:13:09.107 /
17:13:09.107   INFO   3,666.00
00:00:00.000 KEYWORD: BuiltIn.Log ${nearAllIn}
Documentation:
 Logs the given message with the given level.
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.107
17:13:09.107   INFO   1.607976
00:00:00.015 KEYWORD: ${calNearTerms/BaseAmount} = BuiltIn.Run Keyword If      ${isBase}, Calculate Terms Amount, ${nearBaseAmount}, ${nearAllIn}, ELSE, Calculate Base Amount, ${nearTermsAmount}, ${nearAllIn}
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.122 /   00:00:00.015
00:00:00.015 KEYWORD: rateTicketKeywords.Calculate Base Amount  ${nearTermsAmount}, ${nearAllIn}
Documentation:

Calculates the base amount out of the given rate
Start / End / Elapsed: 20190527 17:13:09.107 / 20190527 17:13:09.122 / 00:00:00.015
00:00:00.000 KEYWORD: ${baseAmount} = BuiltIn.Evaluate ${givenAmount} / ${givenRate}
00:00:00.015 KEYWORD: ${result} = rateTicketKeywords.Strip Numeric Commas ${baseAmount}
00:00:00.000 KEYWORD: ${result} = BuiltIn.Convert To Number ${result}, 5
17:13:09.122   INFO   ${calNearTerms/BaseAmount} = 3414.18529
00:00:00.016 KEYWORD: ${otherAmount} = BuiltIn.Run Keyword If ${isBase}, Strip Numeric Commas, ${nearTermsAmount}, ELSE, Strip Numeric Commas, ${nearBaseAmount}
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.122 / 20190527 17:13:09.138 / 00:00:00.016
00:00:00.016 KEYWORD: rateTicketKeywords.Strip Numeric Commas ${nearBaseAmount}
17:13:09.138   INFO   ${otherAmount} = 2279.88
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate ${calNearTerms/BaseAmount} - ${otherAmount}
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate abs(${diff})
Documentation:

Evaluates the given expression in Python and returns the results.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.138 / 00:00:00.000
17:13:09.138   INFO   ${diff} = 1134.30529
00:00:00.000 KEYWORD: ${diff} = BuiltIn.Evaluate ${diff} / ${otherAmount}
Documentation:

Evaluates the given expression in Python and returns the results.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.138 / 00:00:00.000
17:13:09.138   INFO   ${diff} = 0.497528505886
00:00:00.000 KEYWORD: ${status} = BuiltIn.Evaluate ${diff} > 0.0006
00:00:00.015 KEYWORD: BuiltIn.Run Keyword If ${status}, FAIL, the   calculated near terms amount which was inserted in the trade ticked differ to  the near terms amount from the execution dialog, True
Documentation:

Runs the given keyword with the given arguments, if `condition` is true.
Start / End / Elapsed: 20190527 17:13:09.138 / 20190527 17:13:09.153 / 00:00:00.015
00:00:00.015 KEYWORD: BuiltIn.Fail the calculated near terms amount which was inserted in the trade ticked differ to the near terms amount from the  execution dialog, True
Documentation:

Fails the test with the given message and optionally alters its tags.

Source code:
Calculate Terms Amount
[Documentation]  Calculates the terms amount out of the given rate
[Arguments]  ${givenAmount}  ${givenRate}
log  ${givenAmount}
${givenAmount}=  Strip Numeric Commas  ${givenAmount}
#log  ${givenAmount}
${termsAmount}=  Evaluate  ${givenAmount} * ${givenRate}
${result}=  Strip Numeric Commas  ${termsAmount}
${result}=  Convert To Number  ${result}  5
[Return]  ${result}

The code tests the math done by the system being tested.  The number pulled from the application is correct, my answer is way off.

Body:
When I cut and paste the Calculate Base Amount Keyword, I noticed the '=' symbol was missing (see below).  I am not sure what this would do but either it is syntactically correct, or the syntax checker could use some work :).

This line:

${baseAmount}  Evaluate  ${givenAmount} / ${givenRate}

Should be:

${baseAmount}=  Evaluate  ${givenAmount} / ${givenRate}


问:
I want to pass data between pages ionic 4
I want to pass data between pages ionic 4 without changing url.

Code:

app-routing.module.ts

```<code>const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'detail/:id', loadChildren: './detail/detail.module#DetailPageModule' },
];
</code>```

home.ts

```<code>nextClicked(){
    this.navCtrl.navigateForward('/detail/' + '11');
  }
</code>```

detail.ts

```<code>ngOnInit() {
    let output= this.activatedroute.snapshot.paramMap.get('id');
    console.log("data recived is ",JSON.stringify(output))
  }
</code>```

Output: data recived is null

Also the URL in browser is changing to http://localhost:8101/contact/11

I want my url to stay like default http://localhost:8101/ is this possible in ionic 4 ?

please help and thanks in advance!

答:
When you route between pages your URL is meant to change. so if you don't wanna change your URL then the only way is hiding and showing the components using flags. However from ionic 4, It is advisable to use Angular routing instead of Ionic Nav controller, this article can give you the insight about it

You are using NavController API to navigate but extracting the data from angular routing ActivatedRoute API. you should navigate using the Angular Routing API as below

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  ...
})
export class HomeComponent {

  constructor(private router: Router){}

  navigate(){
   this.router.navigate(['/detail', { id: "123" }]);
  }
}
</code>```

and then you can extract using ActivatedRoute API as below

```<code>let id = this.route.snapshot.paramMap.get('id')
</code>```

Body:
I want to pass data between pages ionic 4 without changing url.

Code:

app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'detail/:id', loadChildren: './detail/detail.module#DetailPageModule' },
];

home.ts

nextClicked(){
    this.navCtrl.navigateForward('/detail/' + '11');
  }

detail.ts

ngOnInit() {
    let output= this.activatedroute.snapshot.paramMap.get('id');
    console.log("data recived is ",JSON.stringify(output))
  }

Output: data recived is null

Also the URL in browser is changing to http://localhost:8101/contact/11

I want my url to stay like default http://localhost:8101/ is this possible in ionic 4 ?

please help and thanks in advance!

Body:
When you route between pages your URL is meant to change. so if you don't wanna change your URL then the only way is hiding and showing the components using flags. However from ionic 4, It is advisable to use Angular routing instead of Ionic Nav controller, this article can give you the insight about it

You are using NavController API to navigate but extracting the data from angular routing ActivatedRoute API. you should navigate using the Angular Routing API as below

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  ...
})
export class HomeComponent {

  constructor(private router: Router){}

  navigate(){
   this.router.navigate(['/detail', { id: "123" }]);
  }
}

and then you can extract using ActivatedRoute API as below

let id = this.route.snapshot.paramMap.get('id')


问:
display new line every day form text file automatically
I have a text file that I want to read a new line from it every day
how can I update the start and the end value every day automatically?

$start = 1; // array indexes are starting with zero
$end = 4;   // array indexes are starting with zero

$lines = file('test.txt'); // get lines of file as an array
for($i = $start; $i <= $end && $i < count($lines); $i++) {
    echo $lines[$i];
}

```

答:
As you already have to read the file for every visitor to display the first line of the text, you can write a bit of code to modify the file if needed.

Suppose you have this file:

```<code>2019-05-12
This is line 1
This is line 2
This is line 3
</code>```

Then include this piece for every visitor:

```<code>$text = file('myfile.txt');      // read file into array
$date = $text[0];                // get the last update date
$now = date('Y-m-d',time());     // today
$show = 1;                       // 1 = first text line in array

//if we need to update
if( $date !== $now ){
     $show = 2;                  // 2 = we need a new line
     $text[0] = $now;            // set last update to today
     unset($text[1]);            // delete the old line
     // write back file without the deleted line
     file_put_contents('myfile.txt', implode("\n",$text);
}

echo $text[$show];
</code>```

Not tested the code, but you get the idea

Body:
As you already have to read the file for every visitor to display the first line of the text, you can write a bit of code to modify the file if needed.

Suppose you have this file:

2019-05-12
This is line 1
This is line 2
This is line 3

Then include this piece for every visitor:

$text = file('myfile.txt');      // read file into array
$date = $text[0];                // get the last update date
$now = date('Y-m-d',time());     // today
$show = 1;                       // 1 = first text line in array

//if we need to update
if( $date !== $now ){
     $show = 2;                  // 2 = we need a new line
     $text[0] = $now;            // set last update to today
     unset($text[1]);            // delete the old line
     // write back file without the deleted line
     file_put_contents('myfile.txt', implode("\n",$text);
}

echo $text[$show];

Not tested the code, but you get the idea


问:
Using Postman runner to call API n times for benchmark testing
I am writing a new API and want to be able to see how it fairs when hit with n requests.

I have tried to setup environment variables and use the runner tool within Postman to no avail.

End goal is to run it n times, where I pass in the value of [n] into the body so I can audit (the value of that field is stored in database).

I have setup 2 environment variables

```<code>company=Bulk API Test
requestcount=0
</code>```

My pre-request script is

```<code>let requestCount = +postman.getEnvironmentVariable("requestcount");
if(!requestCount)
{
    requestCount = 0;
}

requestCount++;
postman.setEnvironmentVariable("requestcount", requestCount);
</code>```

Which should update the environment variable requestcount to +1 each time.

My test script is

```<code>var currentCount = +postman.getEnvironmentVariable("requestcount");
if(currentCount < 5) // want it to run 5 times
{
    postman.setNextRequest("https://snipped");
}
else
{
    postman.setNextRequest(null);
}
</code>```

When I run it through the runner it takes much longer than a non-runner execution and the result is the API was only hit once.

答:
If your API Call is always the same, try just using the iteration-count of the postman runner. Just enter there e.g. 5. And your collection will be repeated 5 times.

Cou cann access the iteration over the following property:

```<code>pm.info.iteration
</code>```

to find out, which iteration it was.

If you still need to icrement variables make sure, that they parsed as integers.

```<code>var currentCount =+ parseInt(postman.getEnvironmentVariable("requestcount"));
</code>```

To be honest: The best way for this benchmarking test would be to use a load-test tool e.g. Loadrunner instead of Postman.

Body:
I am writing a new API and want to be able to see how it fairs when hit with n requests.

I have tried to setup environment variables and use the runner tool within Postman to no avail.

End goal is to run it n times, where I pass in the value of [n] into the body so I can audit (the value of that field is stored in database).

I have setup 2 environment variables

company=Bulk API Test
requestcount=0

My pre-request script is

let requestCount = +postman.getEnvironmentVariable("requestcount");
if(!requestCount)
{
    requestCount = 0;
}

requestCount++;
postman.setEnvironmentVariable("requestcount", requestCount);

Which should update the environment variable requestcount to +1 each time.

My test script is

var currentCount = +postman.getEnvironmentVariable("requestcount");
if(currentCount < 5) // want it to run 5 times
{
    postman.setNextRequest("https://snipped");
}
else
{
    postman.setNextRequest(null);
}

When I run it through the runner it takes much longer than a non-runner execution and the result is the API was only hit once.

Body:
If your API Call is always the same, try just using the iteration-count of the postman runner. Just enter there e.g. 5. And your collection will be repeated 5 times.

Cou cann access the iteration over the following property:

pm.info.iteration

to find out, which iteration it was.

If you still need to icrement variables make sure, that they parsed as integers.

var currentCount =+ parseInt(postman.getEnvironmentVariable("requestcount"));

To be honest: The best way for this benchmarking test would be to use a load-test tool e.g. Loadrunner instead of Postman.


问:
Dockerfile alpine image apk cannot find Java 8
I wanted to reduce my docker image and switched to an alpine base image instead. This lead to problems bash not finding apt. Turns out, I have to use apk instead. However, it does not seem to find the java version I need. Here is my dockerfile

```<code>#Use alpine golang
FROM golang:alpine

#Get the code from local code commit repo
WORKDIR /go/src/xxx
COPY . /go/src/xxx

#Install Java and cleanup after in the same layer
RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*

#Install dependencies recursively and remove the third_party directory after it has been used for compiling.
RUN go get ./... && go run setup.go && RUN rm -rf third_party
#More commands...

 ---> 32a6b6b5f196
Step 4/8 : RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*
 ---> Running in bc48930e48be
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
  openjdk-8-jre-headless (missing):
·[91mERROR: unsatisfiable constraints:
·[0m    required by: world[openjdk-8-jre-headless]
The command '/bin/sh -c apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 1
</code>```

I have also tried

```<code>RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
</code>```

According to https://unix.stackexchange.com/questions/342403/openjdk-8-jre-headless-depends-ca-certificates-java-but-it-is-not-going-to-be but that also fails, not sure if the -t flags fault:

```<code>Step 4/7 : RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
 ---> Running in 1e2ef22e7c16
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
·[91mERROR: unsatisfiable constraints:
·[0m  openjdk-8-jre-headless (missing):
    required by: jessie-backports-0[openjdk-8-jre-headless]
  ca-certificates-java (missing):
    required by: jessie-backports-0[ca-certificates-java]
The command '/bin/sh -c apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 3
</code>```

答:
You can check how the official alpine OpenJDK image downloads java and follow the same steps

check Dockerfile

In short, you can add the following code in your Dockerfile

```<code># add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
        echo '#!/bin/sh'; \
        echo 'set -e'; \
        echo; \
        echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
    } > /usr/local/bin/docker-java-home \
    && chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin

ENV JAVA_VERSION 8u212
ENV JAVA_ALPINE_VERSION 8.212.04-r0

RUN set -x \
    && apk add --no-cache \
        openjdk8="$JAVA_ALPINE_VERSION" \
    && [ "$JAVA_HOME" = "$(docker-java-home)" ]
</code>```

I hope this helps

Body:
I wanted to reduce my docker image and switched to an alpine base image instead. This lead to problems bash not finding apt. Turns out, I have to use apk instead. However, it does not seem to find the java version I need. Here is my dockerfile

#Use alpine golang
FROM golang:alpine

#Get the code from local code commit repo
WORKDIR /go/src/xxx
COPY . /go/src/xxx

#Install Java and cleanup after in the same layer
RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*

#Install dependencies recursively and remove the third_party directory after it has been used for compiling.
RUN go get ./... && go run setup.go && RUN rm -rf third_party
#More commands...

 ---> 32a6b6b5f196
Step 4/8 : RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*
 ---> Running in bc48930e48be
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
  openjdk-8-jre-headless (missing):
·[91mERROR: unsatisfiable constraints:
·[0m    required by: world[openjdk-8-jre-headless]
The command '/bin/sh -c apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 1

I have also tried

RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*

According to https://unix.stackexchange.com/questions/342403/openjdk-8-jre-headless-depends-ca-certificates-java-but-it-is-not-going-to-be but that also fails, not sure if the -t flags fault:

Step 4/7 : RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
 ---> Running in 1e2ef22e7c16
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
·[91mERROR: unsatisfiable constraints:
·[0m  openjdk-8-jre-headless (missing):
    required by: jessie-backports-0[openjdk-8-jre-headless]
  ca-certificates-java (missing):
    required by: jessie-backports-0[ca-certificates-java]
The command '/bin/sh -c apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 3

Body:
You can check how the official alpine OpenJDK image downloads java and follow the same steps

check Dockerfile

In short, you can add the following code in your Dockerfile

# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
        echo '#!/bin/sh'; \
        echo 'set -e'; \
        echo; \
        echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
    } > /usr/local/bin/docker-java-home \
    && chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin

ENV JAVA_VERSION 8u212
ENV JAVA_ALPINE_VERSION 8.212.04-r0

RUN set -x \
    && apk add --no-cache \
        openjdk8="$JAVA_ALPINE_VERSION" \
    && [ "$JAVA_HOME" = "$(docker-java-home)" ]

I hope this helps


问:
Set AWS Kinesis cloudformation template
I am new to AWS cloudformation and in need to create a Kinesis datastream, then write records to this stream using python code. I was able to create a data stream through cloudformation template but not able to set the permissions. How I will attache a permission to allow certain usergroup to write to this kinesis data stream using the python library?

My current template code is,

```<code>AWSTemplateFormatVersion: '2010-09-09'
Description: 'This template will create an AWS Kinesis DataStream'

Parameters:

CFNStreamName:
    Description: This will be used to name the Kinesis DataStream
    Type: String
    Default: 'data-stream'

CFNRetensionHours:
    Description: This will be used to set the retension hours
    Type: Number
    Default: 168

CFNShardCount:
    Description: This will be used to set the shard count
    Type: Number
    Default: 2

Resources:
    MongoCDCStream:
Type: AWS::Kinesis::Stream
Properties:
  Name: !Ref CFNStreamName
  RetentionPeriodHours: !Ref CFNRetensionHours
  ShardCount: !Ref CFNShardCount
  StreamEncryption:
      EncryptionType: KMS
      KeyId: alias/aws/kinesis
Outputs:
    MongoCDCStream:
    Value: !Ref MongoCDCStream
    Export:
        Name: !Sub ${AWS::StackName}-MongoCDCStream
</code>```

答:
You will want to pass in (through the cloudformation parameter) either the IAM Role or User that your Python code runs on.

Inside the template, create an IAM Policy or ManagedPolicy that attaches to the IAM Role / User you passed in and assign the correct permission.

```<code>AWSTemplateFormatVersion: '2010-09-09'
Description: 'This template will create an AWS Kinesis DataStream'

Parameters:

CFNStreamName:
    Description: This will be used to name the Kinesis DataStream
    Type: String
    Default: 'data-stream'

CFNRetensionHours:
    Description: This will be used to set the retension hours
    Type: Number
    Default: 168

CFNShardCount:
    Description: This will be used to set the shard count
    Type: Number
    Default: 2

PythonCodeRole:
    Type: String
# ^- Pass in role here.

Resources:
    # Assign permission here.
    PythonCodePlicyAssignmen:
        Type: AWS::IAM::Policy
        Properties:
            PolicyDocument:
                <assign needed permission here>
                Version: "2012-10-17"
                Statement:
                  - Effect: "Allow"
                    Action:
                      - "kinesis:*"
                    Resource: !Ref MongoCDCStream
                    # ^- here, use !Ref to tie in the correct resource id cleanly.
            PolicyName: python-code-permission
            Roles: [!Ref PythonCodeRole]

    MongoCDCStream:
        Type: AWS::Kinesis::Stream
        Properties:
            Name: !Ref CFNStreamName
            RetentionPeriodHours: !Ref CFNRetensionHours
            ShardCount: !Ref CFNShardCount
            StreamEncryption:
              EncryptionType: KMS
              KeyId: alias/aws/kinesis
Outputs:
    MongoCDCStream:
    Value: !Ref MongoCDCStream
    Export:
        Name: !Sub ${AWS::StackName}-MongoCDCStream
</code>```

Title: Set AWS Kinesis cloudformation template

Body:
I am new to AWS cloudformation and in need to create a Kinesis datastream, then write records to this stream using python code. I was able to create a data stream through cloudformation template but not able to set the permissions. How I will attache a permission to allow certain usergroup to write to this kinesis data stream using the python library?

My current template code is,

AWSTemplateFormatVersion: '2010-09-09'
Description: 'This template will create an AWS Kinesis DataStream'

Parameters:

CFNStreamName:
    Description: This will be used to name the Kinesis DataStream
    Type: String
    Default: 'data-stream'

CFNRetensionHours:
    Description: This will be used to set the retension hours
    Type: Number
    Default: 168

CFNShardCount:
    Description: This will be used to set the shard count
    Type: Number
    Default: 2

Resources:
    MongoCDCStream:
Type: AWS::Kinesis::Stream
Properties:
  Name: !Ref CFNStreamName
  RetentionPeriodHours: !Ref CFNRetensionHours
  ShardCount: !Ref CFNShardCount
  StreamEncryption:
      EncryptionType: KMS
      KeyId: alias/aws/kinesis
Outputs:
    MongoCDCStream:
    Value: !Ref MongoCDCStream
    Export:
        Name: !Sub ${AWS::StackName}-MongoCDCStream

Body:
You will want to pass in (through the cloudformation parameter) either the IAM Role or User that your Python code runs on.

Inside the template, create an IAM Policy or ManagedPolicy that attaches to the IAM Role / User you passed in and assign the correct permission.

AWSTemplateFormatVersion: '2010-09-09'
Description: 'This template will create an AWS Kinesis DataStream'

Parameters:

CFNStreamName:
    Description: This will be used to name the Kinesis DataStream
    Type: String
    Default: 'data-stream'

CFNRetensionHours:
    Description: This will be used to set the retension hours
    Type: Number
    Default: 168

CFNShardCount:
    Description: This will be used to set the shard count
    Type: Number
    Default: 2

PythonCodeRole:
    Type: String
# ^- Pass in role here.

Resources:
    # Assign permission here.
    PythonCodePlicyAssignmen:
        Type: AWS::IAM::Policy
        Properties:
            PolicyDocument:
                <assign needed permission here>
                Version: "2012-10-17"
                Statement:
                  - Effect: "Allow"
                    Action:
                      - "kinesis:*"
                    Resource: !Ref MongoCDCStream
                    # ^- here, use !Ref to tie in the correct resource id cleanly.
            PolicyName: python-code-permission
            Roles: [!Ref PythonCodeRole]

    MongoCDCStream:
        Type: AWS::Kinesis::Stream
        Properties:
            Name: !Ref CFNStreamName
            RetentionPeriodHours: !Ref CFNRetensionHours
            ShardCount: !Ref CFNShardCount
            StreamEncryption:
              EncryptionType: KMS
              KeyId: alias/aws/kinesis
Outputs:
    MongoCDCStream:
    Value: !Ref MongoCDCStream
    Export:
        Name: !Sub ${AWS::StackName}-MongoCDCStream


问:
How do I run a 32 bit .NET Core application in Docker
I have a 32 bit (x86) .NET Core 2.2 application I want to run in a Docker container.
A 64 bit version of my application works fine in a container, but the 32 bit version does not start up. No Docker log files are generated.

I publish my application with this command:

```<code>dotnet publish -c Release -r win-x86
</code>```

This creates a self-contained x86 application including an executable.
If I run the executable it works fine.

I then build a container image using this Dockerfile:

```<code>FROM mcr.microsoft.com/dotnet/core/runtime:2.2
WORKDIR /app
COPY bin/Release/netcoreapp2.2/win-x86/publish/ ./
ENTRYPOINT ["DockerX86Test.exe"]
</code>```

and this command:

```<code>docker build -t x86test .
</code>```

When I run the image using this command:

```<code>docker run -it x86test
</code>```

the container exits immediately with no Docker logs generated.

My application is super simple like this:

```<code>class Program
{
    static void Main(string[] args)
    {
        int i = 1;

        do
        {
            Console.WriteLine("Hello World! - " + i);
            Thread.Sleep(600);

        } while (i++ < 10);
    }
}
</code>```

Am I using a wrong base image? I haven't been able to find a .NET Core runtime base image tagged x86.

答:
Changing the base image to mcr.microsoft.com/windows/servercore:ltsc2019 solved my problem.

Apparently the mcr.microsoft.com/dotnet/core/runtime:2.2 image cannot run 32-bit applications.

Body:
I have a 32 bit (x86) .NET Core 2.2 application I want to run in a Docker container.
A 64 bit version of my application works fine in a container, but the 32 bit version does not start up. No Docker log files are generated.

I publish my application with this command:

dotnet publish -c Release -r win-x86

This creates a self-contained x86 application including an executable.
If I run the executable it works fine.

I then build a container image using this Dockerfile:

FROM mcr.microsoft.com/dotnet/core/runtime:2.2
WORKDIR /app
COPY bin/Release/netcoreapp2.2/win-x86/publish/ ./
ENTRYPOINT ["DockerX86Test.exe"]

and this command:

docker build -t x86test .

When I run the image using this command:

docker run -it x86test

the container exits immediately with no Docker logs generated.

My application is super simple like this:

class Program
{
    static void Main(string[] args)
    {
        int i = 1;

        do
        {
            Console.WriteLine("Hello World! - " + i);
            Thread.Sleep(600);

        } while (i++ < 10);
    }
}

Am I using a wrong base image? I haven't been able to find a .NET Core runtime base image tagged x86.


问:
Clicking first link/ patent after search in Google Patents using Selenium in Python
I am trying to click on the first result from the Google patents search page using selenium in python with chromedriver.

It automatically types the company from a list in the search bar and enters.

```<code>        driver.get("https://patents.google.com/")

        searchbar = driver.find_element_by_id("searchInput")
        searchbar.send_keys(Company[i], Keys.ENTER)
</code>```

This is what I used after in order to find the first link and execute the click.

```<code>        time.sleep(20)
        element = driver.find_element_by_xpath("//a[@id='link']")
        element[0].click()
</code>```

However, it does not identify the element for some reason and won't click the link.

This is the HTML:

```<code>  <article class="result style-scope search-result-item">
    <state-modifier class="result-title style-scope search-result-item" act="{"type": "OPEN_RESULT", "result": "$result"}" data-result="patent/US3334718A/en"><a id="link" href="/patent/US3334718A/en?assignee=AAR+CORP&oq=AAR+CORP" class="style-scope state-modifier">
      <h3 class="style-scope search-result-item"><raw-html class="style-scope search-result-item">
<span id="htmlContent" class="style-scope raw-html" style="display: inline;"> Cargo handling appartus</span>
</code>```

I hope it makes sense. Thanks!

答:
It looks that you've forgot to invoke click method.
Try to alter your code a little

```<code>time.sleep(20)
element = driver.find_element_by_xpath("//a[@id='link']")
element[0].click()  # <- add parentheses to invoke the method
</code>```

This is caused, since the functions are objects just like any other object in Python.
If you forget to add parentheses, you are referring to the function object, not the function itself.

Body:
I am trying to click on the first result from the Google patents search page using selenium in python with chromedriver.

It automatically types the company from a list in the search bar and enters.

        driver.get("https://patents.google.com/")

        searchbar = driver.find_element_by_id("searchInput")
        searchbar.send_keys(Company[i], Keys.ENTER)

This is what I used after in order to find the first link and execute the click.

        time.sleep(20)
        element = driver.find_element_by_xpath("//a[@id='link']")
        element[0].click()

However, it does not identify the element for some reason and won't click the link.

This is the HTML:

    <state-modifier class="result-title style-scope search-result-item" act="{"type": "OPEN_RESULT", "result": "$result"}" data-result="patent/US3334718A/en">

<raw-html class="style-scope search-result-item">
 Cargo handling appartus

I hope it makes sense. Thanks!

Body:
It looks that you've forgot to invoke click method.
Try to alter your code a little

time.sleep(20)
element = driver.find_element_by_xpath("//a[@id='link']")
element[0].click()  # <- add parentheses to invoke the method

This is caused, since the functions are objects just like any other object in Python.
If you forget to add parentheses, you are referring to the function object, not the function itself.


问:
How to catch exceptions in JUnit
My JUnit test does not catch the exception because of my return statement in the catch block. When I delete returning statement, the test passes. I want my unit test to work with returning statement if the exception occurs.

I've also tried JUnit 5 stuff but it does not fix the problem.

My method:

```<code>public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp");

    // more code. . .
}
</code>```

My test:

```<code>  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }
</code>```

答:
You are catching the exception with try-catch block, so that throw will never reach the test method: all you need to do is just remove that try catch:

```<code>public ArrayList<Action> parsePlaByPlayTable() {
    //...
    document = Jsoup.connect(url).get();
    //...
}
</code>```

then your test will run fine, since @Test(expected = Exception.class) will catch your exception, succeeding your test

Title: How to catch exceptions in JUnit

Body:
My JUnit test does not catch the exception because of my return statement in the catch block. When I delete returning statement, the test passes. I want my unit test to work with returning statement if the exception occurs.

I've also tried JUnit 5 stuff but it does not fix the problem.

My method:

public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp");

    // more code. . .
}

My test:

  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }

Body:
You are catching the exception with try-catch block, so that throw will never reach the test method: all you need to do is just remove that try catch:

public ArrayList<Action> parsePlaByPlayTable() {
    //...
    document = Jsoup.connect(url).get();
    //...
}

then your test will run fine, since @Test(expected = Exception.class) will catch your exception, succeeding your test


问:
Angular 7 Table with Pagination, Sort, and Filter
Hi does anyone knows how to make a table with pagination, sort and filter in angular. I'm using Creative Tim's Argon Dashboard for Angular and I'm confused how I am going to integrate it to my project

Here's the documentation of the template click me

Here's a sample code of the table

```<code><div class="table-responsive">
    <table class="table align-items-center table-flush">
      <thead class="thead-light">
        <tr>
          <th scope="col">Project</th>
          <th scope="col">Budget</th>
          <th scope="col">Status</th>
          <th scope="col">Users</th>
          <th scope="col">Completion</th>
          <th scope="col"></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">
            <div class="media align-items-center">
              <a href="#" class="avatar rounded-circle mr-3">
                <img alt="Image placeholder" src="assets/img/theme/bootstrap.jpg">
              </a>
              <div class="media-body">
                <span class="mb-0 text-sm">Argon Design System</span>
              </div>
            </div>
          </th>
          <td>
            $2,500 USD
          </td>
          <td>
            <span class="badge badge-dot mr-4">
              <i class="bg-warning"></i> pending
            </span>
          </td>
          <td>
            <div class="avatar-group">
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Ryan Tompson">
                <img alt="Image placeholder" src="assets/img/theme/team-1-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Romina Hadid">
                <img alt="Image placeholder" src="assets/img/theme/team-2-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Alexander Smith">
                <img alt="Image placeholder" src="assets/img/theme/team-3-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Jessica Doe">
                <img alt="Image placeholder" src="assets/img/theme/team-4-800x800.jpg" class="rounded-circle">
              </a>
            </div>
          </td>
          <td>
            <div class="d-flex align-items-center">
              <span class="mr-2">60%</span>
              <div>
                <div class="progress">
                  <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
                </div>
              </div>
            </div>
          </td>
          <td class="text-right">
            <div ngbDropdown placement="bottom-right">
              <a class="btn btn-sm btn-icon-only text-light"  ngbDropdownToggle>
                <i class="fas fa-ellipsis-v"></i>
              </a>
              <div ngbDropdownMenu class=" dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <th scope="row">
            <div class="media align-items-center">
              <a href="#" class="avatar rounded-circle mr-3">
                <img alt="Image placeholder" src="assets/img/theme/angular.jpg">
              </a>
              <div class="media-body">
                <span class="mb-0 text-sm">Angular Now UI Kit PRO</span>
              </div>
            </div>
          </th>
          <td>
            $1,800 USD
          </td>
          <td>
            <span class="badge badge-dot">
              <i class="bg-success"></i> completed
            </span>
          </td>
          <td>
            <div class="avatar-group">
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Ryan Tompson">
                <img alt="Image placeholder" src="assets/img/theme/team-1-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Romina Hadid">
                <img alt="Image placeholder" src="assets/img/theme/team-2-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Alexander Smith">
                <img alt="Image placeholder" src="assets/img/theme/team-3-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Jessica Doe">
                <img alt="Image placeholder" src="assets/img/theme/team-4-800x800.jpg" class="rounded-circle">
              </a>
            </div>
          </td>
          <td>
            <div class="d-flex align-items-center">
              <span class="mr-2">100%</span>
              <div>
                <div class="progress">
                  <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%;"></div>
                </div>
              </div>
            </div>
          </td>
          <td class="text-right">
            <div ngbDropdown  placement="bottom-right">
              <a class="btn btn-sm btn-icon-only text-light"  ngbDropdownToggle>
                <i class="fas fa-ellipsis-v"></i>
              </a>
              <div ngbDropdownMenu class=" dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <th scope="row">
            <div class="media align-items-center">
              <a href="#" class="avatar rounded-circle mr-3">
                <img alt="Image placeholder" src="assets/img/theme/sketch.jpg">
              </a>
              <div class="media-body">
                <span class="mb-0 text-sm">Black Dashboard</span>
              </div>
            </div>
          </th>
          <td>
            $3,150 USD
          </td>
          <td>
            <span class="badge badge-dot mr-4">
              <i class="bg-danger"></i> delayed
            </span>
          </td>
          <td>
            <div class="avatar-group">
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Ryan Tompson">
                <img alt="Image placeholder" src="assets/img/theme/team-1-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Romina Hadid">
                <img alt="Image placeholder" src="assets/img/theme/team-2-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Alexander Smith">
                <img alt="Image placeholder" src="assets/img/theme/team-3-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Jessica Doe">
                <img alt="Image placeholder" src="assets/img/theme/team-4-800x800.jpg" class="rounded-circle">
              </a>
            </div>
          </td>
          <td>
            <div class="d-flex align-items-center">
              <span class="mr-2">72%</span>
              <div>
                <div class="progress">
                  <div class="progress-bar bg-danger" role="progressbar" aria-valuenow="72" aria-valuemin="0" aria-valuemax="100" style="width: 72%;"></div>
                </div>
              </div>
            </div>
          </td>
          <td class="text-right">
            <div ngbDropdown  placement="top-right">
              <a class="btn btn-sm btn-icon-only text-light"  ngbDropdownToggle>
                <i class="fas fa-ellipsis-v"></i>
              </a>
              <div ngbDropdownMenu class=" dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <th scope="row">
            <div class="media align-items-center">
              <a href="#" class="avatar rounded-circle mr-3">
                <img alt="Image placeholder" src="assets/img/theme/react.jpg">
              </a>
              <div class="media-body">
                <span class="mb-0 text-sm">React Material Dashboard</span>
              </div>
            </div>
          </th>
          <td>
            $4,400 USD
          </td>
          <td>
            <span class="badge badge-dot">
              <i class="bg-info"></i> on schedule
            </span>
          </td>
          <td>
            <div class="avatar-group">
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Ryan Tompson">
                <img alt="Image placeholder" src="assets/img/theme/team-1-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Romina Hadid">
                <img alt="Image placeholder" src="assets/img/theme/team-2-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Alexander Smith">
                <img alt="Image placeholder" src="assets/img/theme/team-3-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Jessica Doe">
                <img alt="Image placeholder" src="assets/img/theme/team-4-800x800.jpg" class="rounded-circle">
              </a>
            </div>
          </td>
          <td>
            <div class="d-flex align-items-center">
              <span class="mr-2">90%</span>
              <div>
                <div class="progress">
                  <div class="progress-bar bg-info" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100" style="width: 90%;"></div>
                </div>
              </div>
            </div>
          </td>
          <td class="text-right">
            <div ngbDropdown   placement="top-right">
              <a class="btn btn-sm btn-icon-only text-light"  ngbDropdownToggle>
                <i class="fas fa-ellipsis-v"></i>
              </a>
              <div ngbDropdownMenu class=" dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <th scope="row">
            <div class="media align-items-center">
              <a href="#" class="avatar rounded-circle mr-3">
                <img alt="Image placeholder" src="assets/img/theme/vue.jpg">
              </a>
              <div class="media-body">
                <span class="mb-0 text-sm">Vue Paper UI Kit PRO</span>
              </div>
            </div>
          </th>
          <td>
            $2,200 USD
          </td>
          <td>
            <span class="badge badge-dot mr-4">
              <i class="bg-success"></i> completed
            </span>
          </td>
          <td>
            <div class="avatar-group">
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Ryan Tompson">
                <img alt="Image placeholder" src="assets/img/theme/team-1-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Romina Hadid">
                <img alt="Image placeholder" src="assets/img/theme/team-2-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Alexander Smith">
                <img alt="Image placeholder" src="assets/img/theme/team-3-800x800.jpg" class="rounded-circle">
              </a>
              <a href="#" class="avatar avatar-sm" data-toggle="tooltip" data-original-title="Jessica Doe">
                <img alt="Image placeholder" src="assets/img/theme/team-4-800x800.jpg" class="rounded-circle">
              </a>
            </div>
          </td>
          <td>
            <div class="d-flex align-items-center">
              <span class="mr-2">100%</span>
              <div>
                <div class="progress">
                  <div class="progress-bar bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%;"></div>
                </div>
              </div>
            </div>
          </td>
          <td class="text-right">
            <div ngbDropdown   placement="top-right">
              <a class="btn btn-sm btn-icon-only text-light"  ngbDropdownToggle>
                <i class="fas fa-ellipsis-v"></i>
              </a>
              <div ngbDropdownMenu class=" dropdown-menu-right dropdown-menu-arrow">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</code>```

Here's a sample code of the pagination used

```<code><nav aria-label="...">
<ul class="pagination pagination-sm">
  <li class="page-item disabled">
    <a class="page-link" href="#" tabindex="-1">1</a>
  </li>
  <li class="page-item"><a class="page-link" href="#">2</a></li>
  <li class="page-item active"><a class="page-link" href="#">3</a></li>
</ul>
</code>```

I don't know about the filter. I really don't know how to start I'm kinda new to this. I came from AngularJS 1.6.x

edit: I would like to know I can still use the table design from the template if I integrated some of your suggestions

答: You can use ag-grid which is rich-featured grid, could be use simply to show data with basic functions like sort, filter and pagination but also can be used to do complex operations e.g. export, grouped data if needed (paid version). Comes with pre-defined styling themes dark, light and more.</p>

Body:
Hi does anyone knows how to make a table with pagination, sort and filter in angular. I'm using Creative Tim's Argon Dashboard for Angular and I'm confused how I am going to integrate it to my project

Here's the documentation of the template click me

Here's a sample code of the table

          Project
          Budget
          Status
          Users
          Completion

                Argon Design System

            $2,500 USD

               pending

              60%

                Action
                Another action
                Something else here

                Angular Now UI Kit PRO

            $1,800 USD

               completed

              100%

                Action
                Another action
                Something else here

                Black Dashboard

            $3,150 USD

               delayed

              72%

                Action
                Another action
                Something else here

                React Material Dashboard

            $4,400 USD

               on schedule

              90%

                Action
                Another action
                Something else here

                Vue Paper UI Kit PRO

            $2,200 USD

               completed

              100%

                Action
                Another action
                Something else here

Here's a sample code of the pagination used

    1

2

3

I don't know about the filter. I really don't know how to start I'm kinda new to this. I came from AngularJS 1.6.x

edit: I would like to know I can still use the table design from the template if I integrated some of your suggestions


问:
How to reinit bean object in previously autowired objects?
I need to reinit singleton bean instance for all previously autowired fields.

I tried to remove the bean from registy in app context, and re-register new object.

```<code>ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
((DefaultListableBeanFactory) beanRegistry).destroySingleton("fbdProg");
((DefaultListableBeanFactory) beanRegistry).registerSingleton("fbdProg", program);
</code>```

It works only once, the first time it is called.

The issue is how to reinit the bean to make new instance available in other classes, where it is autowired

答:
If you need a new instance of this bean everytime it is injected, you can use @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) on your bean. E.g:

```<code>@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MyComponent {
    // methods, fields, etc.
}
</code>```

Spring then creates a new instance of MyComponent everytime it is injected into another component. So Bean A will have a different instance of MyComponent than Bean B, evaluating beanA.myComponent != beanB.myComponent to true

Body:
I need to reinit singleton bean instance for all previously autowired fields.

I tried to remove the bean from registy in app context, and re-register new object.

ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
((DefaultListableBeanFactory) beanRegistry).destroySingleton("fbdProg");
((DefaultListableBeanFactory) beanRegistry).registerSingleton("fbdProg", program);

It works only once, the first time it is called.

The issue is how to reinit the bean to make new instance available in other classes, where it is autowired

Body:
If you need a new instance of this bean everytime it is injected, you can use @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) on your bean. E.g:

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MyComponent {
    // methods, fields, etc.
}

Spring then creates a new instance of MyComponent everytime it is injected into another component. So Bean A will have a different instance of MyComponent than Bean B, evaluating beanA.myComponent != beanB.myComponent to true


问:
How display only custom logging in Asp.Net Core
I  created my own custom loger provider FileLogerProviderr to save logs to file.

I added custom FileLoggerProvider in program.cs:

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, logging) =>
                {

                    logging.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
                    logging.SetMinimumLevel(LogLevel.None);

                })
                .UseStartup<Startup>();
</code>```

To test I added log in controller:

```<code>public class HomeController : Controller
    {
        private ILogger<HomeController> logger;

        public HomeController(ILogger<HomeController> log)
        {
            logger = log;
        }
        public IActionResult Index()
        {
            logger.LogDebug($"test index path!!!");
            return View();
        }
}
</code>```

Working, But in file except test index path I see many additional information. I dont need this information. I need only save in file my log from controller.

```<code>Request starting HTTP/1.1 GET http://localhost:44339/
Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing action LoggingTest.Controllers.HomeController.Index (LoggingTest)
Executing action method LoggingTest.Controllers.HomeController.Index (LoggingTest) - Validation state: Valid
test index path!!!
Executed action method LoggingTest.Controllers.HomeController.Index (LoggingTest), returned result Microsoft.AspNetCore.Mvc.ViewResult in 11.8159ms.
Executing ViewResult, running view Index.
Executed ViewResult - view Index executed in 43.4928ms.
Executed action LoggingTest.Controllers.HomeController.Index (LoggingTest) in 224.1184ms
Request finished in 400.2906ms 200 text/html; charset=utf-8
Request starting HTTP/1.1 GET http://localhost:44339/favicon.ico
Sending file. Request path: '/favicon.ico'. Physical path: 'C:\Users\dborovsky\projects\LoggingTest\LoggingTest\wwwroot\favicon.ico'
Request finished in 39.8394ms 200 image/x-icon
</code>```

How I can solve this? Thank you

UPDATE
appsettings.json

```<code>{
  "ConnectionStrings": {
    "DefaultConnection": "CONSTRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "None",
      "System": "None",
      "Microsoft": "None"
    }
  },
  "AllowedHosts": "*"
}
</code>```

答:
Maybe you´ll like to use a configuration to prevent all events gets logged.

I recommend you inject the logger in ConfigureServices (.ConfigureLogging from Program.cs at least you want to log web hosting events):

```<code>public void ConfigureServices(IServiceCollection services)
        {

            services.AddLogging(loggers=>
            {
                loggers.AddConsole();
                loggers.AddDebug();
                loggers.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
</code>```

Then you´ll can configure as follows (make sure you have the enviroment variant properly configurated):

```<code>{
  "ConnectionStrings": {
    "DefaultConnection": "CONSTRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "None",
      "Microsoft": "None"
    }
  },
  "AllowedHosts": "*"
}
</code>```

And the implementation:

```<code>public class HomeController : Controller
    {
        private ILogger<HomeController> logger;

        public HomeController(ILogger<HomeController> log)
        {
            logger = log;
        }
        public IActionResult Index()
        {
            logger.LogDebug($"test index path!!!");
            return View();
        }
}
</code>```

Here is as pretty nice Microsoft´s article about logging:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2

Body:
I  created my own custom loger provider FileLogerProviderr to save logs to file.

I added custom FileLoggerProvider in program.cs:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, logging) =>
                {

                    logging.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
                    logging.SetMinimumLevel(LogLevel.None);

                })
                .UseStartup<Startup>();

To test I added log in controller:

public class HomeController : Controller
    {
        private ILogger<HomeController> logger;

        public HomeController(ILogger<HomeController> log)
        {
            logger = log;
        }
        public IActionResult Index()
        {
            logger.LogDebug($"test index path!!!");
            return View();
        }
}

Working, But in file except test index path I see many additional information. I dont need this information. I need only save in file my log from controller.

Request starting HTTP/1.1 GET http://localhost:44339/
Route matched with {action = "Index", controller = "Home", page = "", area = ""}. Executing action LoggingTest.Controllers.HomeController.Index (LoggingTest)
Executing action method LoggingTest.Controllers.HomeController.Index (LoggingTest) - Validation state: Valid
test index path!!!
Executed action method LoggingTest.Controllers.HomeController.Index (LoggingTest), returned result Microsoft.AspNetCore.Mvc.ViewResult in 11.8159ms.
Executing ViewResult, running view Index.
Executed ViewResult - view Index executed in 43.4928ms.
Executed action LoggingTest.Controllers.HomeController.Index (LoggingTest) in 224.1184ms
Request finished in 400.2906ms 200 text/html; charset=utf-8
Request starting HTTP/1.1 GET http://localhost:44339/favicon.ico
Sending file. Request path: '/favicon.ico'. Physical path: 'C:\Users\dborovsky\projects\LoggingTest\LoggingTest\wwwroot\favicon.ico'
Request finished in 39.8394ms 200 image/x-icon

How I can solve this? Thank you

UPDATE
appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "CONSTRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "None",
      "System": "None",
      "Microsoft": "None"
    }
  },
  "AllowedHosts": "*"
}

Body:
Maybe you´ll like to use a configuration to prevent all events gets logged.

I recommend you inject the logger in ConfigureServices (.ConfigureLogging from Program.cs at least you want to log web hosting events):

public void ConfigureServices(IServiceCollection services)
        {

            services.AddLogging(loggers=>
            {
                loggers.AddConsole();
                loggers.AddDebug();
                loggers.AddProvider(new FileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt")));
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

Then you´ll can configure as follows (make sure you have the enviroment variant properly configurated):

{
  "ConnectionStrings": {
    "DefaultConnection": "CONSTRING"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "None",
      "Microsoft": "None"
    }
  },
  "AllowedHosts": "*"
}

And the implementation:

public class HomeController : Controller
    {
        private ILogger<HomeController> logger;

        public HomeController(ILogger<HomeController> log)
        {
            logger = log;
        }
        public IActionResult Index()
        {
            logger.LogDebug($"test index path!!!");
            return View();
        }
}

Here is as pretty nice Microsoft´s article about logging:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2