问:
Recommendation for python library / model / data-mining tool to find patterns in number sequence
I have a long, cleaned (no duplicates in the order of appearance) sequence of integers in a pandas dataframe and I'm looking for a way to find patterns in it. The patterns i'm looking for could be described with the following parameters and possibly turn up like this:

```<code>example parameters:

A = constant increment of 10
B = constant decrement of 6
C = constant decrement of 3
D = increment of 12 if no decrement larger than 5 within sequence-block

Sequence A-B-A
Sequence D-B-A-C
</code>```

Could someone give me a hint to find the right python tool to achieve this? Recommendations for Tools for automated search of unknown patterns in sequences would be also much appreciated.
Thank you!

UPDATE:

This is the start of the sequence from where I print the constant increments in up and down order

```<code>seq  rt_up  rt_down
0      -      1
-1     1      -
0      2      -
1      3      -
2      -      1
1      -      2
0      -      3
-1     -      4
-2     -      5
-3     -      6
-4     -      7
-5     1      -
-4     2      -
-3     3      -
-2     4      -
-1     5      -
0      6      -
1      -      1
0      -      2
-1     1      -
0      -      1
-1     -      2
-2     -      3
-3     -      4
-4     -      5
-5     -      6
-6     1      -
-5     2      -
-4     3      -
-3     4      -
-2     5      -
-1     6      -
0      7      -
1      8      -
2      9      -
3      -      1
2      -      2
1      -      3
0      -      4
-1     -      5
</code>```

I tried now to bin it with pd.cut:

```<code>bins = [1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8.......
</code>```

So that i can label it like A (rt_up 6) = increment of 6, but I get an error saying:

bins must increase monotonically

I would need a solution to group it in a way that I can adjust the space between A and B in the original sequence, or just say if there's space count it as a sequence of A(rt_up x) and B (rt_down x ), or do not count it.
 To clarify this:
In the above sequence you see rt_up 1-6, then rt_down 1-2, then rt_up only 1 until it's follow by rt_down 1-6 again. The single 1 is the space

答:
I am not sure, what you mean with

D=increment of 12 if no decrement larger than 5 within sequence-block

because I don't know what is a sequence-block.

```<code>seq=[0,-1,0,1,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,0,-1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2,3,2,1,0,-1]
inc=True
counter=0
prev=seq[0]
for item in seq[1:]:
  if prev < item and inc:
    counter=counter+1
  elif prev > item and not inc:
    counter=counter+1
  elif prev < item and not inc:
    # switch from increase to decrease
    # write out letters for increase
    if counter >= 10:
      print('A', end='')
    inc=False
    counter=0
  elif prev > item and inc:
    # switch from decrease to increase
    # write out letters for decrease
    if counter >= 6:
      print('B', end='')
    elif counter >= 3:
      print('C', end='')
    inc=True
    counter=0
print('')
</code>```

For the example-sequence this would give:

CC

Body:
I have a long, cleaned (no duplicates in the order of appearance) sequence of integers in a pandas dataframe and I'm looking for a way to find patterns in it. The patterns i'm looking for could be described with the following parameters and possibly turn up like this:

example parameters:

A = constant increment of 10
B = constant decrement of 6
C = constant decrement of 3
D = increment of 12 if no decrement larger than 5 within sequence-block

Sequence A-B-A
Sequence D-B-A-C

Could someone give me a hint to find the right python tool to achieve this? Recommendations for Tools for automated search of unknown patterns in sequences would be also much appreciated.
Thank you!

UPDATE:

This is the start of the sequence from where I print the constant increments in up and down order

seq  rt_up  rt_down
0      -      1
-1     1      -
0      2      -
1      3      -
2      -      1
1      -      2
0      -      3
-1     -      4
-2     -      5
-3     -      6
-4     -      7
-5     1      -
-4     2      -
-3     3      -
-2     4      -
-1     5      -
0      6      -
1      -      1
0      -      2
-1     1      -
0      -      1
-1     -      2
-2     -      3
-3     -      4
-4     -      5
-5     -      6
-6     1      -
-5     2      -
-4     3      -
-3     4      -
-2     5      -
-1     6      -
0      7      -
1      8      -
2      9      -
3      -      1
2      -      2
1      -      3
0      -      4
-1     -      5

I tried now to bin it with pd.cut:

bins = [1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8.......

So that i can label it like A (rt_up 6) = increment of 6, but I get an error saying:

bins must increase monotonically

I would need a solution to group it in a way that I can adjust the space between A and B in the original sequence, or just say if there's space count it as a sequence of A(rt_up x) and B (rt_down x ), or do not count it.
 To clarify this:
In the above sequence you see rt_up 1-6, then rt_down 1-2, then rt_up only 1 until it's follow by rt_down 1-6 again. The single 1 is the space

Body:
I am not sure, what you mean with

D=increment of 12 if no decrement larger than 5 within sequence-block

because I don't know what is a sequence-block.

seq=[0,-1,0,1,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,0,-1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2,3,2,1,0,-1]
inc=True
counter=0
prev=seq[0]
for item in seq[1:]:
  if prev < item and inc:
    counter=counter+1
  elif prev > item and not inc:
    counter=counter+1
  elif prev < item and not inc:
    # switch from increase to decrease
    # write out letters for increase
    if counter >= 10:
      print('A', end='')
    inc=False
    counter=0
  elif prev > item and inc:
    # switch from decrease to increase
    # write out letters for decrease
    if counter >= 6:
      print('B', end='')
    elif counter >= 3:
      print('C', end='')
    inc=True
    counter=0
print('')

For the example-sequence this would give:

CC


来源: stackexchange

问:
Error code = 0x80070002 (MS Visual Studio) C++ for searching triplet data from one key element
enter image description here

How finding a map triplet pair with one element for example
(4,(?,?))
so i know that int 4 -> how can i find it because i get so much error and four hours of searching for possible solution to filter the coordinates with that key.

```<code> int k = *min_element(min1.begin(), min1.end());

 auto it = myninja.begin();
 it = find(myninja.begin(), myninja.end(), k);
 for (it = myninja.begin(); it != myninja.end(); it++) {
     p.row= (it->second).first;
     p.col = (it->second).second;
 }
</code>```

these are my declarations

```<code>vector <pair<int, pair<int, int> > > myninja;
    vector <int> min1;
</code>```

and this is where i want to put out my min for A* -> f value for minimum range to goal

```<code> int k = *min_element(min1.begin(), min1.end());
</code>```

to keep the actual value from this i want to update the start point with the minimum of f -> so i want to give the point (x,y) so i thought

```<code>vector <pair<int, pair<int, int> > > myninja;
</code>```

would be the best, but always i want to find out from which f(n) value it comes from -> error in iterator/loop or it displays me errorcode

i think i comes from the find function because maybe he can't handle a int k (which i want to search my points)

(F-Value,(x-coordinate,y-coordinate)

also this is not working

```<code>int k = *min_element(min1.begin(), min1.end());
auto result = std::find_if(myninja.begin(),myninja.end(),[k](const auto& mo){return mo.second == val; });

 //RETURN VARIABLE IF FOUND
  if (result != myninja.end())
  int foundkey = (result->second).first;
</code>```

答:
```<code>    int s = myninja.size();
    int j = min1.size();

    for (int i = 0; i < s; i++)
    {
    min1.push_back(myninja[i].first);
    }

    int mic = min1[0];

    for (int i = 0; i <j; i++)
     {
     if (min1[i] < mic)
     mic = min1[i];
     }

     cout << mic;

    for (int i = 0; i < s; i++)
    {
    if (myninja[i].first == mic) {

    // "first" and "second" are used to access
    // 1st and 2nd element of pair respectively

    p.row = myninja[i].second.first;
    p.col = myninja[i].second.second;

    q.push(objects(p.row, p.col, p.dist+1));

    cout << "Min Punkt";
    cout << " x " << p.row << " y " << p.col;

    cout << "Distanz";
    cout << p.dist;

    visit[p.row][p.col] = true;
    break;
}
}
</code>```
<p>// Finally it works but it saves now the same point again and again with the minimum of f.
// i am working on to delete or set it true so after the calculation -> get the new point with other f minimum till the goal.</p>

ContentLicense: CC BY-SA 4.0

Body:
enter image description here

How finding a map triplet pair with one element for example
(4,(?,?))
so i know that int 4 -> how can i find it because i get so much error and four hours of searching for possible solution to filter the coordinates with that key.

 int k = *min_element(min1.begin(), min1.end());

 auto it = myninja.begin();
 it = find(myninja.begin(), myninja.end(), k);
 for (it = myninja.begin(); it != myninja.end(); it++) {
     p.row= (it->second).first;
     p.col = (it->second).second;
 }

these are my declarations

vector <pair<int, pair<int, int> > > myninja;
    vector <int> min1;

and this is where i want to put out my min for A* -> f value for minimum range to goal

 int k = *min_element(min1.begin(), min1.end());

to keep the actual value from this i want to update the start point with the minimum of f -> so i want to give the point (x,y) so i thought

vector <pair<int, pair<int, int> > > myninja;

would be the best, but always i want to find out from which f(n) value it comes from -> error in iterator/loop or it displays me errorcode

i think i comes from the find function because maybe he can't handle a int k (which i want to search my points)

(F-Value,(x-coordinate,y-coordinate)

also this is not working

int k = *min_element(min1.begin(), min1.end());
auto result = std::find_if(myninja.begin(),myninja.end(),[k](const auto& mo){return mo.second == val; });

 //RETURN VARIABLE IF FOUND
  if (result != myninja.end())
  int foundkey = (result->second).first;

Body:
    int s = myninja.size();
    int j = min1.size();

    for (int i = 0; i < s; i++)
    {
    min1.push_back(myninja[i].first);
    }

    int mic = min1[0];

    for (int i = 0; i <j; i++)
     {
     if (min1[i] < mic)
     mic = min1[i];
     }

     cout << mic;

    for (int i = 0; i < s; i++)
    {
    if (myninja[i].first == mic) {

    // "first" and "second" are used to access
    // 1st and 2nd element of pair respectively

    p.row = myninja[i].second.first;
    p.col = myninja[i].second.second;

    q.push(objects(p.row, p.col, p.dist+1));

    cout << "Min Punkt";
    cout << " x " << p.row << " y " << p.col;

    cout << "Distanz";
    cout << p.dist;

    visit[p.row][p.col] = true;
    break;
}
}

// Finally it works but it saves now the same point again and again with the minimum of f.
// i am working on to delete or set it true so after the calculation -> get the new point with other f minimum till the goal.


问:
Gremlin: How to obtain outgoing edges and their target vertices in a single query
Given a set of vertices (say, for simplicity, that I start with one: G.V().hasId("something")), I want to obtain all outgoing edges and their target vertices. I know that .out() will give me all target vertices, but without the information about the edges (which have properties on them, too). On the other hand, .outE() will give me the edges but not the target vertices. Can I obtain both in a single Gremlin query?

答:
Gremlin is as much about transforming graph data as it is navigating graph data. Typically folks seem to understand the navigation first which got you to:

```<code>g.V().hasId("something").outE()
</code>```

You then need to transform those edges into the result you want - one that includes the edge data and it's adjacent vertex. One way to do that is with project():

```<code>g.V().hasId("something").outE()
  project('e','v').
    by().
    by(inV())
</code>```

Each by()-modulator supplied to project() aligns to the keys supplied as arguments. The first applies to "e" and the second to "v". The first by() is empty and is effectively by(identity()) which returns the same argument given to it (i.e. the current edge in the stream).

Body:
Gremlin is as much about transforming graph data as it is navigating graph data. Typically folks seem to understand the navigation first which got you to:

g.V().hasId("something").outE()

You then need to transform those edges into the result you want - one that includes the edge data and it's adjacent vertex. One way to do that is with project():

g.V().hasId("something").outE()
  project('e','v').
    by().
    by(inV())

Each by()-modulator supplied to project() aligns to the keys supplied as arguments. The first applies to "e" and the second to "v". The first by() is empty and is effectively by(identity()) which returns the same argument given to it (i.e. the current edge in the stream).


问:
Disable viewstate for all Label controls in web.config?
Is it possible to disable viewstate for a specific type of controls in web.config?

I know I can disable viewstate for all pages using <pages enableViewState="false">, but what if I wanted to target just all Label controls?

答:
One of the crud way, could be to iterate all controls recursively in the page and disable the view-state for label controls - obvious issue is that you need to do this early in page cycle and then in such case, you may miss the dynamically added controls.

The more elegant solution would be to create a custom control inheriting from say label control and disable the view-state (say in the constructor) - for example

```<code>public class MyLabel : System.Web.UI.WebControls
{
  Public MyLabel()
  {
    EnableViewState = false;
  }
}
</code>```

(Mind you that in a robust implementation, you should ensure that view-state is disabled before it gets saved.)

Now, you can use ASP.NET tag mapping feature to map all label controls to your label controls from web.config.

ContentLicense: CC BY-SA 3.0

Body:
One of the crud way, could be to iterate all controls recursively in the page and disable the view-state for label controls - obvious issue is that you need to do this early in page cycle and then in such case, you may miss the dynamically added controls.

The more elegant solution would be to create a custom control inheriting from say label control and disable the view-state (say in the constructor) - for example

public class MyLabel : System.Web.UI.WebControls
{
  Public MyLabel()
  {
    EnableViewState = false;
  }
}

(Mind you that in a robust implementation, you should ensure that view-state is disabled before it gets saved.)

Now, you can use ASP.NET tag mapping feature to map all label controls to your label controls from web.config.


问:
Enum.TryParse returns true for any numeric values
I'm running into a behavior I wasn't expecting when using Enum.TryParse.

If I have an enum:

```<code>public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}
</code>```

And then I pass a numeric value (as a string) into Enum.TryParse, like:

```<code>MyEnum outputEnum;
bool result = Enum.TryParse("1234", out outputEnum);
</code>```

Despite the string "1234" not being a possible value, result will come back as true, and my outputEnum will have a value of 1234.

Is there a way I can avoid this sort of behavior? I'm trying to write a function which will process arbitrary string input as an enum, and this has thrown a bit of a monkeywrench in my bad-input detection.

答:
Use it like this

```<code>bool result = Enum.TryParse("1234", out MyEnum outputEnum) && Enum.IsDefined(typeof(MyEnum), outputEnum);
</code>```

The value of result will be false but the value of outputEnum is still 1234

Body:
I'm running into a behavior I wasn't expecting when using Enum.TryParse.

If I have an enum:

public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}

And then I pass a numeric value (as a string) into Enum.TryParse, like:

MyEnum outputEnum;
bool result = Enum.TryParse("1234", out outputEnum);

Despite the string "1234" not being a possible value, result will come back as true, and my outputEnum will have a value of 1234.

Is there a way I can avoid this sort of behavior? I'm trying to write a function which will process arbitrary string input as an enum, and this has thrown a bit of a monkeywrench in my bad-input detection.

Body:
Use it like this

bool result = Enum.TryParse("1234", out MyEnum outputEnum) && Enum.IsDefined(typeof(MyEnum), outputEnum);

The value of result will be false but the value of outputEnum is still 1234


问:
Query all rows from Mysql table and store as cache
I have one table required to do some charging in my application. I am trying to load this table in a JSON struct and use it as a cache. This is my approach:

table:

```<code>CREATE TABLE `lwratecarddefinition` (
  `RATECARDID` int(10) DEFAULT NULL AUTO_INCREMENT,
  `RATECARDGROUPID`   int(10)  DEFAULT NULL,
  `SERVICEID` varchar(10) DEFAULT NULL,
  `USAGETYPEID` varchar(10) DEFAULT NULL,
  `CURRENCYCODE` varchar(4) DEFAULT NULL,
  `LEDGERID` varchar(15) DEFAULT NULL,
  `PULSE` varchar(10) DEFAULT NULL,
  `SPECIALPULSE` varchar(10) DEFAULT NULL,
  `NORMALRATE` varchar(10) DEFAULT NULL,
  `OFFPEAKSET` varchar(2) DEFAULT NULL,
  `OFFPEAKRATE` varchar(10) DEFAULT NULL,
  `PEAKRATE` varchar(10) DEFAULT NULL,
  `ONDEMANDSET` varchar(2) DEFAULT NULL,
  `ONDEMANDRATE` varchar(2) DEFAULT NULL,
   KEY `idx_lwratecarddefinition_RATECARDID` (`RATECARDID`),
   KEY `idx_lwratecarddefinition_RATECARDGROUPID` (`RATECARDGROUPID`),
   KEY `idx_lwratecarddefinition_USAGETYPEID` (`USAGETYPEID`),
   KEY `idx_lwratecarddefinition_SERVICEID` (`SERVICEID`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

main.go code snippet - ( my objective is to fetch records in every 1 min using go routine )

```<code>    // load the ratecard first
    lwratecardefinition = getRatecard()
    // update data every 1 second
    go func() {
        for {
            time.Sleep(time.Second)
            lwratecardefinition = getRatecard()
            fmt.Println(lwratecardefinition)
            }
    }()

</code>```

dbfunction.go

```<code>package main

import (
    "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

type Lwratecardefinition struct {
        Ratecardid        int    `json:"ratecardid"`
        Ratecardgroupid   int    `json:"ratecardgroupid"`
        Serviceid         int    `json:"serviceid"`
        Usagetypeid       int    `json:"usagetypeid"`
        Currencycode      int    `json:"currencycode"`
        Ledgerid          string `json:"ledgerid"`
        Pulse             int    `json:"pulse"`
        Specialpulse      int    `json:"specialpulse"`
        Normalrate        int    `json:"normalrate"`
        Offpeakset        int    `json:"offpeakset"`
        Offpeakrate       int    `json:"offpeakrate"`
        Peakrate          int    `json:"peakrate"`
        Ondemandset       int    `json:"ondemandset"`
        Ondemandrate      int    `json:"ondemandrate"`
}

var lwratecardefinition Lwratecardefinition
func getRatecard() Lwratecardefinition {
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/bcsdb")

    // if there is an error opening the connection, handle it
    if err != nil {
        panic(err.Error())
    }

    // defer the close till after the main function has finished
    // executing
    defer db.Close()

var ratecardid,ratecardgroupid,serviceid,usagetypeid,currencycode,pulse,specialpulse,normalrate,offpeakset,offpeakrate,peakrate,ondemandset,ondemandrate int
var ledgerid string

    results, err := db.Query("select ratecardid,ratecardgroupid,serviceid,usagetypeid,currencycode,ledgerid,pulse,specialpulse,normalrate,offpeakset,offpeakrate,peakrate,ondemandset,ondemandrate from lwratecarddefinition")

     if err != nil {
        panic(err.Error())
    }

    for results.Next() {
     err = results.Scan(&ratecardid,&ratecardgroupid,&serviceid,&usagetypeid,&currencycode,&ledgerid,&pulse,&specialpulse,&normalrate,&offpeakset,&offpeakrate,&peakrate,&ondemandset,&ondemandrate)

lwratecardefinition = Lwratecardefinition{Ratecardid: ratecardid, Ratecardgroupid: ratecardgroupid, Serviceid: serviceid, Usagetypeid: usagetypeid, Currencycode: currencycode, Ledgerid: ledgerid, Pulse: pulse, Specialpulse: specialpulse, Normalrate: normalrate, Offpeakset: offpeakset, Offpeakrate: offpeakrate, Peakrate: peakrate, Ondemandset: ondemandset, Ondemandrate: ondemandrate}

}
return lwratecardefinition
}
</code>```

But when I am executing the program I am only getting one row not all rows from mysql table. I need all rows to use it as a cache.
output:

```<code>{4 508 1 201 1 DATA 60 30 2 1 3 1 1 5}
</code>```

Also my final objective is to use these values to find rate and pulse.If
 Ratecardgroupid  = X value and Serviceid = Y value I want to use pulse value from same row.
Please suggest what is wrong here and if the approach is fine to reduce db calls as well logic.

答:
But when I am executing the program I am only getting one row not all rows from mysql table

Because your function only returns single Lwratecardefinition struct, value of which you override in each iteration of the loop. You want to return slice of them, something like:

```<code>func getRatecard() []Lwratecardefinition {
   ...
   var result []Lwratecardefinition
   for results.Next() {
     err = results.Scan(&ratecardid,&ratecardgroupid,&serviceid,&usagetypeid,&currencycode,&ledgerid,&pulse,&specialpulse,&normalrate,&offpeakset,&offpeakrate,&peakrate,&ondemandset,&ondemandrate)
     result = append(result, Lwratecardefinition{Ratecardid: ratecardid, Ratecardgroupid: ratecardgroupid, Serviceid: serviceid, Usagetypeid: usagetypeid, Currencycode: currencycode, Ledgerid: ledgerid, Pulse: pulse, Specialpulse: specialpulse, Normalrate: normalrate, Offpeakset: offpeakset, Offpeakrate: offpeakrate, Peakrate: peakrate, Ondemandset: ondemandset, Ondemandrate: ondemandrate})
   }

   if (results.Err() != nil) {
      // something went wrong while reading records
      ...
   }
   return result
}
</code>```

Body:
I have one table required to do some charging in my application. I am trying to load this table in a JSON struct and use it as a cache. This is my approach:

table:

CREATE TABLE `lwratecarddefinition` (
  `RATECARDID` int(10) DEFAULT NULL AUTO_INCREMENT,
  `RATECARDGROUPID`   int(10)  DEFAULT NULL,
  `SERVICEID` varchar(10) DEFAULT NULL,
  `USAGETYPEID` varchar(10) DEFAULT NULL,
  `CURRENCYCODE` varchar(4) DEFAULT NULL,
  `LEDGERID` varchar(15) DEFAULT NULL,
  `PULSE` varchar(10) DEFAULT NULL,
  `SPECIALPULSE` varchar(10) DEFAULT NULL,
  `NORMALRATE` varchar(10) DEFAULT NULL,
  `OFFPEAKSET` varchar(2) DEFAULT NULL,
  `OFFPEAKRATE` varchar(10) DEFAULT NULL,
  `PEAKRATE` varchar(10) DEFAULT NULL,
  `ONDEMANDSET` varchar(2) DEFAULT NULL,
  `ONDEMANDRATE` varchar(2) DEFAULT NULL,
   KEY `idx_lwratecarddefinition_RATECARDID` (`RATECARDID`),
   KEY `idx_lwratecarddefinition_RATECARDGROUPID` (`RATECARDGROUPID`),
   KEY `idx_lwratecarddefinition_USAGETYPEID` (`USAGETYPEID`),
   KEY `idx_lwratecarddefinition_SERVICEID` (`SERVICEID`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8

main.go code snippet - ( my objective is to fetch records in every 1 min using go routine )

    // load the ratecard first
    lwratecardefinition = getRatecard()
    // update data every 1 second
    go func() {
        for {
            time.Sleep(time.Second)
            lwratecardefinition = getRatecard()
            fmt.Println(lwratecardefinition)
            }
    }()

dbfunction.go

package main

import (
    "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

type Lwratecardefinition struct {
        Ratecardid        int    `json:"ratecardid"`
        Ratecardgroupid   int    `json:"ratecardgroupid"`
        Serviceid         int    `json:"serviceid"`
        Usagetypeid       int    `json:"usagetypeid"`
        Currencycode      int    `json:"currencycode"`
        Ledgerid          string `json:"ledgerid"`
        Pulse             int    `json:"pulse"`
        Specialpulse      int    `json:"specialpulse"`
        Normalrate        int    `json:"normalrate"`
        Offpeakset        int    `json:"offpeakset"`
        Offpeakrate       int    `json:"offpeakrate"`
        Peakrate          int    `json:"peakrate"`
        Ondemandset       int    `json:"ondemandset"`
        Ondemandrate      int    `json:"ondemandrate"`
}

var lwratecardefinition Lwratecardefinition
func getRatecard() Lwratecardefinition {
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/bcsdb")

    // if there is an error opening the connection, handle it
    if err != nil {
        panic(err.Error())
    }

    // defer the close till after the main function has finished
    // executing
    defer db.Close()

var ratecardid,ratecardgroupid,serviceid,usagetypeid,currencycode,pulse,specialpulse,normalrate,offpeakset,offpeakrate,peakrate,ondemandset,ondemandrate int
var ledgerid string

    results, err := db.Query("select ratecardid,ratecardgroupid,serviceid,usagetypeid,currencycode,ledgerid,pulse,specialpulse,normalrate,offpeakset,offpeakrate,peakrate,ondemandset,ondemandrate from lwratecarddefinition")

     if err != nil {
        panic(err.Error())
    }

    for results.Next() {
     err = results.Scan(&ratecardid,&ratecardgroupid,&serviceid,&usagetypeid,&currencycode,&ledgerid,&pulse,&specialpulse,&normalrate,&offpeakset,&offpeakrate,&peakrate,&ondemandset,&ondemandrate)

lwratecardefinition = Lwratecardefinition{Ratecardid: ratecardid, Ratecardgroupid: ratecardgroupid, Serviceid: serviceid, Usagetypeid: usagetypeid, Currencycode: currencycode, Ledgerid: ledgerid, Pulse: pulse, Specialpulse: specialpulse, Normalrate: normalrate, Offpeakset: offpeakset, Offpeakrate: offpeakrate, Peakrate: peakrate, Ondemandset: ondemandset, Ondemandrate: ondemandrate}

}
return lwratecardefinition
}

But when I am executing the program I am only getting one row not all rows from mysql table. I need all rows to use it as a cache.
output:

{4 508 1 201 1 DATA 60 30 2 1 3 1 1 5}

Also my final objective is to use these values to find rate and pulse.If
 Ratecardgroupid  = X value and Serviceid = Y value I want to use pulse value from same row.
Please suggest what is wrong here and if the approach is fine to reduce db calls as well logic.

Body:
But when I am executing the program I am only getting one row not all rows from mysql table

Because your function only returns single Lwratecardefinition struct, value of which you override in each iteration of the loop. You want to return slice of them, something like:

func getRatecard() []Lwratecardefinition {
   ...
   var result []Lwratecardefinition
   for results.Next() {
     err = results.Scan(&ratecardid,&ratecardgroupid,&serviceid,&usagetypeid,&currencycode,&ledgerid,&pulse,&specialpulse,&normalrate,&offpeakset,&offpeakrate,&peakrate,&ondemandset,&ondemandrate)
     result = append(result, Lwratecardefinition{Ratecardid: ratecardid, Ratecardgroupid: ratecardgroupid, Serviceid: serviceid, Usagetypeid: usagetypeid, Currencycode: currencycode, Ledgerid: ledgerid, Pulse: pulse, Specialpulse: specialpulse, Normalrate: normalrate, Offpeakset: offpeakset, Offpeakrate: offpeakrate, Peakrate: peakrate, Ondemandset: ondemandset, Ondemandrate: ondemandrate})
   }

   if (results.Err() != nil) {
      // something went wrong while reading records
      ...
   }
   return result
}


问:
How do I change the owner of a subscription in SQL Server Reporting Services
The previous DBA here set up some SQL Server Reporting Services Reports to run automatically and email the report to users. When he left his accaount was disabled and now they don't work. The status on the subscription reads:

Failure sending mail: The permissions granted to user
  'OURDOMAIN\old_DBA_Username' are insufficient for performing this
  operation.

Is there an easy way to change the owner, I have found the Owner field in the RS database in the subscriptions table and have though of just changing that, but don't want to break our production report service?

The other option of course is to create a new subscription and delete the old, but surly there is a better way.

答:
ntombela's solution worked for us on SSRS 2016, except that we also had to update ModifiedByID.  If we didn't, we were not able to disable/enable subscriptions.  We got a pop-up indicating that the now-disabled ID wasn't found.  The owner showed the correct username, but the Modified By entry still showed the old ID.

I wouldn't have thought it mattered, but it seemed to for us.  On the up side, we stopped seeing the SSRS log file errors like:

ERROR: Throwing Microsoft.ReportingServices.Diagnostics.Utilities.UnknownUserNameException: , Microsoft.ReportingServices.Diagnostics.Utilities.UnknownUserNameException: The user or group name 'AD Domain\olddisabledusername' is not recognized.

OwnerDisplayName: KiwiNige


问:
Add a new rule to .htaccess whitout overwrite https server rule
I have a problem when I try to add a new rule to my .htaccess. On my server I activated a rule which redirects http to https and it works fine but when I add a new rule to my .htaccess then https disappears.

My .htaccess

```<code><IfModule mod_rewrite.c>

Options -Indexes

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/

</IfModule>
</code>```

I need to redirect every request to index.php (mvc) and it should work together with https.

I tried deactivating the redirection from the server and to write everything into my .htaccess like this:

```<code>Options -Indexes

RewriteEngine on

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/
</code>```

But I get the error The page isn't redirecting properly. How to fix it? Thank you.

答:
I've finally solved it with the help of my internet provider. This is the final code:</p>

```<code>RewriteEngine on
RewriteBase /

# force https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^www.
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# redirect to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/
</code>```

Body:
I have a problem when I try to add a new rule to my .htaccess. On my server I activated a rule which redirects http to https and it works fine but when I add a new rule to my .htaccess then https disappears.

My .htaccess

<IfModule mod_rewrite.c>

Options -Indexes

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/

</IfModule>

I need to redirect every request to index.php (mvc) and it should work together with https.

I tried deactivating the redirection from the server and to write everything into my .htaccess like this:

Options -Indexes

RewriteEngine on

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/

But I get the error The page isn't redirecting properly. How to fix it? Thank you.

Body:
I've finally solved it with the help of my internet provider. This is the final code:

RewriteEngine on
RewriteBase /

# force https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP_HOST} ^www.
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# redirect to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L]

ErrorDocument 404 https://%{HTTP_HOST}/
ErrorDocument 403 https://%{HTTP_HOST}/


问:
HTML Hamburger - how to form proper X
I'm trying to build an animated hamburger using css. To do so I use three different span and animate on click - nothing special.

But somehow the transform-origin whatsoever is messed up, hence I can't form a proper X. How can I do so?

let active = false;

const handleNav = () => {
  const hamburger = document.querySelector(".hamburger");
  if (!active) {
    hamburger.classList.add("is-active");
  } else {
    hamburger.classList.remove("is-active");
  }

  active = !active;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hamburger {
  width: 25px;
  cursor: pointer;
}

span {
    display: block;
    width: 100%;
    height: 2px;
    background-color: black;
    margin-bottom: 4px;
    transform-origin: 0 50%;
    transition: all 0.3s;
}

span:last-child {
  margin-bottom: 0;
}

.is-active span:first-child {
  transform: rotate(45deg);
}

.is-active span:nth-child(2) {
  width: 0;
}

.is-active span:last-child {
  transform: rotate(-45deg);
}</code>```

```

答:
One way is to hide the hamburger and display close icon.

Other way is to calculate the width required to make a perfect close icon and set width when active. Here width is around 17.
See the below code.

let active = false;

const handleNav = () => {
  const hamburger = document.querySelector(".hamburger");
  if (!active) {
    hamburger.classList.add("is-active");
  } else {
    hamburger.classList.remove("is-active");
  }

  active = !active;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hamburger {
  width: 25px;
  cursor: pointer;
}

span {
    display: block;
    width: 100%;
    height: 2px;
    background-color: black;
    margin-bottom: 4px;
    transform-origin: 0 50%;
    transition: all 0.3s;
}

span:last-child {
  margin-bottom: 0;
}

.is-active span:first-child {
  transform: rotate(45deg);
  width: 17px
}

.is-active span:nth-child(2) {
  width: 0;
}

.is-active span:last-child {
  transform: rotate(-45deg);
  width: 17px
}</code>```

```

Title: HTML Hamburger - how to form proper X

Body:
I'm trying to build an animated hamburger using css. To do so I use three different span and animate on click - nothing special.

But somehow the transform-origin whatsoever is messed up, hence I can't form a proper X. How can I do so?

let active = false;

const handleNav = () => {
  const hamburger = document.querySelector(".hamburger");
  if (!active) {
    hamburger.classList.add("is-active");
  } else {
    hamburger.classList.remove("is-active");
  }

  active = !active;
}

.hamburger {
  width: 25px;
  cursor: pointer;
}

span {
    display: block;
    width: 100%;
    height: 2px;
    background-color: black;
    margin-bottom: 4px;
    transform-origin: 0 50%;
    transition: all 0.3s;
}

span:last-child {
  margin-bottom: 0;
}

.is-active span:first-child {
  transform: rotate(45deg);
}

.is-active span:nth-child(2) {
  width: 0;
}

.is-active span:last-child {
  transform: rotate(-45deg);
}

Body:
One way is to hide the hamburger and display close icon.

Other way is to calculate the width required to make a perfect close icon and set width when active. Here width is around 17.
See the below code.

let active = false;

const handleNav = () => {
  const hamburger = document.querySelector(".hamburger");
  if (!active) {
    hamburger.classList.add("is-active");
  } else {
    hamburger.classList.remove("is-active");
  }

  active = !active;
}

.hamburger {
  width: 25px;
  cursor: pointer;
}

span {
    display: block;
    width: 100%;
    height: 2px;
    background-color: black;
    margin-bottom: 4px;
    transform-origin: 0 50%;
    transition: all 0.3s;
}

span:last-child {
  margin-bottom: 0;
}

.is-active span:first-child {
  transform: rotate(45deg);
  width: 17px
}

.is-active span:nth-child(2) {
  width: 0;
}

.is-active span:last-child {
  transform: rotate(-45deg);
  width: 17px
}

<div class="hamburger" onclick="handleNav()">
    <span></span>
    <span></span>
    <span></span>
</div>


问:
"Dependent features configured but no package ID was set." When creating a new module Android
I am trying to create a new module. Elements of this module should be visible to the first module.That is why I add implementation project(":messanger") to Build.gradle(:app) but it gives the following error:

```<code>Dependent features configured but no package ID was set.
Execution failed for task ':app:processDebugResources'.
A failure occurred while executing
com.android.build.gradle.internal.tasks.Workers$ActionFacade
AAPT2 aapt2-4.0.0-beta01-6051327-linux Daemon #0: Unexpected error during link, attempting
 to
stop daemon.
 This should not happen under normal circumstances, please file an issue if it does.
</code>```

答:
I integrate the present Reedy answer, stressing that two different plugins must be used for app and modules.

if you move to a buildSrc approach (highly suggested) you should declare two different variables in:
buildSrc/src/main/java/dependencies.kt

```<code>object Plugins {

   const val androidApplication    = "com.android.application"
   const val androidLibrary        = "com.android.library"
}
</code>```

and use them properly in app and mymodule build.gradle

:app

```<code>plugins {
    id(Plugins.androidApplication)
     .......

}
</code>```

and

:mymodule

```<code>plugins {
    id(Plugins.androidLibrary)
     .........
}
</code>```

Body:
I am trying to create a new module. Elements of this module should be visible to the first module.That is why I add implementation project(":messanger") to Build.gradle(:app) but it gives the following error:

Dependent features configured but no package ID was set.
Execution failed for task ':app:processDebugResources'.
A failure occurred while executing
com.android.build.gradle.internal.tasks.Workers$ActionFacade
AAPT2 aapt2-4.0.0-beta01-6051327-linux Daemon #0: Unexpected error during link, attempting
 to
stop daemon.
 This should not happen under normal circumstances, please file an issue if it does.

Body:
I integrate the present Reedy answer, stressing that two different plugins must be used for app and modules.

if you move to a buildSrc approach (highly suggested) you should declare two different variables in:
buildSrc/src/main/java/dependencies.kt

object Plugins {

   const val androidApplication    = "com.android.application"
   const val androidLibrary        = "com.android.library"
}

and use them properly in app and mymodule build.gradle

:app

plugins {
    id(Plugins.androidApplication)
     .......

}

and

:mymodule

plugins {
    id(Plugins.androidLibrary)
     .........
}


问:
Open draft email with signature
I am trying to open an email with Powershell as a draft, which already has a signature displayed.

Is there any way to display the body and signature in the email? There is also often pictures in the signatures so would like to bring them across too if possible.

```<code>$Outlook = New-Object -ComObject Outlook.Application

$Mail = $Outlook.CreateItem(0)
$Mail.To = "my_email@outlook.com"
$Mail.Subject = "Show my signature"
$body = "<body>Test body `r`n`n</body>"
$temp = $mail.body
$mail.htmlbody=get-content $env:appdata\Microsoft\Signatures\*.htm

$mail.body= $text +$mail.body + $temp

$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()
</code>```

EDIT Solution was to add body after .Display()

```<code>$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()

$body = "<body>Test body <br><br></body>"
$mail.HTMLbody = $body + $mail.HTMLbody

</code>```

答:
Outlook inserts the signature when you call the Display method. If the signature is not added then you don't have any signature set for the account under which the item is going to be sent. It seems you didn't set up a correct account that has the property set up by using the SendUsingAccount property.

The signatures are being kept as separate files in the Signatures folder. You can find this folder in the following location;

Windows XP

```<code>C:\Documents and Settings\%username%\Application Data\Microsoft\Signatures

</code>```

Windows Vista, Windows 7, Windows 8 and Windows 10

```<code>C:\Users\%username%\AppData\Roaming\Microsoft\Signatures
</code>```

So, you can read the file content and modify the HTMLBody property.

Title: Open draft email with signature

Body:
I am trying to open an email with Powershell as a draft, which already has a signature displayed.

Is there any way to display the body and signature in the email? There is also often pictures in the signatures so would like to bring them across too if possible.

$Outlook = New-Object -ComObject Outlook.Application

$Mail = $Outlook.CreateItem(0)
$Mail.To = "my_email@outlook.com"
$Mail.Subject = "Show my signature"
$body = "Test body `r`n`n"
$temp = $mail.body
$mail.htmlbody=get-content $env:appdata\Microsoft\Signatures\*.htm

$mail.body= $text +$mail.body + $temp

$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()

EDIT Solution was to add body after .Display()

$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()

$body = "Test body

"
$mail.HTMLbody = $body + $mail.HTMLbody

Body:
Outlook inserts the signature when you call the Display method. If the signature is not added then you don't have any signature set for the account under which the item is going to be sent. It seems you didn't set up a correct account that has the property set up by using the SendUsingAccount property.

The signatures are being kept as separate files in the Signatures folder. You can find this folder in the following location;

Windows XP

C:\Documents and Settings\%username%\Application Data\Microsoft\Signatures

Windows Vista, Windows 7, Windows 8 and Windows 10

C:\Users\%username%\AppData\Roaming\Microsoft\Signatures

So, you can read the file content and modify the HTMLBody property.


问:
Is there a C++ preprocessor directive or similar that I can use to convert units
I am doing a bit of motor control, and instead of saying 39553 encoder ticks, it would be easier for my human brain to say 6.5 inches.  I would like to save processor overhead by converting this at compile time.  Is there a way to do this with preprocessor directives or templates maybe?  Thanks.</p>

答:
You can use user defined literals. For example, here's the implementation for centimeters to the unit meters:

```<code>struct meter {
    double value;
};

constexpr auto operator"" _cm(double cm) -> meter
{
    return meter{cm / 100.0};
}

constexpr auto operator"" _mm(double mm) -> meter
{
    return meter{mm / 1000.0};
}
</code>```

Then use it like this:

```<code>auto length1 = 50_cm;
auto length2 = 500_mm;

std::cout << length1.value + length2.value; // prints 1
</code>```

Body:
You can use user defined literals. For example, here's the implementation for centimeters to the unit meters:

struct meter {
    double value;
};

constexpr auto operator"" _cm(double cm) -> meter
{
    return meter{cm / 100.0};
}

constexpr auto operator"" _mm(double mm) -> meter
{
    return meter{mm / 1000.0};
}

Then use it like this:

auto length1 = 50_cm;
auto length2 = 500_mm;

std::cout << length1.value + length2.value; // prints 1


问:
Razor foreach placing property/variable name in id,name and *for attributes in rendered HTML
Tools & Pltaform: ASP.NET Core MVC 3.1, Visual Studio 2019, Win 10

Update: It's an Upsert view.
I'm trying to loop through properties of the model in Razor page to generate labels and input HTML elements inside the form tag, but the rendered HTML has the "Item" (the name of the variable in foreach) as the value for id, name and *for HTML attributes.

Rendered HTML in browser

```<code><div class="form-group row">
  <div class="col-3">
    <label for="item">item</label>
  </div>
  <div class="col-6">
    <input class="form-control" type="text" id="item" name="item" value="Author">
    <span class="text-danger field-validation-valid" data-valmsg-for="item" data-valmsg-replace="true"></span>
  </div>
</div>
</code>```

HTML displayed in the browser

Razor foreach loop producing the HTML

```<code> @{ var propList = new string[] { "Name", "Author", "ISBN" };}
 @foreach (var item in propList)
    {
        <div class="form-group row">
            <div class="col-3">
                <label asp-for="@item"></label>
            </div>
            <div class="col-6">
                <input asp-for="@item" class="form-control" />
                <span asp-validation-for="@item" class="text-danger"></span>
            </div>
        </div>
    }
</code>```

Can someone explain why this is happening?

Update:

Based on '@Ben Sampica' suggestions, I have made these changes,
How would my view look like, I mean I remember using Model List for a table like view (I have used ASP.NET MVC a few years back, now jumping to .net core), here are the changes I have made,

View:

```<code>@foreach (var book in Model.Books)
  {
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@book.Name"></label>
      </div>
      <div class="col-6">
        <input asp-for="@book.Name" class="form-control" />
        <span asp-validation-for="@book.Name" class="text-danger"></span>
      </div>
    </div>
  }
</code>```

I'm using the exact View model as you described "BooksViewModel"

I haven't stated that in the question before but to be clear I'm creating an Upsert view, so now the ViewModel is a list although I'm only concerned with a single record at a time, the view model is empty on create action because there is no data in the list.

答:
If you look at the Microsoft Docs on ASP.NET Core Tag Helpers you'll see that asp-for on a  will grab the [Display] attribute off the property (if present). As a backup, it'll use the property name. In your case, you're passing in an string collection, so let's dive into what the Razor is seeing

```<code>PropList[]
{
    string item = "Name"
    string item = "Author"
    string item = "ISBN"
}
</code>```

When this is iterated on, there's no Display property, so from our rules above, what's the convention? Using the property name (which you named item in your iterator).

I think what you're trying to do might be better accomplished in a dedicated model class such as:

```<code>public class BookViewModel
{
   public string Name { get; set; }
   public string Author { get; set; }
   public string ISBN { get; set; }
}
</code>```

then on your view

```<code>@using BookViewModel

<form>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.Name"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.Name" class="form-control" />
        <span asp-validation-for="@Model.Name" class="text-danger"></span>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.Author"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.Author" class="form-control" />
        <span asp-validation-for="@Model.Author" class="text-danger"></span>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.ISBN"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.ISBN" class="form-control" />
        <span asp-validation-for="@Model.ISBN" class="text-danger"></span>
      </div>
    </div>
    <button type="submit">Submit</button>
</form>
</code>```

Update Response:

Below response is from the chat conversation b/w the op and the Answer poster

If I was making this, I'd just make two actions (Add & Edit) and share a partial view for the form inputs so that the code is reused as much as possible - while not getting too clever with the solution with this upsert. That's just my opinion. I think this was part of why I was having trouble understanding what you were looking for.

I also wouldn't use things like a reflection to write HTML. If you want to reuse the general layout of a type of input (like a textbox), at most I'd make a view component and pass the property. I would not @foreach an entire model - how would you determine what a dropdown is? What about a checkbox? You'll get yourself in a really bad spot quickly with clever solutions that are unmaintainable.

Finally,

If you STILL want to proceed - you were on the right track originally with reflection - see the following dotnet fiddle. Ignore the compiler warning and copy the @foreach block into your own project.

Foreach on the View Model

Body:
Tools & Pltaform: ASP.NET Core MVC 3.1, Visual Studio 2019, Win 10

Update: It's an Upsert view.
I'm trying to loop through properties of the model in Razor page to generate labels and input HTML elements inside the form tag, but the rendered HTML has the "Item" (the name of the variable in foreach) as the value for id, name and *for HTML attributes.

Rendered HTML in browser

    item

    <input class="form-control" type="text" id="item" name="item" value="Author">

HTML displayed in the browser

Razor foreach loop producing the HTML

 @{ var propList = new string[] { "Name", "Author", "ISBN" };}
 @foreach (var item in propList)
    {

                <input asp-for="@item" class="form-control" />

    }

Can someone explain why this is happening?

Update:

Based on '@Ben Sampica' suggestions, I have made these changes,
How would my view look like, I mean I remember using Model List for a table like view (I have used ASP.NET MVC a few years back, now jumping to .net core), here are the changes I have made,

View:

@foreach (var book in Model.Books)
  {

        <input asp-for="@book.Name" class="form-control" />

  }

I'm using the exact View model as you described "BooksViewModel"

I haven't stated that in the question before but to be clear I'm creating an Upsert view, so now the ViewModel is a list although I'm only concerned with a single record at a time, the view model is empty on create action because there is no data in the list.

Body:
If you look at the Microsoft Docs on ASP.NET Core Tag Helpers you'll see that asp-for on a <label> will grab the [Display] attribute off the property (if present). As a backup, it'll use the property name. In your case, you're passing in an string collection, so let's dive into what the Razor is seeing

PropList[]
{
    string item = "Name"
    string item = "Author"
    string item = "ISBN"
}

When this is iterated on, there's no Display property, so from our rules above, what's the convention? Using the property name (which you named item in your iterator).

I think what you're trying to do might be better accomplished in a dedicated model class such as:

public class BookViewModel
{
   public string Name { get; set; }
   public string Author { get; set; }
   public string ISBN { get; set; }
}

then on your view

@using BookViewModel

<form>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.Name"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.Name" class="form-control" />
        <span asp-validation-for="@Model.Name" class="text-danger"></span>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.Author"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.Author" class="form-control" />
        <span asp-validation-for="@Model.Author" class="text-danger"></span>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-3">
        <label asp-for="@Model.ISBN"></label>
      </div>
      <div class="col-6">
        <input asp-for="@Model.ISBN" class="form-control" />
        <span asp-validation-for="@Model.ISBN" class="text-danger"></span>
      </div>
    </div>
    <button type="submit">Submit</button>
</form>

Update Response:

Below response is from the chat conversation b/w the op and the Answer poster

If I was making this, I'd just make two actions (Add & Edit) and share a partial view for the form inputs so that the code is reused as much as possible - while not getting too clever with the solution with this upsert. That's just my opinion. I think this was part of why I was having trouble understanding what you were looking for.

I also wouldn't use things like a reflection to write HTML. If you want to reuse the general layout of a type of input (like a textbox), at most I'd make a view component and pass the property. I would not @foreach an entire model - how would you determine what a dropdown is? What about a checkbox? You'll get yourself in a really bad spot quickly with clever solutions that are unmaintainable.

Finally,

If you STILL want to proceed - you were on the right track originally with reflection - see the following dotnet fiddle. Ignore the compiler warning and copy the @foreach block into your own project.

Foreach on the View Model


问:
R frequency tables using a sequence over a collection
I have this collection

```<code>x <- c(3,4,5,7,7,9,9,9,10,10,10,10,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,15,15)
</code>```

And I want to get the frequencies of each value of the sequence 3:15 within that collection. If I do  table(x) it gives me the frequencies of the existing values, but for example, the value 6 would have a frequency value of 0 and is not shown with table().

答:
Use factor with levels in table.

```<code>table(factor(x, levels = 3:15))

# 3  4  5  6  7  8  9 10 11 12 13 14 15
# 1  1  1  0  2  0  3  4  7 10 14  3  2
</code>```

Or for a general case :

```<code>table(factor(x, levels = min(x):max(x)))
</code>```

Body:
I have this collection

x <- c(3,4,5,7,7,9,9,9,10,10,10,10,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,15,15)

And I want to get the frequencies of each value of the sequence 3:15 within that collection. If I do  table(x) it gives me the frequencies of the existing values, but for example, the value 6 would have a frequency value of 0 and is not shown with table().

Body:
Use factor with levels in table.

table(factor(x, levels = 3:15))

# 3  4  5  6  7  8  9 10 11 12 13 14 15
# 1  1  1  0  2  0  3  4  7 10 14  3  2

Or for a general case :

table(factor(x, levels = min(x):max(x)))


问:
Solving the algorithm question using javascript
I don't know how to think about a question. Since I know the people here are much more experienced and guiding, I would like to ask you. I'd appreciate it if you could solve the problem and explain it. Question:

"Think that you have an unlimited number of carrots, but limited number of carrot types. Also, you have one bag that can hold a limited weight. Each type of carrot has a weight and a price. Write a function that takes carrotTypes and capacity and return the maximum value the bag can hold."

I'm not sure I fully understand the question and understand how I can do it. I'd be very happy if you could help me.

let carrotTypes = [{
    price: 100,
    kg: 2
  },
  {
    price: 120,
    kg: 4
  },
  {
    price: 80,
    kg: 7
  }
];

let bagCapacity = 36; //kg

getMaxValue(carrotTypes, bagCapacity)

function getMaxValue(carrotTypes, capacity) {

  carrotTypes.forEach(carrot => {
     console.log(carrot);
  });

}```

答:
You could take a brute force method and get all possible vcombinations and return the one with the smallest total.

The result is a bag which the count of items of the same index of the given data.

function getMaxValue(data, target) {
    function iter(index, bag, weight, total) {
        if (weight > target) return;
        if (weight === target) {
            if (!result || total < result.total) result = { bag, weight, total };
            return;
        }
        let temp = [...bag];
        temp[index]++;
        iter(index, temp, weight + data[index].kg, total + data[index].price);
        if (++index >= data.length) return;
        iter(index, bag, weight, total);
    }

    var result;
    iter(0, data.map(_ => 0), 0, 0);
    return result;
}

let carrotTypes = [{ price: 100, kg: 2 }, { price: 120, kg: 4 }, { price: 80, kg: 7 }],
    bagCapacity = 36,
    bag = getMaxValue(carrotTypes, bagCapacity);

console.log(bag);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could take a brute force method and get all possible vcombinations and return the one with the smallest total.

The result is a bag which the count of items of the same index of the given data.

function getMaxValue(data, target) {
    function iter(index, bag, weight, total) {
        if (weight > target) return;
        if (weight === target) {
            if (!result || total < result.total) result = { bag, weight, total };
            return;
        }
        let temp = [...bag];
        temp[index]++;
        iter(index, temp, weight + data[index].kg, total + data[index].price);
        if (++index >= data.length) return;
        iter(index, bag, weight, total);
    }

    var result;
    iter(0, data.map(_ => 0), 0, 0);
    return result;
}

let carrotTypes = [{ price: 100, kg: 2 }, { price: 120, kg: 4 }, { price: 80, kg: 7 }],
    bagCapacity = 36,
    bag = getMaxValue(carrotTypes, bagCapacity);

console.log(bag);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How can I "think OOP" when using R?
I am a statistics graduate student who works a lot with R.  I am familiar with OOP in other programming contexts.  I even see its use in various statistical packages that define new classes for storing data.

At this stage in my graduate career, I am usually coding some algorithm for some class assignment--something that takes in raw data and gives some kind of output.  I would like to make it easier to reuse code, and establish good coding habits, especially before I move on to more involved research.  Please offer some advice on how to "think OOP" when doing statistical programming in R.

答:
I would argue that you shouldn't. Try to think about R in terms of a workflow. There's some useful workflow suggestions on this page:

Workflow for statistical analysis and report writing

Another important consideration is line-by-line analysis vs. reproducible research. There's a good discussion here:

writing functions vs. line-by-line interpretation in an R workflow

Title: How can I "think OOP" when using R?


问:
How to sum the value from dynamic nested array field and create a object for per input field
I am trying to develop a number grading system for a course using Angular 8. The real scenario is quite complex, so I separated the part and created a new project to explain where I have the problem. If you look at the image you will get an idea, what I am trying to accomplish. Assume this is the grade form of one course. For a course, there can have different exams. Students who are enrolled in this course, they will attend those specific exams for this course and then teacher will submit the number using this form. Suppose, for the first row first column (Mid Exam), the form should not allow you to provide more than 25 marks or less than zero. If you put 20 on the Mid Exam field then Total will show 20, GP will show 0.00, Grade will show F. Then if you put 30 on the Final exam field, Total value will be updated to 50, GP will be updated to 0.00 and will be updated to F. Again if you put 40 on the Assessment field,  Total value will be updated to 90, GP will be updated to 4.00 and will be updated to A. Same thing will be happened to for all the row. If you click on the Save button, numbers will be submitted.

Now I am describing the code that I tried and my problem, here studentList,  examList and gradePointList array will populate the data for a course from backend service. I created populateSomeDemoData method to generate this data. studentList is an array of the Student object which contains students' id and name. examList is an array of the Exam object which contains exam id, exam name and total marks of this exam. gradePointList contains the range of the number of letter grade and grade point. Suppose if the total mark is between 90 (minimumNumber) and 100 (maximumNumber) the grade point will be 4.00 and letter grade will be A. I tried to create a form gradeForm and applied a loop on examList for per row to create input field. But for this, I couldn't able to access the specific field using form control that's why I failed to calculate total marks and grade point for a row. Also for the same reason, I failed to create the list of Grade object which will be sent to the backend. Grade is the object of every field which will contain student, exam and number. If a field is updated, this grade object will also be updated. If Save button triggers, this number list will be passed to the backend.

HTML part is:

```<code><form [formGroup]="gradeForm" (ngSubmit)="saveGrade()">
  <table>
    <thead>
    <tr>
      <th> #</th>
      <th>Student</th>
      <th *ngFor="let exam of examList">{{exam.name}} ({{exam.marks}}%)</th>
      <th>Total</th>
      <th>GP</th>
      <th>Grade</th>
    </tr>
    </thead>

    <tbody>
    <tr *ngFor="let student of studentList; let i = index">
      <th> {{ i + 1 }} </th>
      <th> {{ student.id }} <br/> {{student.name}} </th>
      <th *ngFor="let grade of gradeFields.controls; let j = index" formArrayName="gradeFields">
        <input type="number" [formControlName]="j">
      </th>
      <th>??</th>
      <th>??</th>
      <th>??</th>
    </tr>
    </tbody>
  </table>

  <div class="wrapper">
    <button class="button">Save Grade</button>
  </div>
</form>
</code>```

TypeScript Part is:

```<code>export class AppComponent {

  public gradeForm: FormGroup;

  // This arrays will populate dynamically from the database
  public examList: Exam[] = [];
  public studentList: Student[] = [];
  public gradePointList: GradePoint[] = [];
  public gradeList: Grade[] = [];

  constructor(private formBuilder: FormBuilder) {

    this.populateSomeDemoData();

    this.createGradeForm();
  }

  createGradeForm(): void {
    this.gradeForm = this.formBuilder.group({
      gradeFields: this.formBuilder.array([
        this.formBuilder.control('')
      ])
    });

    for (let i = 0; i < this.examList.length - 1; i++) {
      this.gradeFields.push(this.formBuilder.control(''));
    }
  }

  get gradeFields() {
    return this.gradeForm.get('gradeFields') as FormArray;
  }

  saveGrade(): void {
    console.log(this.gradeForm.get('gradeFields').value);
    console.log(this.gradeList);
    console.log('Grade List Saved');
  }

  populateSomeDemoData(): void {
    // Static value for populating arrays for easy explanation
    const midTerm = new Exam();
    midTerm.id = '1';
    midTerm.name = 'Mid Exam';
    midTerm.marks = 25;

    const finalExam = new Exam();
    finalExam.id = '2';
    finalExam.name = 'Final Exam';
    finalExam.marks = 30;

    const assessmentExam = new Exam();
    assessmentExam.id = '3';
    assessmentExam.name = 'Assessment';
    assessmentExam.marks = 40;

    const attendance = new Exam();
    attendance.id = '4';
    attendance.name = 'Attendance';
    attendance.marks = 5;

    this.examList.push(midTerm);
    this.examList.push(finalExam);
    this.examList.push(assessmentExam);
    this.examList.push(attendance);

    // Static value for populating arrays for easy explanation
    const student1 = new Student();
    student1.id = '14101561';
    student1.name = 'Petey Cruiser';

    const student2 = new Student();
    student2.id = '14112201';
    student2.name = 'Bob Frapples';

    const student3 = new Student();
    student3.id = '14112202';
    student3.name = 'Paul Molive';

    const student4 = new Student();
    student4.id = '16113004';
    student4.name = 'Anna Mull';

    const student5 = new Student();
    student5.id = '16113005';
    student5.name = 'Gail Forcewind';

    this.studentList.push(student1);
    this.studentList.push(student2);
    this.studentList.push(student3);
    this.studentList.push(student4);
    this.studentList.push(student5);

    // Static value for populating arrays for easy explanation
    const aGradePoint = new GradePoint();
    aGradePoint.minimumNumber = 90;
    aGradePoint.maximumNumber = 100;
    aGradePoint.gradePoint = 4;
    aGradePoint.letterGrade = 'A';

    const bGradePoint = new GradePoint();
    bGradePoint.minimumNumber = 80;
    bGradePoint.maximumNumber = 89;
    bGradePoint.gradePoint = 3.5;
    bGradePoint.letterGrade = 'B';

    const cGradePoint = new GradePoint();
    cGradePoint.minimumNumber = 70;
    cGradePoint.maximumNumber = 79;
    cGradePoint.gradePoint = 3;
    cGradePoint.letterGrade = 'C';

    const dGradePoint = new GradePoint();
    dGradePoint.minimumNumber = 60;
    dGradePoint.maximumNumber = 69;
    dGradePoint.gradePoint = 2.5;
    dGradePoint.letterGrade = 'D';

    const fGradePoint = new GradePoint();
    fGradePoint.minimumNumber = 0;
    fGradePoint.maximumNumber = 59;
    fGradePoint.gradePoint = 0;
    fGradePoint.letterGrade = 'F';
    this.gradePointList.push(aGradePoint);
    this.gradePointList.push(bGradePoint);
    this.gradePointList.push(cGradePoint);
    this.gradePointList.push(dGradePoint);
    this.gradePointList.push(fGradePoint);
  }
}

export class Student {
  public id: string;
  public name: string;

  constructor(student?) {
    student = student || {};
    this.id = student.id || null;
    this.name = student.name || null;
  }
}

export class Exam {
  public id: string;
  public name: string;
  public marks: number;

  constructor(exam?) {
    exam = exam || {};
    this.id = exam.id || null;
    this.name = exam.name || null;
    this.marks = exam.marks || 0;
  }
}

export class GradePoint {
  public minimumNumber: number;
  public maximumNumber: number;
  public gradePoint: number;
  public letterGrade: string;

  constructor(gradePoint?) {
    gradePoint = gradePoint || {};
    this.minimumNumber = gradePoint.minimumNumber || 0;
    this.maximumNumber = gradePoint.maximumNumber || 59;
    this.gradePoint = gradePoint.gradePoint || 0;
    this.letterGrade = gradePoint.letterGrade || 'F';
  }
}

export class Grade {
  public student: Student;
  public exam: Exam;
  public number: number;

  constructor(grade?) {
    grade = grade || {};
    this.student = grade.student || null;
    this.exam = grade.exam || null;
    this.number = grade.number || null;
  }
}
</code>```

I have created a StackBlitz for better understanding of the code. Please click on this link to view the code. Click here

I saw a lot of post which is related to Form Arrays but my scenario is quite different. Here I don't have any Add button to push array or calculate the values. And there are fixed forms for all cases. But in my case, the array also will be generated from the list because examList is dynamic.

I assume I have problem with creating on the form or my approaches are wrong. Please help me to accomplish my objective generate total marks and creating Grade list. It would be appreciated. Thanks in advance.

答:
Thanks to Munzer. He gave me idea and show me a sample. I solved the problem completely according to his answer. Since I solved it completely, I am sharing the details if it helps someone. To solve the problem, I created the form dynamically. For each student, I made a group and created a  form control for each exam. Then I loop through multiple student lists and again I loop through the marks fields of each student group and add form control. You will get the clear idea from createGradeForm method. Here is the StackBlitz link:  https://stackblitz.com/edit/grade-upload-9nnr8p

TS File:

```<code>export class AppComponent {

    public gradeForm: FormGroup;

    // This arrays will populate dynamically from the database
    public examList: Exam[] = [];
    public studentList: Student[] = [];
    public gradePointList: GradePoint[] = [];

    constructor(private formBuilder: FormBuilder) {
        this.populateSomeDemoData();
        this.createGradeForm();
    }

    private createGradeForm(): void {
        this.gradeForm = this.formBuilder.group({});

        this.studentList.forEach(student => {
            this.gradeForm.addControl(student.id, this.formBuilder.array([]));
            this.examList.forEach(exam => {
                const grade: Grade = new Grade();
                grade.student = student;
                grade.exam = exam;
                grade.number = 0; // Replace the number if previously saved

                const studentGrades: FormArray = this.gradeForm.get(student.id) as FormArray;
                studentGrades.push(this.createGradeFormGroup(grade));
            });
        });
    }

    createGradeFormGroup(grade: Grade): FormGroup {
        return this.formBuilder.group({
            student: [grade.student, [Validators.required]],
            exam: [grade.exam, [Validators.required]],
            number: [grade.number, [Validators.required, Validators.min(-1), Validators.max(grade.exam.marks)]]
        });
    }

    getMaxNumberValue(index: number): number {
        if (this.examList[index]) {
            return this.examList[index].marks;
        }
        return 0;
    }

    getTotalNumber(studentId: string): number {
        let totalNumber = 0;

        const studentWiseGradeList: any[] = this.gradeForm.getRawValue();
        if (studentWiseGradeList && studentWiseGradeList[studentId]) {
            studentWiseGradeList[studentId].forEach(grade => {
                if (grade.student.id === studentId) {
                    if (grade.number < 0 || grade.number > grade.exam.marks) {
                        // Ignoring the error number
                    } else {
                        totalNumber += grade.number;
                    }
                }
            });
        }
        return totalNumber;
    }

    getGradePoint(studentId: string): number {
        let gradePoint = 0;
        const totalMarks = this.getTotalNumber(studentId);
        this.gradePointList.forEach(gp => {
            if (gp.minimumNumber <= totalMarks && gp.maximumNumber >= totalMarks) {
                gradePoint = gp.gradePoint;
            }
        });
        return gradePoint;
    }

    getLetterGrade(studentId: string): string {
        let letterGrade = 'F';
        const totalMarks = this.getTotalNumber(studentId);
        this.gradePointList.forEach(gp => {
            if (gp.minimumNumber <= totalMarks && gp.maximumNumber >= totalMarks) {
                letterGrade = gp.letterGrade;
            }
        });
        return letterGrade;
    }

    saveGrade(): void {
        if (this.gradeForm.status === 'INVALID') {
            alert('Grade has invalid entry');
            return;
        }
        const gradeList: Grade[] = [];
        const studentWiseGradeList: any[] = this.gradeForm.getRawValue();
        if (studentWiseGradeList) {
            for (const studentId in studentWiseGradeList) {
                if (studentId) {
                    studentWiseGradeList[studentId].forEach(gradeObj => {
                        if (gradeObj.student.id === studentId) {
                            if (gradeObj.number < 0 || gradeObj.number > gradeObj.exam.marks) {
                                alert('Grade has invalid entry');
                                return;
                            } else {
                                const grade: Grade = new Grade();
                                grade.student = gradeObj.student;
                                grade.exam = gradeObj.exam;
                                grade.number = gradeObj.number;
                                gradeList.push(grade);
                            }
                        }
                    });
                }
            }
        } else {
            alert('Grade is invalid');
            return;
        }

        console.log(gradeList);
        console.log('Grade list saved');
    }

}
</code>```

HTML:

```<code><form [formGroup]="gradeForm" (ngSubmit)="saveGrade()">
    <table>
        <thead>
        <tr>
            <th> #</th>
            <th>Student</th>
            <th *ngFor="let exam of examList">{{exam.name}} ({{exam.marks}}%)</th>
            <th>Total</th>
            <th>GP</th>
            <th>Grade</th>
        </tr>
        </thead>

        <tbody>
        <tr *ngFor="let student of studentList; let i = index">
            <th> {{ i + 1 }} </th>
            <th> {{ student.id }} <br/> {{student.name}} </th>
            <th *ngFor="let grade of gradeForm.get(student.id)?.controls; let j = index">
                <input required min="0" [max]="getMaxNumberValue(j)" [class.inValid]="!gradeForm.get(student.id)?.controls[j].valid" type="number" [formControl]="gradeForm.get(student.id)?.controls[j].controls.number" />
            </th>
            <th>{{getTotalNumber(student.id)}}</th>
            <th>{{getGradePoint(student.id)}}</th>
            <th>{{getLetterGrade(student.id)}}</th>
        </tr>
        </tbody>
    </table>

    <div class="wrapper">
        <button class="button">Save Grade</button>
    </div>
</form>

```{{this.gradeForm.getRawValue() | json}}```
</code>```

I hope this example will help others if someone has the similar scenario.

Body:
I am trying to develop a number grading system for a course using Angular 8. The real scenario is quite complex, so I separated the part and created a new project to explain where I have the problem. If you look at the image you will get an idea, what I am trying to accomplish. Assume this is the grade form of one course. For a course, there can have different exams. Students who are enrolled in this course, they will attend those specific exams for this course and then teacher will submit the number using this form. Suppose, for the first row first column (Mid Exam), the form should not allow you to provide more than 25 marks or less than zero. If you put 20 on the Mid Exam field then Total will show 20, GP will show 0.00, Grade will show F. Then if you put 30 on the Final exam field, Total value will be updated to 50, GP will be updated to 0.00 and will be updated to F. Again if you put 40 on the Assessment field,  Total value will be updated to 90, GP will be updated to 4.00 and will be updated to A. Same thing will be happened to for all the row. If you click on the Save button, numbers will be submitted.

Now I am describing the code that I tried and my problem, here studentList,  examList and gradePointList array will populate the data for a course from backend service. I created populateSomeDemoData method to generate this data. studentList is an array of the Student object which contains students' id and name. examList is an array of the Exam object which contains exam id, exam name and total marks of this exam. gradePointList contains the range of the number of letter grade and grade point. Suppose if the total mark is between 90 (minimumNumber) and 100 (maximumNumber) the grade point will be 4.00 and letter grade will be A. I tried to create a form gradeForm and applied a loop on examList for per row to create input field. But for this, I couldn't able to access the specific field using form control that's why I failed to calculate total marks and grade point for a row. Also for the same reason, I failed to create the list of Grade object which will be sent to the backend. Grade is the object of every field which will contain student, exam and number. If a field is updated, this grade object will also be updated. If Save button triggers, this number list will be passed to the backend.

HTML part is:

<form [formGroup]="gradeForm" (ngSubmit)="saveGrade()">

       #
      Student
      {{exam.name}} ({{exam.marks}}%)
      Total
      GP
      Grade

       {{ i + 1 }}
       {{ student.id }}
 {{student.name}}

        <input type="number" [formControlName]="j">

      ??
      ??
      ??

    <button class="button">Save Grade</button>

</form>

TypeScript Part is:

export class AppComponent {

  public gradeForm: FormGroup;

  // This arrays will populate dynamically from the database
  public examList: Exam[] = [];
  public studentList: Student[] = [];
  public gradePointList: GradePoint[] = [];
  public gradeList: Grade[] = [];

  constructor(private formBuilder: FormBuilder) {

    this.populateSomeDemoData();

    this.createGradeForm();
  }

  createGradeForm(): void {
    this.gradeForm = this.formBuilder.group({
      gradeFields: this.formBuilder.array([
        this.formBuilder.control('')
      ])
    });

    for (let i = 0; i < this.examList.length - 1; i++) {
      this.gradeFields.push(this.formBuilder.control(''));
    }
  }

  get gradeFields() {
    return this.gradeForm.get('gradeFields') as FormArray;
  }

  saveGrade(): void {
    console.log(this.gradeForm.get('gradeFields').value);
    console.log(this.gradeList);
    console.log('Grade List Saved');
  }

  populateSomeDemoData(): void {
    // Static value for populating arrays for easy explanation
    const midTerm = new Exam();
    midTerm.id = '1';
    midTerm.name = 'Mid Exam';
    midTerm.marks = 25;

    const finalExam = new Exam();
    finalExam.id = '2';
    finalExam.name = 'Final Exam';
    finalExam.marks = 30;

    const assessmentExam = new Exam();
    assessmentExam.id = '3';
    assessmentExam.name = 'Assessment';
    assessmentExam.marks = 40;

    const attendance = new Exam();
    attendance.id = '4';
    attendance.name = 'Attendance';
    attendance.marks = 5;

    this.examList.push(midTerm);
    this.examList.push(finalExam);
    this.examList.push(assessmentExam);
    this.examList.push(attendance);

    // Static value for populating arrays for easy explanation
    const student1 = new Student();
    student1.id = '14101561';
    student1.name = 'Petey Cruiser';

    const student2 = new Student();
    student2.id = '14112201';
    student2.name = 'Bob Frapples';

    const student3 = new Student();
    student3.id = '14112202';
    student3.name = 'Paul Molive';

    const student4 = new Student();
    student4.id = '16113004';
    student4.name = 'Anna Mull';

    const student5 = new Student();
    student5.id = '16113005';
    student5.name = 'Gail Forcewind';

    this.studentList.push(student1);
    this.studentList.push(student2);
    this.studentList.push(student3);
    this.studentList.push(student4);
    this.studentList.push(student5);

    // Static value for populating arrays for easy explanation
    const aGradePoint = new GradePoint();
    aGradePoint.minimumNumber = 90;
    aGradePoint.maximumNumber = 100;
    aGradePoint.gradePoint = 4;
    aGradePoint.letterGrade = 'A';

    const bGradePoint = new GradePoint();
    bGradePoint.minimumNumber = 80;
    bGradePoint.maximumNumber = 89;
    bGradePoint.gradePoint = 3.5;
    bGradePoint.letterGrade = 'B';

    const cGradePoint = new GradePoint();
    cGradePoint.minimumNumber = 70;
    cGradePoint.maximumNumber = 79;
    cGradePoint.gradePoint = 3;
    cGradePoint.letterGrade = 'C';

    const dGradePoint = new GradePoint();
    dGradePoint.minimumNumber = 60;
    dGradePoint.maximumNumber = 69;
    dGradePoint.gradePoint = 2.5;
    dGradePoint.letterGrade = 'D';

    const fGradePoint = new GradePoint();
    fGradePoint.minimumNumber = 0;
    fGradePoint.maximumNumber = 59;
    fGradePoint.gradePoint = 0;
    fGradePoint.letterGrade = 'F';
    this.gradePointList.push(aGradePoint);
    this.gradePointList.push(bGradePoint);
    this.gradePointList.push(cGradePoint);
    this.gradePointList.push(dGradePoint);
    this.gradePointList.push(fGradePoint);
  }
}

export class Student {
  public id: string;
  public name: string;

  constructor(student?) {
    student = student || {};
    this.id = student.id || null;
    this.name = student.name || null;
  }
}

export class Exam {
  public id: string;
  public name: string;
  public marks: number;

  constructor(exam?) {
    exam = exam || {};
    this.id = exam.id || null;
    this.name = exam.name || null;
    this.marks = exam.marks || 0;
  }
}

export class GradePoint {
  public minimumNumber: number;
  public maximumNumber: number;
  public gradePoint: number;
  public letterGrade: string;

  constructor(gradePoint?) {
    gradePoint = gradePoint || {};
    this.minimumNumber = gradePoint.minimumNumber || 0;
    this.maximumNumber = gradePoint.maximumNumber || 59;
    this.gradePoint = gradePoint.gradePoint || 0;
    this.letterGrade = gradePoint.letterGrade || 'F';
  }
}

export class Grade {
  public student: Student;
  public exam: Exam;
  public number: number;

  constructor(grade?) {
    grade = grade || {};
    this.student = grade.student || null;
    this.exam = grade.exam || null;
    this.number = grade.number || null;
  }
}

I have created a StackBlitz for better understanding of the code. Please click on this link to view the code. Click here

I saw a lot of post which is related to Form Arrays but my scenario is quite different. Here I don't have any Add button to push array or calculate the values. And there are fixed forms for all cases. But in my case, the array also will be generated from the list because examList is dynamic.

I assume I have problem with creating on the form or my approaches are wrong. Please help me to accomplish my objective generate total marks and creating Grade list. It would be appreciated. Thanks in advance.

Body:
Thanks to Munzer. He gave me idea and show me a sample. I solved the problem completely according to his answer. Since I solved it completely, I am sharing the details if it helps someone. To solve the problem, I created the form dynamically. For each student, I made a group and created a  form control for each exam. Then I loop through multiple student lists and again I loop through the marks fields of each student group and add form control. You will get the clear idea from createGradeForm method. Here is the StackBlitz link:  https://stackblitz.com/edit/grade-upload-9nnr8p

TS File:

export class AppComponent {

    public gradeForm: FormGroup;

    // This arrays will populate dynamically from the database
    public examList: Exam[] = [];
    public studentList: Student[] = [];
    public gradePointList: GradePoint[] = [];

    constructor(private formBuilder: FormBuilder) {
        this.populateSomeDemoData();
        this.createGradeForm();
    }

    private createGradeForm(): void {
        this.gradeForm = this.formBuilder.group({});

        this.studentList.forEach(student => {
            this.gradeForm.addControl(student.id, this.formBuilder.array([]));
            this.examList.forEach(exam => {
                const grade: Grade = new Grade();
                grade.student = student;
                grade.exam = exam;
                grade.number = 0; // Replace the number if previously saved

                const studentGrades: FormArray = this.gradeForm.get(student.id) as FormArray;
                studentGrades.push(this.createGradeFormGroup(grade));
            });
        });
    }

    createGradeFormGroup(grade: Grade): FormGroup {
        return this.formBuilder.group({
            student: [grade.student, [Validators.required]],
            exam: [grade.exam, [Validators.required]],
            number: [grade.number, [Validators.required, Validators.min(-1), Validators.max(grade.exam.marks)]]
        });
    }

    getMaxNumberValue(index: number): number {
        if (this.examList[index]) {
            return this.examList[index].marks;
        }
        return 0;
    }

    getTotalNumber(studentId: string): number {
        let totalNumber = 0;

        const studentWiseGradeList: any[] = this.gradeForm.getRawValue();
        if (studentWiseGradeList && studentWiseGradeList[studentId]) {
            studentWiseGradeList[studentId].forEach(grade => {
                if (grade.student.id === studentId) {
                    if (grade.number < 0 || grade.number > grade.exam.marks) {
                        // Ignoring the error number
                    } else {
                        totalNumber += grade.number;
                    }
                }
            });
        }
        return totalNumber;
    }

    getGradePoint(studentId: string): number {
        let gradePoint = 0;
        const totalMarks = this.getTotalNumber(studentId);
        this.gradePointList.forEach(gp => {
            if (gp.minimumNumber <= totalMarks && gp.maximumNumber >= totalMarks) {
                gradePoint = gp.gradePoint;
            }
        });
        return gradePoint;
    }

    getLetterGrade(studentId: string): string {
        let letterGrade = 'F';
        const totalMarks = this.getTotalNumber(studentId);
        this.gradePointList.forEach(gp => {
            if (gp.minimumNumber <= totalMarks && gp.maximumNumber >= totalMarks) {
                letterGrade = gp.letterGrade;
            }
        });
        return letterGrade;
    }

    saveGrade(): void {
        if (this.gradeForm.status === 'INVALID') {
            alert('Grade has invalid entry');
            return;
        }
        const gradeList: Grade[] = [];
        const studentWiseGradeList: any[] = this.gradeForm.getRawValue();
        if (studentWiseGradeList) {
            for (const studentId in studentWiseGradeList) {
                if (studentId) {
                    studentWiseGradeList[studentId].forEach(gradeObj => {
                        if (gradeObj.student.id === studentId) {
                            if (gradeObj.number < 0 || gradeObj.number > gradeObj.exam.marks) {
                                alert('Grade has invalid entry');
                                return;
                            } else {
                                const grade: Grade = new Grade();
                                grade.student = gradeObj.student;
                                grade.exam = gradeObj.exam;
                                grade.number = gradeObj.number;
                                gradeList.push(grade);
                            }
                        }
                    });
                }
            }
        } else {
            alert('Grade is invalid');
            return;
        }

        console.log(gradeList);
        console.log('Grade list saved');
    }

}

HTML:

<form [formGroup]="gradeForm" (ngSubmit)="saveGrade()">
    <table>
        <thead>
        <tr>
            <th> #</th>
            <th>Student</th>
            <th *ngFor="let exam of examList">{{exam.name}} ({{exam.marks}}%)</th>
            <th>Total</th>
            <th>GP</th>
            <th>Grade</th>
        </tr>
        </thead>

        <tbody>
        <tr *ngFor="let student of studentList; let i = index">
            <th> {{ i + 1 }} </th>
            <th> {{ student.id }} <br/> {{student.name}} </th>
            <th *ngFor="let grade of gradeForm.get(student.id)?.controls; let j = index">
                <input required min="0" [max]="getMaxNumberValue(j)" [class.inValid]="!gradeForm.get(student.id)?.controls[j].valid" type="number" [formControl]="gradeForm.get(student.id)?.controls[j].controls.number" />
            </th>
            <th>{{getTotalNumber(student.id)}}</th>
            <th>{{getGradePoint(student.id)}}</th>
            <th>{{getLetterGrade(student.id)}}</th>
        </tr>
        </tbody>
    </table>

    <div class="wrapper">
        <button class="button">Save Grade</button>
    </div>
</form>

<pre>{{this.gradeForm.getRawValue() | json}}</pre>

I hope this example will help others if someone has the similar scenario.


问:
Error is Trying to get property 'id' of non-object, but seems object has
I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -

```<code>        try{
            ///try to connect with database
            $conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $ex){
            echo "error";
        }
        $mysqlcode="SELECT * FROM users";
        $ret=$conn->query($mysqlcode);
        foreach($ret as $ret1)
        print $ret1->id;
</code>```

in the browser,
showing this error:

Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44

In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.

答:
I have checked your code. Everything is fine. Just do this.</p>

```<code>         foreach($ret as $ret1)
            print $ret1['id'];
</code>```

Body:
I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -

        try{
            ///try to connect with database
            $conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $ex){
            echo "error";
        }
        $mysqlcode="SELECT * FROM users";
        $ret=$conn->query($mysqlcode);
        foreach($ret as $ret1)
        print $ret1->id;

in the browser,
showing this error:

Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44

In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.

Body:
I have checked your code. Everything is fine. Just do this.

         foreach($ret as $ret1)
            print $ret1['id'];


问:
How to reset all array elements?
This is the shortest I came up with, after extensive googling and studying the sources:

```<code>let mut buf = [0u8; 200];
for elem in buf.iter_mut() {
    *elem = 0;
}
</code>```

Is there really no way to make this a one-liner, like buf.set_all(0)?

答:
in your scene, this is my solution:

let mut buf = [1u8; 200];
unsafe {
    std::ptr::write_volatile(&mut buf, [0u8;200]);
}
```

<blockquote>
  <p>Is there really no way to make this a one-liner, like buf.set_all(0)?</p>
</blockquote>

<p>and you also can do like this:</p>

<pre class="lang-rust prettyprint-override"><code>struct Buf([u8;200]);
impl Buf {
    fn clear(&mut self) {
        unsafe {
            std::ptr::write_volatile(&mut self.0, [0u8;200]);
        }
    }
}

fn main() {
    let mut buf1 = Buf([1u8; 200]);
    let mut buf2 = Buf([2u8; 200]);
    buf1.clear();
    buf2.clear();
    println!("{}, {}", buf1.0[199], buf2.0[0]);
}
</code>```

Title: How to reset all array elements?

Body:
This is the shortest I came up with, after extensive googling and studying the sources:

let mut buf = [0u8; 200];
for elem in buf.iter_mut() {
    *elem = 0;
}

Is there really no way to make this a one-liner, like buf.set_all(0)?

Body:
in your scene, this is my solution:

let mut buf = [1u8; 200];
unsafe {
    std::ptr::write_volatile(&mut buf, [0u8;200]);
}

Is there really no way to make this a one-liner, like buf.set_all(0)?

and you also can do like this:

struct Buf([u8;200]);
impl Buf {
    fn clear(&mut self) {
        unsafe {
            std::ptr::write_volatile(&mut self.0, [0u8;200]);
        }
    }
}

fn main() {
    let mut buf1 = Buf([1u8; 200]);
    let mut buf2 = Buf([2u8; 200]);
    buf1.clear();
    buf2.clear();
    println!("{}, {}", buf1.0[199], buf2.0[0]);
}


问:
How to Change a single strings color within a QlineEdit
I am working on calculator and when I click on "+" button I want the "+" to be in green color instead of white without changing the white color for the numbers

And this is the code of the button "+":

```<code>def plus(self):
    splus=self.QlineEdit.text()
    self.lineEdit.setText(splus+"+")
</code>```

and to make my question simple and clear I want the output to be like this :

答:
You may try  to toggle the widget color with

```<code>    splus.setStyleSheet("QLineEdit { background: rgb(xxx,xxx,xxx); selection-
    background-color: rgb(xxx,xxx,xxx); }")
</code>```

To be fired by the QLineEdit's clicked event as:

```<code>    splus.clicked.connect(self.toggleColors)
</code>```

Hope it works for you.

Body:
I am working on calculator and when I click on "+" button I want the "+" to be in green color instead of white without changing the white color for the numbers

And this is the code of the button "+":

def plus(self):
    splus=self.QlineEdit.text()
    self.lineEdit.setText(splus+"+")

and to make my question simple and clear I want the output to be like this :

Body:
You may try  to toggle the widget color with

    splus.setStyleSheet("QLineEdit { background: rgb(xxx,xxx,xxx); selection-
    background-color: rgb(xxx,xxx,xxx); }")

To be fired by the QLineEdit's clicked event as:

    splus.clicked.connect(self.toggleColors)

Hope it works for you.


问:
In Pytube, is there any way to get the highest audio quality stream?
I was trying to make a really simple python code to get me the stream with the highest quality audio, so I first tried something like this

```<code>def get_highest_audio(url):
    yt = YouTube(url)
    best_audio_stream = yt.streams.filter(only_audio=True).all()[1]
    return best_audio_stream
</code>```

Which did return a stream, but it wasn't the stream with the highest quality audio, so I tried to find a function in the pytube library.

While there was a get_highest_resolution() function, there was not a get_highest_audio_resolution() function.

So I tried to get the audio resolution by hand, but there wasn't a function that got the audio resolution of a stream.

Is there any way to create this function?

答:
You can just use:

```<code>yt.streams.get_audio_only()
</code>```

this gets the highest bitrate audio stream. It defaults to mp4.

Body:
I was trying to make a really simple python code to get me the stream with the highest quality audio, so I first tried something like this

def get_highest_audio(url):
    yt = YouTube(url)
    best_audio_stream = yt.streams.filter(only_audio=True).all()[1]
    return best_audio_stream

Which did return a stream, but it wasn't the stream with the highest quality audio, so I tried to find a function in the pytube library.

While there was a get_highest_resolution() function, there was not a get_highest_audio_resolution() function.

So I tried to get the audio resolution by hand, but there wasn't a function that got the audio resolution of a stream.

Is there any way to create this function?

Body:
You can just use:

yt.streams.get_audio_only()

this gets the highest bitrate audio stream. It defaults to mp4.


问:
How to use OpenGL-ES 2.0 in linux and Android
HI

I am having a ubuntu 10.10 enable laptop . I have run examples of OpenGL-ES 2.0  on Ubuntu 10.10 . now I want to run the codes in Android platform . How would I proceed .

Maybe I have to run android on ubuntu 10.10 and then run in the android but I don't know how to do that .

The thing is that I want to run the codes on Android in Ubuntu enable laptop.
if anyone is having suggestions .Please let me know this.

Sudhanshu

答:
Just read the Android Documentation: it is all perfectly explained there for any Operating system. Just follow the steps and you will get there.

One important point though, pick a minimum of API Level 8 for your project when you get there because the OpenGL ES bindings for 2.0 were only added then.


问:
How to stop the jumping jack of text change in React
How to smoothly transition from text to svg in react.
As soon as I click on next button shown in pic as ">" ,the text changes to svg.But there is some sort of jumping due to change in overall height.
How can I smoothly transition between two.

Note: Unfortunately, I can't share the code as this is not a personal
  project.

答:
You can set the height of the containing element to the heighest element. Therefore you need to place them in a row with a negative margin-right so that they overlay each other. Only the element that you make visible will be shown when you hide the other elements with visibility: hidden;

Here is an example:

var elements = document.querySelectorAll('.block__element');

document.querySelector('button').addEventListener('click', () => {
  elements.forEach(element => {
    if(element.classList.contains('block__element--visible')) {
      element.classList.remove('block__element--visible');
    } else {
      element.classList.add('block__element--visible');
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.block {
  background: #aaa;
  display: flex;
}
.block__element {
  width: 100%;
  margin-right: -100%;
  visibility: hidden;
  opacity: 0;
  transition: visibility 1s, opacity 1s;
}
.block__element--visible {
  visibility: visible;
  opacity: 1;
}</code>```

Content 1

Longer content 2

<button>Toggle between elements</button>```

Body:
You can set the height of the containing element to the heighest element. Therefore you need to place them in a row with a negative margin-right so that they overlay each other. Only the element that you make visible will be shown when you hide the other elements with visibility: hidden;

Here is an example:

var elements = document.querySelectorAll('.block__element');

document.querySelector('button').addEventListener('click', () => {
  elements.forEach(element => {
    if(element.classList.contains('block__element--visible')) {
      element.classList.remove('block__element--visible');
    } else {
      element.classList.add('block__element--visible');
    }
  })
});

.block {
  background: #aaa;
  display: flex;
}
.block__element {
  width: 100%;
  margin-right: -100%;
  visibility: hidden;
  opacity: 0;
  transition: visibility 1s, opacity 1s;
}
.block__element--visible {
  visibility: visible;
  opacity: 1;
}

<div class="block">
  <div class="block__element block__element--visible">
    <div style="background: #f00">Content 1</div>
  </div>
  <div class="block__element">
    <div style="height: 200px; background: #0f0">Longer content 2</div>
  </div>
</div>
<button>Toggle between elements</button>