问:
Selected row not highlighted in jqgrid
I have written the function for row selection.It is not highlighting the selected row(sometimes highlighting sometimes other row highlighted) and not displaying the icons the way I have written it. following is the code
                    multiselect : true,
                   iconSet: "fontAwesome",
                    datatype : "json",
                    loadonce : true,
                    rowNum : 10,
                    rowList : [ 10, 20, 30 ],
                    toppager:true,
                    pager : '#prowed1',
                    sortname : 'id',
                    viewrecords : true,
                    sortorder : "asc",
                    editurl : "editGrid.html",
                    onSelectRow : function(rowId) {
                        var rowId = jQuery("#list1").jqGrid('getGridParam',
                                'selarrrow');
                        if (rowId.length > 1) {
                            $("#list1_iledit").addClass('ui-state-disabled');
                        }
                    },

```<code>$("#list1").jqGrid(
            "navGrid",
            "#prowed1",
            {
                cloneToTop:true,
                formatter : "checkboxFontAwesome4",
                 addicon:"fa fa-plus ",
                add : true,
                delicon:"fa fa-trash",
                del : true,
                searchicon:"fa fa-search",
                search : true,
                refreshicon:"fa fa-refresh",
                refresh : true,
                editicon:"fa fa-edit ",
                edit : true,
                saveicon : 'fa fa-floppy-o',
                save : true,

            },`{ // edit options
                afterSubmit : function() {
                    location.reload(true);
                },
                beforeShowForm : function(form) {
                    $("td .navButton navButton-ltr").hide();
                },
                closeAfterEdit : true
            },
            { // add options
                beforeShowForm : function(form) {
                    $("#buName").removeAttr("readonly");
                },
                closeAfterAdd : true,
                clearAfterAdd : true
            },
            { // del options
                serializeDelData : function(postdata) {
                    return {
                        'buName' : $('#list1').jqGrid('getCell',
                                postdata.id, 'buName'),
                        'oper' : 'del'
                    }
                }
            }

    );` $("#list1").jqGrid('inlineNav', "#prowed1", {
        //cloneToTop:true,
        //iconSet: "fontAwesome",
        add : false,
        edit : true,
        editicon : 'fa fa-pencil-square-o',
        save : true,
        saveicon : 'fa fa-floppy-o',
        editParams : {
            aftersavefunc : function(id) {
                jQuery('#list1').jqGrid('setSelection', id, false);
            },
        },
    });`
</code>```

答:
Dumb on my part, but I had the property beforeSelectRow set in the grid code that I had copied from another project. This of course was blocking any selection of a grid row.</p>
```<code>    beforeSelectRow: function (rowid, e) {
        return false;
    },
</code>```

Title: Selected row not highlighted in jqgrid

Body:
I have written the function for row selection.It is not highlighting the selected row(sometimes highlighting sometimes other row highlighted) and not displaying the icons the way I have written it. following is the code
                    multiselect : true,
                   iconSet: "fontAwesome",
                    datatype : "json",
                    loadonce : true,
                    rowNum : 10,
                    rowList : [ 10, 20, 30 ],
                    toppager:true,
                    pager : '#prowed1',
                    sortname : 'id',
                    viewrecords : true,
                    sortorder : "asc",
                    editurl : "editGrid.html",
                    onSelectRow : function(rowId) {
                        var rowId = jQuery("#list1").jqGrid('getGridParam',
                                'selarrrow');
                        if (rowId.length > 1) {
                            $("#list1_iledit").addClass('ui-state-disabled');
                        }
                    },

$("#list1").jqGrid(
            "navGrid",
            "#prowed1",
            {
                cloneToTop:true,
                formatter : "checkboxFontAwesome4",
                 addicon:"fa fa-plus ",
                add : true,
                delicon:"fa fa-trash",
                del : true,
                searchicon:"fa fa-search",
                search : true,
                refreshicon:"fa fa-refresh",
                refresh : true,
                editicon:"fa fa-edit ",
                edit : true,
                saveicon : 'fa fa-floppy-o',
                save : true,

            },`{ // edit options
                afterSubmit : function() {
                    location.reload(true);
                },
                beforeShowForm : function(form) {
                    $("td .navButton navButton-ltr").hide();
                },
                closeAfterEdit : true
            },
            { // add options
                beforeShowForm : function(form) {
                    $("#buName").removeAttr("readonly");
                },
                closeAfterAdd : true,
                clearAfterAdd : true
            },
            { // del options
                serializeDelData : function(postdata) {
                    return {
                        'buName' : $('#list1').jqGrid('getCell',
                                postdata.id, 'buName'),
                        'oper' : 'del'
                    }
                }
            }

    );` $("#list1").jqGrid('inlineNav', "#prowed1", {
        //cloneToTop:true,
        //iconSet: "fontAwesome",
        add : false,
        edit : true,
        editicon : 'fa fa-pencil-square-o',
        save : true,
        saveicon : 'fa fa-floppy-o',
        editParams : {
            aftersavefunc : function(id) {
                jQuery('#list1').jqGrid('setSelection', id, false);
            },
        },
    });`

Body:
Dumb on my part, but I had the property beforeSelectRow set in the grid code that I had copied from another project. This of course was blocking any selection of a grid row.

    beforeSelectRow: function (rowid, e) {
        return false;
    },


来源: stackexchange

问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
If you use SQL Server, there's a feature that allows you to generate a script to create the entire database. Executing the script once a valid connection string is given is rather easy to do through the usual .NET Sql classes (SqlConnection etc).

However, for such a simple data model, SQL Server might be overkill. You should investigate other smaller DB's like SQLite.

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: SirDemon


问:
How to handle a price change in DB just when a customer is placing an order online?
I have a Product database table with columns such as product_id, price, and inventory_count.

A user clicks to buy a certain product at a certain price. My program generates a confirmation page listing the product and the price. Everything is fine and the user clicks "Confirm". My program updates the inventory_count of that product and charges the user's credit card the amount listed in the product's price.

But during the time after the confirmation page is generated but before the user clicks "Confirm", the price of that product has been changed. So the user might have seen a price of $10 in the confirmation page but after he clicks "Confirm" the price in the Product table has already been changed to $11 and that's what he will be charged.

What's the best way to handle a situation like this? I'm using  MySQL and Python if that's relevant.

答:
I my opinion you should avoid situations like this (if I were your customer I would be disappointed).
But if you can't, when customer press confirm, do the last check of price and show message to user if it changed.</p>

ContentLicense: CC BY-SA 3.0


问:
Rearanging data file in AWK providing subtotals and totals
I have the following data:

```<code>cat st_in.txt
2015-01-01  2   A   FI
2015-02-03  4   B   VI
2015-03-01  6   A   FI
2015-01-08  -4  C   VE
2016-01-05  -3  B   VE
2016-02-03  -1  D   FE
2016-04-01  -2  B   FE
2016-06-13  -5  D   VE
2017-01-01  2   A   VI
2017-02-03  3   A   VI
2017-02-04  8   C   FI
2017-01-05  -1  B   FE
</code>```

I want to output the data in this way (without comments of course):

```<code>        2015    2016    2017    # ...

A       0       0       5       # $2>0 && $4~/VI/       Ordered alphabetically asc
B       4       0       0       #       .                       .
sumVI   4       0       5

A       8       0       0       # $2>0 && $4~/FI/               .
C       0       0       8       #       .                       .
sumFI   8       0       8

sumI    12      0       13      # sumI=sumFI+sumVI

B       0       -3      0       # $2<0 && $4~/VE/               .
C       -4      0       0       #       .                       .
D       0       -5      0       #       .                       .
sumVE   -4      -8      0

B       0       -2      -1      # $2<0 && $4~/FE/               .
sumFE   0       -2      -1      #       .

sumE    -4      -10     -1      # sumE=sumFE+sumVE

NET     8       -10     12      # NET=sumI+sumE
</code>```

I am new to awk and not sure how to approach this. I have read on gnu.org awk manual about multi-dimensional arrays and arrays of arrays, which I assume I will be needing here but don't fully understand how they work. I am able to do this for one year but not multiple years. Please note that st_in.txt is very large and spans more years than in this sample. Also is there a good resource that you can recommend to learn how to pivot data tables in awk.

This is what I have attempted so far. This however does not work:

```<code>cat trans1
#!/usr/bin/env bash

awk '
    BEGIN{OFS="\t"
    cat[$3]
    height[$4][$3] +=$2
    width[substr($1,1,4)][$4][$3] +=$2
    }

    END{
    PROCINFO["sorted_in"]="@ind_str_asc";
    for (width in height){
        for (cat in height[width]){
            if($2>0 && $4~/VI/)
                {print cat, height[width]}
            else if($2>0 && $4~/FI/)
                {print cat, height[width]}
            else if($2<0 && $4~/VE/)
                {print cat, height[width]}
            else {print cat, height[width]}}}

    }
' "${@:--}"
</code>```

I get the following error:

```<code>awk: cmd. line:11: (FILENAME=st_in.txt FNR=12) fatal: attempt to use array `width' in a scalar context
</code>```

答:
Not the complete solution but a more structured approach which requires the final formatting...

```<code>$ awk 'BEGIN {SUBSEP=FS}
             {split($1,f1,"-");
              s=substr($4,2); y=f1[1];
              a[s,$4,y,$3]=+$2;
              a[s,$4,y,"sum"$4]+=$2;
              a[s,"+",y,"sum"s]+=$2;
              a["+","+",y,"NET"]+=$2}
       END   {for(k in a) print k,a[k]}' file |
 sort -k1,2r -k4,4 -k3,3

I VI 2017 A 3
I VI 2015 B 4
I VI 2015 sumVI 4
I VI 2017 sumVI 5
I FI 2015 A 6
I FI 2017 C 8
I FI 2015 sumFI 8
I FI 2017 sumFI 8
I + 2015 sumI 12
I + 2017 sumI 13
E VE 2016 B -3
E VE 2015 C -4
E VE 2016 D -5
E VE 2015 sumVE -4
E VE 2016 sumVE -8
E FE 2016 B -2
E FE 2017 B -1
E FE 2016 D -1
E FE 2016 sumFE -3
E FE 2017 sumFE -1
E + 2015 sumE -4
E + 2016 sumE -11
E + 2017 sumE -1
+ + 2015 NET 8
+ + 2016 NET -11
+ + 2017 NET 12
</code>```

this creates various subtotals based on the keys of the array, at the end it prints the whole array (and subtotals). By carefully choosing the key you can calculate what you need.

s is the top level category, y is the year.

```<code>              a[s,$4,y,$3]=+$2;
</code>```

sums up all repeated entries since uses all the fields

```<code>              a[s,$4,y,"sum"$4]+=$2;
</code>```

groups based on field 4 values (VI,FI, etc.)

```<code>              a[s,"+",y,"sum"s]+=$2;
</code>```

group based on top level category (I,E)

```<code>              a["+","+",y,"NET"]+=$2}
</code>```

this sums up everything based on the year. Finally

```<code>  END   {for(k in a) print k,a[k]}
</code>```

at the end of the file, extract all the entries from the array and print.

```<code>  sort -k1,2r -k4,4 -k3,3
</code>```

does the sorting based on I/E VI,FI A/B/.. and year.

For example, as an exercise you can add the overall sum easily by dropping or replacing y with a constant (I used +).

ContentLicense: CC BY-SA 4.0

Body:
I have the following data:

cat st_in.txt
2015-01-01  2   A   FI
2015-02-03  4   B   VI
2015-03-01  6   A   FI
2015-01-08  -4  C   VE
2016-01-05  -3  B   VE
2016-02-03  -1  D   FE
2016-04-01  -2  B   FE
2016-06-13  -5  D   VE
2017-01-01  2   A   VI
2017-02-03  3   A   VI
2017-02-04  8   C   FI
2017-01-05  -1  B   FE

I want to output the data in this way (without comments of course):

        2015    2016    2017    # ...

A       0       0       5       # $2>0 && $4~/VI/       Ordered alphabetically asc
B       4       0       0       #       .                       .
sumVI   4       0       5

A       8       0       0       # $2>0 && $4~/FI/               .
C       0       0       8       #       .                       .
sumFI   8       0       8

sumI    12      0       13      # sumI=sumFI+sumVI

B       0       -3      0       # $2<0 && $4~/VE/               .
C       -4      0       0       #       .                       .
D       0       -5      0       #       .                       .
sumVE   -4      -8      0

B       0       -2      -1      # $2<0 && $4~/FE/               .
sumFE   0       -2      -1      #       .

sumE    -4      -10     -1      # sumE=sumFE+sumVE

NET     8       -10     12      # NET=sumI+sumE

I am new to awk and not sure how to approach this. I have read on gnu.org awk manual about multi-dimensional arrays and arrays of arrays, which I assume I will be needing here but don't fully understand how they work. I am able to do this for one year but not multiple years. Please note that st_in.txt is very large and spans more years than in this sample. Also is there a good resource that you can recommend to learn how to pivot data tables in awk.

This is what I have attempted so far. This however does not work:

cat trans1
#!/usr/bin/env bash

awk '
    BEGIN{OFS="\t"
    cat[$3]
    height[$4][$3] +=$2
    width[substr($1,1,4)][$4][$3] +=$2
    }

    END{
    PROCINFO["sorted_in"]="@ind_str_asc";
    for (width in height){
        for (cat in height[width]){
            if($2>0 && $4~/VI/)
                {print cat, height[width]}
            else if($2>0 && $4~/FI/)
                {print cat, height[width]}
            else if($2<0 && $4~/VE/)
                {print cat, height[width]}
            else {print cat, height[width]}}}

    }
' "${@:--}"

I get the following error:

awk: cmd. line:11: (FILENAME=st_in.txt FNR=12) fatal: attempt to use array `width' in a scalar context

Body:
Not the complete solution but a more structured approach which requires the final formatting...

$ awk 'BEGIN {SUBSEP=FS}
             {split($1,f1,"-");
              s=substr($4,2); y=f1[1];
              a[s,$4,y,$3]=+$2;
              a[s,$4,y,"sum"$4]+=$2;
              a[s,"+",y,"sum"s]+=$2;
              a["+","+",y,"NET"]+=$2}
       END   {for(k in a) print k,a[k]}' file |
 sort -k1,2r -k4,4 -k3,3

I VI 2017 A 3
I VI 2015 B 4
I VI 2015 sumVI 4
I VI 2017 sumVI 5
I FI 2015 A 6
I FI 2017 C 8
I FI 2015 sumFI 8
I FI 2017 sumFI 8
I + 2015 sumI 12
I + 2017 sumI 13
E VE 2016 B -3
E VE 2015 C -4
E VE 2016 D -5
E VE 2015 sumVE -4
E VE 2016 sumVE -8
E FE 2016 B -2
E FE 2017 B -1
E FE 2016 D -1
E FE 2016 sumFE -3
E FE 2017 sumFE -1
E + 2015 sumE -4
E + 2016 sumE -11
E + 2017 sumE -1
+ + 2015 NET 8
+ + 2016 NET -11
+ + 2017 NET 12

this creates various subtotals based on the keys of the array, at the end it prints the whole array (and subtotals). By carefully choosing the key you can calculate what you need.

s is the top level category, y is the year.

              a[s,$4,y,$3]=+$2;

sums up all repeated entries since uses all the fields

              a[s,$4,y,"sum"$4]+=$2;

groups based on field 4 values (VI,FI, etc.)

              a[s,"+",y,"sum"s]+=$2;

group based on top level category (I,E)

              a["+","+",y,"NET"]+=$2}

this sums up everything based on the year. Finally

  END   {for(k in a) print k,a[k]}

at the end of the file, extract all the entries from the array and print.

  sort -k1,2r -k4,4 -k3,3

does the sorting based on I/E VI,FI A/B/.. and year.

For example, as an exercise you can add the overall sum easily by dropping or replacing y with a constant (I used +).


问:
how to show a new window on the second or third monitor of uwp win 10
I want my program to be able to select the monitor on which a new window will be opened

now my code looks like this:

```<code>AppWindow appWindow = await AppWindow.TryCreateAsync();
Frame OpenPage1 = new Frame();
OpenPage1.Navigate(typeof(Projector));
ElementCompositionPreview.SetAppWindowContent(appWindow, OpenPage1);
appWindow.Presenter.RequestPresentation(AppWindowPresentationKind.FullScreen);

await appWindow.TryShowAsync();
</code>```

It opens a window on the current monitor. I want the window to open on the selected monitor

Additional question: How can I prevent this window from collapsing?

答:
how to show a new window on the second or third monitor of uwp win 10

As Raymond Chen said you could use RequestMoveToDisplayRegion method to display AppWindow in secondary DisplayRegion.

For code sample you could refer to AppWindow  official code sample Scenario2_DisplayRegion.

```<code> DisplayRegion secondaryDisplayRegion = GetOtherDisplayRegion(ApplicationView.GetForCurrentView().GetDisplayRegions()[0]);
 if (secondaryDisplayRegion != null)
  {
     appWindow.RequestMoveToDisplayRegion(secondaryDisplayRegion);
  }
</code>```

Body:
I want my program to be able to select the monitor on which a new window will be opened

now my code looks like this:

AppWindow appWindow = await AppWindow.TryCreateAsync();
Frame OpenPage1 = new Frame();
OpenPage1.Navigate(typeof(Projector));
ElementCompositionPreview.SetAppWindowContent(appWindow, OpenPage1);
appWindow.Presenter.RequestPresentation(AppWindowPresentationKind.FullScreen);

await appWindow.TryShowAsync();

It opens a window on the current monitor. I want the window to open on the selected monitor

Additional question: How can I prevent this window from collapsing?

Body:
how to show a new window on the second or third monitor of uwp win 10

As Raymond Chen said you could use RequestMoveToDisplayRegion method to display AppWindow in secondary DisplayRegion.

For code sample you could refer to AppWindow  official code sample Scenario2_DisplayRegion.

 DisplayRegion secondaryDisplayRegion = GetOtherDisplayRegion(ApplicationView.GetForCurrentView().GetDisplayRegions()[0]);
 if (secondaryDisplayRegion != null)
  {
     appWindow.RequestMoveToDisplayRegion(secondaryDisplayRegion);
  }


问:
How to catch java.lang.NoClassDefFoundError?
I made an application which take elf file(*.a and *.o) and give list of methods name, but if someone renames any file into *.a or *.o then it will show:

```<code>Exception occurred during event dispatching:
java.lang.NoClassDefFoundError: org/eclipse/core/resources/IWorkspaceRunnable
    at org.eclipse.cdt.utils.AR.<init>(AR.java:237)
    at com.lge.windowELF.ElfBinaryArchive.<init>(ElfBinaryArchive.java:24)
    at com.lge.windowELF.ELFParserLibraryFile.createBinaryArchive(ELFParserLibraryFile.java:230)
    at com.lge.windowELF.ELFParserLibraryFile.<init>(ELFParserLibraryFile.java:46)
    at com.lge.windowELF.ELFWrapper.<init>(ELFWrapper.java:36)
    at com.lge.windowELF.ELF_UIIntegrated.actionPerformed(ELF_UIIntegrated.java:510)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
</code>```

In this situation I want to give some warning message. This exception is not caught by try/catch.

答:
I just wanted to add an answer in response to it not being recommended to catch this error. I think it's fine in the right situation and if done in the right way. I can think of several situations where it makes sense

if your application relies on an end user supplying some of the dependencies

some of the dependencies are pre-installed by another application

you just want to give a cleaner error message and exit

For me this is very common, I supply an application and the OPs team supply the environment. If certain dependencies don't exist I log an error saying that functionality does not exist but my application continues to run.

I would also add that you need to make sure within the catch block that the dependencies you use there have been confirmed to exist. This isn't that hard, if you need a jar for logging for example and you've used it previously in your code with success then you're all good. If the logging dependency didn't exist then it shouldn't be possible for your code to get that far anyway.

Body:
I made an application which take elf file(*.a and *.o) and give list of methods name, but if someone renames any file into *.a or *.o then it will show:

Exception occurred during event dispatching:
java.lang.NoClassDefFoundError: org/eclipse/core/resources/IWorkspaceRunnable
    at org.eclipse.cdt.utils.AR.<init>(AR.java:237)
    at com.lge.windowELF.ElfBinaryArchive.<init>(ElfBinaryArchive.java:24)
    at com.lge.windowELF.ELFParserLibraryFile.createBinaryArchive(ELFParserLibraryFile.java:230)
    at com.lge.windowELF.ELFParserLibraryFile.<init>(ELFParserLibraryFile.java:46)
    at com.lge.windowELF.ELFWrapper.<init>(ELFWrapper.java:36)
    at com.lge.windowELF.ELF_UIIntegrated.actionPerformed(ELF_UIIntegrated.java:510)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)

In this situation I want to give some warning message. This exception is not caught by try/catch.


问:
If this is not a DIR in my what could it be? Trying to access a file
What could id.json be? I'm trying to access/or inspect the file.</p>
```<code> Directory of C:\Users\ssand\.config\solana

02/09/2022  12:42 PM    <DIR>          .
02/09/2022  12:42 PM    <DIR>          ..
02/09/2022  11:05 AM    <DIR>          cli
02/09/2022  12:42 PM               239 id.json
02/09/2022  10:50 AM    <DIR>          install
               1 File(s)            239 bytes
               4 Dir(s)   7,804,948,480 bytes free
</code>```

答:
It is a file, not a directory. Files don't have <DIR> written near them, but have their size.

From the name, it seems like a JSON file. These files can be opened as text.

Body:
What could id.json be? I'm trying to access/or inspect the file.

 Directory of C:\Users\ssand\.config\solana

02/09/2022  12:42 PM    <DIR>          .
02/09/2022  12:42 PM    <DIR>          ..
02/09/2022  11:05 AM    <DIR>          cli
02/09/2022  12:42 PM               239 id.json
02/09/2022  10:50 AM    <DIR>          install
               1 File(s)            239 bytes
               4 Dir(s)   7,804,948,480 bytes free


问:
Unrecognized Token C/C++(7) Error in Visual Studio Code
Unrecognized Token C/C++(7) Error in Visual Studio Code

I am unsure why I am receiving these error messages; I am trying to compile c++11 code on VSC.

Please help? Thank you

see code here

For example, on Line 7 there is an "Unrecognized Token C/C++(7) Error" :

```<code>string str = “fine”;
</code>```

答: Yes, you are using fancy unicode quotes. It may happen when you copy code from some messenger. Messengers often replace original quotes to that type of quotes.</p>

Body:
Unrecognized Token C/C++(7) Error in Visual Studio Code

I am unsure why I am receiving these error messages; I am trying to compile c++11 code on VSC.

Please help? Thank you

see code here

For example, on Line 7 there is an "Unrecognized Token C/C++(7) Error" :

string str = “fine”;


问:
symbolic solution of linear equations using Sympy
Basically I have [5x5][5x1]=[0] and would like to have the symbolic expression of the solution.

Here is my code.

```<code>from sympy import symbols, solve
gm1, gm2, gm4                   = symbols(['gm1', 'gm2', 'gm4'])
gds1, gds2, gds3, gds4, gds5    = symbols(['gds1', 'gds2', 'gds3', 'gds4', 'gds5'])
s                               = symbols(['s'])
Cd, CF , Cin, Ct                = symbols(['Cd', 'CF', 'Cin', 'Ct'])
K                               = symbols(['K'])
vb, vc, ve, vout, iin           = symbols(['vb', 'vc', 've', 'vout', 'iin'])

sol = solve([-(gds1+gds3+(s*Cd))*vb + (gm1+gds1)*ve + -gm1*vout, \
          -gm4*vb + (gds4-gds2-(s*Cin)-(s*CF))*vc + (gds2+gm2)*ve + s*CF*vout + iin, \
        gds1*vb + gds2*vc + (-(s*Ct)-gds5-gds1-gm1-gm2-gds2)*ve + gm1*vout, \
        K*vc + vout], [vout])
print(sol)
</code>```

but, I got this error

```<code>TypeError: can't multiply sequence by non-int of type 'Symbol'
</code>```

From here, symbolic multiplication seems working just fine.

I am not sure whether I describe my problem in a way that does not comply with Sympy or something else.

What did I miss here?

答:
The problem is in the assignment of the single symbols s and K.  If instead you do:

```<code>s, K = symbols(['s', 'K'])
</code>```

Or:

```<code>s = symbols('s')
K = symbols('K')
</code>```

Whether you get the right answer or not is another matter :)

Body:
Basically I have [5x5][5x1]=[0] and would like to have the symbolic expression of the solution.

Here is my code.

from sympy import symbols, solve
gm1, gm2, gm4                   = symbols(['gm1', 'gm2', 'gm4'])
gds1, gds2, gds3, gds4, gds5    = symbols(['gds1', 'gds2', 'gds3', 'gds4', 'gds5'])
s                               = symbols(['s'])
Cd, CF , Cin, Ct                = symbols(['Cd', 'CF', 'Cin', 'Ct'])
K                               = symbols(['K'])
vb, vc, ve, vout, iin           = symbols(['vb', 'vc', 've', 'vout', 'iin'])

sol = solve([-(gds1+gds3+(s*Cd))*vb + (gm1+gds1)*ve + -gm1*vout, \
          -gm4*vb + (gds4-gds2-(s*Cin)-(s*CF))*vc + (gds2+gm2)*ve + s*CF*vout + iin, \
        gds1*vb + gds2*vc + (-(s*Ct)-gds5-gds1-gm1-gm2-gds2)*ve + gm1*vout, \
        K*vc + vout], [vout])
print(sol)

but, I got this error

TypeError: can't multiply sequence by non-int of type 'Symbol'

From here, symbolic multiplication seems working just fine.

I am not sure whether I describe my problem in a way that does not comply with Sympy or something else.

What did I miss here?

Body:
The problem is in the assignment of the single symbols s and K.  If instead you do:

s, K = symbols(['s', 'K'])

Or:

s = symbols('s')
K = symbols('K')

Whether you get the right answer or not is another matter :)


问:
C# Hackerrank Duplicated Products
First off, yes I am a 'noob' regarding C# anyway. I am an AS/400 programmer looking to learn .NET\C#. This is one of those blasted hackerrank questions called 'duplicated products'. My question is:

What is "OUTPUT_PATH" is supposed to be replaced with? I keep receiving the error 'Value cannot be null.(Parameter 'path')

Can you get this to compile and run successfully in Visual Studio on your computer and if so can you please indicate how?

I have researched this for literal hours but have yet to find someone who can answer this clearly or at all. There is usually just some hurling of insults....i.e., 'noob...this is one of those 'hackerrank' questions...' etc., as replies.

Thanks.

```<code>class Result
{

    /*
     * Complete the 'numDuplicates' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING_ARRAY name
     *  2. INTEGER_ARRAY price
     *  3. INTEGER_ARRAY weight
     */

    public static int numDuplicates(List<string> name, List<int> price, List<int> weight)
    {
        ISet<string> uniqueProducts = new HashSet<string>();
        for (int i = 0; i < name.Count; i++)
        {
            uniqueProducts.Add(name[i] + " " + price[i] + " " + weight[i]);
        }
        return name.Count - uniqueProducts.Count;  // Editor JT added this hint, to detect numDuplicates it should be - uniqueProducts.Distinct();
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int nameCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<string> name = new List<string>();

        for (int i = 0; i < nameCount; i++)
        {
            string nameItem = Console.ReadLine();
            name.Add(nameItem);
        }

        int priceCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> price = new List<int>();

        for (int i = 0; i < priceCount; i++)
        {
            int priceItem = Convert.ToInt32(Console.ReadLine().Trim());
            price.Add(priceItem);
        }

        int weightCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> weight = new List<int>();

        for (int i = 0; i < weightCount; i++)
        {
            int weightItem = Convert.ToInt32(Console.ReadLine().Trim());
            weight.Add(weightItem);
        }

        int result = Result.numDuplicates(name, price, weight);

        textWriter.WriteLine(String.Join(" ", result));

        textWriter.Flush();
        textWriter.Close();
    }
}
}
</code>```

答:
Save the file as Solution.cs
You can compile the file from command prompt with csc Solution.cs and run with Solution.exe inside the visual studio powershell.</p>
```<code>//Add following required namespaces
using System;
using System.Collections.Generic;
using System.IO;

class Result
{

    /*
     * Complete the 'numDuplicates' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING_ARRAY name
     *  2. INTEGER_ARRAY price
     *  3. INTEGER_ARRAY weight
     */

    public static int numDuplicates(List<string> name, List<int> price, List<int> weight)
    {
        ISet<string> uniqueProducts = new HashSet<string>();
        for (int i = 0; i < name.Count; i++)
        {
            uniqueProducts.Add(name[i] + " " + price[i] + " " + weight[i]);
        }
        return name.Count - uniqueProducts.Count;  // Editor JT added this hint, to detect numDuplicates it should be - uniqueProducts.Distinct();
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        //Create a folder "temp" under c: drive and add the following line
        System.Environment.SetEnvironmentVariable("OUTPUT_PATH","c:\\temp\\Output.txt");
        TextWriter textWriter = new StreamWriter(System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        Console.WriteLine("Enter how many names you want to enter. e.g 3 ");
        int nameCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<string> name = new List<string>();

        for (int i = 0; i < nameCount; i++)
        {
            Console.WriteLine("Enter name " + (i + 1));
            string nameItem = Console.ReadLine();
            name.Add(nameItem);
        }

        Console.WriteLine("Enter how many prices you want to enter. e.g 3 ");
        int priceCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> price = new List<int>();

        for (int i = 0; i < priceCount; i++)
        {
            Console.WriteLine("Enter price " + (i + 1));
            int priceItem = Convert.ToInt32(Console.ReadLine().Trim());
            price.Add(priceItem);
        }

        Console.WriteLine("Enter how many weighs you want to enter. e.g 3 ");
        int weightCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> weight = new List<int>();

        for (int i = 0; i < weightCount; i++)
        {
            Console.WriteLine("Enter weight " + (i + 1));
            int weightItem = Convert.ToInt32(Console.ReadLine().Trim());
            weight.Add(weightItem);
        }

        int result = Result.numDuplicates(name, price, weight);

        textWriter.WriteLine(String.Join(" ", result));

        textWriter.Flush();
        textWriter.Close();
    }
}
</code>```

Title: C# Hackerrank Duplicated Products

Body:
First off, yes I am a 'noob' regarding C# anyway. I am an AS/400 programmer looking to learn .NET\C#. This is one of those blasted hackerrank questions called 'duplicated products'. My question is:

What is "OUTPUT_PATH" is supposed to be replaced with? I keep receiving the error 'Value cannot be null.(Parameter 'path')

Can you get this to compile and run successfully in Visual Studio on your computer and if so can you please indicate how?

I have researched this for literal hours but have yet to find someone who can answer this clearly or at all. There is usually just some hurling of insults....i.e., 'noob...this is one of those 'hackerrank' questions...' etc., as replies.

Thanks.

class Result
{

    /*
     * Complete the 'numDuplicates' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING_ARRAY name
     *  2. INTEGER_ARRAY price
     *  3. INTEGER_ARRAY weight
     */

    public static int numDuplicates(List<string> name, List<int> price, List<int> weight)
    {
        ISet<string> uniqueProducts = new HashSet<string>();
        for (int i = 0; i < name.Count; i++)
        {
            uniqueProducts.Add(name[i] + " " + price[i] + " " + weight[i]);
        }
        return name.Count - uniqueProducts.Count;  // Editor JT added this hint, to detect numDuplicates it should be - uniqueProducts.Distinct();
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int nameCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<string> name = new List<string>();

        for (int i = 0; i < nameCount; i++)
        {
            string nameItem = Console.ReadLine();
            name.Add(nameItem);
        }

        int priceCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> price = new List<int>();

        for (int i = 0; i < priceCount; i++)
        {
            int priceItem = Convert.ToInt32(Console.ReadLine().Trim());
            price.Add(priceItem);
        }

        int weightCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> weight = new List<int>();

        for (int i = 0; i < weightCount; i++)
        {
            int weightItem = Convert.ToInt32(Console.ReadLine().Trim());
            weight.Add(weightItem);
        }

        int result = Result.numDuplicates(name, price, weight);

        textWriter.WriteLine(String.Join(" ", result));

        textWriter.Flush();
        textWriter.Close();
    }
}
}

Body:
Save the file as Solution.cs
You can compile the file from command prompt with csc Solution.cs and run with Solution.exe inside the visual studio powershell.

//Add following required namespaces
using System;
using System.Collections.Generic;
using System.IO;

class Result
{

    /*
     * Complete the 'numDuplicates' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts following parameters:
     *  1. STRING_ARRAY name
     *  2. INTEGER_ARRAY price
     *  3. INTEGER_ARRAY weight
     */

    public static int numDuplicates(List<string> name, List<int> price, List<int> weight)
    {
        ISet<string> uniqueProducts = new HashSet<string>();
        for (int i = 0; i < name.Count; i++)
        {
            uniqueProducts.Add(name[i] + " " + price[i] + " " + weight[i]);
        }
        return name.Count - uniqueProducts.Count;  // Editor JT added this hint, to detect numDuplicates it should be - uniqueProducts.Distinct();
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        //Create a folder "temp" under c: drive and add the following line
        System.Environment.SetEnvironmentVariable("OUTPUT_PATH","c:\\temp\\Output.txt");
        TextWriter textWriter = new StreamWriter(System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        Console.WriteLine("Enter how many names you want to enter. e.g 3 ");
        int nameCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<string> name = new List<string>();

        for (int i = 0; i < nameCount; i++)
        {
            Console.WriteLine("Enter name " + (i + 1));
            string nameItem = Console.ReadLine();
            name.Add(nameItem);
        }

        Console.WriteLine("Enter how many prices you want to enter. e.g 3 ");
        int priceCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> price = new List<int>();

        for (int i = 0; i < priceCount; i++)
        {
            Console.WriteLine("Enter price " + (i + 1));
            int priceItem = Convert.ToInt32(Console.ReadLine().Trim());
            price.Add(priceItem);
        }

        Console.WriteLine("Enter how many weighs you want to enter. e.g 3 ");
        int weightCount = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> weight = new List<int>();

        for (int i = 0; i < weightCount; i++)
        {
            Console.WriteLine("Enter weight " + (i + 1));
            int weightItem = Convert.ToInt32(Console.ReadLine().Trim());
            weight.Add(weightItem);
        }

        int result = Result.numDuplicates(name, price, weight);

        textWriter.WriteLine(String.Join(" ", result));

        textWriter.Flush();
        textWriter.Close();
    }
}


问:
Java, converting string to integers then add all the integers together
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.</p>

```<code>String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

for (int i = 0; i < 8; i++){

// Stuck

}
</code>```

答:
How about that (I skipped exceptions...):</p>

```<code>String[] sNums = jTextField1.getText().replaceAll("[^1-9]", "").split("(?<!^)");
int sum = 0;
for (String s : sNums) {
    sum += Integer.parseInt(s); // add all digits
}

while (sum > 9) { // add all digits of the number, until left with one-digit number
    int temp = 0;
    while (sum > 0) {
        temp += sum % 10;
        sum = sum / 10;
    }
    sum = temp;
}
</code>```

Body:
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.

String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

for (int i = 0; i < 8; i++){

// Stuck

}

Body:
How about that (I skipped exceptions...):

String[] sNums = jTextField1.getText().replaceAll("[^1-9]", "").split("(?<!^)");
int sum = 0;
for (String s : sNums) {
    sum += Integer.parseInt(s); // add all digits
}

while (sum > 9) { // add all digits of the number, until left with one-digit number
    int temp = 0;
    while (sum > 0) {
        temp += sum % 10;
        sum = sum / 10;
    }
    sum = temp;
}


问:
Swiftui - Cannot present Form inside Sheet or FullScreenCover
When using a Form on a view and presenting it with either .sheet or .fullScreenCover the view is never presented and instead memory is quickly gobbled until the app crashes. Removing the form and replacing it with anything else works just fine.

Inside top level view, the sheet or full screen uses:

```<code>        .fullScreenCover(isPresented: $showProfile, content: {
            NavigationView {
                ProfileNumberView()
            }
        })
</code>```

OR

```<code>        .sheet(isPresented: $showProfile, content: {
            NavigationView {
                ProfileNumberView()
            }
        })
</code>```

The view it's launching can be as simple as:

```<code>var body: some View {
    Form {
        Text("TEST")
    }
}
</code>```

Again doing this causes the app to simply gobble up memory until a crash and no view is presented. If I simply remove the Form tag, the the view will present as normal. I have also tried embedding the NavigationView inside the form view (above the Form tag) but to no avail.

Why can I not present a view using a Form in this manner?

Update: I have discovered the source of the issue is when the top level view contains a List. If there is no list the screens present just fine, but it seems we cannot present a form within a cover or sheet if the parent has a list in it. Still not clear why that would be the case but commenting out the list and the sheet or fullscreencover worked.

答:
The turned out to be something that was not directly related to the code I posted above. It's worth posting the answer though as I am sure others may run into this. The problem was styling given to the list in order to paint a background with an image. Specifically:

```<code>UITableViewCell.appearance().backgroundColor = .clear
let imageView = UIImageView(image: UIImage(named: "gradientBackground"))
imageView.contentMode = .scaleToFill
UITableView.appearance().backgroundView = imageView
</code>```

This styling of the list for some reason prevents you from presenting a sheet or full screen cover that has a form. Very unclear why and I need this background, so while this particular issue is resolved, the functionality required is not.

Body:
When using a Form on a view and presenting it with either .sheet or .fullScreenCover the view is never presented and instead memory is quickly gobbled until the app crashes. Removing the form and replacing it with anything else works just fine.

Inside top level view, the sheet or full screen uses:

        .fullScreenCover(isPresented: $showProfile, content: {
            NavigationView {
                ProfileNumberView()
            }
        })

OR

        .sheet(isPresented: $showProfile, content: {
            NavigationView {
                ProfileNumberView()
            }
        })

The view it's launching can be as simple as:

var body: some View {
    Form {
        Text("TEST")
    }
}

Again doing this causes the app to simply gobble up memory until a crash and no view is presented. If I simply remove the Form tag, the the view will present as normal. I have also tried embedding the NavigationView inside the form view (above the Form tag) but to no avail.

Why can I not present a view using a Form in this manner?

Update: I have discovered the source of the issue is when the top level view contains a List. If there is no list the screens present just fine, but it seems we cannot present a form within a cover or sheet if the parent has a list in it. Still not clear why that would be the case but commenting out the list and the sheet or fullscreencover worked.

Body:
The turned out to be something that was not directly related to the code I posted above. It's worth posting the answer though as I am sure others may run into this. The problem was styling given to the list in order to paint a background with an image. Specifically:

UITableViewCell.appearance().backgroundColor = .clear
let imageView = UIImageView(image: UIImage(named: "gradientBackground"))
imageView.contentMode = .scaleToFill
UITableView.appearance().backgroundView = imageView

This styling of the list for some reason prevents you from presenting a sheet or full screen cover that has a form. Very unclear why and I need this background, so while this particular issue is resolved, the functionality required is not.


问:
How to parse invalid JSON contianing invalid number
I work with a legacy customer who sends me webhook events. Sometimes their system sends me a   value that looks like this

[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]
```

I am using python's json.loads to parse the data sent to me. Here the ts is an invalid number and python gives json.decoder.JSONDecodeError whenever I try to parse this string.

It is okay with me to get None in ts field if I can not parse it.

What would be a smart (& possibly generic) way to solve this problem?

答:
This may not be so generic, but you can try using yaml to load:

```<code>import yaml

s = '[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074","ts":16XX445656000}]'
yaml.safe_load(s)
</code>```

Output:

```<code>[{'id': 'LXKhRA3RHtaVBhnczVRJLdr',
  'ecc': '0X6',
  'cph': 'X1X4X77074',
  'ts': '16XX445656000'}]
</code>```

Body:
I work with a legacy customer who sends me webhook events. Sometimes their system sends me a   value that looks like this

[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]

I am using python's json.loads to parse the data sent to me. Here the ts is an invalid number and python gives json.decoder.JSONDecodeError whenever I try to parse this string.

It is okay with me to get None in ts field if I can not parse it.

What would be a smart (& possibly generic) way to solve this problem?

Body:
This may not be so generic, but you can try using yaml to load:

import yaml

s = '[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074","ts":16XX445656000}]'
yaml.safe_load(s)

Output:

[{'id': 'LXKhRA3RHtaVBhnczVRJLdr',
  'ecc': '0X6',
  'cph': 'X1X4X77074',
  'ts': '16XX445656000'}]


问:
Trying to Add Markers to Leaflet Map with button click (Using Angular)
I have the following code where I am creating a leaflet map on initial load of the page. I have about four jsons with lat/lon data that I would like to populate the map. What I'm looking for is four buttons that when clicked will add the json data as markers to the map.

What I'm getting is an error indicating the following:
Cannot read properties of undefined (reading 'addLayer').

Map Component:

```<code>import { Component, AfterViewInit, OnInit } from '@angular/core';
import { MapPointsService } from './map-points.service';
import * as L from 'leaflet';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css'],
})
export class MapComponent implements AfterViewInit {
  private map: L.Map | L.LayerGroup<any> | undefined;
  area: any;
  markersLayer = new L.LayerGroup();

  private initMap(): void {
    this.map = L.map('map', {
      center: [4.5709, -74.2973],
      zoom: 3,
    });

    this.area = this.map;

    const tiles = L.tileLayer(
      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      {
        maxZoom: 18,
        minZoom: 3,
        attribution:
          '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      }
    );

    tiles.addTo(this.map);
  }

  constructor(private mapService: MapPointsService) {}

  ngAfterViewInit(): void {
    this.initMap();
    // this.mapService.jsonMarkers(this.area);
  }

  addMarkers(): void {
    this.mapService.jsonMarkers(this.area);
  }
}
</code>```

MapService

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// import { MapComponent } from './map.component';
import * as L from 'leaflet';

@Injectable({
  providedIn: 'root',
})
export class MapPointsService {
  constructor(private http: HttpClient) {}

  jsonMarkers(map: L.Map): void {
    this.http
      .get('/assets/data/<my_json>.json')
      .subscribe((res: any) => {
        for (const area of res.<json_item>) {
          const lon = are.Longitude;
          const lat = are.Latitude;
          const marker = L.marker([lat, lon]);
          /*if (map.hasLayer(marker)) {
            map.removeLayer(marker);
          }*/
          marker.addTo(map);

          // console.log(markers);
        }
      });
  }
}

</code>```

Info Component that calls function

```<code>import { Component, OnInit } from '@angular/core';
import { MapPointsService } from '../map/map-points.service';
import { MapComponent } from '../map/map.component';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-information',
  templateUrl: './information.component.html',
  styleUrls: ['./information.component.css'],
})
export class InformationComponent implements OnInit {
  /**
   * showSpinner boolean
   */
  showSpinner = false;
  constructor(
    private _snackBar: MatSnackBar,
    private mapService: MapPointsService
  ) {}

  ngOnInit(): void {}

  run(msg: string): void {
    const snackBarRef = this._snackBar.open('Running ' + msg, 'Close', {
      duration: 3000,
    });
    snackBarRef.afterDismissed().subscribe(() => {
      this.showSpinner = false;
    });
    this.showSpinner = true;
  }

  mapData() {
    let data = new MapComponent(this.mapService);
    data.addMarkers();
  }
}

</code>```

Info Html

```<code><button type="button" (click)='mapData()'></button>
</code>```

答:
If you manually instantiate an Angular component with just the new keyword (let data = new MapComponent(this.mapService)), it will not be mounted anywhere, and in particular its lifecycle methods, like ngAfterViewInit, will not be called.

Then in your case, this.map and this.area remain undefined, leading to your error message.

Since you do not show your templates, it is hard to tell how your components are supposed to be related.

In case your <app-information> (InformationComponent) contains the <app-map> (MapComponent), you can use @ViewChild in InformationComponent to get a reference to the child MapComponent, and from there you can call its addMarkers method.

In case they are in the opposite situation, IIRC you can just request a MapComponent type in InformationComponent constructor, and Angular will inject it from its ancestors tree.

And if they are somehow siblings, then you could manage from a common ancestor:

get a ref to the MapComponent as described first

add an @Output event emitter on InformationComponent that fires when your button is clicked, and in the ancestor you listen to that event, and call the MapComponent.addMarkers method.

Body:
I have the following code where I am creating a leaflet map on initial load of the page. I have about four jsons with lat/lon data that I would like to populate the map. What I'm looking for is four buttons that when clicked will add the json data as markers to the map.

What I'm getting is an error indicating the following:
Cannot read properties of undefined (reading 'addLayer').

Map Component:

import { Component, AfterViewInit, OnInit } from '@angular/core';
import { MapPointsService } from './map-points.service';
import * as L from 'leaflet';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css'],
})
export class MapComponent implements AfterViewInit {
  private map: L.Map | L.LayerGroup<any> | undefined;
  area: any;
  markersLayer = new L.LayerGroup();

  private initMap(): void {
    this.map = L.map('map', {
      center: [4.5709, -74.2973],
      zoom: 3,
    });

    this.area = this.map;

    const tiles = L.tileLayer(
      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      {
        maxZoom: 18,
        minZoom: 3,
        attribution:
          '© OpenStreetMap',
      }
    );

    tiles.addTo(this.map);
  }

  constructor(private mapService: MapPointsService) {}

  ngAfterViewInit(): void {
    this.initMap();
    // this.mapService.jsonMarkers(this.area);
  }

  addMarkers(): void {
    this.mapService.jsonMarkers(this.area);
  }
}

MapService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// import { MapComponent } from './map.component';
import * as L from 'leaflet';

@Injectable({
  providedIn: 'root',
})
export class MapPointsService {
  constructor(private http: HttpClient) {}

  jsonMarkers(map: L.Map): void {
    this.http
      .get('/assets/data/<my_json>.json')
      .subscribe((res: any) => {
        for (const area of res.<json_item>) {
          const lon = are.Longitude;
          const lat = are.Latitude;
          const marker = L.marker([lat, lon]);
          /*if (map.hasLayer(marker)) {
            map.removeLayer(marker);
          }*/
          marker.addTo(map);

          // console.log(markers);
        }
      });
  }
}

Info Component that calls function

import { Component, OnInit } from '@angular/core';
import { MapPointsService } from '../map/map-points.service';
import { MapComponent } from '../map/map.component';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-information',
  templateUrl: './information.component.html',
  styleUrls: ['./information.component.css'],
})
export class InformationComponent implements OnInit {
  /**
   * showSpinner boolean
   */
  showSpinner = false;
  constructor(
    private _snackBar: MatSnackBar,
    private mapService: MapPointsService
  ) {}

  ngOnInit(): void {}

  run(msg: string): void {
    const snackBarRef = this._snackBar.open('Running ' + msg, 'Close', {
      duration: 3000,
    });
    snackBarRef.afterDismissed().subscribe(() => {
      this.showSpinner = false;
    });
    this.showSpinner = true;
  }

  mapData() {
    let data = new MapComponent(this.mapService);
    data.addMarkers();
  }
}

Info Html

<button type="button" (click)='mapData()'></button>


问:
Flutter Firebase local change doesn't update listener stream
I'm relying on Firebase Firestore offline capabilities, so I'm not using await on my queries as stated on the Access Data Offline Firebase doc. I'm expecting that when I write something I'll get an immediate reflection on my read stream, however, I'm only getting an update when the server/remote has been updated. Basically:

Update something in the DB. Note, I'm not using await

```<code> _db.doc(parentDoc).collection(DocInnerCollection).doc(childDoc).update({
        "name": value,
      });
</code>```

I expect my listeners to be updated immediately. Note I've set the includeMetadataChanges to true as stated in the above doc.

```<code>_db.doc(parentDoc)
    .collection(DocInnerCollection)
    .orderBy('start_date', 'desc')
    .limitToLast(1)
    .snapshots(includeMetadataChanges: true)
    .map((snapshot) {
  print(snapshot.metadata.isFromCache)
});
</code>```

However, I get no such update and instead I only get an update when the server has been updated.

答:
You're requesting only one document with .limitToLast(1), yet are not providing a sort order for your query. This essentially means that you'll get a random document from your collection, and the chances of that being the newly updated document are close to zero.

If you want the latest (not just last) document, you need some ordering criteria to determine what latest means. Typically you'd do this by:

Adding a lastUpdated field to your documents, and setting that to firebase.firestore.FieldValue.serverTimestamp().

Ordering your query on that timestamp with orderBy('lastUpdated', 'desc').

And then limiting to the first result with limit(1).

Body:
I'm relying on Firebase Firestore offline capabilities, so I'm not using await on my queries as stated on the Access Data Offline Firebase doc. I'm expecting that when I write something I'll get an immediate reflection on my read stream, however, I'm only getting an update when the server/remote has been updated. Basically:

Update something in the DB. Note, I'm not using await

 _db.doc(parentDoc).collection(DocInnerCollection).doc(childDoc).update({
        "name": value,
      });

I expect my listeners to be updated immediately. Note I've set the includeMetadataChanges to true as stated in the above doc.

_db.doc(parentDoc)
    .collection(DocInnerCollection)
    .orderBy('start_date', 'desc')
    .limitToLast(1)
    .snapshots(includeMetadataChanges: true)
    .map((snapshot) {
  print(snapshot.metadata.isFromCache)
});

However, I get no such update and instead I only get an update when the server has been updated.


问:
Why appending on slice modified another slice?

package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9)

    fmt.Println(a, b)
}
```

output:

[0 1 2 9] [9 4 5 6]

Did append modified the underlay array as  []int{0, 1, 2, 9, 4, 5, 6}?
Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.

Thanks for any hints, much appreciated

答:
Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.

a := src[:3] created a slice (a pointer to the src head, length=3, capacity=7)

b := src[3:] created a slice(a pointer to the src[3],length=4, capacity=4)

a and b shares the same memory created by src

a = append(a, 9),when appending to the same slice, as long as it does not exceed cap, it is the same array that is modified

Did append modified the underlay array as []int{0, 1, 2, 9, 4, 5, 6}

YES

If the append exceed the cap of a, new array will be allocated and data will be copied the the new array

try this out:

package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)

    fmt.Println(a, b)
}

```

Output:

[0 1 2 9 9 9 9 9 9 9 9 9 9] [3 4 5 6]

Body:
package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9)

    fmt.Println(a, b)
}

output:

[0 1 2 9] [9 4 5 6]

Did append modified the underlay array as  []int{0, 1, 2, 9, 4, 5, 6}?
Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.

Thanks for any hints, much appreciated

Body:
Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.

a := src[:3] created a slice (a pointer to the src head, length=3, capacity=7)

b := src[3:] created a slice(a pointer to the src[3],length=4, capacity=4)

a and b shares the same memory created by src

a = append(a, 9),when appending to the same slice, as long as it does not exceed cap, it is the same array that is modified

Did append modified the underlay array as []int{0, 1, 2, 9, 4, 5, 6}

YES

If the append exceed the cap of a, new array will be allocated and data will be copied the the new array

try this out:

package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)

    fmt.Println(a, b)
}

Output:

[0 1 2 9 9 9 9 9 9 9 9 9 9] [3 4 5 6]


答:
For every element in result, you need to convert it to an int, then add it to some variable, maybe called sum.</p>

```<code>int sum = 0;

// for every String in the result array
for (int i = 0; i < BOUND; i++) {
  // convert s[i] to int value
  // add the int value to sum
}
</code>```

Title: Java, converting string to integers then add all the integers together

Body:
For every element in result, you need to convert it to an int, then add it to some variable, maybe called sum.

int sum = 0;

// for every String in the result array
for (int i = 0; i < BOUND; i++) {
  // convert s[i] to int value
  // add the int value to sum
}


问:
Equivalent for FETCH FIRST WITH TIES in Postgres 11 with comparable performance
Given the following DDL

```<code>CREATE TABLE numbers (
    id     BIGSERIAL PRIMARY KEY,
    number BIGINT
);
CREATE INDEX ON numbers (number);
</code>```

In PostgreSQL 13 I can use the following query:

```<code>SELECT *
FROM numbers
WHERE number > 1
ORDER BY number
FETCH FIRST 1000 ROWS WITH TIES
</code>```

It produces a very effective query plan and performs well enough with large tables:

Limit  (cost=...)
  ->  Index Scan using numbers_number_idx on numbers  (cost=...)
        Index Cond: (number > 1)
```
<p>Is there an equivalent for that in PostgreSQL 11 that gives a similar query plan and comparable performance for large (10TB+) tables?</p>
<p>This answer suggests to use the following query:</p>
```WITH cte AS (
    SELECT *, RANK() OVER (ORDER BY number) AS rnk
    FROM numbers
    WHERE number > 1
)
SELECT *
FROM cte
WHERE rnk <= 1000;
```
<p>But it is not really usable for large tables because performance is many times worse.</p>
<pre class="lang-none prettyprint-override"><code>Subquery Scan on cte  (cost=...)
  Filter: (cte.rnk <= 1000)
  ->  WindowAgg  (cost=...)
        ->  Index Scan using numbers_number_idx on numbers  (cost=...)
              Index Cond: (number > 1)
</code>```

答:
You won't get the performance of the extremely convenient WITH TIES in Postgres 13 or later. See:

Get top row(s) with highest value, with ties

But there are always options ...

Faster SQL variant

Should be faster for big tables because it avoids to rank the whole table like the simple solution in the referenced answer.

WITH cte AS (
   SELECT *, row_number() OVER (ORDER  BY number, id) AS rn  -- ORDER must match
   FROM   numbers
   WHERE  number > 1
   ORDER  BY number, id  -- tiebreaker to make it deterministic
   LIMIT  1000
   )
TABLE cte
UNION ALL
(
SELECT n.*, 1000 + row_number() OVER (ORDER BY n.id) AS rn
FROM   numbers n, (SELECT number, id FROM cte WHERE rn = 1000) AS max
WHERE  n.number = max.number
AND    n.id > max.id
ORDER  BY n.id
);
```
<p><code>id</code> is any <code>UNIQUE NOT NULL</code> column in your table that lends itself as tiebreaker, typically the <code>PRIMARY KEY</code>.</p>
<p>Sort by that <em>additionally</em>, which has the (maybe welcome) side effect that you get a deterministically ordered result.</p>
<p>Ideally, you have a multicolumn <strong>index</strong> on <code>(number, id)</code> for this. But it will use the existing index on just <code>(number)</code>, too. Resulting performance depends on cardinalities and data types.<br />
Related:</p>
<ul>
<li>Is a composite index also good for queries on the first field?</li>
</ul>
<p>Since the CTE query counts as <em>one</em> command, there is <strong>no race condition</strong> under concurrent write load. All parts of the command see the same snapshot of the table in default isolation level <code>READ COMMITTED</code>.</p>
<p>I might wrap this into a simple SQL function (or prepared statement) and pass <code>LIMIT</code> to it for convenience.</p>
<h3>Alternative with PL/pgSQL</h3>
<p>Only running a single <code>SELECT</code> probably outweighs the added overhead. Works optimally with the existing index on just <code>(number)</code>:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION foo(_bound int, _limit int, OUT _row public.numbers)
  RETURNS SETOF public.numbers
  LANGUAGE plpgsql AS
$func$
DECLARE
   _ct int := 0;
   _number int;  -- match type!
BEGIN
   FOR _row IN
      SELECT *
      FROM   public.numbers
      WHERE  number > _bound
      ORDER  BY number
   LOOP
      _ct := _ct + 1;
      CASE
      WHEN _ct < _limit THEN
         -- do nothing
      WHEN _ct > _limit THEN
         EXIT WHEN _row.number > _number;
      WHEN _ct = _limit THEN
         _number := _row.number;
      END CASE;

      RETURN NEXT;
   END LOOP;
END
$func$;
</code>```

But it's tailored for just the one query. Gets tedious for varying queries.

Body:
Given the following DDL

CREATE TABLE numbers (
    id     BIGSERIAL PRIMARY KEY,
    number BIGINT
);
CREATE INDEX ON numbers (number);

In PostgreSQL 13 I can use the following query:

SELECT *
FROM numbers
WHERE number > 1
ORDER BY number
FETCH FIRST 1000 ROWS WITH TIES

It produces a very effective query plan and performs well enough with large tables:

Limit  (cost=...)
  ->  Index Scan using numbers_number_idx on numbers  (cost=...)
        Index Cond: (number > 1)

Is there an equivalent for that in PostgreSQL 11 that gives a similar query plan and comparable performance for large (10TB+) tables?

This answer suggests to use the following query:

WITH cte AS (
    SELECT *, RANK() OVER (ORDER BY number) AS rnk
    FROM numbers
    WHERE number > 1
)
SELECT *
FROM cte
WHERE rnk <= 1000;

But it is not really usable for large tables because performance is many times worse.

Subquery Scan on cte  (cost=...)
  Filter: (cte.rnk <= 1000)
  ->  WindowAgg  (cost=...)
        ->  Index Scan using numbers_number_idx on numbers  (cost=...)
              Index Cond: (number > 1)

Body:
You won't get the performance of the extremely convenient WITH TIES in Postgres 13 or later. See:

Get top row(s) with highest value, with ties

But there are always options ...

Faster SQL variant

Should be faster for big tables because it avoids to rank the whole table like the simple solution in the referenced answer.

WITH cte AS (
   SELECT *, row_number() OVER (ORDER  BY number, id) AS rn  -- ORDER must match
   FROM   numbers
   WHERE  number > 1
   ORDER  BY number, id  -- tiebreaker to make it deterministic
   LIMIT  1000
   )
TABLE cte
UNION ALL
(
SELECT n.*, 1000 + row_number() OVER (ORDER BY n.id) AS rn
FROM   numbers n, (SELECT number, id FROM cte WHERE rn = 1000) AS max
WHERE  n.number = max.number
AND    n.id > max.id
ORDER  BY n.id
);

id is any UNIQUE NOT NULL column in your table that lends itself as tiebreaker, typically the PRIMARY KEY.

Sort by that additionally, which has the (maybe welcome) side effect that you get a deterministically ordered result.

Ideally, you have a multicolumn index on (number, id) for this. But it will use the existing index on just (number), too. Resulting performance depends on cardinalities and data types.

Related:

Is a composite index also good for queries on the first field?

Since the CTE query counts as one command, there is no race condition under concurrent write load. All parts of the command see the same snapshot of the table in default isolation level READ COMMITTED.

I might wrap this into a simple SQL function (or prepared statement) and pass LIMIT to it for convenience.

Alternative with PL/pgSQL

Only running a single SELECT probably outweighs the added overhead. Works optimally with the existing index on just (number):

CREATE OR REPLACE FUNCTION foo(_bound int, _limit int, OUT _row public.numbers)
  RETURNS SETOF public.numbers
  LANGUAGE plpgsql AS
$func$
DECLARE
   _ct int := 0;
   _number int;  -- match type!
BEGIN
   FOR _row IN
      SELECT *
      FROM   public.numbers
      WHERE  number > _bound
      ORDER  BY number
   LOOP
      _ct := _ct + 1;
      CASE
      WHEN _ct < _limit THEN
         -- do nothing
      WHEN _ct > _limit THEN
         EXIT WHEN _row.number > _number;
      WHEN _ct = _limit THEN
         _number := _row.number;
      END CASE;

      RETURN NEXT;
   END LOOP;
END
$func$;

But it's tailored for just the one query. Gets tedious for varying queries.


问:
How to perform a query to return the number of rows that fulfils each column criteria
I have a table called Bookings and the schema is as follows;

```<code>id | name | pizza     | country

1  | catA | pepperoni | USA
2  | catB | Sicilian  | USA
3  | catA | pepperoni | Greece
4  | catA | Sicilian  | Greece
</code>```

How can I perform a query such that it returns for me the number of rows each value in  column appear.

Example;

```<code>name
catA | 3
catB | 1

pizza
pepperoni | 2
Sicilian | 2

country:
USA | 2
Greece | 2
</code>```

答:
I believe you need to use a group by statement for this type of query. https://www.w3schools.com/sql/sql_groupby.asp

A group by statement lets you use aggregate functions such as COUNT().

```<code>SELECT name, COUNT(name) FROM Bookings GROUP BY name;

SELECT pizza, COUNT(pizza) FROM Bookings  GROUP BY pizza;

SELECT country, COUNT(country) FROM Bookings  GROUP BY country;
</code>```

If you would like the output of all queries to be in a single result:

```<code>SELECT name, COUNT(name), 'name' FROM Bookings GROUP BY name
UNION
SELECT pizza, COUNT(pizza), 'pizza' FROM Bookings  GROUP BY pizza
UNION
SELECT country, COUNT(country), 'country' FROM Bookings  GROUP BY country;
</code>```

Body:
I have a table called Bookings and the schema is as follows;

id | name | pizza     | country

1  | catA | pepperoni | USA
2  | catB | Sicilian  | USA
3  | catA | pepperoni | Greece
4  | catA | Sicilian  | Greece

How can I perform a query such that it returns for me the number of rows each value in  column appear.

Example;

name
catA | 3
catB | 1

pizza
pepperoni | 2
Sicilian | 2

country:
USA | 2
Greece | 2

Body:
I believe you need to use a group by statement for this type of query. https://www.w3schools.com/sql/sql_groupby.asp

A group by statement lets you use aggregate functions such as COUNT().

SELECT name, COUNT(name) FROM Bookings GROUP BY name;

SELECT pizza, COUNT(pizza) FROM Bookings  GROUP BY pizza;

SELECT country, COUNT(country) FROM Bookings  GROUP BY country;

If you would like the output of all queries to be in a single result:

SELECT name, COUNT(name), 'name' FROM Bookings GROUP BY name
UNION
SELECT pizza, COUNT(pizza), 'pizza' FROM Bookings  GROUP BY pizza
UNION
SELECT country, COUNT(country), 'country' FROM Bookings  GROUP BY country;


问:
Google Apps Script successfully triggers On Form Submit, but function will not execute
I'm trying to copy a row from the linked form responses sheet "main" to another sheet "sub" if a value in the form response matches a particular criteria, Column 4 = "Subset"

I have onFormSubmit set up as a trigger with Deployment - Head, Source - Spreadsheet, Event - On form submit. When I submit the form, the trigger for onFormSubmit logs the execution as Completed but the row does not copy to the "sub" sheet.

The getLast function allows me to move the row to the next available position in the "sub" sheet starting in the second column because I have checkboxes in the first column all the way down the sheet.

The code works as is when using the onEdit function and manually entering "Subset" into column 4. I can't seem to figure out why nothing happens with onFormSubmit even though the trigger is successfully executed. Please help!

```<code>function onFormSubmit(e) {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var s = e.source.getActiveSheet();
 var r = e.source.getActiveRange();

 if(s.getName() == "main" && r.getColumn() == 4 && r.getValue() == "Subset") {
  var row = r.getRow();
  var numColumns = s.getLastColumn();
  var targetSheet = ss.getSheetByName("sub");
  var column = targetSheet.getRange("B:B").getValues();
  var lastRow = getLast(column);
  var target = targetSheet.getRange(lastRow + 1, 2);
  s.getRange(row, 1, 1, numColumns).copyTo(target);
 }
}

function getLast(range){
 var rowNum = 0;
 var blank = false;
 for(var row = 0; row < range.length; row++){

  if(range[row][0] === "" && !blank){
   rowNum = row;
   blank = true;
  }else if(range[row][0] !== ""){
   blank = false;
  }
 }
 return rowNum;
}
</code>```

答:
I thought that from your question, when your script is run by OnSubmit trigger, the if statement of if(s.getName() == "main" && r.getColumn() == 4 && r.getValue() == "Subset") {} might be always false, because in this case, the range is not the column "D". By this, your script doesn't work. I thought that this might be the reason of your issue.

When the OnSubmit trigger is fired, in order to run the script in the if statement, how about the following modification?

Modified script:

function onFormSubmit(e) {
  var range = e.range;
  var sheet = range.getSheet();
  var srcRange = sheet.getRange(range.rowStart, 1, 1, sheet.getLastColumn());
  if (srcRange.getValues()[0][3] == "Subset") { // srcRange.getValues()[0][3] means the column "D".
    var targetSheet = e.source.getSheetByName("sub");
    var column = targetSheet.getRange("B:B").getValues();
    var lastRow = getLast(column);
    var target = targetSheet.getRange(lastRow + 1, 2);
    srcRange.copyTo(target);
  }
}
```

Body:
I'm trying to copy a row from the linked form responses sheet "main" to another sheet "sub" if a value in the form response matches a particular criteria, Column 4 = "Subset"

I have onFormSubmit set up as a trigger with Deployment - Head, Source - Spreadsheet, Event - On form submit. When I submit the form, the trigger for onFormSubmit logs the execution as Completed but the row does not copy to the "sub" sheet.

The getLast function allows me to move the row to the next available position in the "sub" sheet starting in the second column because I have checkboxes in the first column all the way down the sheet.

The code works as is when using the onEdit function and manually entering "Subset" into column 4. I can't seem to figure out why nothing happens with onFormSubmit even though the trigger is successfully executed. Please help!

function onFormSubmit(e) {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var s = e.source.getActiveSheet();
 var r = e.source.getActiveRange();

 if(s.getName() == "main" && r.getColumn() == 4 && r.getValue() == "Subset") {
  var row = r.getRow();
  var numColumns = s.getLastColumn();
  var targetSheet = ss.getSheetByName("sub");
  var column = targetSheet.getRange("B:B").getValues();
  var lastRow = getLast(column);
  var target = targetSheet.getRange(lastRow + 1, 2);
  s.getRange(row, 1, 1, numColumns).copyTo(target);
 }
}

function getLast(range){
 var rowNum = 0;
 var blank = false;
 for(var row = 0; row < range.length; row++){

  if(range[row][0] === "" && !blank){
   rowNum = row;
   blank = true;
  }else if(range[row][0] !== ""){
   blank = false;
  }
 }
 return rowNum;
}


问:
How to test `verify` of an express middleware in Jest
I have a function which returns a middleware as such:

const jsonParser = () => {
  return express.json({
    limit: '5mb',
    verify: (req, res, buf) => {
      // If the incoming request is a stripe event,
      if (req.headers['some-header']) {
        httpContext.set('raw-body', buf.toString());
      }
    },
  });
};
```
<p>I would like to test that the <code>httpContext.set</code>is indeed called when the <code>some-header</code> header is present.</p>
<p>My test:</p>
<pre class="lang-js prettyprint-override"><code>describe('jsonParser middleware', () => {
  it('sets the http context', async () => {
    const req = {
      headers: {
        'some-header': 'some-sig',
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        some: 'thing',
      }),
    };

    const res = {};
    const middleware = jsonParser();

    middleware(req, res, () => {});

    expect(httpContext.set).toHaveBeenCalled();
  });
});
</code>```

I have no idea how to make the test run the function passed to verify. Express docs state that the content type should be json, but nothing more. Anyone that can point me in the right direction is highly appreciated.

Thank you.

答:
as mentioned in the comments i want to give you an example of an integration test which tests the header and jsonwebtoken. i am also using the express framework but i wrote my code in JS.

this is a test for creating a forumpost in a forum i built. a middleware is checking for the token of the user so this case could be similiar to yours.

```<code>const request = require('supertest');

test('create authorized 201', async () => {
  const forumCountBefore = await ForumPost.countDocuments();
  const response = await request(app)
    .post('/api/forumPosts')
    .set({
      Authorization: `Bearer ${forumUserOne.tokens[0].token}`,
      userData: {
        userId: forumUserOneId,
        email: 'forum@controller.com',
        username: 'forum',
      },
    })
    .send(forumPost)
    .expect(201);
  expect(response.body.message).toBe('created forumPost');

  const forumCountAfter = await ForumPost.countDocuments();
  expect(forumCountBefore + 1).toBe(forumCountAfter);
});
</code>```

i am using mongoDB thats why i use ForumPost.countDocuments to count the amount of entries in the DB.

as you can see in the test i use supertest (imported as request) to send an http call. in the set block i set the authorization token. this causes the middleware to be executed in the integration test.

the test can only pass when the code of the middleware gets executed correctly so it should cover the code of your middleware.

Body:
I have a function which returns a middleware as such:

const jsonParser = () => {
  return express.json({
    limit: '5mb',
    verify: (req, res, buf) => {
      // If the incoming request is a stripe event,
      if (req.headers['some-header']) {
        httpContext.set('raw-body', buf.toString());
      }
    },
  });
};

I would like to test that the httpContext.setis indeed called when the some-header header is present.

My test:

describe('jsonParser middleware', () => {
  it('sets the http context', async () => {
    const req = {
      headers: {
        'some-header': 'some-sig',
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        some: 'thing',
      }),
    };

    const res = {};
    const middleware = jsonParser();

    middleware(req, res, () => {});

    expect(httpContext.set).toHaveBeenCalled();
  });
});

I have no idea how to make the test run the function passed to verify. Express docs state that the content type should be json, but nothing more. Anyone that can point me in the right direction is highly appreciated.

Thank you.

Body:
as mentioned in the comments i want to give you an example of an integration test which tests the header and jsonwebtoken. i am also using the express framework but i wrote my code in JS.

this is a test for creating a forumpost in a forum i built. a middleware is checking for the token of the user so this case could be similiar to yours.

const request = require('supertest');

test('create authorized 201', async () => {
  const forumCountBefore = await ForumPost.countDocuments();
  const response = await request(app)
    .post('/api/forumPosts')
    .set({
      Authorization: `Bearer ${forumUserOne.tokens[0].token}`,
      userData: {
        userId: forumUserOneId,
        email: 'forum@controller.com',
        username: 'forum',
      },
    })
    .send(forumPost)
    .expect(201);
  expect(response.body.message).toBe('created forumPost');

  const forumCountAfter = await ForumPost.countDocuments();
  expect(forumCountBefore + 1).toBe(forumCountAfter);
});

i am using mongoDB thats why i use ForumPost.countDocuments to count the amount of entries in the DB.

as you can see in the test i use supertest (imported as request) to send an http call. in the set block i set the authorization token. this causes the middleware to be executed in the integration test.

the test can only pass when the code of the middleware gets executed correctly so it should cover the code of your middleware.


问:
Member of type multiple interfaces
I am trying to declare a Property (or Function for that matter) of a type that satisfies several interfaces. I'm assuming this can't be done in C# or VB. My question is, if it makes sense to define a type that implements multiple interfaces, why cant you define a member of such?
Ex.
I can do this

```<code>interface IBar
{ String BarMember; }

interface IFoo
{ String FooMember; }

class FooBar : IBar, IFoo
{
    public string BarMember{get;set;}
    public string FooMember{get;set;}
}
</code>```

so why cant i do this

```<code>class SomeClass
{
    public {IBar, IFoo} FooBarMember {get;set;}
}
</code>```

in this case FooBar would satisfy SomeClass.FooBarMember?

The reason I need this is simply that i need a member that satisfies those interface requirements. I dont care what the actual concrete class is.
I know i can combine both of the interfaces by creating a new interface that combines both of them, but why should i have to do that?

答:
You can implementing multiple interfaces on a method using generics as follows:

```<code>     public void SetMultipleInterfaceObject<T>(T item)
     where T : IInterface1, IInterface2 {
        _multipleInterfaceObject = item;
     }

</code>```

You can store the multiple interface object as follows. I'm not sure if there is a better way to do this. If there is, I haven't found it yet:

```<code>     private object _multipleInterfaceObject;
     public IInterface1? Interface1Object => (IInterface1) _compositeInterfaceObject;
     public IInterface2? Interface2Object => (IInterface2) _compositeInterfaceObject;

</code>```

Title: Member of type multiple interfaces

Body:
I am trying to declare a Property (or Function for that matter) of a type that satisfies several interfaces. I'm assuming this can't be done in C# or VB. My question is, if it makes sense to define a type that implements multiple interfaces, why cant you define a member of such?
Ex.
I can do this

interface IBar
{ String BarMember; }

interface IFoo
{ String FooMember; }

class FooBar : IBar, IFoo
{
    public string BarMember{get;set;}
    public string FooMember{get;set;}
}

so why cant i do this

class SomeClass
{
    public {IBar, IFoo} FooBarMember {get;set;}
}

in this case FooBar would satisfy SomeClass.FooBarMember?

The reason I need this is simply that i need a member that satisfies those interface requirements. I dont care what the actual concrete class is.
I know i can combine both of the interfaces by creating a new interface that combines both of them, but why should i have to do that?

Body:
You can implementing multiple interfaces on a method using generics as follows:

     public void SetMultipleInterfaceObject<T>(T item)
     where T : IInterface1, IInterface2 {
        _multipleInterfaceObject = item;
     }

You can store the multiple interface object as follows. I'm not sure if there is a better way to do this. If there is, I haven't found it yet:

     private object _multipleInterfaceObject;
     public IInterface1? Interface1Object => (IInterface1) _compositeInterfaceObject;
     public IInterface2? Interface2Object => (IInterface2) _compositeInterfaceObject;


问:
Installing MSSQL functions in PHP
I'm trying to connect to my SQL server through PHP. Obviously using MySQL php functions do not work, how do I go about installing MSSQL functions for PHP on OSX? After exhausting google, I thought there would be a lot more tutorials are resources available which suggests to me this isn't the best way to connect to an SQL server.

Thank you in advance!

答: You need to ensure that PHP has been compiled with MySQL support, or that you have enabled the MySQL extension. You can check your PHP.ini file to determine if you need to uncomment those lines or not. Usually this is the case.</p>

Title: Installing MSSQL functions in PHP


问:
Why wont my Void Main run my public static int[] C#
I'm having a hard time understanding why my method will not execute in my void Main. I have an array for the parameter but it will not execute.

```<code>   class Program
    {
        static void Main(string[] args)
        {
            TwoSums([2, 7, 11, 15],9); //Error is here.
        }

        public static int [] TwoSums(int[] nums, int target)
        {
            for(int i = 0; i <nums.Length; i++)
            {
                for(int j = i+1; i< nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                        i,j
                     };
                }
            }
            return Array.Empty<int>();
        }
    }
</code>```

答:
Based on the code you gave, you should be getting errors similar to the following:

Compilation error (line 7, col 11): Invalid expression term '['

Compilation error (line 7, col 12): ) expected

Compilation error (line 7, col 13): ; expected

Compilation error (line 7, col 13): Invalid expression term ','

Compilation error (line 7, col 15): ; expected

... more errors ...

When you look at the line TwoSums([2, 7, 11, 15],9); what is [2, 7, 11, 15] in the context of this usage? You want it to be an array, you know it's an array, but the compiler doesn't know it's an array. You have to define your arrays in some way to let the system know, "Oh, hey, this is an array". For example, TwoSums( new [] { 2, 7, 11, 15 }, 9); might be worth trying.

Body:
I'm having a hard time understanding why my method will not execute in my void Main. I have an array for the parameter but it will not execute.

   class Program
    {
        static void Main(string[] args)
        {
            TwoSums([2, 7, 11, 15],9); //Error is here.
        }

        public static int [] TwoSums(int[] nums, int target)
        {
            for(int i = 0; i <nums.Length; i++)
            {
                for(int j = i+1; i< nums.Length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    return new int[]
                     {
                        i,j
                     };
                }
            }
            return Array.Empty<int>();
        }
    }


问:
I can't center align my image border radius with the text
How to center text with the image having border-radius of 50%, horizontally.

Below is the code:

```<code><div>
<img src="images/kristen.png" alt=""  class="box">
<span>Kristen Wu</span>
</code>```

```<code>.box{
border-radius: 50%;
display: flex;
height: 40px;
align-items: center;
text-align: center;
margin-top: 20px;
}
</code>```

答:
The easiest way to align something to centre in HTML is the center tag.
You can use that to centre anything. And the code you wrote for border radius is also correct.

PS. center is the right spelling for the code. IF you write centre, it wont work

Body:
How to center text with the image having border-radius of 50%, horizontally.

Below is the code:

Kristen Wu

.box{
border-radius: 50%;
display: flex;
height: 40px;
align-items: center;
text-align: center;
margin-top: 20px;
}


问:
Find largest set of lines which are parallel but not colinear
I have a 5 lines below with each line representing a,b,c in ax+by+c = 0

```<code>1 0 0
1 2 3
3 4 5
30 40 0
30 40 50
</code>```

I want to find the largest set of non colinear parallel lines from these lines. The result in the above case will be:-

```<code>set of 2 lines
3 4 5
30 40 0
</code>```

The brute force approach would be to go through all the possible combinations which would be O(n*(n+1)/2) and update the largest possible set after each iteration.

Is there any way to find the set size faster?

答:
A solution would be to transform the coordinates into (angle, distance from origin). Finding the largest set will then be O(nlogn).

Assuming that (a,b) are never both 0, find the distance to origin d using d = c/|(a,b)|. Then, find the angle θ using θ = atan2(b,a). You then have a list of coordinates that looks like this:

```<code>[[θ0,d0],
 [θ1,d1],
...
]
</code>```

Sort this list using θ as the key.

Remove all elements that you consider colinear given a threshold. Simply parse the list to check if some pairs of consecutive elements have approximately the same value. Do not forget to test the last element with the first element to account for 360° = 0°. If you encounter a colinear pair, remove one of the element.

Using a minimum and maximum index starting at 0, increase the maximum index until the difference between the first angle (at min index) and the last angle (at max index) pass the angle tolerance that you can accept as being parallel (do not forget to consider that 359.999° is close to 0°). If the size of the set (max index - min index) is bigger than your current best set, note it as the current best. Then, increase the minimum index by one and continue increasing the maximum index until the angle difference test fail again. Continue to do so until the minimum index reaches the end of the list and do not forget to make the maximum index wrap to 0 to consider the cases close to 0° and 360°.

To make it easier to find the elements in the user provided list, you can add the original index to the transformed list, e.g., [[θ0,d0,0],[θ1,d1,1],...].

Some implementation details to consider to avoid making it accidentally O(n^2): Removing an element from an contiguous array is O(n), so instead of removing colinear elements every time you encounter one, note the index in a separate list and recreate the array in a second pass. If you instead use a linked list, the min/max index should be replaced by iterators to avoid the O(n) random access using an index to access an element.

Body:
I have a 5 lines below with each line representing a,b,c in ax+by+c = 0

1 0 0
1 2 3
3 4 5
30 40 0
30 40 50

I want to find the largest set of non colinear parallel lines from these lines. The result in the above case will be:-

set of 2 lines
3 4 5
30 40 0

The brute force approach would be to go through all the possible combinations which would be O(n*(n+1)/2) and update the largest possible set after each iteration.

Is there any way to find the set size faster?

Body:
A solution would be to transform the coordinates into (angle, distance from origin). Finding the largest set will then be O(nlogn).

Assuming that (a,b) are never both 0, find the distance to origin d using d = c/|(a,b)|. Then, find the angle θ using θ = atan2(b,a). You then have a list of coordinates that looks like this:

[[θ0,d0],
 [θ1,d1],
...
]

Sort this list using θ as the key.

Remove all elements that you consider colinear given a threshold. Simply parse the list to check if some pairs of consecutive elements have approximately the same value. Do not forget to test the last element with the first element to account for 360° = 0°. If you encounter a colinear pair, remove one of the element.

Using a minimum and maximum index starting at 0, increase the maximum index until the difference between the first angle (at min index) and the last angle (at max index) pass the angle tolerance that you can accept as being parallel (do not forget to consider that 359.999° is close to 0°). If the size of the set (max index - min index) is bigger than your current best set, note it as the current best. Then, increase the minimum index by one and continue increasing the maximum index until the angle difference test fail again. Continue to do so until the minimum index reaches the end of the list and do not forget to make the maximum index wrap to 0 to consider the cases close to 0° and 360°.

To make it easier to find the elements in the user provided list, you can add the original index to the transformed list, e.g., [[θ0,d0,0],[θ1,d1,1],...].

Some implementation details to consider to avoid making it accidentally O(n^2): Removing an element from an contiguous array is O(n), so instead of removing colinear elements every time you encounter one, note the index in a separate list and recreate the array in a second pass. If you instead use a linked list, the min/max index should be replaced by iterators to avoid the O(n) random access using an index to access an element.


问:
What GUI tool can I use for building applications that interact with multiple APIs?
My company uses a lot of different web services on daily bases. I find that I repeat same steps over and over again on daily bases.

For example, when I start a new project, I perform the following actions:

Create a new client & project in Liquid Planner.

Create a new client Freshbooks

Create a project in Github or Codebasehq

Developers to Codebasehq or Github who are going to be working on this project

Create tasks in Ticketing system on Codebasehq and tasks in Liquid Planner

This is just when starting new projects. When I have to track tasks, it gets even trickier because I have to monitor tasks in 2 different systems.

So my question is, is there a tool that I can use to create a web service that will automate some of these interactions? Ideally, it would be something that would allow me to graphically work with the web service API and produce an executable that I can run on a server.

I don't want to build it from scratch. I know, I can do it with Python or RoR, but I don't want to get that low level.

I would like to add my sources and pass data around from one service to another. What could I use? Any suggestions?

答:
What about Apache Camel?

Camel lets you create the Enterprise Integration Patterns to implement routing and mediation rules in either a Java based Domain Specific Language (or Fluent API), via Spring based Xml Configuration files or via the Scala DSL. This means you get smart completion of routing rules in your IDE whether in your Java, Scala or XML editor.

Apache Camel uses URIs so that it can easily work directly with any kind of Transport or messaging model such as HTTP, ActiveMQ, JMS, JBI, SCA, MINA or CXF Bus API together with working with pluggable Data Format options.


答:
If the problem is always in the ts key, and this value is always a string of numbers and letters, you could just remove it before trying to parse:

```<code>import re

jstr = """[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]"""

jstr_sanitized = re.sub(r',?\s*\"ts\":[A-Z0-9]+', "", jstr)
jobj = json.loads(jstr_sanitized)

# [{'id': 'LXKhRA3RHtaVBhnczVRJLdr', 'ecc': '0X6', 'cph': 'X1X4X77074'}]
</code>```

Regex explanation (try online):

,?\s*\"ts\":[A-Z0-9]+

,?                      Zero or one commas
  \s*                   Any number of whitespace characters
     \"ts\":            Literally "ts":
            [A-Z0-9]+   One or more uppercase letters or numbers
```
<hr />
<p>Alternatively, you could catch the <code>JSONDecodeError</code> and look at its <code>pos</code> attribute for the offending character. Then, you could either remove just that character and try again, or look for the next space, comma, or bracket and remove characters until that point before you try again.</p>
```jstr = """[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]"""
while True:
    try:
        jobj = json.loads(jstr)
        break
    except json.JSONDecodeError as ex:
        jstr = jstr[:ex.pos] + jstr[ex.pos+1:]
```
<p>This mangles the output so that the <code>ts</code> key is now a valid integer (after removing the <code>X</code>s) but since you don't care about that anyway, it should be fine:</p>
```[{'id': 'LXKhRA3RHtaVBhnczVRJLdr',
  'ecc': '0X6',
  'cph': 'X1X4X77074',
  'ts': 16445656000}]
```

Since you'd end up repeatedly re-parsing the initial valid part, this is probably not a great idea if you have a huge json string, or there are lots of places that could throw an error, but it should be fine for the kind of example you have shown.

Title: How to parse invalid JSON contianing invalid number

Body:
I work with a legacy customer who sends me webhook events. Sometimes their system sends me a   value that looks like this

[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]

I am using python's json.loads to parse the data sent to me. Here the ts is an invalid number and python gives json.decoder.JSONDecodeError whenever I try to parse this string.

It is okay with me to get None in ts field if I can not parse it.

What would be a smart (& possibly generic) way to solve this problem?

Body:
If the problem is always in the ts key, and this value is always a string of numbers and letters, you could just remove it before trying to parse:

import re

jstr = """[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]"""

jstr_sanitized = re.sub(r',?\s*\"ts\":[A-Z0-9]+', "", jstr)
jobj = json.loads(jstr_sanitized)

# [{'id': 'LXKhRA3RHtaVBhnczVRJLdr', 'ecc': '0X6', 'cph': 'X1X4X77074'}]

Regex explanation (try online):

,?\s*\"ts\":[A-Z0-9]+

,?                      Zero or one commas
  \s*                   Any number of whitespace characters
     \"ts\":            Literally "ts":
            [A-Z0-9]+   One or more uppercase letters or numbers

Alternatively, you could catch the JSONDecodeError and look at its pos attribute for the offending character. Then, you could either remove just that character and try again, or look for the next space, comma, or bracket and remove characters until that point before you try again.

jstr = """[{"id":"LXKhRA3RHtaVBhnczVRJLdr","ecc":"0X6","cph":"X1X4X77074", "ts":16XX445656000}]"""
while True:
    try:
        jobj = json.loads(jstr)
        break
    except json.JSONDecodeError as ex:
        jstr = jstr[:ex.pos] + jstr[ex.pos+1:]

This mangles the output so that the ts key is now a valid integer (after removing the Xs) but since you don't care about that anyway, it should be fine:

[{'id': 'LXKhRA3RHtaVBhnczVRJLdr',
  'ecc': '0X6',
  'cph': 'X1X4X77074',
  'ts': 16445656000}]

Since you'd end up repeatedly re-parsing the initial valid part, this is probably not a great idea if you have a huge json string, or there are lots of places that could throw an error, but it should be fine for the kind of example you have shown.