问:
How to profile end to end performance of Oracle stored procedure
I want to know how long my stored procedure is taking to execute from the time an external process hits the database and says execute this to the time the database returns back to the process and says here ya go.

Is there a simple easy way to do this very basic task?

Of course a report of what is happening during the stored procedure execution and how much of the stored procedure's time is spent doing each task (inserts, plsql string manipulation etc.) would be a bonus, but I really just want something simple and easy to use. (And free)

答:
If you are looking to write your own time lapse into your PL/SQL programs the below is my template code for doing this.  Also, this requires no assistance from your DBA.  My DBA's are often reluctant to give me more access to more things.  That, and I hate waiting for them to actually give me access.

```<code>/* This procedure is simply an example of parsing out an Elapsed time into their individual time parts */
/*   In other words it provides to the user the elapsed time in hours : minutes : seconds . milliseconds */

DECLARE

  G_START_TIME1     NUMBER        := DBMS_UTILITY.GET_TIME;
  G_START_TIME2     NUMBER        := DBMS_UTILITY.GET_TIME;
  vG_ELAPSED_TIME   VARCHAR2(200);

  /* Variables below are used for storing Elapsed time. */
  RETVAL           NUMBER;
  hourss            NUMBER;
  minutess          NUMBER;
  secondss          NUMBER;
  millisecondss     NUMBER;
    n_hrs         NUMBER := 360000;
    n_mins        NUMBER := 6000;
    n_secs        NUMBER := 100;
    n_sixty       NUMBER := 60;
    n_thirty      NUMBER := 30;
    n_ten         NUMBER := 10;

  v_PrintTime     VARCHAR2(200);

  /* The procedure below is simply used to simulate the passage of time */
  PROCEDURE waste_time(pn_Seconds NUMBER) IS

  n_CentiSeconds  NUMBER  :=  pn_Seconds * 100;
  n_ProgramStart  NUMBER  := DBMS_UTILITY.GET_TIME; /* dbms_utility_get_time returns times in hundreds of a second */

  BEGIN
    WHILE DBMS_UTILITY.GET_TIME < n_ProgramStart + n_CentiSeconds
    LOOP
      null;
    END LOOP;
  END waste_time;

BEGIN

  G_START_TIME1   :=    -2019618227; --dbms_utility.get_time;

  --waste_time(1);
  --dbms_output.put_line('1 Second Wasted'|| chr(10));

  G_START_TIME2   :=    G_START_TIME1 + 366110; ---2019619227; --dbms_utility.get_time;

  dbms_output.put_line('Start_time: '||G_START_TIME1);
  dbms_output.put_line('End_time:   '||G_START_TIME2||chr(10));

  vG_ELAPSED_TIME :=  G_START_TIME2 - G_START_TIME1;
  millisecondss   :=  vG_ELAPSED_TIME * n_ten;
  secondss        :=  vG_ELAPSED_TIME / n_secs;
  minutess        :=  vG_ELAPSED_TIME / n_mins;
  hourss          :=  vG_ELAPSED_TIME / n_hrs;

  dbms_output.put_line('Total Time: '||millisecondss ||' Milliseconds');
  dbms_output.put_line('Total Time: '||vG_ELAPSED_TIME ||' Centiseconds');
  dbms_output.put_line('Total Time: '||secondss ||' Seconds');
  dbms_output.put_line('Total Time: '||minutess ||' Minutes');
  dbms_output.put_line('Total Time: '||hourss ||' Hours');

  millisecondss   :=  mod(vG_ELAPSED_TIME * n_ten, 1000);            /* Milliseconds into Seconds.  Returns left over millisedonds */
  secondss        :=  trunc(mod(vG_ELAPSED_TIME / n_secs, n_sixty)); /* Seconds into hours.  Returns how many seconds are left over */
  minutess        :=  trunc(mod(vG_ELAPSED_TIME / n_mins, n_sixty)); /* Seconds into hours.  Returns how many seconds are left over */
  hourss          :=  trunc(vG_ELAPSED_TIME / n_hrs);                /* Spit out hours only using just trunc here.  Since we don't need to build up Days we can leave this as is */

  v_PrintTime     :=  hourss ||':'|| minutess ||':'|| secondss ||'.'|| millisecondss;

  dbms_output.put_line(chr(10) ||'Elapsed Time: '|| v_PrintTime);

END;
</code>```

Body:
If you are looking to write your own time lapse into your PL/SQL programs the below is my template code for doing this.  Also, this requires no assistance from your DBA.  My DBA's are often reluctant to give me more access to more things.  That, and I hate waiting for them to actually give me access.

/* This procedure is simply an example of parsing out an Elapsed time into their individual time parts */
/*   In other words it provides to the user the elapsed time in hours : minutes : seconds . milliseconds */

DECLARE

  G_START_TIME1     NUMBER        := DBMS_UTILITY.GET_TIME;
  G_START_TIME2     NUMBER        := DBMS_UTILITY.GET_TIME;
  vG_ELAPSED_TIME   VARCHAR2(200);

  /* Variables below are used for storing Elapsed time. */
  RETVAL           NUMBER;
  hourss            NUMBER;
  minutess          NUMBER;
  secondss          NUMBER;
  millisecondss     NUMBER;
    n_hrs         NUMBER := 360000;
    n_mins        NUMBER := 6000;
    n_secs        NUMBER := 100;
    n_sixty       NUMBER := 60;
    n_thirty      NUMBER := 30;
    n_ten         NUMBER := 10;

  v_PrintTime     VARCHAR2(200);

  /* The procedure below is simply used to simulate the passage of time */
  PROCEDURE waste_time(pn_Seconds NUMBER) IS

  n_CentiSeconds  NUMBER  :=  pn_Seconds * 100;
  n_ProgramStart  NUMBER  := DBMS_UTILITY.GET_TIME; /* dbms_utility_get_time returns times in hundreds of a second */

  BEGIN
    WHILE DBMS_UTILITY.GET_TIME < n_ProgramStart + n_CentiSeconds
    LOOP
      null;
    END LOOP;
  END waste_time;

BEGIN

  G_START_TIME1   :=    -2019618227; --dbms_utility.get_time;

  --waste_time(1);
  --dbms_output.put_line('1 Second Wasted'|| chr(10));

  G_START_TIME2   :=    G_START_TIME1 + 366110; ---2019619227; --dbms_utility.get_time;

  dbms_output.put_line('Start_time: '||G_START_TIME1);
  dbms_output.put_line('End_time:   '||G_START_TIME2||chr(10));

  vG_ELAPSED_TIME :=  G_START_TIME2 - G_START_TIME1;
  millisecondss   :=  vG_ELAPSED_TIME * n_ten;
  secondss        :=  vG_ELAPSED_TIME / n_secs;
  minutess        :=  vG_ELAPSED_TIME / n_mins;
  hourss          :=  vG_ELAPSED_TIME / n_hrs;

  dbms_output.put_line('Total Time: '||millisecondss ||' Milliseconds');
  dbms_output.put_line('Total Time: '||vG_ELAPSED_TIME ||' Centiseconds');
  dbms_output.put_line('Total Time: '||secondss ||' Seconds');
  dbms_output.put_line('Total Time: '||minutess ||' Minutes');
  dbms_output.put_line('Total Time: '||hourss ||' Hours');

  millisecondss   :=  mod(vG_ELAPSED_TIME * n_ten, 1000);            /* Milliseconds into Seconds.  Returns left over millisedonds */
  secondss        :=  trunc(mod(vG_ELAPSED_TIME / n_secs, n_sixty)); /* Seconds into hours.  Returns how many seconds are left over */
  minutess        :=  trunc(mod(vG_ELAPSED_TIME / n_mins, n_sixty)); /* Seconds into hours.  Returns how many seconds are left over */
  hourss          :=  trunc(vG_ELAPSED_TIME / n_hrs);                /* Spit out hours only using just trunc here.  Since we don't need to build up Days we can leave this as is */

  v_PrintTime     :=  hourss ||':'|| minutess ||':'|| secondss ||'.'|| millisecondss;

  dbms_output.put_line(chr(10) ||'Elapsed Time: '|| v_PrintTime);

END;


来源: stackexchange

问:
"Could not reach Firestore backend", multiple Firebase apps, Android
I'm migrating from Realtime Database to Firestore. Because I can't have both a Realtime Database instance and a Firestore instance in the same project, I have to init the Firestore instance manually, rather than have it pick up the google-services.json file automatically as part of the build. I've done that like this:

```<code>    FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
            .setProjectId("***")
            .setApiKey("***")
            .setApplicationId("***")
            .setDatabaseUrl("https://***.firebaseio.com")
            .build();
    FirebaseApp firebaseApp = FirebaseApp.initializeApp(this, firebaseOptions, "dev");
    FirebaseFirestore db = FirebaseFirestore.getInstance(firebaseApp);
</code>```

All the values are taken from the google-services.json file I downloaded for the new project.

Calling FirebaseFirestore.getInstance() is fine, but when I later try to get a document, I see this in logcat:

```<code>W/Firestore: (0.6.6-dev) [OnlineStateTracker]: Could not reach Firestore backend.
</code>```

The Task for a get() call to a Document has an exception message of:

```<code>Failed to get document because the client is offline.
</code>```

The device is online, for sure. The new project in the console does NOT have the SHA certificate fingerprints set, because I can't use the same one as for the original project.

What am I missing?

[Edit]

答:
I know that is a little late for the answer. In my case, I had the same problem because I try to test Datastore and I lose the possibility to use Firestore in my project. When I try to create a new project for Firestore,  I have to init the Firestore instance manually and I had the same problem.

In my case, the problem was that one of the parameters of FirebaseOptions was wrong (in my case was project_id because I had put project_number). I had taken all parameters from google_services.json from the new project:

```<code>FirebaseOptions.Builder()
            .setApplicationId("X:XXXXXXXX:android:YYYYYYY") // FROM client_info -> mobilesdk_app_id.
            .setApiKey("AIzaXXXXXXXXXXX") // FROM api_key -> current_key
            .setDatabaseUrl("https://XXXXXXX.firebaseio.com") // FROM firebase_url.
            .setProjectId("XXXXXXXX") //FROM project_id
            .setStorageBucket("XXXXXXX.appspot.com") //FROM storage_bucket
            .build();
</code>```

After that everything start to work fine.

ContentLicense: CC BY-SA 4.0

Body:
I'm migrating from Realtime Database to Firestore. Because I can't have both a Realtime Database instance and a Firestore instance in the same project, I have to init the Firestore instance manually, rather than have it pick up the google-services.json file automatically as part of the build. I've done that like this:

    FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
            .setProjectId("***")
            .setApiKey("***")
            .setApplicationId("***")
            .setDatabaseUrl("https://***.firebaseio.com")
            .build();
    FirebaseApp firebaseApp = FirebaseApp.initializeApp(this, firebaseOptions, "dev");
    FirebaseFirestore db = FirebaseFirestore.getInstance(firebaseApp);

All the values are taken from the google-services.json file I downloaded for the new project.

Calling FirebaseFirestore.getInstance() is fine, but when I later try to get a document, I see this in logcat:

W/Firestore: (0.6.6-dev) [OnlineStateTracker]: Could not reach Firestore backend.

The Task for a get() call to a Document has an exception message of:

Failed to get document because the client is offline.

The device is online, for sure. The new project in the console does NOT have the SHA certificate fingerprints set, because I can't use the same one as for the original project.

What am I missing?

[Edit]

Body:
I know that is a little late for the answer. In my case, I had the same problem because I try to test Datastore and I lose the possibility to use Firestore in my project. When I try to create a new project for Firestore,  I have to init the Firestore instance manually and I had the same problem.

In my case, the problem was that one of the parameters of FirebaseOptions was wrong (in my case was project_id because I had put project_number). I had taken all parameters from google_services.json from the new project:

FirebaseOptions.Builder()
            .setApplicationId("X:XXXXXXXX:android:YYYYYYY") // FROM client_info -> mobilesdk_app_id.
            .setApiKey("AIzaXXXXXXXXXXX") // FROM api_key -> current_key
            .setDatabaseUrl("https://XXXXXXX.firebaseio.com") // FROM firebase_url.
            .setProjectId("XXXXXXXX") //FROM project_id
            .setStorageBucket("XXXXXXX.appspot.com") //FROM storage_bucket
            .build();

After that everything start to work fine.


问:
Is there a way to get my emacs to recognize my bash aliases and custom functions when I run a shell command?
In my shell environment I have aliases and custom functions. When I am in an instance of emacs (I always use emacs -nw) and I execute a shell command (M-!) I cannot use them. This makes sense since I imagine it launches it's own subshell to do these... but is there a way (maybe in my .emacs) to get this to work? Perhaps even if it involved sourcing an environment by default before executing any shell command given?

答:
We need to enable alias expansion in non-interactive shells, preferably only when they are called from emacs (to avoid causing subtle differences when we run other shells).  What worked for me was to create two files: ~/.alias has all my aliases, e.g.

```<code>alias python python27
</code>```

and ~/.aliasExpand has

```<code>source ~/.alias
shopt -s expand_aliases
</code>```

I also, of course, replaced all my aliases in .bashrc with

```<code>source ~/.alias
</code>```

Finally, I added this to my .emacs:

```<code>(setenv "BASH_ENV" "~/.aliasExpand")
</code>```

I tried Keith Flower's solution (of making shells interactive), and I got

bash: cannot set terminal process group (-1): Inappropriate ioctl for device
  bash: no job control in this shell

Note that I got this through Glenn Jackman's and Nicholas Dudebout's hints.

If you are willing to risk having all your shells have alias expansion and you don't mind running all your .bashrc for every emacs shell, you can simplify this to adding

```<code>shopt -s expand_aliases
</code>```

to your .bashrc and

```<code>(setenv "BASH_ENV" "~/.bashrc")
</code>```

to your .emacs

Body:
We need to enable alias expansion in non-interactive shells, preferably only when they are called from emacs (to avoid causing subtle differences when we run other shells).  What worked for me was to create two files: ~/.alias has all my aliases, e.g.

alias python python27

and ~/.aliasExpand has

source ~/.alias
shopt -s expand_aliases

I also, of course, replaced all my aliases in .bashrc with

source ~/.alias

Finally, I added this to my .emacs:

(setenv "BASH_ENV" "~/.aliasExpand")

I tried Keith Flower's solution (of making shells interactive), and I got

bash: cannot set terminal process group (-1): Inappropriate ioctl for device
  bash: no job control in this shell

Note that I got this through Glenn Jackman's and Nicholas Dudebout's hints.

If you are willing to risk having all your shells have alias expansion and you don't mind running all your .bashrc for every emacs shell, you can simplify this to adding

shopt -s expand_aliases

to your .bashrc and

(setenv "BASH_ENV" "~/.bashrc")

to your .emacs


问:
Floating DIV Containers
Am actually creating a News Container and within it news content with heading, images(if any), summary and eventually a read more link.

The news content is placed in a DIV with a fixed width but i dont want a fixed height however.

The issue is that i want the containers to float on the left, which works but since the height are not the same am getting a white space between the 3rd and 4th one.

How can i fix this?

答:
you no need to specify height.the height will be automatically adjusted based on the content size.

```<code><div id="news-content"></div>
</code>```

css

```<code>#news-content
{
width:100%;
float:left;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Floating DIV Containers

Body:
you no need to specify height.the height will be automatically adjusted based on the content size.

<div id="news-content"></div>

css

#news-content
{
width:100%;
float:left;
}


问:
Performing an update on the path '_id' would modify the immutable field '_id'
I am trying to UPDATE fields in mongo database. However, I get the hollowing error.

MongoError: Performing an update on the path '_id' would modify the
  immutable field '_id'

My Code to update.

```<code>app.put("/api/inventory/:sku", (req, res, next) => {
  const inventory = new Inventory({
    _id: req.body.id,
    sku: req.body.sku,
    total_qty: req.body.total_qty,
    current_qty: req.body.current_qty
  });
  Inventory.updateOne({ sku: req.params.sku }, req.body).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});
</code>```

答:
_id is auto-generated - for a more in-depth explanation about what it is, see this answer.

You can't create this field - it's created when you create any new document. You need to use the id field (no leading underscore _):

```<code>const inventory = new Inventory({
  id: req.body.id,
  sku: req.body.sku,
  total_qty: req.body.total_qty,
  current_qty: req.body.current_qty
});
</code>```

Body:
I am trying to UPDATE fields in mongo database. However, I get the hollowing error.

MongoError: Performing an update on the path '_id' would modify the
  immutable field '_id'

My Code to update.

app.put("/api/inventory/:sku", (req, res, next) => {
  const inventory = new Inventory({
    _id: req.body.id,
    sku: req.body.sku,
    total_qty: req.body.total_qty,
    current_qty: req.body.current_qty
  });
  Inventory.updateOne({ sku: req.params.sku }, req.body).then(result => {
    res.status(200).json({ message: "Update successful!" });
  });
});

Body:
_id is auto-generated - for a more in-depth explanation about what it is, see this answer.

You can't create this field - it's created when you create any new document. You need to use the id field (no leading underscore _):

const inventory = new Inventory({
  id: req.body.id,
  sku: req.body.sku,
  total_qty: req.body.total_qty,
  current_qty: req.body.current_qty
});


问:
Inserting my default Outlook Signature into an Email
Trying to insert my default Outlook signature. I can't seem to get it to work.  Any thoughts on this would be appreciated.

I can't seem to get it to work with .HTML

```<code>Sub Send_email_fromexcel()

    Dim edress As String
    Dim subj As String
    Dim message As String
    Dim outlookapp As Object
    Dim outlookmailitem As Object
    Dim path As String
    Dim lastrow As Integer
    Dim x As Integer
    Dim header As String
    Dim header1 As String
    Dim header2 As String
    Dim header3 As String
    Dim header4 As String
    Dim header5 As String
    Dim header6 As String
    Dim header7 As String
    Dim hearder8 As String
    Dim data As String
    Dim data1 As String
    Dim data2 As String
    Dim data3 As String
    Dim data4 As String
    Dim data5 As String
    Dim data6 As String
    Dim sig As String

    x = 2
    Do While Sheet1.Cells(x, 1) <> ""

        Set outlookapp = CreateObject("Outlook.Application")
        Set outlookmailitem = outlookapp.createitem(0)

        edress = Sheet1.Cells(x, 1)
        subj = Sheet1.Cells(x, 2)
        header = Sheet1.Cells(1, 3)
        header2 = Sheet1.Cells(1, 4)
        header3 = Sheet1.Cells(1, 5)
        header4 = Sheet1.Cells(1, 6)
        header5 = Sheet1.Cells(1, 7)
        header6 = Sheet1.Cells(1, 8)
        header7 = Sheet1.Cells(1, 9)
        header8 = Sheet1.Cells(1, 10)

        data = Sheet1.Cells(x, 3)
        data1 = Sheet1.Cells(x, 4)
        data2 = Sheet1.Cells(x, 5)
        data3 = Sheet1.Cells(x, 6)
        data4 = Sheet1.Cells(x, 7)
        data5 = Sheet1.Cells(x, 8)
        data6 = Sheet1.Cells(x, 9)

        outlookmailitem.To = edress
        outlookmailitem.cc = ""
        outlookmailitem.bcc = ""
        outlookmailitem.Subject = subj
        outlookmailitem.body = "Good afternoon," & vbNewLine & " " & vbNewLine & "I'm just reaching out because we are attempting to process rewards for customers that were referred using the Lawn Doctor Referral Rewards Program,… I have put it in this email." & vbNewLine & "Please update your records accordingly by going into …(s). Please let me know when this has been completed and I will push their Amazon Gift Card out." & vbCrLf & header & " " & header2 & " " & header3 & " " & header4 & " " & header5 & " " & header6 & " " & header7 & " " & header8 & _
        vbCrLf & data & " " & data1 & " " & data2 & " " & data3 & " " & data4 & " " & data5 & " " & data6 & _
        vbCrLf & vbNewLine & "Regards"

        outlookmailitem.display
        outlookmailitem.send

        lastrow = lastrow + 1
        edress = ""
        x = x + 1

    Loop

    Set outlookapp = Nothing
    Set outlookmailitem = Nothing

End Sub
</code>```

答:
You need something like this. First create a function and then call it in your outlook code just before the email details and when you put the email details do something like  .HTMLBody = emailMessage & Signature

```<code>'Change only Mysig.htm to the name of your signature
    sigString = Environ("appdata") & _
                "\Microsoft\Signatures\Mysig.htm"

    If Dir(sigString) <> "" Then
        Signature = GetBoiler(sigString)
    Else
        Signature = ""
    End If

Function GetBoiler(ByVal sFile As String) As String

    Dim FSO As Object
    Dim ts As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set ts = FSO.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function
</code>```

Full code as example to make more sense of the above snippet.

```<code>Sub SendEmail()

    Dim outlookApp As Object
    Dim outlookMail As Object
    Dim sigString As String
    Dim Signature As String
    Dim insertPhoto As String
    Dim photoSize As String
    Dim outlookPA As Outlook.PropertyAccessor

    Set outlookApp = CreateObject("Outlook.Application")
    Set outlookMail = outlookApp.CreateItem(0)

    'Change only Mysig.htm to the name of your signature
    sigString = Environ("appdata") & _
                "\Microsoft\Signatures\Mysig.htm"

    If Dir(sigString) <> "" Then
        Signature = GetBoiler(sigString)
    Else
        Signature = ""
    End If

    insertPhoto = "C:\Users\marius.dragan\Desktop\Presale.jpg" 'Picture path
    photoSize = "<img src=""cid:Presale.jpg""height=400 width=400>" 'Change image name here

    emailMessage = "<BODY style=font-size:11pt;font-family:Calibri>Dear " & titleName & " " & fullName & "," & _
                    "<p>I hope my email will find you very well." & _
                    "<p>Our <strong>sales preview</strong> starts on Thursday the 22nd until Sunday the 25th of November." & _
                    "<p>I look forward to welcoming you into the store to shop on preview.<p>" & _
                    "<p> It really is the perfect opportunity to get some fabulous pieces for the fast approaching festive season." & _
                    "<p>Please feel free to contact me and book an appointment." & _
                    "<p>I look forward to seeing you then." & _
                    "<p>" & photoSize & _
                    "<p>"

    With outlookMail
        .To = clientEmail
        .CC = ""
        .BCC = ""
        .Subject = "PRIVATE SALE"
        .BodyFormat = 2
        .Attachments.Add insertPhoto, 1, 0
        .HTMLBody = emailMessage & Signature 'Including photo insert and signature
        .Importance = 2
        .ReadReceiptRequested = True
        .Display 'Needs to display the email and then send to display in line image
        .send 'this will send the email without review

    End With

    Set outlookApp = Nothing
    Set outlookMail = Nothing
End Sub
Function GetBoiler(ByVal sFile As String) As String

    Dim FSO As Object
    Dim ts As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set ts = FSO.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function
</code>```

Body:
Trying to insert my default Outlook signature. I can't seem to get it to work.  Any thoughts on this would be appreciated.

I can't seem to get it to work with .HTML

Sub Send_email_fromexcel()

    Dim edress As String
    Dim subj As String
    Dim message As String
    Dim outlookapp As Object
    Dim outlookmailitem As Object
    Dim path As String
    Dim lastrow As Integer
    Dim x As Integer
    Dim header As String
    Dim header1 As String
    Dim header2 As String
    Dim header3 As String
    Dim header4 As String
    Dim header5 As String
    Dim header6 As String
    Dim header7 As String
    Dim hearder8 As String
    Dim data As String
    Dim data1 As String
    Dim data2 As String
    Dim data3 As String
    Dim data4 As String
    Dim data5 As String
    Dim data6 As String
    Dim sig As String

    x = 2
    Do While Sheet1.Cells(x, 1) <> ""

        Set outlookapp = CreateObject("Outlook.Application")
        Set outlookmailitem = outlookapp.createitem(0)

        edress = Sheet1.Cells(x, 1)
        subj = Sheet1.Cells(x, 2)
        header = Sheet1.Cells(1, 3)
        header2 = Sheet1.Cells(1, 4)
        header3 = Sheet1.Cells(1, 5)
        header4 = Sheet1.Cells(1, 6)
        header5 = Sheet1.Cells(1, 7)
        header6 = Sheet1.Cells(1, 8)
        header7 = Sheet1.Cells(1, 9)
        header8 = Sheet1.Cells(1, 10)

        data = Sheet1.Cells(x, 3)
        data1 = Sheet1.Cells(x, 4)
        data2 = Sheet1.Cells(x, 5)
        data3 = Sheet1.Cells(x, 6)
        data4 = Sheet1.Cells(x, 7)
        data5 = Sheet1.Cells(x, 8)
        data6 = Sheet1.Cells(x, 9)

        outlookmailitem.To = edress
        outlookmailitem.cc = ""
        outlookmailitem.bcc = ""
        outlookmailitem.Subject = subj
        outlookmailitem.body = "Good afternoon," & vbNewLine & " " & vbNewLine & "I'm just reaching out because we are attempting to process rewards for customers that were referred using the Lawn Doctor Referral Rewards Program,… I have put it in this email." & vbNewLine & "Please update your records accordingly by going into …(s). Please let me know when this has been completed and I will push their Amazon Gift Card out." & vbCrLf & header & " " & header2 & " " & header3 & " " & header4 & " " & header5 & " " & header6 & " " & header7 & " " & header8 & _
        vbCrLf & data & " " & data1 & " " & data2 & " " & data3 & " " & data4 & " " & data5 & " " & data6 & _
        vbCrLf & vbNewLine & "Regards"

        outlookmailitem.display
        outlookmailitem.send

        lastrow = lastrow + 1
        edress = ""
        x = x + 1

    Loop

    Set outlookapp = Nothing
    Set outlookmailitem = Nothing

End Sub

Body:
You need something like this. First create a function and then call it in your outlook code just before the email details and when you put the email details do something like  .HTMLBody = emailMessage & Signature

'Change only Mysig.htm to the name of your signature
    sigString = Environ("appdata") & _
                "\Microsoft\Signatures\Mysig.htm"

    If Dir(sigString) <> "" Then
        Signature = GetBoiler(sigString)
    Else
        Signature = ""
    End If

Function GetBoiler(ByVal sFile As String) As String

    Dim FSO As Object
    Dim ts As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set ts = FSO.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function

Full code as example to make more sense of the above snippet.

Sub SendEmail()

    Dim outlookApp As Object
    Dim outlookMail As Object
    Dim sigString As String
    Dim Signature As String
    Dim insertPhoto As String
    Dim photoSize As String
    Dim outlookPA As Outlook.PropertyAccessor

    Set outlookApp = CreateObject("Outlook.Application")
    Set outlookMail = outlookApp.CreateItem(0)

    'Change only Mysig.htm to the name of your signature
    sigString = Environ("appdata") & _
                "\Microsoft\Signatures\Mysig.htm"

    If Dir(sigString) <> "" Then
        Signature = GetBoiler(sigString)
    Else
        Signature = ""
    End If

    insertPhoto = "C:\Users\marius.dragan\Desktop\Presale.jpg" 'Picture path
    photoSize = "<img src=""cid:Presale.jpg""height=400 width=400>" 'Change image name here

    emailMessage = "<BODY style=font-size:11pt;font-family:Calibri>Dear " & titleName & " " & fullName & "," & _
                    "<p>I hope my email will find you very well." & _
                    "<p>Our <strong>sales preview</strong> starts on Thursday the 22nd until Sunday the 25th of November." & _
                    "<p>I look forward to welcoming you into the store to shop on preview.<p>" & _
                    "<p> It really is the perfect opportunity to get some fabulous pieces for the fast approaching festive season." & _
                    "<p>Please feel free to contact me and book an appointment." & _
                    "<p>I look forward to seeing you then." & _
                    "<p>" & photoSize & _
                    "<p>"

    With outlookMail
        .To = clientEmail
        .CC = ""
        .BCC = ""
        .Subject = "PRIVATE SALE"
        .BodyFormat = 2
        .Attachments.Add insertPhoto, 1, 0
        .HTMLBody = emailMessage & Signature 'Including photo insert and signature
        .Importance = 2
        .ReadReceiptRequested = True
        .Display 'Needs to display the email and then send to display in line image
        .send 'this will send the email without review

    End With

    Set outlookApp = Nothing
    Set outlookMail = Nothing
End Sub
Function GetBoiler(ByVal sFile As String) As String

    Dim FSO As Object
    Dim ts As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set ts = FSO.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function


问:
Order files numerically in specific folder
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

```<code>        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();
</code>```

Windows Explore

Console Output

答:
You can just use a OrderBy linq statement and parse out the file name to get what you want. Also you don't need ToList() if all you want is a simple list such as IEnumerable.

For example:

var txtFiles = Directory.EnumerateFiles(folder, "*.txt")
                         .Select(Path.GetFileName)
                         .OrderBy(file =>
                         {
                             string[] nameParts = file.Split('_');
                             if (nameParts.Length > 0)
                             {
                                 int sortValue;
                                 if (int.TryParse(nameParts[0], out sortValue))
                                 {
                                     return sortValue;
                                 }
                             }
                             return 0;
                         });
```

Body:
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();

Windows Explore

Console Output


问:
How do I make a sorted list of items based on multiple list of sorted items?
I am trying to get a sorted master list from smaller lists. This can be in python or R.

in R, I have

```<code>l1<-c("a","c","d")
l2<-c("a","b","e")
l3<-c("a","c","e")
l4<-c("a","b","c","e")
l5<-c("b","c","d")

m<-unique(c(l1,l2,l3,l4,l5))
</code>```

The output I was expecting is a,b,c,d,e.

In python

```<code>l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]
</code>```

expected result is ["a","b","c","d","e"]
I started with making a set and going over each list and checking with index but it started getting complex.

Thank you for help.

EDIT:
I think I confused you with having a alphabetically sorted list. Those list items could be random. the real order may not be a,b,c,d,e.

```<code>l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]
</code>```

in this case expected order is ["e","b","d","a"] not ["a","b","d","e"]

for more clarity, think about few people trying to name US states from east to west.

```<code>person 1 says, Florida, Louisiana, Nevada,California.
person 2 says  Alabama, Mississippi, Louisiana, new Mexico, Nevada
person 3 says Florida, Alabama, Texas, New Mexico, California
person 4 says Alabama, Mississippi, Texas, Nevada
person 5 says Mississippi Louisiana, Nevada
</code>```

and I am trying to get right order from information above.

So, here, We will start with Florida, Louisiana, Nevada, California. Now, adding second, it would be, (Alabama, Florida),Louisiana,New Mexico, Nevada, California. Adding 3rd (breaks the tie of Alabama/Florida),Florida, Alabama, Louisiana, Texas, New Mexico, Nevada, California and adding 4th makes Florida, Alabama, (Mississippi/Louisiana), Texas, New Mexico, Nevada, California. adding 5th breaks tie of Mississippi and Louisiana.

答:
Aaaand the actual answer: https://www.python.org/doc/essays/graphs/

Good hunting! :D

This should do it for your original question:

l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

s = set()
s.update(l1, l2, l3, l4, l5)
l = sorted(s)
l
#['a', 'b', 'c', 'd', 'e']
```

<p>For your edited question, let's consider a slight variation on your second example:</p>

<pre class="lang-py prettyprint-override"><code>l1=["e","a"]
l2=["e","b","d"]
l3=["b","c","a"]
</code>```

(Squint at l3.) In this case, the set of lists is underdetermined, as there is no unique ordering between d and c. Without a rule for deciding ties, no algorithm is possible.

Body:
I am trying to get a sorted master list from smaller lists. This can be in python or R.

in R, I have

l1<-c("a","c","d")
l2<-c("a","b","e")
l3<-c("a","c","e")
l4<-c("a","b","c","e")
l5<-c("b","c","d")

m<-unique(c(l1,l2,l3,l4,l5))

The output I was expecting is a,b,c,d,e.

In python

l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

expected result is ["a","b","c","d","e"]
I started with making a set and going over each list and checking with index but it started getting complex.

Thank you for help.

EDIT:
I think I confused you with having a alphabetically sorted list. Those list items could be random. the real order may not be a,b,c,d,e.

l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]

in this case expected order is ["e","b","d","a"] not ["a","b","d","e"]

for more clarity, think about few people trying to name US states from east to west.

person 1 says, Florida, Louisiana, Nevada,California.
person 2 says  Alabama, Mississippi, Louisiana, new Mexico, Nevada
person 3 says Florida, Alabama, Texas, New Mexico, California
person 4 says Alabama, Mississippi, Texas, Nevada
person 5 says Mississippi Louisiana, Nevada

and I am trying to get right order from information above.

So, here, We will start with Florida, Louisiana, Nevada, California. Now, adding second, it would be, (Alabama, Florida),Louisiana,New Mexico, Nevada, California. Adding 3rd (breaks the tie of Alabama/Florida),Florida, Alabama, Louisiana, Texas, New Mexico, Nevada, California and adding 4th makes Florida, Alabama, (Mississippi/Louisiana), Texas, New Mexico, Nevada, California. adding 5th breaks tie of Mississippi and Louisiana.

Body:
Aaaand the actual answer: https://www.python.org/doc/essays/graphs/

Good hunting! :D

This should do it for your original question:

l1=["a","c","d"]
l2=["a","b","e"]
l3=["a","c","e"]
l4=["a","b","c","e"]
l5=["b","c","d"]

s = set()
s.update(l1, l2, l3, l4, l5)
l = sorted(s)
l
#['a', 'b', 'c', 'd', 'e']

For your edited question, let's consider a slight variation on your second example:

l1=["e","a"]
l2=["e","b","d"]
l3=["b","c","a"]

(Squint at l3.) In this case, the set of lists is underdetermined, as there is no unique ordering between d and c. Without a rule for deciding ties, no algorithm is possible.


问:
TS(2352) Declare object with dynamic properties and one property with specific type
I need to create object which will contain one property with name 'state' which will have generic type and all other properties will be functions with overriden context. I'm not sure that it is possible, because of this I decided to write to here.

I have a code:

declare interface ContextModule<State> {
  state: State
}

export declare interface SuperModule<State = any> {
  state?: State | any,
  [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}

const lol = {
  getFoo (): any {
    return this.state.foo
  }
} as SuperModule
```

<p>In this code I don't have any errors. It executes successfully, but if I will add</p>

<pre class="lang-js prettyprint-override"><code>declare interface ContextModule<State> {
  state: State
}

export declare interface SuperModule<State = any> {
  state?: State | any,
  [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}

const lol = {
  getFoo (): any {
    return this.state.foo
  },
+  state: {       // added this property
+    foo: 'string'
+  }
} as SuperModule
</code>```

Then I will see output

```<code>Conversion of type '{ getFoo(this: ContextModule<any>): any; state: { foo: string; }; }' to type 'SuperModule<any>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Property 'state' is incompatible with index signature.
    Type '{ foo: string; }' is not comparable to type '(this: ContextModule<any>, ...args: any[]) => any'.
      Type '{ foo: string; }' provides no match for the signature '(this: ContextModule<any>, ...args: any[]): any'.ts(2352)
</code>```

I understand that problem linked with that TypeScript trying to cast property state to [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any, but why if I declared this property before declaration for dynamic properties

May be somebody saw the same problem. Hope on your help, thanks!

答:
The only way I could get this to work cleanly is using an intersection type, but it appears that the intersection of dynamic types and types with fixed properties (of differing type to the dynamic props) can only be created using Object.assign.

Here is my simplified example of how this might work:

```<code>interface MyType {
    requiredProp1: string
}
interface MyOtherType{
    [key: string]: number
}
type ISect = MyType & MyOtherType

const obj: ISect = Object.assign({ requiredProp1: "ff" }, { foo: 1 })

const rp1 = obj.requiredProp1 //string
const foo = obj.foo //number
</code>```

Body:
I need to create object which will contain one property with name 'state' which will have generic type and all other properties will be functions with overriden context. I'm not sure that it is possible, because of this I decided to write to here.

I have a code:

declare interface ContextModule<State> {
  state: State
}

export declare interface SuperModule<State = any> {
  state?: State | any,
  [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}

const lol = {
  getFoo (): any {
    return this.state.foo
  }
} as SuperModule

In this code I don't have any errors. It executes successfully, but if I will add

declare interface ContextModule<State> {
  state: State
}

export declare interface SuperModule<State = any> {
  state?: State | any,
  [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}

const lol = {
  getFoo (): any {
    return this.state.foo
  },
+  state: {       // added this property
+    foo: 'string'
+  }
} as SuperModule

Then I will see output

Conversion of type '{ getFoo(this: ContextModule<any>): any; state: { foo: string; }; }' to type 'SuperModule<any>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Property 'state' is incompatible with index signature.
    Type '{ foo: string; }' is not comparable to type '(this: ContextModule<any>, ...args: any[]) => any'.
      Type '{ foo: string; }' provides no match for the signature '(this: ContextModule<any>, ...args: any[]): any'.ts(2352)

I understand that problem linked with that TypeScript trying to cast property state to [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any, but why if I declared this property before declaration for dynamic properties

May be somebody saw the same problem. Hope on your help, thanks!

Body:
The only way I could get this to work cleanly is using an intersection type, but it appears that the intersection of dynamic types and types with fixed properties (of differing type to the dynamic props) can only be created using Object.assign.

Here is my simplified example of how this might work:

interface MyType {
    requiredProp1: string
}
interface MyOtherType{
    [key: string]: number
}
type ISect = MyType & MyOtherType

const obj: ISect = Object.assign({ requiredProp1: "ff" }, { foo: 1 })

const rp1 = obj.requiredProp1 //string
const foo = obj.foo //number


问:
Counting multidimensional array in PHP
I have a large multidimensional array, which is output into an HTML table. Each second-level array has the same number of values. I need to count how many of the key/value pairs in the first array, which is [247326] in this example. Is there a way to do it without looping through?</p>

```<code>Array
(
    [247326] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144815] => 0
            ...
            [144909] => 0
        )

    [247327] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144909] => 0
        )

    [247328] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144789] => 0
        )

)
</code>```

答:
Suppose your array is called $array then you can get the number of key/value pairs in items 247326 with:

```<code>$pairs = count($array[247326]);
</code>```

The result will be in $pairs. It you don't know the first item in the array you can get it with reset() like so:

```<code>$first = reset($array);
$pairs = count($first);
</code>```

This is so simple that I must have misunderstood your question?

Title: Counting multidimensional array in PHP

Body:
I have a large multidimensional array, which is output into an HTML table. Each second-level array has the same number of values. I need to count how many of the key/value pairs in the first array, which is [247326] in this example. Is there a way to do it without looping through?

Array
(
    [247326] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144815] => 0
            ...
            [144909] => 0
        )

    [247327] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144909] => 0
        )

    [247328] => Array
        (
            [144784] => 0
            [144785] => 0
            [144787] => 1
            [144788] => 0
            ...
            [144789] => 0
        )

)

Body:
Suppose your array is called $array then you can get the number of key/value pairs in items 247326 with:

$pairs = count($array[247326]);

The result will be in $pairs. It you don't know the first item in the array you can get it with reset() like so:

$first = reset($array);
$pairs = count($first);

This is so simple that I must have misunderstood your question?


问:
PHP URL Rewriting for the link
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       document.location="delete_row.php";
       return false;
     }
</script>
</head>

<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
  {?>
  <tr>
  <td><?php echo $row['name'];?></td>
  <td><?php echo $row['age'];?></td>
  <td><a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete</a></td>
  </tr>
  <?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
</code>```

This is the PHP part with file name delete_row.php

```<code><?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
</code>```

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

答:
You can use a small form, with the "delete" button being a submit button.  Set the method to "post."  An example:

```<code><form action="delete_row.php" method="post">
  <input type="hidden" name="row" value="5">
  <input type="submit" value="Delete">
</form>
</code>```

In your PHP file, you can then use the POST values rather than GET values. This is more correct, as well -- GET actions should be idempotent (i.e. should have no effects except returning the requested information).

Title: PHP URL Rewriting for the link

Body:
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>

Name
Age

<?php
while($row = mysql_fetch_array($result))
  {?>

  <?php echo $row['name'];?>
  <?php echo $row['age'];?>
  <a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete

  <?php } ?>

<?php
mysql_close($con);
?>

This is the PHP part with file name delete_row.php

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

Body:
You can use a small form, with the "delete" button being a submit button.  Set the method to "post."  An example:

<form action="delete_row.php" method="post">
  <input type="hidden" name="row" value="5">
  <input type="submit" value="Delete">
</form>

In your PHP file, you can then use the POST values rather than GET values. This is more correct, as well -- GET actions should be idempotent (i.e. should have no effects except returning the requested information).


问:
Spring WS is not generating wsdl operations for all the public methods in the Endpoint class
I have a Spring endpoint class with two public methods. But when Spring is auto-generating the wsdl it doesn't include the second public method. Could you pleas let me know what is wrong and what needs to be done. I am using Spring 4.3 and below are the classes.

Configuration class

```<code>@EnableWs
@Configuration
public class SoapServiceConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);

        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "policies")
    public DefaultWsdl11Definition policyserviceWsdl11Definition(@Autowired @Qualifier("swissSchema") XsdSchema swissSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("PoliciesPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://www.testcomp.com/iaworkflow/soapservice");
        wsdl11Definition.setSchema(swissSchema);
        return wsdl11Definition;
    }

    @Bean(name = "bankservice")
    public DefaultWsdl11Definition bankServiceWsdlDefinition(@Autowired @Qualifier("bankSchema")XsdSchema bankSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("BankAPIPort");
        wsdl11Definition.setLocationUri("/ws/bankapi");
        wsdl11Definition.setTargetNamespace("http://www.testcomp.com/consumer/bankservice/soapservice");
        wsdl11Definition.setSchema(bankSchema);
        return wsdl11Definition;
    }

    @Bean
    @Qualifier("bankSchema")
    public XsdSchema bankSchema() {
        return new SimpleXsdSchema(new ClassPathResource("bankservice.xsd"));
    }

    @Bean
    @Qualifier("swissSchema")
    public XsdSchema swissSchema() {
        return new SimpleXsdSchema(new ClassPathResource("policylookup.xsd"));
    }
}
</code>```

Endpoint

```<code>@Endpoint
public class BankingServiceEndpoint {
    private static final String NAMESPACE_URI = "http://www.testcomp.com/consumer/bankservice/soapservice";

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "BankInfoSearchRequest")
    @ResponsePayload
    public BankInfoSearchResponse getBankInfo(@RequestPayload BankInfoSearchRequest request) {

        BankInfoSearchResponse response = createDummyResponse(request.getPolicyNumber(),request.getLimit());
        return response;
    }

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "BankVerificationRequest")
    @ResponsePayload
    public BankVerificationResponse verifyBankInformation(@RequestPayload BankVerificationRequest request) {

        return BankVerificationResponse.builder().build();
    }
}
</code>```

Generated WSDL

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://www.testcomp.com/consumer/bankservice/soapservice" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.testcomp.com/consumer/bankservice/soapservice" targetNamespace="http://www.testcomp.com/consumer/bankservice/soapservice">
  <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.testcomp.com/consumer/bankservice/soapservice" version="1.0">

    <xs:element name="BankInfoSearchRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="policyNumber" type="xs:string"/>
                <xs:element name="limit" type="xs:int"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="BankInfoSearchResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="1" name="policyNumber" nillable="false" type="xs:string"/>
                <xs:element name="bankdatas" type="tns:BankDatas"/>
                <xs:element maxOccurs="1" name="error" nillable="true" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="BankDatas">
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="bankinfo" type="tns:BankInfo"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankInfo">
        <xs:sequence>
            <xs:element name="AccountNumber" type="xs:string"/>
            <xs:element name="RoutingNumber" type="xs:string"/>
            <xs:element name="BankName" type="xs:string"/>
            <xs:element name="VerificationDescription" type="xs:string"/>
            <xs:element name="VerificationCode" type="xs:string"/>
            <xs:element name="Verified" type="xs:boolean"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankVerificationRequest">
        <xs:sequence>
            <xs:element maxOccurs="1" name="PolicyOwnerInformation" type="tns:PolicyOwnerInformation"/>
            <xs:element maxOccurs="1" name="BankInfo" type="tns:BankInfo"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="PolicyOwnerInformation">
        <xs:sequence>
            <xs:element name="FirstName" type="xs:string"/>
            <xs:element name="MiddleName" type="xs:string"/>
            <xs:element name="LastName" type="xs:string"/>
            <xs:element name="SSN" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankVerificationResponse">
        <xs:sequence>
            <xs:element maxOccurs="1" name="PolicyOwnerInformation" type="tns:PolicyOwnerInformation"/>
            <xs:element maxOccurs="1" name="Bankinfo" type="tns:BankInfo"/>
            <xs:element name="BankVerificationTransactionId" type="xs:string"/>
            <xs:element name="ItemReferenceId" type="xs:string"/>
            <xs:element name="SubmittedBy" type="xs:string"/>
            <xs:element name="VerificationResponse" type="xs:string"/>
            <xs:element name="VerificationStatus" type="xs:string"/>
            <xs:element name="BankVerificationTransactionType" type="xs:string"/>
            <xs:element name="Created" type="xs:string"/>
            <xs:element name="Success" type="xs:string"/>
            <xs:element name="Error" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>
  </wsdl:types>
  <wsdl:message name="BankInfoSearchResponse">
    <wsdl:part element="tns:BankInfoSearchResponse" name="BankInfoSearchResponse">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="BankInfoSearchRequest">
    <wsdl:part element="tns:BankInfoSearchRequest" name="BankInfoSearchRequest">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="BankAPIPort">
    <wsdl:operation name="BankInfoSearch">
      <wsdl:input message="tns:BankInfoSearchRequest" name="BankInfoSearchRequest">
    </wsdl:input>
      <wsdl:output message="tns:BankInfoSearchResponse" name="BankInfoSearchResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="BankAPIPortSoap11" type="tns:BankAPIPort">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="BankInfoSearch">
      <soap:operation soapAction=""/>
      <wsdl:input name="BankInfoSearchRequest">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="BankInfoSearchResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="BankAPIPortService">
    <wsdl:port binding="tns:BankAPIPortSoap11" name="BankAPIPortSoap11">
      <soap:address location="http://localhost:9080/workflowintg/ws/bankapi"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
</code>```

答: I figured out the issue. There was a problem in the XSD. I declared the root element as xs:complexType instead of xs:element.

Body:
I have a Spring endpoint class with two public methods. But when Spring is auto-generating the wsdl it doesn't include the second public method. Could you pleas let me know what is wrong and what needs to be done. I am using Spring 4.3 and below are the classes.

Configuration class

@EnableWs
@Configuration
public class SoapServiceConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);

        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "policies")
    public DefaultWsdl11Definition policyserviceWsdl11Definition(@Autowired @Qualifier("swissSchema") XsdSchema swissSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("PoliciesPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://www.testcomp.com/iaworkflow/soapservice");
        wsdl11Definition.setSchema(swissSchema);
        return wsdl11Definition;
    }

    @Bean(name = "bankservice")
    public DefaultWsdl11Definition bankServiceWsdlDefinition(@Autowired @Qualifier("bankSchema")XsdSchema bankSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("BankAPIPort");
        wsdl11Definition.setLocationUri("/ws/bankapi");
        wsdl11Definition.setTargetNamespace("http://www.testcomp.com/consumer/bankservice/soapservice");
        wsdl11Definition.setSchema(bankSchema);
        return wsdl11Definition;
    }

    @Bean
    @Qualifier("bankSchema")
    public XsdSchema bankSchema() {
        return new SimpleXsdSchema(new ClassPathResource("bankservice.xsd"));
    }

    @Bean
    @Qualifier("swissSchema")
    public XsdSchema swissSchema() {
        return new SimpleXsdSchema(new ClassPathResource("policylookup.xsd"));
    }
}

Endpoint

@Endpoint
public class BankingServiceEndpoint {
    private static final String NAMESPACE_URI = "http://www.testcomp.com/consumer/bankservice/soapservice";

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "BankInfoSearchRequest")
    @ResponsePayload
    public BankInfoSearchResponse getBankInfo(@RequestPayload BankInfoSearchRequest request) {

        BankInfoSearchResponse response = createDummyResponse(request.getPolicyNumber(),request.getLimit());
        return response;
    }

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "BankVerificationRequest")
    @ResponsePayload
    public BankVerificationResponse verifyBankInformation(@RequestPayload BankVerificationRequest request) {

        return BankVerificationResponse.builder().build();
    }
}

Generated WSDL

<?xml version="1.0" encoding="UTF-8" standalone="no"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://www.testcomp.com/consumer/bankservice/soapservice" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.testcomp.com/consumer/bankservice/soapservice" targetNamespace="http://www.testcomp.com/consumer/bankservice/soapservice">
  <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://www.testcomp.com/consumer/bankservice/soapservice" version="1.0">

    <xs:element name="BankInfoSearchRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="policyNumber" type="xs:string"/>
                <xs:element name="limit" type="xs:int"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="BankInfoSearchResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="1" name="policyNumber" nillable="false" type="xs:string"/>
                <xs:element name="bankdatas" type="tns:BankDatas"/>
                <xs:element maxOccurs="1" name="error" nillable="true" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="BankDatas">
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="bankinfo" type="tns:BankInfo"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankInfo">
        <xs:sequence>
            <xs:element name="AccountNumber" type="xs:string"/>
            <xs:element name="RoutingNumber" type="xs:string"/>
            <xs:element name="BankName" type="xs:string"/>
            <xs:element name="VerificationDescription" type="xs:string"/>
            <xs:element name="VerificationCode" type="xs:string"/>
            <xs:element name="Verified" type="xs:boolean"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankVerificationRequest">
        <xs:sequence>
            <xs:element maxOccurs="1" name="PolicyOwnerInformation" type="tns:PolicyOwnerInformation"/>
            <xs:element maxOccurs="1" name="BankInfo" type="tns:BankInfo"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="PolicyOwnerInformation">
        <xs:sequence>
            <xs:element name="FirstName" type="xs:string"/>
            <xs:element name="MiddleName" type="xs:string"/>
            <xs:element name="LastName" type="xs:string"/>
            <xs:element name="SSN" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BankVerificationResponse">
        <xs:sequence>
            <xs:element maxOccurs="1" name="PolicyOwnerInformation" type="tns:PolicyOwnerInformation"/>
            <xs:element maxOccurs="1" name="Bankinfo" type="tns:BankInfo"/>
            <xs:element name="BankVerificationTransactionId" type="xs:string"/>
            <xs:element name="ItemReferenceId" type="xs:string"/>
            <xs:element name="SubmittedBy" type="xs:string"/>
            <xs:element name="VerificationResponse" type="xs:string"/>
            <xs:element name="VerificationStatus" type="xs:string"/>
            <xs:element name="BankVerificationTransactionType" type="xs:string"/>
            <xs:element name="Created" type="xs:string"/>
            <xs:element name="Success" type="xs:string"/>
            <xs:element name="Error" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>
  </wsdl:types>
  <wsdl:message name="BankInfoSearchResponse">
    <wsdl:part element="tns:BankInfoSearchResponse" name="BankInfoSearchResponse">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="BankInfoSearchRequest">
    <wsdl:part element="tns:BankInfoSearchRequest" name="BankInfoSearchRequest">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="BankAPIPort">
    <wsdl:operation name="BankInfoSearch">
      <wsdl:input message="tns:BankInfoSearchRequest" name="BankInfoSearchRequest">
    </wsdl:input>
      <wsdl:output message="tns:BankInfoSearchResponse" name="BankInfoSearchResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="BankAPIPortSoap11" type="tns:BankAPIPort">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="BankInfoSearch">
      <soap:operation soapAction=""/>
      <wsdl:input name="BankInfoSearchRequest">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="BankInfoSearchResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="BankAPIPortService">
    <wsdl:port binding="tns:BankAPIPortSoap11" name="BankAPIPortSoap11">
      <soap:address location="http://localhost:9080/workflowintg/ws/bankapi"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


问:
Python Pptx - Modify Existing Table
I'm very new to the python-pptx module, so please excuse my ignorance. I'm trying to modify an existing table in a PowerPoint file, but I don't see anywhere in the documentation where I can do this.

I see where you can use the add_table() method to create a new table, but I only need to modify an existing table with data from a Pandas dataframe.

答:
There are multiple ways to select a shape in python-pptx. The best way to go around this is to know the id of the shape, you can get the id either by opening up the xml and finding the shape, or you can loop over all the shapes in the slide and print the id that way. However, you can still select the shape without knowing its id.

If you know the shape id, you can search the slide for that shape's id, something like this will return the shape you want.

```<code>for shape in slide.shapes:
    if shape.shape_id == shape_id:
        return shape
</code>```

If you don't know the shape id, there are a few ways to get the shape, they're all a bit hacky, but they will all work.

If there's only one instance of that shape type in the slide, this is straight forward, just search for a shape with that shape type in the slide.

```<code>for shape in slide.shapes:
    if shape.shape_type == your_shape_type:
        return shape
</code>```

If there's more than one instance of that shape type in the slide (i.e there's more than one table) it gets more complicated, you can set up some identifying feature (put placeholder text). For instance, I set up a chart with a placeholder series name, and this is how I select it in python.

```<code>for shape in slide.shapes:
    if shape.has_chart:
        if str([s.name for s in shape.chart.series][0]) == series_name:
            return shape
</code>```

Title: Python Pptx - Modify Existing Table

Body:
There are multiple ways to select a shape in python-pptx. The best way to go around this is to know the id of the shape, you can get the id either by opening up the xml and finding the shape, or you can loop over all the shapes in the slide and print the id that way. However, you can still select the shape without knowing its id.

If you know the shape id, you can search the slide for that shape's id, something like this will return the shape you want.

for shape in slide.shapes:
    if shape.shape_id == shape_id:
        return shape

If you don't know the shape id, there are a few ways to get the shape, they're all a bit hacky, but they will all work.

If there's only one instance of that shape type in the slide, this is straight forward, just search for a shape with that shape type in the slide.

for shape in slide.shapes:
    if shape.shape_type == your_shape_type:
        return shape

If there's more than one instance of that shape type in the slide (i.e there's more than one table) it gets more complicated, you can set up some identifying feature (put placeholder text). For instance, I set up a chart with a placeholder series name, and this is how I select it in python.

for shape in slide.shapes:
    if shape.has_chart:
        if str([s.name for s in shape.chart.series][0]) == series_name:
            return shape


答:
For Python:

```<code># Create list of lists
lsts = [l1, l2, l3, l4, l5]
s = set()

# Add lists to set
for lst in lsts:
  s.update(lst)

# Sort set
sorted(s)
</code>```

Edit After OP's update:

```<code>def sort_lists(lsts):
  list_of_hashes = []
  for lst in lsts:
    list_of_hashes.append({k: v for v, k in enumerate(lst)})

  result_hash = dict()
  for hash_item in list_of_hashes:
    for key, value in hash_item.items():
      if result_hash.get(key):
        result_hash[key] += value
      else:
        result_hash[key] = value
  print(result_hash)
  sorted_results = sorted(result_hash.items(), key=lambda kv: kv[1])
  print(sorted_results)
  return [tup[0] for tup in sorted_results]
</code>```

```<code># Test Case 1
l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]

print(sort_lists([l1,l2,l3]))
>> ['e', 'd', 'b', 'a']
</code>```

```<code># Test Case 2
s1 = ['Florida', 'Louisiana', 'Nevada', 'California']
s2 = ['Alabama', 'Mississippi', 'Louisiana', 'New Mexico', 'Nevada']
s3 = ['Florida', 'Alabama', 'Texas', 'New Mexico', 'California']
s4 = ['Alabama', 'Mississippi', 'Texas', 'Nevada']
s5 = ['Mississippi', 'Louisiana', 'Nevada']
print(sort_lists([s1,s2,s3,s4,s5]))
>> ['Florida', 'Alabama', 'Mississippi', 'Louisiana', 'Texas', 'New Mexico', 'California', 'Nevada']
</code>```

Title: How do I make a sorted list of items based on multiple list of sorted items?

Body:
For Python:

# Create list of lists
lsts = [l1, l2, l3, l4, l5]
s = set()

# Add lists to set
for lst in lsts:
  s.update(lst)

# Sort set
sorted(s)

Edit After OP's update:

def sort_lists(lsts):
  list_of_hashes = []
  for lst in lsts:
    list_of_hashes.append({k: v for v, k in enumerate(lst)})

  result_hash = dict()
  for hash_item in list_of_hashes:
    for key, value in hash_item.items():
      if result_hash.get(key):
        result_hash[key] += value
      else:
        result_hash[key] = value
  print(result_hash)
  sorted_results = sorted(result_hash.items(), key=lambda kv: kv[1])
  print(sorted_results)
  return [tup[0] for tup in sorted_results]

# Test Case 1
l1=["e","a"]
l2=["e","b","d"]
l3=["b","d","a"]

print(sort_lists([l1,l2,l3]))
>> ['e', 'd', 'b', 'a']

# Test Case 2
s1 = ['Florida', 'Louisiana', 'Nevada', 'California']
s2 = ['Alabama', 'Mississippi', 'Louisiana', 'New Mexico', 'Nevada']
s3 = ['Florida', 'Alabama', 'Texas', 'New Mexico', 'California']
s4 = ['Alabama', 'Mississippi', 'Texas', 'Nevada']
s5 = ['Mississippi', 'Louisiana', 'Nevada']
print(sort_lists([s1,s2,s3,s4,s5]))
>> ['Florida', 'Alabama', 'Mississippi', 'Louisiana', 'Texas', 'New Mexico', 'California', 'Nevada']


问:
Multiplication of several columns
I want to multiply some counts in specific locations (0-100, 0-12 etc.., individual variable columns) by the number of days a count is present (days)

Here is an example of my data:

```<code>df <- structure(list(month = c("Apr", "Apr", "Aug", "Aug", "Aug", "Sep"
), Year = c(2018, 2018, 2018, 2018, 2018, 2018), First =
 structure(c(17995,
 17998, 17750, 17758, 17770, 17778), class = "Date"), Last =
 structure(c(17999,
 17998, 17750, 17761, 17771, 17778), class = "Date"), days = c(5,
 1, 1, 4, 2, 1), `0-100` = c(1, 0, 1, 1, 1, 1), `0-12` = c(0,
 0, 1, 1, 1, 1), `0-25` = c(1, 1, 1, 1, 1, 1), `0-50` = c(1, 0,
1, 1, 1, 1)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
 "data.frame"))
</code>```

So i was thinking something along the lines of:

```<code>df2 <- df %>%
  mutate("0-100b" = days * "0-100", "0-12b" = days * "0-12", "0-25b" = days * "0-25", "0-50b" = days * "0-25")
</code>```

Which one doesn't seem to work, but two there must be a more concise way than writing out each multiplication too ... if i had many more columns this seems a little tedious.

ok edit for col names:

```<code>colnames(df) <- c("month", "Year", "First", "Last" , "days", "V", "I",
"II", "III")

df2 <- df %>%
mutate(Vb = days * V, Ib = days * I, IIb = days *
       II, IIIb = days * III)
</code>```

答:
Like I said above, you can select improperly named columns by wrapping them in backticks. One of the places that naming rules are laid out is in the docs of the base function make.names.

The easiest solution to having improper names is to just create data with valid names to begin with...but in practice, that isn't always possible. There are several ways to change the names into valid ones. The aforementioned make.names does this from a character vector.

If you're working in a larger piped workflow, you can use rename_all with a few string manipulation functions to 1) convert to lowercase, 2) replace - with _, and 3) prepend an x before any leading digits. You can also use janitor::clean_names, which cleans all the names in a data frame.

library(dplyr)

df %>%
  rename_all(~tolower(.) %>%
               stringr::str_replace_all(., "\\-", "_") %>%
               stringr::str_replace("^\\b(?=\\d)", "x"))
# omitted: same names as below
```

<p>With clean names, you can use <code>mutate_at</code>, select the columns, and pass it a function to multiply by <code>days</code>. If you use a named list, the name is appended to create new columns, instead of replacing them.</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  janitor::clean_names() %>%
  mutate_at(vars(x0_100:x0_50), list(b = ~. * days))
#> # A tibble: 6 x 13
#>   month  year first      last        days x0_100 x0_12 x0_25 x0_50 x0_100_b
#>   <chr> <dbl> <date>     <date>     <dbl>  <dbl> <dbl> <dbl> <dbl>    <dbl>
#> 1 Apr    2018 2019-04-09 2019-04-13     5      1     0     1     1        5
#> 2 Apr    2018 2019-04-12 2019-04-12     1      0     0     1     0        0
#> 3 Aug    2018 2018-08-07 2018-08-07     1      1     1     1     1        1
#> 4 Aug    2018 2018-08-15 2018-08-18     4      1     1     1     1        4
#> 5 Aug    2018 2018-08-27 2018-08-28     2      1     1     1     1        2
#> 6 Sep    2018 2018-09-04 2018-09-04     1      1     1     1     1        1
#> # … with 3 more variables: x0_12_b <dbl>, x0_25_b <dbl>, x0_50_b <dbl>
</code>```

In this case, it might also make sense to select columns by regex:

df %>%
  janitor::clean_names() %>%
  mutate_at(vars(matches("^x\\d")), list(b = ~. * days))
# same output as above
```

Title: Multiplication of several columns

Body:
I want to multiply some counts in specific locations (0-100, 0-12 etc.., individual variable columns) by the number of days a count is present (days)

Here is an example of my data:

df <- structure(list(month = c("Apr", "Apr", "Aug", "Aug", "Aug", "Sep"
), Year = c(2018, 2018, 2018, 2018, 2018, 2018), First =
 structure(c(17995,
 17998, 17750, 17758, 17770, 17778), class = "Date"), Last =
 structure(c(17999,
 17998, 17750, 17761, 17771, 17778), class = "Date"), days = c(5,
 1, 1, 4, 2, 1), `0-100` = c(1, 0, 1, 1, 1, 1), `0-12` = c(0,
 0, 1, 1, 1, 1), `0-25` = c(1, 1, 1, 1, 1, 1), `0-50` = c(1, 0,
1, 1, 1, 1)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
 "data.frame"))

So i was thinking something along the lines of:

df2 <- df %>%
  mutate("0-100b" = days * "0-100", "0-12b" = days * "0-12", "0-25b" = days * "0-25", "0-50b" = days * "0-25")

Which one doesn't seem to work, but two there must be a more concise way than writing out each multiplication too ... if i had many more columns this seems a little tedious.

ok edit for col names:

colnames(df) <- c("month", "Year", "First", "Last" , "days", "V", "I",
"II", "III")

df2 <- df %>%
mutate(Vb = days * V, Ib = days * I, IIb = days *
       II, IIIb = days * III)

Body:
Like I said above, you can select improperly named columns by wrapping them in backticks. One of the places that naming rules are laid out is in the docs of the base function make.names.

The easiest solution to having improper names is to just create data with valid names to begin with...but in practice, that isn't always possible. There are several ways to change the names into valid ones. The aforementioned make.names does this from a character vector.

If you're working in a larger piped workflow, you can use rename_all with a few string manipulation functions to 1) convert to lowercase, 2) replace - with _, and 3) prepend an x before any leading digits. You can also use janitor::clean_names, which cleans all the names in a data frame.

library(dplyr)

df %>%
  rename_all(~tolower(.) %>%
               stringr::str_replace_all(., "\\-", "_") %>%
               stringr::str_replace("^\\b(?=\\d)", "x"))
# omitted: same names as below

With clean names, you can use mutate_at, select the columns, and pass it a function to multiply by days. If you use a named list, the name is appended to create new columns, instead of replacing them.

df %>%
  janitor::clean_names() %>%
  mutate_at(vars(x0_100:x0_50), list(b = ~. * days))
#> # A tibble: 6 x 13
#>   month  year first      last        days x0_100 x0_12 x0_25 x0_50 x0_100_b
#>   <chr> <dbl> <date>     <date>     <dbl>  <dbl> <dbl> <dbl> <dbl>    <dbl>
#> 1 Apr    2018 2019-04-09 2019-04-13     5      1     0     1     1        5
#> 2 Apr    2018 2019-04-12 2019-04-12     1      0     0     1     0        0
#> 3 Aug    2018 2018-08-07 2018-08-07     1      1     1     1     1        1
#> 4 Aug    2018 2018-08-15 2018-08-18     4      1     1     1     1        4
#> 5 Aug    2018 2018-08-27 2018-08-28     2      1     1     1     1        2
#> 6 Sep    2018 2018-09-04 2018-09-04     1      1     1     1     1        1
#> # … with 3 more variables: x0_12_b <dbl>, x0_25_b <dbl>, x0_50_b <dbl>

In this case, it might also make sense to select columns by regex:

df %>%
  janitor::clean_names() %>%
  mutate_at(vars(matches("^x\\d")), list(b = ~. * days))
# same output as above


问:
Testing Generic Angular Components (not Generic Class)
Is it possible to test an Angular Generic Component?

As an example, if I have

```<code>@Component({
    ...
})
export class MyComponent<T> implements OnInit {
   public constructor(
      private context: T
   );
}
</code>```

Where T can be any number of classes.

Then eventually I want to write a Jasmine test, but I am not able to determine the proper syntax for when creating the test fixture:

```<code>fixture = TestBed.createComponent(MyComponent<MyTestObject>);
</code>```

It is here that TSLint complains:

```<code>Value of type 'typeof MyComponent' is not callable. Did you mean to include new?
</code>```

It clearly thinks that I need a constructor (?), but is unclear how or where to implement that.

Is what I am attempting even possible?  I can find examples of generic components.  I can't find examples on setting up a test fixture / component

答:
I imagine that TestBed.createComponent() expects a javascript class as an argument. MyComponent<MyTestObject> is not valid javascript.

Perhaps you intended to put TestBed.createComponent(MyComponent as typeof MyComponent<MyTestObject>) (or maybe the proper syntax is MyComponent as (typeof MyComponent)<MyTestObject> -- I'm not sure).

Alternatively, if TestBed#createComponent() is generic, you'd probably want to do TestBed.createComponent<MyComponent<MyTestObject>>(MyComponent).

Body:
Is it possible to test an Angular Generic Component?

As an example, if I have

@Component({
    ...
})
export class MyComponent<T> implements OnInit {
   public constructor(
      private context: T
   );
}

Where T can be any number of classes.

Then eventually I want to write a Jasmine test, but I am not able to determine the proper syntax for when creating the test fixture:

fixture = TestBed.createComponent(MyComponent<MyTestObject>);

It is here that TSLint complains:

Value of type 'typeof MyComponent' is not callable. Did you mean to include new?

It clearly thinks that I need a constructor (?), but is unclear how or where to implement that.

Is what I am attempting even possible?  I can find examples of generic components.  I can't find examples on setting up a test fixture / component


问:
Vue is not updating select in DOM after created method
I have this roles array, in created method I made a call to dispatch and get roles from api call, so I suppose it should load with created function.

Now I use console.log to print roles after dispatching getRoles adn it prints already but it doesn't update in the DOM.

If you notice this part where I just show {{roles}} inside the component after form and dropdown, this part and select updates after I make small change in the component and save, after hot reload it shows the data but not with first time with created

The problem is that, data gets fetched and printed in first load but the roles array doesn't get updated in the DOM.

```<code><template>
  <div class="container">
    <form class="card offset-3 col-6 text-center border border-light p-5">
      <div class="form-group">
        <label for="formGroupExampleInput">Roles</label>
      </div>

      <select class="browser-default custom-select">
        <option selected>Choose a role to assign permissions</option>
        <option v-for="role in roles" key="role.display_name" value="1"> {{role.name}} </option>
      </select>

    </form>
    roles :{{ roles }}
  </div>
</template>

<script>
export default {
  data: {
    return: {
      roles: []
    }
  },
  created() {
      this.$store
        .dispatch('getRoles')
        .then(() => {
          this.roles = this.$store.getters.getRoles
          console.log('roles', this.roles)
        })
        .catch(() =>  {
          console.log('roles request failed')
        })
  }
}
</script>

</code>```

答:
The problem was in returning data so I replaced it with

```<code>data: () => ({
      roleName: '',
      roles: []
    })
</code>```

and it is working fine now

Body:
I have this roles array, in created method I made a call to dispatch and get roles from api call, so I suppose it should load with created function.

Now I use console.log to print roles after dispatching getRoles adn it prints already but it doesn't update in the DOM.

If you notice this part where I just show {{roles}} inside the component after form and dropdown, this part and select updates after I make small change in the component and save, after hot reload it shows the data but not with first time with created

The problem is that, data gets fetched and printed in first load but the roles array doesn't get updated in the DOM.

<template>

    <form class="card offset-3 col-6 text-center border border-light p-5">

        Roles

      <select class="browser-default custom-select">
        <option selected>Choose a role to assign permissions</option>
        <option v-for="role in roles" key="role.display_name" value="1"> {{role.name}} </option>
      </select>

    </form>
    roles :{{ roles }}

</template>

Body:
The problem was in returning data so I replaced it with

data: () => ({
      roleName: '',
      roles: []
    })

and it is working fine now


答:
If you want it in order you better sort it. using .OrderBy extension method. </p>

```<code>string folder = @"C:\Testing\";
var txtFiles = Directory.GetFiles(folder, "*.txt")
               .Select(Path.GetFileName)
               .OrderBy(x => x)
               .ToList();
foreach (var f in txtFiles)
{
 Console.WriteLine(f);
}
Console.ReadKey();
</code>```

Title: Order files numerically in specific folder

Body:
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();

Windows Explore

Console Output

Body:
If you want it in order you better sort it. using .OrderBy extension method.

string folder = @"C:\Testing\";
var txtFiles = Directory.GetFiles(folder, "*.txt")
               .Select(Path.GetFileName)
               .OrderBy(x => x)
               .ToList();
foreach (var f in txtFiles)
{
 Console.WriteLine(f);
}
Console.ReadKey();


问:
How can I accept Lower , upper and mixed case query strings
What is the best way to deal with case options for the following scenario

i want to be able to check if the req.query String
rowCount, rowcount or ROWCOUNT exists and then get the value of it.
hope there is a simple way to check if the querystring in any type of case exists.

if i use

```<code>if (!req.query.rowcount) {var t_rowcount = parseInt(25)}
</code>```

it will not match if the querystring is rowCount

fyi i am running NodeJs on a windows 2016 server

答:
With some help of rakesh answer i was able to come up with a solution which does what i need.

```<code>app.use(function(req, res, next) {
  for (const key in req.query) {

    if( (key.toLowerCase() === key ) == false){
    req.query[key.toLowerCase()] = req.query[key]
    delete req.query[key]
    }
  }
</code>```

this middleware actually gets all keys in the req.query object, checks if the key is all lowercase, if it is we don't touch it. If not we create new key with the lowercase key and afterwards delete the original non lowercase key so the object size stays same.

Also if someone need this in upper or camel case this can be done by simply changing tolowerCase out

Body:
What is the best way to deal with case options for the following scenario

i want to be able to check if the req.query String
rowCount, rowcount or ROWCOUNT exists and then get the value of it.
hope there is a simple way to check if the querystring in any type of case exists.

if i use

if (!req.query.rowcount) {var t_rowcount = parseInt(25)}

it will not match if the querystring is rowCount

fyi i am running NodeJs on a windows 2016 server

Body:
With some help of rakesh answer i was able to come up with a solution which does what i need.

app.use(function(req, res, next) {
  for (const key in req.query) {

    if( (key.toLowerCase() === key ) == false){
    req.query[key.toLowerCase()] = req.query[key]
    delete req.query[key]
    }
  }

this middleware actually gets all keys in the req.query object, checks if the key is all lowercase, if it is we don't touch it. If not we create new key with the lowercase key and afterwards delete the original non lowercase key so the object size stays same.

Also if someone need this in upper or camel case this can be done by simply changing tolowerCase out


问:
How can I add another variable in my entity?
I am really new to hibernate/spring data and I had my entity set up just fine, but now I tried to add another variable (orchestra) to my entity, but I always get the following error:  Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: backend.entity.Orchestra, at table: group_table, for columns: [org.hibernate.mapping.Column(orchestra)]

What do i have to do to update my Entity?

```<code>@Entity
@Table(name = "group_table")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @Column
    @NotNull
    private String name;

    @Column
    private Orchestra orchestra; //<- trying to add
</code>```

答:
Your mapping is not correct. Packaging for backend.entity.Orchestra suggests it is an @Entity, therefore you need to:

remove the @Column annotation

mark your relation as either @OneToOne or @ManyToOne.

possibly specify join columns, depending on your db structure.

Body:
I am really new to hibernate/spring data and I had my entity set up just fine, but now I tried to add another variable (orchestra) to my entity, but I always get the following error:  Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: backend.entity.Orchestra, at table: group_table, for columns: [org.hibernate.mapping.Column(orchestra)]

What do i have to do to update my Entity?

@Entity
@Table(name = "group_table")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @Column
    @NotNull
    private String name;

    @Column
    private Orchestra orchestra; //<- trying to add


问:
How can I access JavaScript object in array?
My question is how can I Access the object in the array. As an example how can I access the property country?

```<code>var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]
</code>```

答:
If you know the index you just use the index

```<code>arr1[1].country;
</code>```

If you want to look it up by country code you can find it

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}];

const getCountry = (array, code) => array.find(country => country.code === code);

console.log(getCountry(arr1, 'de'));```

Body:
My question is how can I Access the object in the array. As an example how can I access the property country?

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]

Body:
If you know the index you just use the index

arr1[1].country;

If you want to look it up by country code you can find it

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}];

const getCountry = (array, code) => array.find(country => country.code === code);

console.log(getCountry(arr1, 'de'));


问:
Evaluate constraint expression as boolean
I want to evaluate if a constraint is respected or not in Pyomo when the values of the variables contained in constraint expression are known.

Use case: We know that one particular constraint sometimes makes the problem infeasible, depending on the value of the variable. Instead of sending the problem to the solver to test if the problem is feasible, converting the constraint expression to a boolean type would be enough to determine if the constraint is the culprit.

For the sake of providing a feasible example, here would be the code:

```<code>from pyomo.environ import ConcreteModel, Var, Constraint
model = ConcreteModel()
model.X = Var()

def constraint_rule(model):
    return model.X <= 1
model.a_constraint = Constraint(rule=constraint_rule)
</code>```

Now, let's try to work with the expression to evaluate:

```<code># Let's define the expression in this way:
expression = constraint_rule(model)

# Let's show that the expression is what we expected:
print(str(expression))
</code>```

The previous statement should print X <= 1.0.

Now, the tricky part is how to evaluate the expression.

```<code>if expression == True:
    print("feasible")
else:
    print("infeasible")
</code>```

creates an TypeError Exception (TypeError: Cannot create an EqualityExpression where one of the sub-expressions is a relational expression: X <= 1.0).

The last example doesn't work because constraint_rule doesn't return a boolean but a Pyomo expression.

Finally, I know that something like

```<code>def evaluate_constraint_a_expression(model):
    return value(model.X) <= 1
</code>```

would work, but I can't assume that I will always know the content of my constraint expression, so I need a robust way of evaluating it.

Is there a clever way of achieving this? Like, evaluating the expression as a boolean and evaluating the left hand side and right hand side of the expression at the same time?

答:
The solution is to use value function. Even if it says that it evaluates an expression to a numeric value, it also converts the expression to a boolean value if it is an equality/inequality expression, like the rule of a constraint.

Let's suppose that the model is defined the way it is in the question, then the rest of the code should be:

```<code>from pyomo.environ import value
if value(expression) == True:
    print("feasible")
else:
    print("infeasible")
</code>```

where expression is defined as written in the question.

However, be advised that numeric precision in Python using this method can be different than the one provided by the solver. Therefore, it is possible that this method will show that a constraint is infeasible while it is just a matter of numeric imprecision of under 1e-10. So, while it is useful in finding if most constraints are feasible, it also generates some false positives.

Body:
I want to evaluate if a constraint is respected or not in Pyomo when the values of the variables contained in constraint expression are known.

Use case: We know that one particular constraint sometimes makes the problem infeasible, depending on the value of the variable. Instead of sending the problem to the solver to test if the problem is feasible, converting the constraint expression to a boolean type would be enough to determine if the constraint is the culprit.

For the sake of providing a feasible example, here would be the code:

from pyomo.environ import ConcreteModel, Var, Constraint
model = ConcreteModel()
model.X = Var()

def constraint_rule(model):
    return model.X <= 1
model.a_constraint = Constraint(rule=constraint_rule)

Now, let's try to work with the expression to evaluate:

# Let's define the expression in this way:
expression = constraint_rule(model)

# Let's show that the expression is what we expected:
print(str(expression))

The previous statement should print X <= 1.0.

Now, the tricky part is how to evaluate the expression.

if expression == True:
    print("feasible")
else:
    print("infeasible")

creates an TypeError Exception (TypeError: Cannot create an EqualityExpression where one of the sub-expressions is a relational expression: X <= 1.0).

The last example doesn't work because constraint_rule doesn't return a boolean but a Pyomo expression.

Finally, I know that something like

def evaluate_constraint_a_expression(model):
    return value(model.X) <= 1

would work, but I can't assume that I will always know the content of my constraint expression, so I need a robust way of evaluating it.

Is there a clever way of achieving this? Like, evaluating the expression as a boolean and evaluating the left hand side and right hand side of the expression at the same time?

Body:
The solution is to use value function. Even if it says that it evaluates an expression to a numeric value, it also converts the expression to a boolean value if it is an equality/inequality expression, like the rule of a constraint.

Let's suppose that the model is defined the way it is in the question, then the rest of the code should be:

from pyomo.environ import value
if value(expression) == True:
    print("feasible")
else:
    print("infeasible")

where expression is defined as written in the question.

However, be advised that numeric precision in Python using this method can be different than the one provided by the solver. Therefore, it is possible that this method will show that a constraint is infeasible while it is just a matter of numeric imprecision of under 1e-10. So, while it is useful in finding if most constraints are feasible, it also generates some false positives.