问:
Execute SQL Statement stored in table column
I have insert statement in DB2 database table column and i want to execute that in store procedure

Table:

```<code>TB_SQL
(
DATA_SQL VARCHAR(12000)
)
</code>```

DATA_SQL column contains INSERT statements. for example :

SELECT * FROM TB_SQL

```<code>INSERT INTO ADDRESS (COL1, COL2)
SELECT COL1, COL2 FROM DEMO WHERE TYPE='ADDRESS'
</code>```

How to PREPARE and EXECUTE the INSERT STATEMENT from DATA_SQL Column in DB2 Store Procedure ?

Code I tried:

```<code>SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY ;
</code>```

In reality the above PREPARE AND EXECUTE will only prepare SELECT statement and execute SELECT statement.
What i want is, I want to execute the statement that comes as output from SELECT statement.

I also have below option to store the INSERT statement again in another variable

```<code>SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY INTO v_INSERT_STATEMENT;
        PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
        EXECUTE SQL_INSERT;

</code>```

I believe now i have insert statement stored in v_INSERT_STATEMENT
And again prepared SQL from variable and then executed. But this is not working.

Body:
I have insert statement in DB2 database table column and i want to execute that in store procedure

Table:

TB_SQL
(
DATA_SQL VARCHAR(12000)
)

DATA_SQL column contains INSERT statements. for example :

SELECT * FROM TB_SQL

INSERT INTO ADDRESS (COL1, COL2)
SELECT COL1, COL2 FROM DEMO WHERE TYPE='ADDRESS'

How to PREPARE and EXECUTE the INSERT STATEMENT from DATA_SQL Column in DB2 Store Procedure ?

Code I tried:

SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY ;

In reality the above PREPARE AND EXECUTE will only prepare SELECT statement and execute SELECT statement.
What i want is, I want to execute the statement that comes as output from SELECT statement.

I also have below option to store the INSERT statement again in another variable

SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY INTO v_INSERT_STATEMENT;
        PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
        EXECUTE SQL_INSERT;

I believe now i have insert statement stored in v_INSERT_STATEMENT
And again prepared SQL from variable and then executed. But this is not working.


来源: stackexchange

问:
How can I forge a DHCP Discovery packet using Bash?
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

```<code>tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap
</code>```

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

答:
Full Solution

The solution is similar to 'hacker' with the difference that the UDP Discover package will be generated manually in the shell.

The code is only intended to replace the given MAC of the network card with the form of spaces instead of colons and assigning to a variable (type in Bash):

```<code># manualy:
MAC=ab:ab:ab:ab:ab:ab; MAC=`printf "$(echo $MAC | sed 's/:/ /g')%.0s"`
# or automaticaly:
MAC=`printf "$(echo $(ifconfig -a |awk -v RS= '/eth0/' |awk '/ether/ {print($2)}') | sed 's/:/ /g')%.0s"`
# or simply type (spaces instead of colons!):
MAC="a6 a6 a6 a6 a6 a6"
</code>```

Using xxd generate a file containing the DHCPDISCOVER package ready to be sent. I use the fact that the checksum is not checked in practice by all DHCP servers. This avoids significant complications with the checksum calculation and its recording. The only element that needs to be changed is the MAC of the network card.

The site was very helpful: DHCP (in Russian)

```<code>echo -e $(echo -n -e "01 01 06 00 62 48 94 CA 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 $MAC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 63 82 53 63 35 01 01 FF") |xxd -r -p >blobfile
</code>```

For the DHCPDISCOVER packet to reach the DHCP server without distortion, it must be sent as binary data. Unfortunately, Bash receives some binary sequences as control commands.

HEX codes from 00 to 1F are the range for control characters, different depending on the system. Many of them will be interpreted by BASH, e.g. 1F, 0d etc.
Added to this are control sequences, e.g. 082008 or 610860.

MAC addresses are theoretically 16777216, they usually contain parts identifying the manufacturer and hardware.
There are more and more producers, also computers, there is also the practice of assigning imaginary or generating random MAC addresses. The chance of using control characters is therefore considerable.

This excludes the use of echo Bash*. We will use cat.

```<code>cat blobfile | nc -w1 -u -b 255.255.255.255 67
</code>```

A fragment of the result from Wireshark:

```<code>Client MAC address: ab:ab:ab:ab:ab:ab (ab:ab:ab:ab:ab:ab)
Option: (53) DHCP Message Type (Discover)
</code>```

The solution boils down to 2 lines of code using only cat and xxd and netcat assuming manually entering the MAC address in the shell.

I didn't find a way to make Bash immune to binary data without breaking it. That is why I suggest excluding it from the package sending phase  It may make sense to write the generator in C which will get rid of redirection to the file and the cat program and pack everything into 1 line. However, this is not the subject of the question.

EDIT:

The solution to the Bash problem is to install the rc shell from Plan 9. It is very small (96kB), fast, and most importantly, does not interpret binary characters as controlling. I checked on the standard version rc 1.7.4-1 Debian Linux available via apt. Now just follow the instructions below to send the correct DHCP Discover packet without using cat and the stub file, only shell and xxd and nc.

```<code>MAC='08 20 08 1f 0d ff'
echo -n -e "01 01 06 00 62 48 94 CA 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 $MAC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 63 82 53 63 35 01 01 FF" |xxd -r -p | nc -w1 -u -b 255.255.255.255 67
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to send via network (LAN) a classic DHCP Discover package using command line, in order to trigger a response from any DHCP server listening, so I could capture it with something like (say my IP address is 192.168.0.30 ):

tcpdump -i eth0 host 192.168.0.30 -n -s 0 -vvv -w listening.pcap

I think about this as a simple method to detect rogue DHCP servers on a network.

How can I do this using Bash ?

Further data:

Other tools allowed, but lets try to keep ti simple: NetCat, sed, grep... etc.

Similar example for forging WOL packet: Bash one-line command to send wake on LAN magic packet without specific tool

Body:
Full Solution

The solution is similar to 'hacker' with the difference that the UDP Discover package will be generated manually in the shell.

The code is only intended to replace the given MAC of the network card with the form of spaces instead of colons and assigning to a variable (type in Bash):

# manualy:
MAC=ab:ab:ab:ab:ab:ab; MAC=`printf "$(echo $MAC | sed 's/:/ /g')%.0s"`
# or automaticaly:
MAC=`printf "$(echo $(ifconfig -a |awk -v RS= '/eth0/' |awk '/ether/ {print($2)}') | sed 's/:/ /g')%.0s"`
# or simply type (spaces instead of colons!):
MAC="a6 a6 a6 a6 a6 a6"

Using xxd generate a file containing the DHCPDISCOVER package ready to be sent. I use the fact that the checksum is not checked in practice by all DHCP servers. This avoids significant complications with the checksum calculation and its recording. The only element that needs to be changed is the MAC of the network card.

The site was very helpful: DHCP (in Russian)

echo -e $(echo -n -e "01 01 06 00 62 48 94 CA 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 $MAC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 63 82 53 63 35 01 01 FF") |xxd -r -p >blobfile

For the DHCPDISCOVER packet to reach the DHCP server without distortion, it must be sent as binary data. Unfortunately, Bash receives some binary sequences as control commands.

HEX codes from 00 to 1F are the range for control characters, different depending on the system. Many of them will be interpreted by BASH, e.g. 1F, 0d etc.
Added to this are control sequences, e.g. 082008 or 610860.

MAC addresses are theoretically 16777216, they usually contain parts identifying the manufacturer and hardware.
There are more and more producers, also computers, there is also the practice of assigning imaginary or generating random MAC addresses. The chance of using control characters is therefore considerable.

This excludes the use of echo Bash*. We will use cat.

cat blobfile | nc -w1 -u -b 255.255.255.255 67

A fragment of the result from Wireshark:

Client MAC address: ab:ab:ab:ab:ab:ab (ab:ab:ab:ab:ab:ab)
Option: (53) DHCP Message Type (Discover)

The solution boils down to 2 lines of code using only cat and xxd and netcat assuming manually entering the MAC address in the shell.

I didn't find a way to make Bash immune to binary data without breaking it. That is why I suggest excluding it from the package sending phase  It may make sense to write the generator in C which will get rid of redirection to the file and the cat program and pack everything into 1 line. However, this is not the subject of the question.

EDIT:

The solution to the Bash problem is to install the rc shell from Plan 9. It is very small (96kB), fast, and most importantly, does not interpret binary characters as controlling. I checked on the standard version rc 1.7.4-1 Debian Linux available via apt. Now just follow the instructions below to send the correct DHCP Discover packet without using cat and the stub file, only shell and xxd and nc.

MAC='08 20 08 1f 0d ff'
echo -n -e "01 01 06 00 62 48 94 CA 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 $MAC 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 63 82 53 63 35 01 01 FF" |xxd -r -p | nc -w1 -u -b 255.255.255.255 67


问:
Issue getting my jquery dialog to open up and show
I have the following javascript function

```<code> <script type="text/javascript">
   function ShowAlert(id) {
     //  alert('I am here' + id);
       $(id).dialog('open');

   }

var dl;
$(document).ready(function () {
    //setup edit person dialog
    $('#editPerson').dialog({
        //Setting up the dialog properties.
        show: "blind",
        hide: "fold",
        resizable: false,
        modal: true,
        height: 400,
        width: 700,
        title: "Modify Member"
    });
            $("#<%=ButtonAdd.ClientID %>").click(function () {
                var dl = $("#divDlg").dialog({
                    //Setting up the dialog properties.
                    show: "blind",
                    hide: "fold",
                    resizable: false,
                    modal: true,
                    height: 400,
                    width: 700
                });
               // dl.parent().appendTo(jQuery('form:first'));
            });

    //Adding a event handler for the close button that will close the dialog
    $("a[id*=ButtonCloseDlg]").click(function (e) {
        $("#divDlg").dialog("close");
        return false;
    });

});
</code>```

In my gridviews item template for my edit button I have the following to call the function. Which works to show an alert but can't get it to show the dialog? Is it because possibly the postback happening on the grid causing it to close?

```<code>   <ItemTemplate>
       <asp:Button ID="ButtonEdit" runat="server" CausesValidation="false"
            CommandName="EditMember" OnClientClick='ShowAlert("#editPerson");'
            Text="Edit" />
   </ItemTemplate>
</code>```

Any help would be greatly appriated.

答:
I'd be very cautious about using

```<code>$("#<%=ButtonAdd.ClientID %>").click(...
</code>```

in client-side javascript code.

A better approach would be to use jQuery's "attribute ends with" selector.  Considering that ASP.Net appends your ID from the ASPX page to end of its generated HTML (try viewing the source of the page after it's loaded in the browser), this should get around it - assuming that's the problem..

ContentLicense: CC BY-SA 3.0

Body:
I'd be very cautious about using

$("#<%=ButtonAdd.ClientID %>").click(...

in client-side javascript code.

A better approach would be to use jQuery's "attribute ends with" selector.  Considering that ASP.Net appends your ID from the ASPX page to end of its generated HTML (try viewing the source of the page after it's loaded in the browser), this should get around it - assuming that's the problem..


问:
Django MySQL full text search
I need to implement full text search for my Django application, running MySQL as backend.

Let's say I've got a model as follows:

```<code>class MyItem(models.Model):
    title = models.CharField()
    short_description = models.TextField()
    description = models.TextField()
</code>```

I would like to have results first for search term occurences in title, then in short_description and at the end in description field. I'll be happier if I don't have to use additional modules/applications for this task.

答: Django provides full-text functionality for PostgreSQL's only.</p>

Title: Django MySQL full text search

Body:
I need to implement full text search for my Django application, running MySQL as backend.

Let's say I've got a model as follows:

class MyItem(models.Model):
    title = models.CharField()
    short_description = models.TextField()
    description = models.TextField()

I would like to have results first for search term occurences in title, then in short_description and at the end in description field. I'll be happier if I don't have to use additional modules/applications for this task.


问:
How to check if a string is date?
I am having string like

```<code>"11-04-2015 22:01:13:053" or "32476347656435"
</code>```

How can I check if string is Date?

Checking String if it is numeric using regex

```<code>String regex = "[0-9]+";
</code>```

答:
You can use Apache Commons Validator. It provides validation framework for validating date, time, numbers, currency, IP address, email, and URL.

Maven dependency:

```<code><dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>
</code>```

Example:

```<code>assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true))
</code>```

Title: How to check if a string is date?

Body:
I am having string like

"11-04-2015 22:01:13:053" or "32476347656435"

How can I check if string is Date?

Checking String if it is numeric using regex

String regex = "[0-9]+";

Body:
You can use Apache Commons Validator. It provides validation framework for validating date, time, numbers, currency, IP address, email, and URL.

Maven dependency:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>

Example:

assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true))


问:
Highcharts instance created in which Angular life cycle hook
I am currently using Angular 7+ with Highcharts API.

I integrated Highcharts using the following Official Github Link.

There is a callbackFunction in Highcharts which we can use to get the chart instance .
However, i am yet to figure out 2 things:

When does the actual instance of chart gets created along with the options, like in which lifecycle hook in Angular? Or is it independent of the lifecycle hooks.

I saw a developer's example in which he used the callbackFunction while inside the ngOnInit lifecycle hook and it worked ( i.e we got a chart instance from the callback ). However the same did not work for ngOnChanges hook.

So my point was that, suppose there is an @Input property related to graph data which is to be rendered by the Highcharts.chart ( like say appending a new series ), then i would have to use ngOnChanges method in order to detect changes in input property and ngOnChanges would be called before ngOnInit as per this . How would i get the chart instance then ? and how would i do an addSeries then ?

Why does addSeries work only on button click and not in ngOnInit ? Uncomment line number 59 inside hello.component.ts to see it.

Link to the code.

Please see hello.component.ts for any details.

答:
As per explanation given by @pc_coder , i removed ngOnInit, and implemented addSeries inside ngOnChanges and it worked.

```<code>export class HelloComponent implements OnChanges {
  @Input() name: string;
  @Input() newData: any;
  title = 'AngularTest';
  chartCreated;

  Highcharts: typeof Highcharts = Highcharts;
  chartCallback: Highcharts.ChartCallbackFunction;
  updateFlag: boolean = false;
  clicked:boolean = false;

  chartOptions: Highcharts.Options = {
    series: [{
      data: [1, 2, 3],
      type: 'line'
    }]
  };

  // ngOnInit(){
  //   console.log('Inside ngOnInit');
  //   this.chartCallback = (chart) => {
  //               this.chartCreated = chart;
  //               console.log('chart: ' + chart); // shows object
  //           }
  //
  // }

  ngOnChanges(){
    console.log('Inside ngOnchanges');
    this.chartCallback = (chart) => {
                this.chartCreated = chart;
                console.log('chart: ' + chart);
                this.chartCreated.addSeries(this.newData); // This worked :)
            }

  }

  onClick(){
    if(this.clicked==false){
      this.chartCreated.series[0].data[0].update(4);
      this.clicked = true;
    //this.chartCreated.addSeries(this.newData); // works on uncommenting
    }
    else{
      this.chartCreated.series[0].data[0].update(1);
      this.clicked = false;
    }
  }
}
</code>```

It supports his point that : " callback is async and does not depend on OnInit/OnChanges " and also " chart instance is created after the options for it is set ".

Body:
As per explanation given by @pc_coder , i removed ngOnInit, and implemented addSeries inside ngOnChanges and it worked.

export class HelloComponent implements OnChanges {
  @Input() name: string;
  @Input() newData: any;
  title = 'AngularTest';
  chartCreated;

  Highcharts: typeof Highcharts = Highcharts;
  chartCallback: Highcharts.ChartCallbackFunction;
  updateFlag: boolean = false;
  clicked:boolean = false;

  chartOptions: Highcharts.Options = {
    series: [{
      data: [1, 2, 3],
      type: 'line'
    }]
  };

  // ngOnInit(){
  //   console.log('Inside ngOnInit');
  //   this.chartCallback = (chart) => {
  //               this.chartCreated = chart;
  //               console.log('chart: ' + chart); // shows object
  //           }
  //
  // }

  ngOnChanges(){
    console.log('Inside ngOnchanges');
    this.chartCallback = (chart) => {
                this.chartCreated = chart;
                console.log('chart: ' + chart);
                this.chartCreated.addSeries(this.newData); // This worked :)
            }

  }

  onClick(){
    if(this.clicked==false){
      this.chartCreated.series[0].data[0].update(4);
      this.clicked = true;
    //this.chartCreated.addSeries(this.newData); // works on uncommenting
    }
    else{
      this.chartCreated.series[0].data[0].update(1);
      this.clicked = false;
    }
  }
}

It supports his point that : " callback is async and does not depend on OnInit/OnChanges " and also " chart instance is created after the options for it is set ".


问:
Result of function vs loop
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

```<code>input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715
</code>```

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

```<code>for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773
</code>```

答:
After calling return statements the function does not continue and all information is lost that has not been either returned or is not referenced by a variable outside the function scope.

The answer from Anwarvic should do the trick.

Title: Result of function vs loop

Body:
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773


问:
Removing/undoing a merge on Sourcetree
I made quite few changes in my project (I was working on a remote branch and not the master), I committed them and created a pull request on BitBucket and merged the branch to master. I had forgotten to push my changes after the commit. Now, after trying switching the current branch to my remote branch and reverting to the commit before the merge, I managed to get all my changes back and back them up elsewhere in my system. What I want to do now is undo the bad merge that I did. Each time I click on the merge and select "Reverse commit", I get the following error message:

"error: Commit  is a merge but no -m option was given.

fatal: revert failed"

The branches look like this now:

I want to remove the merge and bring it to a state such that it doesn't say master(4 behind) anymore.

答:
Follow this step by step:

REVERTING A MERGE COMMIT

Master was merged and pushed into Develop with conflicts/unwanted codes.

To revert using Sourcetree:

Select Develop, Select the last commit to which branch has to be reverted.

Right click on that branch and select “Reset develop to this commit”.

From the pop up select hard from drop down at the left bottom. Its done.

There should be no pull thereafter. If any pull occurs revert using terminal as below.

Now Merge master into develop.

To revert using Terminal:

Select Develop, Select the last commit to which branch has to be reverted.

Open terminal from the Sourcetree

type git reset --hard <commit_before_merge id long one>

If any pull count appear in the sourcetree then type git push -f,  and its done.

Merge master into develop.

Title: Removing/undoing a merge on Sourcetree


问:
Show class probabilities from Numpy array
I've had a look through and I don't think stack has an answer for this, I am fairly new at this though any help is appreciated.

I'm using an AWS Sagemaker endpoint to return a png mask and I'm trying to display the probability as a whole of each class.

So first stab does this:

```<code>np.set_printoptions(threshold=np.inf)
pred_map = np.argmax(mask, axis=0)

non_zero_mask = pred_map[pred_map != 0]) # get everything but background

# print(np.bincount(pred_map[pred_map != 0]).argmax()) # Ignore this line as it just shows the most probable

num_classes = 6
plt.imshow(pred_map, vmin=0, vmax=num_classes-1, cmap='jet')
plt.show()
</code>```

As you can see I'm removing the background pixels, now I need to show class 1,2,3,4,5 have X probability based on the number of pixels they occupy - I'm unsure if I'll reinvent the wheel by simply taking the total number of elements from the original mask then looping and counting each pixel/class number etc - are there inbuilt methods for this please?

Update:

So after typing this out had a little think and reworded some of searches and came across this.

```<code>    unique_elements, counts_elements = np.unique(pred_map[pred_map != 0], return_counts=True)
    print(np.asarray((unique_elements, counts_elements)))
#[[    2     3]
#[87430  2131]]
</code>```

So then I'd just calculate the % based on this or is there a better way? For example I'd do

```<code>87430 / 89561(total number of pixels in the mask) * 100
</code>```

Giving 2 in this case a 97% probability.

Update for Joe's comment below:

```<code>rec = Record()
recordio = mx.recordio.MXRecordIO(results_file, 'r')
protobuf = rec.ParseFromString(recordio.read())
values = list(rec.features["target"].float32_tensor.values)
shape = list(rec.features["shape"].int32_tensor.values)
shape = np.squeeze(shape)
mask = np.reshape(np.array(values), shape)
mask = np.squeeze(mask, axis=0)
</code>```

答:
My first thought was to use np.digitize and write a nice solution.

But then I realized how you can hack it in 10 lines:

```<code>import numpy as np
import matplotlib.pyplot as plt

size = (10, 10)

x = np.random.randint(0, 7, size) # your classes, seven excluded.

# empty array, filled with mask and number of occurrences.
x_filled = np.zeros_like(x)

for i in range(1, 7):

    mask = x == i
    count_mask = np.count_nonzero(mask)

    x_filled[mask] = count_mask

print(x_filled)

plt.imshow(x_filled)
plt.colorbar()
plt.show()
</code>```

I am not sure about the axis convention with imshow
at the moment, you might have to flip the y axis so up is up.

Body:
I've had a look through and I don't think stack has an answer for this, I am fairly new at this though any help is appreciated.

I'm using an AWS Sagemaker endpoint to return a png mask and I'm trying to display the probability as a whole of each class.

So first stab does this:

np.set_printoptions(threshold=np.inf)
pred_map = np.argmax(mask, axis=0)

non_zero_mask = pred_map[pred_map != 0]) # get everything but background

# print(np.bincount(pred_map[pred_map != 0]).argmax()) # Ignore this line as it just shows the most probable

num_classes = 6
plt.imshow(pred_map, vmin=0, vmax=num_classes-1, cmap='jet')
plt.show()

As you can see I'm removing the background pixels, now I need to show class 1,2,3,4,5 have X probability based on the number of pixels they occupy - I'm unsure if I'll reinvent the wheel by simply taking the total number of elements from the original mask then looping and counting each pixel/class number etc - are there inbuilt methods for this please?

Update:

So after typing this out had a little think and reworded some of searches and came across this.

    unique_elements, counts_elements = np.unique(pred_map[pred_map != 0], return_counts=True)
    print(np.asarray((unique_elements, counts_elements)))
#[[    2     3]
#[87430  2131]]

So then I'd just calculate the % based on this or is there a better way? For example I'd do

87430 / 89561(total number of pixels in the mask) * 100

Giving 2 in this case a 97% probability.

Update for Joe's comment below:

rec = Record()
recordio = mx.recordio.MXRecordIO(results_file, 'r')
protobuf = rec.ParseFromString(recordio.read())
values = list(rec.features["target"].float32_tensor.values)
shape = list(rec.features["shape"].int32_tensor.values)
shape = np.squeeze(shape)
mask = np.reshape(np.array(values), shape)
mask = np.squeeze(mask, axis=0)

Body:
My first thought was to use np.digitize and write a nice solution.

But then I realized how you can hack it in 10 lines:

import numpy as np
import matplotlib.pyplot as plt

size = (10, 10)

x = np.random.randint(0, 7, size) # your classes, seven excluded.

# empty array, filled with mask and number of occurrences.
x_filled = np.zeros_like(x)

for i in range(1, 7):

    mask = x == i
    count_mask = np.count_nonzero(mask)

    x_filled[mask] = count_mask

print(x_filled)

plt.imshow(x_filled)
plt.colorbar()
plt.show()

I am not sure about the axis convention with imshow
at the moment, you might have to flip the y axis so up is up.


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
A priority queue seems to be the best option for you.

As you can see, the pop functions has a constant complexity and the push function is logarithmic in time.


问:
type checking in javascript
How can I check if a variable is currently an integer type?  I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)</p>

答:
A clean approach

You can consider using a very small, dependency-free library like Issable. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error

// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')

define({
    primitives: 'number',
    nameOfTyping: 'integer',
    toPass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
is(4.4).custom('integer') // throws error
is(8).customer('integer') // returns true
```
<p>If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.</p>
<pre class="lang-js prettyprint-override"><code>function test (string, boolean) {
    // any of these below will throw errors to protect you
    is(string).string()
    is(boolean).boolean()

    // continue with your code.
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: type checking in javascript

Body:
A clean approach

You can consider using a very small, dependency-free library like Issable. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error

// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')

define({
    primitives: 'number',
    nameOfTyping: 'integer',
    toPass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
is(4.4).custom('integer') // throws error
is(8).customer('integer') // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    is(string).string()
    is(boolean).boolean()

    // continue with your code.
}


问:
Python, Kivy. Limit input values between two numbers with a TextInput filter
I need a TextInput filter with a minimum (1) and a maximum (100) value. The filter should allow integer only + I want to avoid: 'ValueError: could not convert string to float or int:'.

So my goal is: TextInput let numbers between 1-100 only.

I tried a few solutions like simple if-else code but it wasn't elegant, simple enough  and top of that my code become a little bit messy too.

This is why I thought I need a TextInput filter. I know there are samples on the offical site and I tried to create a filter but it seems my knowledge is not enough for that (yet).

Could you help me to solve this?

I've created a simple example:

My file .py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty

class NewTextInput(TextInput):
    input_filter = ObjectProperty('int', allownone=True)

    max_characters = 2
    def insert_text(self, substring, from_undo=False):
        if len(self.text) > self.max_characters and self.max_characters > 0:
            substring = ""
        TextInput.insert_text(self, substring, from_undo)

    #This is where I need the filter.
    #min_value = 1
    #max_value = 100
    #def insert_text(self, substring, from_undo=False):
       #...

class MyApp(App):
    def build(self):
        pass

if __name__ == '__main__':
    MyApp().run()
</code>```

My file .kv

```<code>BoxLayout:
    orientation: 'horizontal'
    Label:
        text: "Sample"
    NewTextInput:
</code>```

答:
Try this:</p>

```<code>class MyTextInput(TextInput):
    def __init__(self, **kwargs):
        super(MyTextInput, self).__init__(**kwargs)
        self.input_filter = 'int'

    def insert_text(self, substring, from_undo=False):
        if substring in string.digits:
            cc, cr = self.cursor
            text = self._lines[cr]
            new_text = text[:cc] + substring + text[cc:]
            if int(new_text) > 100:
                return
        super(MyTextInput, self).insert_text(substring, from_undo=from_undo)
</code>```

Body:
I need a TextInput filter with a minimum (1) and a maximum (100) value. The filter should allow integer only + I want to avoid: 'ValueError: could not convert string to float or int:'.

So my goal is: TextInput let numbers between 1-100 only.

I tried a few solutions like simple if-else code but it wasn't elegant, simple enough  and top of that my code become a little bit messy too.

This is why I thought I need a TextInput filter. I know there are samples on the offical site and I tried to create a filter but it seems my knowledge is not enough for that (yet).

Could you help me to solve this?

I've created a simple example:

My file .py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty

class NewTextInput(TextInput):
    input_filter = ObjectProperty('int', allownone=True)

    max_characters = 2
    def insert_text(self, substring, from_undo=False):
        if len(self.text) > self.max_characters and self.max_characters > 0:
            substring = ""
        TextInput.insert_text(self, substring, from_undo)

    #This is where I need the filter.
    #min_value = 1
    #max_value = 100
    #def insert_text(self, substring, from_undo=False):
       #...

class MyApp(App):
    def build(self):
        pass

if __name__ == '__main__':
    MyApp().run()

My file .kv

BoxLayout:
    orientation: 'horizontal'
    Label:
        text: "Sample"
    NewTextInput:

Body:
Try this:

class MyTextInput(TextInput):
    def __init__(self, **kwargs):
        super(MyTextInput, self).__init__(**kwargs)
        self.input_filter = 'int'

    def insert_text(self, substring, from_undo=False):
        if substring in string.digits:
            cc, cr = self.cursor
            text = self._lines[cr]
            new_text = text[:cc] + substring + text[cc:]
            if int(new_text) > 100:
                return
        super(MyTextInput, self).insert_text(substring, from_undo=from_undo)


问:
How to change pyplot background colour in region of interest?
I have a dataframe with a datetime index:

```<code>            A  B
date
2020-05-04  0  0
2020-05-05  5  0
2020-05-07  2  0
2020-05-09  2  0
2020-05-18 -5  0
2020-05-19 -1  0
2020-05-20  0  0
2020-05-21  1  0
2020-05-22  0  0
2020-05-23  3  0
2020-05-24  1  1
2020-05-25  0  1
2020-05-26  4  1
2020-05-27  3  1
</code>```

I want to make a lineplot to track A over time and colour the background of the plot red when the values of B are 1. I have implemented this code to make the graph:

```<code>from matplotlib import dates as mdates
from matplotlib.colors import ListedColormap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cmap = ListedColormap(['white','red'])

ax.plot(data['A'])
ax.set_xlabel('')
plt.xticks(rotation = 30)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              data['B'].values[np.newaxis],
              cmap = cmap, alpha = 0.4)
plt.axhline(y = 0, color = 'black')
plt.tight_layout()
</code>```

This gives me this graph:

But the red region incorrectly starts from 2020-05-21 rather than 2020-05-24 and it doesn't end at the end date in the dataframe. How can I alter my code to fix this?

答:
If you change ax.pcolorfast(ax.get_xlim(), ... by ax.pcolor(data.index, ... you get what you want. The problem with the current code is that by using ax.get_xlim(), it creates a uniform rectangular grid while your index is not uniform (dates are missing), so the coloredmeshed is not like expected. The whole thing is:

```<code>from matplotlib import dates as mdates
from matplotlib.colors import ListedColormap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cmap = ListedColormap(['white','red'])

fig = plt.figure()
ax = fig.add_subplot()

ax.plot(data['A'])
ax.set_xlabel('')

plt.xticks(rotation = 30)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
#here are the two changes use pcolor
ax.pcolor(data.index, #use data.index to create the proper grid
          ax.get_ylim(),
          data['B'].values[np.newaxis],
          cmap = cmap, alpha = 0.4,
          linewidth=0, antialiased=True)
plt.axhline(y = 0, color = 'black')
plt.tight_layout()
</code>```

and you get

Body:
I have a dataframe with a datetime index:

            A  B
date
2020-05-04  0  0
2020-05-05  5  0
2020-05-07  2  0
2020-05-09  2  0
2020-05-18 -5  0
2020-05-19 -1  0
2020-05-20  0  0
2020-05-21  1  0
2020-05-22  0  0
2020-05-23  3  0
2020-05-24  1  1
2020-05-25  0  1
2020-05-26  4  1
2020-05-27  3  1

I want to make a lineplot to track A over time and colour the background of the plot red when the values of B are 1. I have implemented this code to make the graph:

from matplotlib import dates as mdates
from matplotlib.colors import ListedColormap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cmap = ListedColormap(['white','red'])

ax.plot(data['A'])
ax.set_xlabel('')
plt.xticks(rotation = 30)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              data['B'].values[np.newaxis],
              cmap = cmap, alpha = 0.4)
plt.axhline(y = 0, color = 'black')
plt.tight_layout()

This gives me this graph:

But the red region incorrectly starts from 2020-05-21 rather than 2020-05-24 and it doesn't end at the end date in the dataframe. How can I alter my code to fix this?

Body:
If you change ax.pcolorfast(ax.get_xlim(), ... by ax.pcolor(data.index, ... you get what you want. The problem with the current code is that by using ax.get_xlim(), it creates a uniform rectangular grid while your index is not uniform (dates are missing), so the coloredmeshed is not like expected. The whole thing is:

from matplotlib import dates as mdates
from matplotlib.colors import ListedColormap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

cmap = ListedColormap(['white','red'])

fig = plt.figure()
ax = fig.add_subplot()

ax.plot(data['A'])
ax.set_xlabel('')

plt.xticks(rotation = 30)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
#here are the two changes use pcolor
ax.pcolor(data.index, #use data.index to create the proper grid
          ax.get_ylim(),
          data['B'].values[np.newaxis],
          cmap = cmap, alpha = 0.4,
          linewidth=0, antialiased=True)
plt.axhline(y = 0, color = 'black')
plt.tight_layout()

and you get


问:
Face Detection and extracting the faces using Bounding Box and creating a new Bitmap
How do I use the Rect rect = face.getBoundingBox() data to crop out the detected face from the bitmap and save it as a new bitmap.  Ive attempted to construct the bitmap using rect.left etc and simply display the extracted face in imageview.. but it does not seem to work.

Also, is it possible to access the faces directly?
If I understand correctly the detector creates a List of FirebaseVisionFace, what are these listings?
How does it list a face?
Is it possible to access them?

```<code>private void processFaceDetection(final Bitmap bitmap) {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);  //firebaseVisionImage is an object created from bitmap firebase uses to detect faces

        FirebaseVisionFaceDetectorOptions firebaseVisionFaceDetectorOptions  = new FirebaseVisionFaceDetectorOptions.Builder().build();

        FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(firebaseVisionFaceDetectorOptions);

        firebaseVisionFaceDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
            @Override
            public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
                int counter = 0;

                for (FirebaseVisionFace face : firebaseVisionFaces) {
                    Rect rect = face.getBoundingBox();
                    RectOverlay rectOverlay = new RectOverlay(graphicOverlay, rect);
                    graphicOverlay.add(rectOverlay);
                    Bitmap faceSaved = Bitmap.createBitmap(Math.round(Math.abs(rect.left - rect.right)), Math.round(Math.abs(rect.top - rect.bottom)), Bitmap.Config.ALPHA_8);
                    imageview.setImageBitmap(facesaved);
                    imageview.setVisibility(View.VISIBLE);
                    counter++;

                }
</code>```

答:
ANSWER:
To use the rect data, which can be gathered using rect.toShortString(), produces 4 values for left, top, right, bottom. i.e. [280,495][796,1011].  These are created by the FirebaseVisionFaceDetector and are stored in a list (List) for each detected face.

To save the bitmap data contained within different rects(faces)

```<code>for (FirebaseVisionFace face : firebaseVisionFaces) {
Rect rect = face.getBoundingBox();

Bitmap original = Bitmap.createScaledBitmap(capturedImage, cameraView.getWidth(), cameraView.getHeight(), false); //scaled bitmap created from captured image

Bitmap faceCrop = Bitmap.createBitmap(original, rect.left, rect.top, rect.width(), rect.height()); //face cropped using rect values

</code>```

faceCrop contains the face-only bitmap data contained within the parameters of the rect.

Hope this helps....

Body:
How do I use the Rect rect = face.getBoundingBox() data to crop out the detected face from the bitmap and save it as a new bitmap.  Ive attempted to construct the bitmap using rect.left etc and simply display the extracted face in imageview.. but it does not seem to work.

Also, is it possible to access the faces directly?
If I understand correctly the detector creates a List of FirebaseVisionFace, what are these listings?
How does it list a face?
Is it possible to access them?

private void processFaceDetection(final Bitmap bitmap) {
        FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);  //firebaseVisionImage is an object created from bitmap firebase uses to detect faces

        FirebaseVisionFaceDetectorOptions firebaseVisionFaceDetectorOptions  = new FirebaseVisionFaceDetectorOptions.Builder().build();

        FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(firebaseVisionFaceDetectorOptions);

        firebaseVisionFaceDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
            @Override
            public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
                int counter = 0;

                for (FirebaseVisionFace face : firebaseVisionFaces) {
                    Rect rect = face.getBoundingBox();
                    RectOverlay rectOverlay = new RectOverlay(graphicOverlay, rect);
                    graphicOverlay.add(rectOverlay);
                    Bitmap faceSaved = Bitmap.createBitmap(Math.round(Math.abs(rect.left - rect.right)), Math.round(Math.abs(rect.top - rect.bottom)), Bitmap.Config.ALPHA_8);
                    imageview.setImageBitmap(facesaved);
                    imageview.setVisibility(View.VISIBLE);
                    counter++;

                }

Body:
ANSWER:
To use the rect data, which can be gathered using rect.toShortString(), produces 4 values for left, top, right, bottom. i.e. [280,495][796,1011].  These are created by the FirebaseVisionFaceDetector and are stored in a list (List) for each detected face.

To save the bitmap data contained within different rects(faces)

for (FirebaseVisionFace face : firebaseVisionFaces) {
Rect rect = face.getBoundingBox();

Bitmap original = Bitmap.createScaledBitmap(capturedImage, cameraView.getWidth(), cameraView.getHeight(), false); //scaled bitmap created from captured image

Bitmap faceCrop = Bitmap.createBitmap(original, rect.left, rect.top, rect.width(), rect.height()); //face cropped using rect values

faceCrop contains the face-only bitmap data contained within the parameters of the rect.

Hope this helps....


问:
Return Original List using Substring in LINQ
I have the following data

```<code>ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04
</code>```

This is what I want to return:

```<code> ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04
</code>```

My approach

Get all the list of items starting with A

```<code>var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();
</code>```

use substring

```<code>var items = allItems.Select(x => x.Substring(1));
</code>```

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?

答:
This is kind of a duplicate of finding max/min of an object sequence based on a property of the object. Which is asked originally (I think) here

Building off that answer you could do something like what I've shown below.  Obviously you don't need the local methods and the one function to get the index assumes the ItemName format is stable and always 4 chars.

```<code>            MyItem[] items = new MyItem[]
            {
                new MyItem() { Id = 1, ItemName = "A100", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A400", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A500", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A600", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D100", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D900", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
            };

        Func<string,char> getKey = (name) => name[0];
        Func<char, int> toInt = (ch) => ch - '0';
        Func<string, int> getValue = (name) => (toInt(name[1]) * 100) + (toInt(name[2]) * 10) + toInt(name[3]);

        var maxA = items.Where(i => 'A' == getKey(i.ItemName)).Aggregate((m, x) => getValue(x.ItemName) > getValue(m.ItemName) ? x : m);

        Console.WriteLine(maxA.ItemName);
</code>```

Body:
I have the following data

ItemId | ItemName | ItemBy | ItemCreatedOn
  1    | A100     |  User1 |  2016-10-04
  2    | A200     |  User1 |  2016-10-04
  3    | A300     |  User1 |  2016-10-04
  4    | A400     |  User1 |  2016-10-04
  5    | A600     |  User1 |  2016-10-04
  6    | D100     |  User1 |  2016-10-04
  7    | D900     |  User1 |  2016-10-04
  8    | D200     |  User1 |  2016-10-04
  9    | D300     |  User1 |  2016-10-04

This is what I want to return:

 ItemId | ItemName | ItemBy | ItemCreatedOn
  5     | A600   |  User1 |  2016-10-04

My approach

Get all the list of items starting with A

var allItems = db.Items.Where(x.ItemName[0] == itemName[0]).ToList();

use substring

var items = allItems.Select(x => x.Substring(1));

The above returns a list of string, but I want to return a list of all the items without A so that I can use Max() on ItemName to get the record I need

How can I return the list of objects and then use Max correctly?

Body:
This is kind of a duplicate of finding max/min of an object sequence based on a property of the object. Which is asked originally (I think) here

Building off that answer you could do something like what I've shown below.  Obviously you don't need the local methods and the one function to get the index assumes the ItemName format is stable and always 4 chars.

            MyItem[] items = new MyItem[]
            {
                new MyItem() { Id = 1, ItemName = "A100", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A400", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A500", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "A600", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D100", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D900", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D200", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
                new MyItem() { Id = 1, ItemName = "D300", ItemBy = "User1", ItemCreatedOn = DateTime.Parse("2016-10-04") },
            };

        Func<string,char> getKey = (name) => name[0];
        Func<char, int> toInt = (ch) => ch - '0';
        Func<string, int> getValue = (name) => (toInt(name[1]) * 100) + (toInt(name[2]) * 10) + toInt(name[3]);

        var maxA = items.Where(i => 'A' == getKey(i.ItemName)).Aggregate((m, x) => getValue(x.ItemName) > getValue(m.ItemName) ? x : m);

        Console.WriteLine(maxA.ItemName);


问:
How to extract the last digits of strings using regular expressions?
I have a bunch of colnames

```<code>L_1_3
L_2_23
L_3_91
L_3_16
</code>```

I want to replace these colnames with new names using the last digits following the _ like this:

```<code>3
23
91
16
</code>```

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

答:
If that is the pattern that works for you for 2 digits, the only thing you would have to do is to make one of the digits optional using ?

```<code>L_\\d\\d?_
</code>```

Regex demo | R demo

If you must match the whole pattern, you could use a capturing group and use anchors to assert the start ^ and the end $ of the string and use the group in the replacement.

```<code>^L_\\d\\d?_(\\d+)$
</code>```

In parts

```
^      Start of string
L_     Match L_
\d     Match a digit
\d?    Match a digit and repeat 0 or 1 times
_      Match _
(      Capture group 1
  \d+  Match a digit and repeat 1 or more times
)      Close group
$      End of string
```

Regex demo | R demo

```<code>X <- c("L_1_3", "L_2_23", "L_3_91", "L_3_16")
gsub("^L_\\d\\d?_(\\d+)$", "\\1", X)
</code>```

Output

```<code>[1] "3"  "23" "91" "16"
</code>```

Body:
I have a bunch of colnames

L_1_3
L_2_23
L_3_91
L_3_16

I want to replace these colnames with new names using the last digits following the _ like this:

3
23
91
16

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
If that is the pattern that works for you for 2 digits, the only thing you would have to do is to make one of the digits optional using ?

L_\\d\\d?_

Regex demo | R demo

If you must match the whole pattern, you could use a capturing group and use anchors to assert the start ^ and the end $ of the string and use the group in the replacement.

^L_\\d\\d?_(\\d+)$

In parts

^      Start of string
L_     Match L_
\d     Match a digit
\d?    Match a digit and repeat 0 or 1 times
_      Match _
(      Capture group 1
  \d+  Match a digit and repeat 1 or more times
)      Close group
$      End of string

Regex demo | R demo

X <- c("L_1_3", "L_2_23", "L_3_91", "L_3_16")
gsub("^L_\\d\\d?_(\\d+)$", "\\1", X)

Output

[1] "3"  "23" "91" "16"


问:
South data migration 'instance' error when using south freeze orm
I have a south datamigration that is trying to create new objects based on data found in other models.  When trying to create a new object for the given 'destination' model I keep getting:

```<code>Cannot assign "<ContentType: ContentType object>": "Publishing.content_type" must be a "ContentType" instance.
</code>```

It seems that there is something wrong with the 'instance' when accessed via the South freeze ORM, e.g.:

```<code>ContentType = orm['contenttypes.ContentType']
content_type_kwargs = {
    'model': ContentModel._meta.module_name,
    'app_label': ContentModel._meta.app_label, }
content_type = ContentType.objects.get(**content_type_kwargs)

# further down

publishing_kwargs = {
    'site': Site.objects.get_current(),
    'publishing_type': publishing_type,
    'start': start,
    'content_type': content_type,
    'object_id': content_object.id, }

publishing = orm.Publishing(**publishing_kwargs) # Produces the error above
</code>```

Now I've verified many times that the content_type is in fact an instance of ContentType -- yet somehow django doesn't think so.

Is there a difference between the 'freezed', south orm version of the instance and the native django one?

What else might this possibly be?

答:
It's due to the way that South handles models. You must freeze any model you need to work with in your migration. The models in the app where the migration resides get frozen automatically; anything else you must freeze manually:

```<code>python manage.py schemamigration --auto yourapp --freeze contenttypes
</code>```

If you have multiple apps you need to freeze, repeat the --freeze argument as many times as necessary:

```<code>python manage.py schemamigration --auto yourapp --freeze contenttypes --freeze someotherapp ...
</code>```

One other thing. When you access these additional frozen models you have to use the old-style South API:

```<code>orm['contenttypes.contenttype'].objects.all()
</code>```

Something like orm.ContentType won't work.

Body:
I have a south datamigration that is trying to create new objects based on data found in other models.  When trying to create a new object for the given 'destination' model I keep getting:

Cannot assign "<ContentType: ContentType object>": "Publishing.content_type" must be a "ContentType" instance.

It seems that there is something wrong with the 'instance' when accessed via the South freeze ORM, e.g.:

ContentType = orm['contenttypes.ContentType']
content_type_kwargs = {
    'model': ContentModel._meta.module_name,
    'app_label': ContentModel._meta.app_label, }
content_type = ContentType.objects.get(**content_type_kwargs)

# further down

publishing_kwargs = {
    'site': Site.objects.get_current(),
    'publishing_type': publishing_type,
    'start': start,
    'content_type': content_type,
    'object_id': content_object.id, }

publishing = orm.Publishing(**publishing_kwargs) # Produces the error above

Now I've verified many times that the content_type is in fact an instance of ContentType -- yet somehow django doesn't think so.

Is there a difference between the 'freezed', south orm version of the instance and the native django one?

What else might this possibly be?

Body:
It's due to the way that South handles models. You must freeze any model you need to work with in your migration. The models in the app where the migration resides get frozen automatically; anything else you must freeze manually:

python manage.py schemamigration --auto yourapp --freeze contenttypes

If you have multiple apps you need to freeze, repeat the --freeze argument as many times as necessary:

python manage.py schemamigration --auto yourapp --freeze contenttypes --freeze someotherapp ...

One other thing. When you access these additional frozen models you have to use the old-style South API:

orm['contenttypes.contenttype'].objects.all()

Something like orm.ContentType won't work.


问:
print value of char array which is loaded with void pointer
I have below code where I am passing address of array of charectors to function "GetStr". GetStr function prototype is fixed.

Here in below code I am passing command line argument where string to function "GetStr" and update the value in the address of variable "str".

PRoblem:
At Print 1, I am getting the value what I passed from command line arguments. A Print 2 in main function, I am unable to print or get the value back. Could you please let me know how to print the value at "Print 2" statement

```<code>int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argv[1] != '\0'){
            RetVal = argv[1];
        }
        else{
            RetVal = '\0';
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}
</code>```

Driver:

```<code>int main(int argc, char **argv)
{
    char str[8];

    GetStr(str,argc,argv);

    cout<<"HH: "<<((char *)(str))<<endl;  ->>>  PRINT 2
  }
</code>```

答:
You have to use strcpy() to copy a string. You're just assigning the address of argv[1] to the local variable RetVal, which has no effect on the array in the caller.

You should also check argc to determine if argv[1] has been supplied.

```<code>int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argc >= 2){
            strcpy((char*)RetVal, argv[1]); // copy first argument
        }
        else{
            *(char*)RetVal = '\0'; // Set to empty string
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}
</code>```

Note that it's necessary to cast RetVal before indirecting through it in the assignment, because you can't dereference a void pointer.

Body:
I have below code where I am passing address of array of charectors to function "GetStr". GetStr function prototype is fixed.

Here in below code I am passing command line argument where string to function "GetStr" and update the value in the address of variable "str".

PRoblem:
At Print 1, I am getting the value what I passed from command line arguments. A Print 2 in main function, I am unable to print or get the value back. Could you please let me know how to print the value at "Print 2" statement

int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argv[1] != '\0'){
            RetVal = argv[1];
        }
        else{
            RetVal = '\0';
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}

Driver:

int main(int argc, char **argv)
{
    char str[8];

    GetStr(str,argc,argv);

    cout<<"HH: "<<((char *)(str))<<endl;  ->>>  PRINT 2
  }

Body:
You have to use strcpy() to copy a string. You're just assigning the address of argv[1] to the local variable RetVal, which has no effect on the array in the caller.

You should also check argc to determine if argv[1] has been supplied.

int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argc >= 2){
            strcpy((char*)RetVal, argv[1]); // copy first argument
        }
        else{
            *(char*)RetVal = '\0'; // Set to empty string
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}

Note that it's necessary to cast RetVal before indirecting through it in the assignment, because you can't dereference a void pointer.


问:
'File name differs from already included file name only in casing' on relative path with same casing

Error TS1149: File name 'C:/Project/frontend/scripts/State.ts' differs from already included file name '../frontend/scripts/State.ts' only in casing.

I've triple checked the casing in our references and the actual files have the correct casing as well. As far as I can tell, this is solely because the relative path uses incorrect casing, or perhaps it's just because of the relative path itself?

The thing is, it compiles just fine on Mac and Linux, but throws this error on Windows.

If it helps, forceConsistentCasingInFileNames is enabled in the tsconfig, and we're using tsify to compile.

答: For me, the issue occurred when a file was quickly renamed from someFile.ts to SomeFile.ts. Restarting my IDE (Visual Studio Code) made the warning go away.


问:
method not allowed:POST
my code show errors:

```<code>method not allowed: POST
method not allowed: /home/
</code>```

while running the server
I couldn't find where the error is and whenever I click search in my html form it again reidirects me to http://127.0.0.1:8000/home/
here is my app's  view.py

```<code>class HomePageView(TemplateView):
    template_name = 'home.html'

class ResultPageView(TemplateView):
    template_name = 'results.html'

def search(request):
    if request.method == 'POST':
        MYSearch = Searchform(request.POST)

        if form.is_valid():
            return redirect('/thanks/')
        else:
            MYSearch = Searchform()

    return render(request, 'results.html',{"MYSearch":MYSearch})
</code>```

forms.py

```<code>class Searchform(forms.Form):
    source = forms.CharField(max_length=100)
    destination = forms.CharField(max_length=100)
</code>```

urls.py

```<code>urlpatterns = [

    path('results/', ResultPageView.as_view(), name='results'),
    path('home/', HomePageView.as_view(), name='search'),
]
</code>```

edit 1

I have added my html code for the form as well

```<code><form name = "form" action = "{% url "search" %}"
    method = "POST" >{% csrf_token %}
    <div style = "max-width:470px;">
        <center>
           <input type = "text"
              placeholder = "source" name = "source" />
        </center>
    </div>
    <div style = "max-width:470px;">
        <center>
           <input type = "text"
              placeholder = "destination" name = "destination" />
        </center>
    </div>
    <button type = "submit" value = "Search" >
        <strong>Search</strong>
    </button>
</code>```

答:
Since you're using TemplateView, an automatic GET method is implemented for both the pages. But the search function is actually trying to capture a POST request for home.html. Read this on when and when not to use TemplateView:

https://www.agiliq.com/blog/2017/12/when-and-how-use-django-templateview/

If I am correct, the search function is where you're rendering your form and it only allows GET requests. So it should be,

```<code>def search(request):
    my_search = SearchForm()
    return render(request, 'home.html',{"MYSearch": my_search}) # Render the form in home page

def results(request):
    if request.method == 'POST':
        my_search = SearchForm(request.POST)
        if form.is_valid():
            return render(request, 'results.html')
</code>```

So you can get rid of both the HomePageView and ResultPageView class and set the URLs as,

```<code>path('results/', views.results, name='results')
path('home/', views.search, name='search')
</code>```

Essentially, there is an even shorter way to do this, by combining both the functions into one i.e., render the form if its a GET request and view results if it is a POST request.

```<code>def search(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SearchForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return render(request, 'result.html', # parameters to pass, if any)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})
</code>```

Then URLs would be,

```<code>path('results/', views.search(), name='results')
path('home/', views.search(), name='search')
</code>```

It is described in the official documentation.

https://docs.djangoproject.com/en/3.0/topics/forms/

You also need to change the action attribute of form in the html file.

```<code><form action="result/">
</code>```

For a full-fledged example, check this out:
https://djangobook.com/mdj2-django-forms/

Title: method not allowed:POST

Body:
my code show errors:

method not allowed: POST
method not allowed: /home/

while running the server
I couldn't find where the error is and whenever I click search in my html form it again reidirects me to http://127.0.0.1:8000/home/
here is my app's  view.py

class HomePageView(TemplateView):
    template_name = 'home.html'

class ResultPageView(TemplateView):
    template_name = 'results.html'

def search(request):
    if request.method == 'POST':
        MYSearch = Searchform(request.POST)

        if form.is_valid():
            return redirect('/thanks/')
        else:
            MYSearch = Searchform()

    return render(request, 'results.html',{"MYSearch":MYSearch})

forms.py

class Searchform(forms.Form):
    source = forms.CharField(max_length=100)
    destination = forms.CharField(max_length=100)

urls.py

urlpatterns = [

    path('results/', ResultPageView.as_view(), name='results'),
    path('home/', HomePageView.as_view(), name='search'),
]

edit 1

I have added my html code for the form as well

<form name = "form" action = "{% url "search" %}"
    method = "POST" >{% csrf_token %}

           <input type = "text"
              placeholder = "source" name = "source" />

           <input type = "text"
              placeholder = "destination" name = "destination" />

    <button type = "submit" value = "Search" >
        Search
    </button>

Body:
Since you're using TemplateView, an automatic GET method is implemented for both the pages. But the search function is actually trying to capture a POST request for home.html. Read this on when and when not to use TemplateView:

https://www.agiliq.com/blog/2017/12/when-and-how-use-django-templateview/

If I am correct, the search function is where you're rendering your form and it only allows GET requests. So it should be,

def search(request):
    my_search = SearchForm()
    return render(request, 'home.html',{"MYSearch": my_search}) # Render the form in home page

def results(request):
    if request.method == 'POST':
        my_search = SearchForm(request.POST)
        if form.is_valid():
            return render(request, 'results.html')

So you can get rid of both the HomePageView and ResultPageView class and set the URLs as,

path('results/', views.results, name='results')
path('home/', views.search, name='search')

Essentially, there is an even shorter way to do this, by combining both the functions into one i.e., render the form if its a GET request and view results if it is a POST request.

def search(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SearchForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return render(request, 'result.html', # parameters to pass, if any)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

Then URLs would be,

path('results/', views.search(), name='results')
path('home/', views.search(), name='search')

It is described in the official documentation.

https://docs.djangoproject.com/en/3.0/topics/forms/

You also need to change the action attribute of form in the html file.

<form action="result/">

For a full-fledged example, check this out:
https://djangobook.com/mdj2-django-forms/


问:
How to transform CSV rows with the same keys into hash
I have parsed the .csv file and received the following headers:

```<code>"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"
</code>```

There are values for each. I need to map it to hash dynamically in the following way:

```<code>{date => {start: value, due: value}, amount => {total: value, left: value}}
</code>```

Please, could you suggest a way. I've tried to use it as an array like:

```<code>[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
</code>```

and then

```<code>.each_slice(2)
</code>```

but after that I got stuck. Thanks in advance

答:
Given:

```<code>headers = [["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
values= [1, 2, 3, 4]
</code>```

```<code>Hash[headers.zip(values)].each_with_object({}) do |(keys, value), memo|
  pk = keys.first.downcase.to_sym
  memo[pk] ||= {}
  memo[pk][keys.last.downcase.to_sym] = value
end
</code>```

Output:

```<code>=> {:date=>{:start=>1, :due=>2}, :amount=>{:total=>3, :left=>4}}
</code>```

Body:
I have parsed the .csv file and received the following headers:

"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"

There are values for each. I need to map it to hash dynamically in the following way:

{date => {start: value, due: value}, amount => {total: value, left: value}}

Please, could you suggest a way. I've tried to use it as an array like:

[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]

and then

.each_slice(2)

but after that I got stuck. Thanks in advance

Body:
Given:

headers = [["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
values= [1, 2, 3, 4]

Hash[headers.zip(values)].each_with_object({}) do |(keys, value), memo|
  pk = keys.first.downcase.to_sym
  memo[pk] ||= {}
  memo[pk][keys.last.downcase.to_sym] = value
end

Output:

=> {:date=>{:start=>1, :due=>2}, :amount=>{:total=>3, :left=>4}}


答:
Your function should not take it's argument from a global variable.
You can define your function so that it accepts one value, and returns the caluclated result for this value.

```<code>def newvalue(input):
    value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
    return value
</code>```

You can then query it in a few different fashions :

In a loop

```<code>for i in [0.1, 0.2]:
    print(newvalue(i))
</code>```

Or via list comprehension :

```<code>inputs = [0.1,0.2]
answers = [newvalue(i) for i in inputs]

print(answers)

</code>```

Title: Result of function vs loop

Body:
My first script doesn't return the result of the whole input list, and the second one doesnt return iterable tuple. Any advice?

input= [0.1, 0.2]
def newvalue():
    for i in input:
        value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
        return value[0]
print(newvalue()) #1.8229239584193715

If I use the following script it does the work and it prints all the values which results from the input list, but the problem with this script that I can't iterate through the calculated values.

for i in input:
    value = integrate.quad(lambda i: (np.exp(-i)) / i, i, np.inf)
    print(value[0]) #1.8229239584193715
                    #1.2226505441838773

Body:
Your function should not take it's argument from a global variable.
You can define your function so that it accepts one value, and returns the caluclated result for this value.

def newvalue(input):
    value=integrate.quad(lambda i:(np.exp(-i))/i,i,np.inf)
    return value

You can then query it in a few different fashions :

In a loop

for i in [0.1, 0.2]:
    print(newvalue(i))

Or via list comprehension :

inputs = [0.1,0.2]
answers = [newvalue(i) for i in inputs]

print(answers)


问:
Combining Vectors using a Loop
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

```<code>m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)
</code>```

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

```<code>for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}
</code>```

Thanks for your help!

答:
An option with flatten

```<code>library(purrr)
mget(ls(pattern = "^m\\d+")) %>%
    flatten_dbl
#[1] 0 2 4 1 4 3
</code>```

Title: Combining Vectors using a Loop

Body:
If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

m1 = c(0, 2, 4)
m2 = c(1, 4)
m3 = (3)

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}

Thanks for your help!

Body:
An option with flatten

library(purrr)
mget(ls(pattern = "^m\\d+")) %>%
    flatten_dbl
#[1] 0 2 4 1 4 3


问:
How to get pass this error "Value cannot be null. Parameter name: entity"
```<code>        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }
</code>```

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

答:
It means that matchCaseNumber is null.

When you create matchCaseNumber you use .FirstOrDefault() which returns the first instance or the default value for that type (which is null for reference types).

In other words, your query:

```<code>from CaseNumberKey in dc.GetTable<reportsSent>()
select CaseNumberKey
</code>```

appears to be returning no data.

Body:
        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

Body:
It means that matchCaseNumber is null.

When you create matchCaseNumber you use .FirstOrDefault() which returns the first instance or the default value for that type (which is null for reference types).

In other words, your query:

from CaseNumberKey in dc.GetTable<reportsSent>()
select CaseNumberKey

appears to be returning no data.


问:
How can I use a javascript variable in css?
I'm trying to generate a grid with Javascript. The user should input a number to establish the size of the grid. If I run the code with a specific number inserted into the javascript code and css it works fine, but as soon as I change the number with a variable and use only the user input it gives me a weird grid.

Here's the code

    const container = document.querySelector(".container");

    //CREATE GRID
    function grid (size) {
        size = prompt("How many squares wide do you want your grid to be?");
        container.style.gridTemplateColumns = "repeat(7, 1ft)";
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const square = document.createElement("div");
                square.classList.add("square");
                square.style = "background-color: white; border: 1px solid black";
                container.appendChild(square);
            }
        }
    }

    grid(7);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    width: 500px;
    height: 500px;
    border: 2px dotted lightgray;

    }</code>```

```

In this case if I select 7 as the user input it works, but if I replace 7 with "size", which is the variable it doesn't

答:
You can use your var size updated from your prompt modal :

Snippet below and possible use : https://codepen.io/gc-nomade/pen/xxZxwoM

const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  size = prompt("How many squares wide do you want your grid to be?");
  container.style.gridTemplateColumns = "repeat(" + size + ", 1fr)";
  for (let i = 0; i < size; i++) {
      const square = document.createElement("div");
      square.classList.add("square");
      square.style = "background-color: white; border: 1px solid black";
      square.textContent = i;
      container.appendChild(square);

  }
}

grid(7);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: grid;
width: 500px;
}</code>```

```

here a version with css variables https://codepen.io/gc-nomade/pen/zYrYrOM

Body:
I'm trying to generate a grid with Javascript. The user should input a number to establish the size of the grid. If I run the code with a specific number inserted into the javascript code and css it works fine, but as soon as I change the number with a variable and use only the user input it gives me a weird grid.

Here's the code

    const container = document.querySelector(".container");

    //CREATE GRID
    function grid (size) {
        size = prompt("How many squares wide do you want your grid to be?");
        container.style.gridTemplateColumns = "repeat(7, 1ft)";
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const square = document.createElement("div");
                square.classList.add("square");
                square.style = "background-color: white; border: 1px solid black";
                container.appendChild(square);
            }
        }
    }

    grid(7);

    .container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    width: 500px;
    height: 500px;
    border: 2px dotted lightgray;

    }

In this case if I select 7 as the user input it works, but if I replace 7 with "size", which is the variable it doesn't

Body:
You can use your var size updated from your prompt modal :

Snippet below and possible use : https://codepen.io/gc-nomade/pen/xxZxwoM

const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  size = prompt("How many squares wide do you want your grid to be?");
  container.style.gridTemplateColumns = "repeat(" + size + ", 1fr)";
  for (let i = 0; i < size; i++) {
      const square = document.createElement("div");
      square.classList.add("square");
      square.style = "background-color: white; border: 1px solid black";
      square.textContent = i;
      container.appendChild(square);

  }
}

grid(7);

.container {
display: grid;
width: 500px;
}

<div class="container">  </div>

here a version with css variables https://codepen.io/gc-nomade/pen/zYrYrOM


问:
JProfiler: why can't I attach to running JVM?
I just downloaded JProfiler and tried to connect to a remote JVM.

When I click "OK" I get an error message saying:
"Another application is listening on port 8888. Please check your port configuration".

I also succeeded to profile this machine with 8888 with Java Mission Control (JMC). However, JMC asked me for a username and password and only then allowed the connection.

答:
JProfiler does not use JMX to connect to a profiled JVM, it uses its own protocol. Also, you can only use the attach mode in your screen shot if the profiling agent is already loaded. You would either have to start the profiled JVM with the -agentpath=... VM parameter as given by "Session->Integration Wizards->New Remote Integration" or run the command line tool bin/jpenable on the remote machine to prepare a selected process for profiling. This will tell you the port you have to connect to.

Alternatively, you can use the "quick attach" feature in the start center to connect to any remote unrprofiled JVM through SSH. Then you do not have to prepare the JVM for profiling.


问:
Custom function in function chain - To get Length of Array
I am trying to extract the length of an array while mapping it.

Here is what happens:

First I have an array of objects. Each object has a key of posts where I store the posts for that object. My code takes all the posts from all the objects and maps them to a new array so that I can show all the posts from all the objects to the user on the front end.

I'd like to show only 10 posts at a time. So I put a .slice(0, page * 10) - the variable page is controlled by a button at the bottom of the page. If the user hits the button, the page then increases the number of posts on the screen.

This all works great. BUT - I'd like to be able to count the total number of posts and only show the button when there are more posts available. Is there a way to extract the number of posts while still allowing it to map the results from this function below?

{
  bandTypes === "all"
    ? allBands
      .filter(band => {
        if (showType !== 'Show Type') {
          return band.showTypes.includes(showType)
        } else {
          return band
        }
      })
      .reduce(
        (allPosts, band) =>
          allPosts.concat(
            (band.youtube.length > 0 &&
              band.bandBio !== "n/a" &&
              band.bandGenre !== "n/a")
              ? band.posts.map((post) => ({ post, band }))
              : []
          ),
        []
      )
      .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
      .slice(0, page * 10)
      .map(({ post, band }) =>
{convertPost(post, band)}
)
    : null
}
```

It would be great if I could just put an anonymous function in there somewhere that sets the state to the length of the array.

答:
I think that trying to accomplish this without any temporary variables is not going to be very efficient and probably would be quite ugly.

I think you should first create the array of all posts and then simply use it's length inside the return of your component.

Here's an example of how I would do it:

```<code>const MyComponent = () => {
    let allPosts = []
    if (bandTypes === "all") {
        allPosts = allBands
            .filter((band) => {
                if (showType !== "Show Type") {
                    return band.showTypes.includes(showType)
                } else {
                    return band
                }
            })
            .reduce(
                (allPosts, band) =>
                    allPosts.concat(
                        band.youtube.length > 0 &&
                            band.bandBio !== "n/a" &&
                            band.bandGenre !== "n/a"
                            ? band.posts.map((post) => ({
                                  post,
                                  band,
                              }))
                            : []
                    ),
                []
            )
            .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
    }

    return (
        <div>
            {allPosts.slice(0, page * 10).map(({ post, band }) => (
                <div key={uuidv4()}>{convertPost(post, band)}</div>
            ))}
            {allPosts.length < page * 10 && <button>Show more posts</button>}
        </div>
    )
}
</code>```

(BTW using something like uuidv4 for the key isn't ideal, because React is less efficient with rendering then. It's better base the key on something that is unique to each post and doesn't change for each render, for example an id from the database or something of this sort)

Body:
I am trying to extract the length of an array while mapping it.

Here is what happens:

First I have an array of objects. Each object has a key of posts where I store the posts for that object. My code takes all the posts from all the objects and maps them to a new array so that I can show all the posts from all the objects to the user on the front end.

I'd like to show only 10 posts at a time. So I put a .slice(0, page * 10) - the variable page is controlled by a button at the bottom of the page. If the user hits the button, the page then increases the number of posts on the screen.

This all works great. BUT - I'd like to be able to count the total number of posts and only show the button when there are more posts available. Is there a way to extract the number of posts while still allowing it to map the results from this function below?

{
  bandTypes === "all"
    ? allBands
      .filter(band => {
        if (showType !== 'Show Type') {
          return band.showTypes.includes(showType)
        } else {
          return band
        }
      })
      .reduce(
        (allPosts, band) =>
          allPosts.concat(
            (band.youtube.length > 0 &&
              band.bandBio !== "n/a" &&
              band.bandGenre !== "n/a")
              ? band.posts.map((post) => ({ post, band }))
              : []
          ),
        []
      )
      .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
      .slice(0, page * 10)
      .map(({ post, band }) =>
{convertPost(post, band)}
)
    : null
}

It would be great if I could just put an anonymous function in there somewhere that sets the state to the length of the array.

Body:
I think that trying to accomplish this without any temporary variables is not going to be very efficient and probably would be quite ugly.

I think you should first create the array of all posts and then simply use it's length inside the return of your component.

Here's an example of how I would do it:

const MyComponent = () => {
    let allPosts = []
    if (bandTypes === "all") {
        allPosts = allBands
            .filter((band) => {
                if (showType !== "Show Type") {
                    return band.showTypes.includes(showType)
                } else {
                    return band
                }
            })
            .reduce(
                (allPosts, band) =>
                    allPosts.concat(
                        band.youtube.length > 0 &&
                            band.bandBio !== "n/a" &&
                            band.bandGenre !== "n/a"
                            ? band.posts.map((post) => ({
                                  post,
                                  band,
                              }))
                            : []
                    ),
                []
            )
            .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
    }

    return (
        <div>
            {allPosts.slice(0, page * 10).map(({ post, band }) => (
                <div key={uuidv4()}>{convertPost(post, band)}</div>
            ))}
            {allPosts.length < page * 10 && <button>Show more posts</button>}
        </div>
    )
}

(BTW using something like uuidv4 for the key isn't ideal, because React is less efficient with rendering then. It's better base the key on something that is unique to each post and doesn't change for each render, for example an id from the database or something of this sort)


问:
React 16.11 componentDidMount infinite loop
We have upgraded from react 16.9 to 6.11, and now we have infinite loop when side effect in componentDidMount. </p>

```<code>export class DataComponent extends PureComponent {
    componentDidMount() {
        this.props.setData({id: 'new'});
    }
    render() {
        return <Text>{this.props.data.id}</Text>
    }
}

const mamStateToProps = (state) => ({
    data: state.data
});
const mapDispatchToProps = dispatch => ({
    setData: (data) => dispatch(setDataAction(data));
});

const DataContainer = connect(mamStateToProps, mapDispatchToProps)(DataComponent);
</code>```

<p>The code is totally simple. But when it is mounting componentDidMount calling in loop until maximum call stack.
Any ideas? </p>

```<code>"react": "16.11.0",
"react-native": "0.62.2",
</code>```

答:
```<code>componentDidMount() {
    this.props.setData({id: 'new'}); //add .props
}
</code>```

Body:
We have upgraded from react 16.9 to 6.11, and now we have infinite loop when side effect in componentDidMount.

export class DataComponent extends PureComponent {
    componentDidMount() {
        this.props.setData({id: 'new'});
    }
    render() {
        return <Text>{this.props.data.id}</Text>
    }
}

const mamStateToProps = (state) => ({
    data: state.data
});
const mapDispatchToProps = dispatch => ({
    setData: (data) => dispatch(setDataAction(data));
});

const DataContainer = connect(mamStateToProps, mapDispatchToProps)(DataComponent);

The code is totally simple. But when it is mounting componentDidMount calling in loop until maximum call stack.
Any ideas?

"react": "16.11.0",
"react-native": "0.62.2",