问:
Change the color of a character-pointtype in gnuplot
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

```<code>set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o
</code>```

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:

答:
Character point types are rendered by the same driver routine that handles labels and other text.  Therefore the color is taken from the current font and font properties apply, including color:

```<code>set sample 11
plot sin(x) with point pointtype "µ" textcolor rgb "violet" font "/:Bold,15"
</code>```

Body:
I am trying to set the color of a character-defined point type in gnuplot. Although I can select the desire color of a system defined point type, I cannot do the same with the character-defined one. Below I present a minimal example.

set samples 5
set term pdf
set o "mwe.pdf"

p x with points lt rgb "violet" pt "V",\
  x with points lt rgb "violet" pt 2

set o

The result looks like this:

I also tried to set the color with the lc variable method and feeding the keyword using with a column ("#005893"), buit it still doesn't change the color.

Question

How can I set the color of the letter to achieve something like this:

Body:
Character point types are rendered by the same driver routine that handles labels and other text.  Therefore the color is taken from the current font and font properties apply, including color:

set sample 11
plot sin(x) with point pointtype "µ" textcolor rgb "violet" font "/:Bold,15"


来源: stackexchange

问:
What's the difference between a "pull request" and a "branch"?
What's the difference between a "pull request" and a "branch"?

pull request
  branch

答:
Git has a seldom-used command git request-pull. The request tells others where and which ref to fetch to retrieve the pending changes, so that they can apply these changes if necessary.

Generate a request asking your upstream project to pull changes into
  their tree.

A pull request is a variation realized by hosting services like Github and Gitlab with the help of Git refs. The format is refs/pull/${number}/head. A branch is also a kind of ref, in the format of refs/heads/foo(local branch) or refs/remotes/origin/foo(remote tracking branch). Gerrit, another hosting service, implements the pending changes in another form, a change with one or more patchsets in the format like refs/changes/11/23411/1.

We can use git fetch origin refs/pull/98/head or git fetch origin master to fetch the pull request or the branch and retrieve the pending changes from the remote repository to the local repository.

A pull request and a branch are both refs. They have different formats. They serve different purposes. A pull request is usually generated from a branch by the hosting service.

ContentLicense: CC BY-SA 4.0


问:
jQuery onClick function to submit data to php "not defined"
The following button calls a jQuery function onClick.  However, the Firefox dev console says "postData is not defined."

Here is the button and the jQuery script.

```<code>    <div class="center_text_grid flex-item EMail_Pwd">

    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>

function sendReply() {
    // autoresponder
}

postData().done(sendReply);

</script>

</form><br>

<br><br><br>

<!-- ________________ -->

<script type="text/javascript">

function postData() {
    return $.ajax({
    var datastring = $("#echo_test").serialize();
    $.ajax({
       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
});
}
</code>```

Why does the console say the function postData is not defined?

Thanks for any ideas.

答:
Remove onclick from the button and add handler in the $(document.ready) function:

```<code><button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)">Click to Submit Data</button></div>

...

<script type="text/javascript">
    $(function(){
      function postData() {
        return $.ajax({
        var datastring = $("#echo_test").serialize();
        $.ajax({
           type: "POST",
           url: "echo_test.php",
           data: {post: datastring},
        });
      });

      $("#btn_joinnow").click(postData);
    });
</script>
</code>```

Body:
The following button calls a jQuery function onClick.  However, the Firefox dev console says "postData is not defined."

Here is the button and the jQuery script.

    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button>

function sendReply() {
    // autoresponder
}

postData().done(sendReply);

</script>

</form>

Body:
Remove onclick from the button and add handler in the $(document.ready) function:

<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)">Click to Submit Data</button></div>

...

<script type="text/javascript">
    $(function(){
      function postData() {
        return $.ajax({
        var datastring = $("#echo_test").serialize();
        $.ajax({
           type: "POST",
           url: "echo_test.php",
           data: {post: datastring},
        });
      });

      $("#btn_joinnow").click(postData);
    });
</script>


问:
How to extract elements from a JSONL file with changing elements?
I want to extract "text" from the tokens in a JSONL file. If a label is present then I want to extract that as well. If it is not present then I want to insert "O" as a value for the label

```<code>{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is coded in python.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"coded","id":2},
{"text":"in","id":3},
{"text":"python","label":"Programming"},
{"text":".","id":5}]}
</code>```

The code that can be used to extract the text and id from the tokens is as follows if no label is present: (thanks to @DeveshKumarSingh in my previous question)

```<code>import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i['id']+1) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)
</code>```

Expected output:

答:
You can use dict.get to find the label when present, else replace it with a default value O that is i.get('label','O')

```<code>import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i.get('label','O')) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)
</code>```

The output will be

```<code>[(1, 'This', 'O'),
 (1, 'is', 'O'),
(1, 'the', 'O'),
(1, 'first', 'O'),
(1, 'sentence', 'O'),
(1, '.', 'O'),
(2, 'This', 'O'),
(2, 'is', 'O'),
(2, 'coded', 'O'),
(2, 'in', 'O'),
(2, 'python', 'Programming'),
(2, '.', 'O')]
</code>```

Body:
I want to extract "text" from the tokens in a JSONL file. If a label is present then I want to extract that as well. If it is not present then I want to insert "O" as a value for the label

{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is coded in python.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"coded","id":2},
{"text":"in","id":3},
{"text":"python","label":"Programming"},
{"text":".","id":5}]}

The code that can be used to extract the text and id from the tokens is as follows if no label is present: (thanks to @DeveshKumarSingh in my previous question)

import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i['id']+1) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)

Expected output:

Body:
You can use dict.get to find the label when present, else replace it with a default value O that is i.get('label','O')

import jsonlines

#Open the file, iterate over the tokens and make the tuples
result = [(idx+1, i['text'], i.get('label','O')) for idx, obj in enumerate(jsonlines.open('file.txt')) for i in obj['tokens']]

print(result)

The output will be

[(1, 'This', 'O'),
 (1, 'is', 'O'),
(1, 'the', 'O'),
(1, 'first', 'O'),
(1, 'sentence', 'O'),
(1, '.', 'O'),
(2, 'This', 'O'),
(2, 'is', 'O'),
(2, 'coded', 'O'),
(2, 'in', 'O'),
(2, 'python', 'Programming'),
(2, '.', 'O')]


问:
Assign max value of group to all rows in that group
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)
```

<p>which gives</p>

<pre class="lang-r prettyprint-override"><code>    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5
</code>```

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23
```

<p>As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits. </p>

<p>In the end, this should be the result: </p>

<pre class="lang-r prettyprint-override"><code>Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23
</code>```

How do I go about this?

答:
An option would be to group by 'Student_ID', mutate the 'Credits' with max of 'Credits' and filter the rows with 'Appraisal.Type' as "Grade supervisor"

```<code>library(dplyr)
df1 %>%
   group_by(Student_ID) %>%
   dplyr::mutate(Credits = max(Credits)) %>%
   ungroup %>%
   filter(Appraisal.Type == "Grade supervisor")
# A tibble: 2 x 5
#  Appraisal.Type   Resits Credits Course_code Student_ID
#  <chr>             <int>   <dbl> <chr>            <int>
#1 Grade supervisor      0     6.5 ABC1000             10
#2 Grade supervisor      0     6.5 ABC1003             10
</code>```

If we also need 'Course_code' to be included in the grouping

```<code>df2 %>%
  group_by(Student_ID, Course_code) %>%
  dplyr::mutate(Credits = max(Credits)) %>%
  filter(Appraisal.Type == "Grade supervisor")
# A tibble: 3 x 5
# Groups:   Student_ID, Course_code [3]
#  Appraisal.Type   Resits Credits Course_code Student_ID
#  <chr>             <int>   <dbl> <chr>            <int>
#1 Grade supervisor      0     6.5 ABC1000             10
#2 Grade supervisor      0     6.5 ABC1003             10
#3 Grade supervisor      0    12   ABC1294             23
</code>```

NOTE: I case, plyr package is also loaded, there can be some masking of functions esp summarise/mutate which is also found in plyr.  To prevent it, either do this on a fresh session without loading plyr or explicitly specify dplyr::mutate

data

```<code>df1 <- structure(list(Appraisal.Type = c("Final result", "Final result",
"Grade supervisor", "Grade supervisor"), Resits = c(0L, 0L, 0L,
0L), Credits = c(6.5, 6.5, 0, 0), Course_code = c("ABC1000",
"ABC1003", "ABC1000", "ABC1003"), Student_ID = c(10L, 10L, 10L,
10L)), class = "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(Appraisal.Type = c("Final result", "Final result",
"Grade supervisor", "Grade supervisor", "Final result", "Grade supervisor"
), Resits = c(0L, 0L, 0L, 0L, 0L, 0L), Credits = c(6.5, 6.5,
0, 0, 12, 0), Course_code = c("ABC1000", "ABC1003", "ABC1000",
"ABC1003", "ABC1294", "ABC1294"), Student_ID = c(10L, 10L, 10L,
10L, 23L, 23L)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Body:
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)

which gives

    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23

As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits.

In the end, this should be the result:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23

How do I go about this?

Body:
An option would be to group by 'Student_ID', mutate the 'Credits' with max of 'Credits' and filter the rows with 'Appraisal.Type' as "Grade supervisor"

library(dplyr)
df1 %>%
   group_by(Student_ID) %>%
   dplyr::mutate(Credits = max(Credits)) %>%
   ungroup %>%
   filter(Appraisal.Type == "Grade supervisor")
# A tibble: 2 x 5
#  Appraisal.Type   Resits Credits Course_code Student_ID
#  <chr>             <int>   <dbl> <chr>            <int>
#1 Grade supervisor      0     6.5 ABC1000             10
#2 Grade supervisor      0     6.5 ABC1003             10

If we also need 'Course_code' to be included in the grouping

df2 %>%
  group_by(Student_ID, Course_code) %>%
  dplyr::mutate(Credits = max(Credits)) %>%
  filter(Appraisal.Type == "Grade supervisor")
# A tibble: 3 x 5
# Groups:   Student_ID, Course_code [3]
#  Appraisal.Type   Resits Credits Course_code Student_ID
#  <chr>             <int>   <dbl> <chr>            <int>
#1 Grade supervisor      0     6.5 ABC1000             10
#2 Grade supervisor      0     6.5 ABC1003             10
#3 Grade supervisor      0    12   ABC1294             23

NOTE: I case, plyr package is also loaded, there can be some masking of functions esp summarise/mutate which is also found in plyr.  To prevent it, either do this on a fresh session without loading plyr or explicitly specify dplyr::mutate

data

df1 <- structure(list(Appraisal.Type = c("Final result", "Final result",
"Grade supervisor", "Grade supervisor"), Resits = c(0L, 0L, 0L,
0L), Credits = c(6.5, 6.5, 0, 0), Course_code = c("ABC1000",
"ABC1003", "ABC1000", "ABC1003"), Student_ID = c(10L, 10L, 10L,
10L)), class = "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(Appraisal.Type = c("Final result", "Final result",
"Grade supervisor", "Grade supervisor", "Final result", "Grade supervisor"
), Resits = c(0L, 0L, 0L, 0L, 0L, 0L), Credits = c(6.5, 6.5,
0, 0, 12, 0), Course_code = c("ABC1000", "ABC1003", "ABC1000",
"ABC1003", "ABC1294", "ABC1294"), Student_ID = c(10L, 10L, 10L,
10L, 23L, 23L)), class = "data.frame", row.names = c(NA, -6L))


问:
How can I format multiple CSS grids to look the same
I have a php file that generates my html page with a grid container filled with contents for a each movie in the specified directory. All nested inside a foreach loop.

I'd like it to look like the top two movies in the photo.

It looks like:

Code:
CSS:

.grid-item {
  justify-content: center;
  display: grid;
  grid-gap: 10px;
  padding: 10px;
}

.item1 {
  grid-column:1 / span 1;
  grid-row: 1 / span 1;
}

.item2 {
  grid-column: 1 / span 1;
  grid-row: 2 / span 2;
}

.item3 {
  display: flex;
  grid-column: 2 / span 2;
  grid-row: 1 / span 3;
  align-items: center;
}

.grid-containerTest {
  width: 95%;
  display: grid;
  grid-gap: 20px;
  margin: auto auto 5px;
  flex-direction: column;
  top: 10px;
  bottom: 5px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid black;
}```
</div>
</div>
</p>

<p>PHP/HTML:</p>

```echo '
';
    if (file_exists($dir . '/xml/' . $withoutExt . '.xml')){
    echo '

' . $xml->title . '

';
    }else{
        echo '

' . $withoutExt . '

';
    }
    echo '
<video width="300" height="400" poster="'. $image .'" controls preload="none">';
    echo '<source src="'. $movie .'" type="video/mp4"></video>
';
    echo '
' . $xml->overview . '
';
    echo '

';
```

答:
I realized the error just a few seconds after posting:
justify-content just needed changed from center to left or removed completely from the following snippet of code:</p>

```<code>.grid-item {
  justify-content: center;
  display: grid;
  grid-gap: 10px;
  padding: 10px;
}
</code>```

Body:
I have a php file that generates my html page with a grid container filled with contents for a each movie in the specified directory. All nested inside a foreach loop.

I'd like it to look like the top two movies in the photo.

It looks like:

Code:
CSS:

.grid-item {
  justify-content: center;
  display: grid;
  grid-gap: 10px;
  padding: 10px;
}

.item1 {
  grid-column:1 / span 1;
  grid-row: 1 / span 1;
}

.item2 {
  grid-column: 1 / span 1;
  grid-row: 2 / span 2;
}

.item3 {
  display: flex;
  grid-column: 2 / span 2;
  grid-row: 1 / span 3;
  align-items: center;
}

.grid-containerTest {
  width: 95%;
  display: grid;
  grid-gap: 20px;
  margin: auto auto 5px;
  flex-direction: column;
  top: 10px;
  bottom: 5px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid black;
}

PHP/HTML:

echo '
';
    if (file_exists($dir . '/xml/' . $withoutExt . '.xml')){
    echo '

' . $xml->title . '

';
    }else{
        echo '

' . $withoutExt . '

';
    }
    echo '
<video width="300" height="400" poster="'. $image .'" controls preload="none">';
    echo '<source src="'. $movie .'" type="video/mp4"></video>
';
    echo '
' . $xml->overview . '
';
    echo '

';

Body:
I realized the error just a few seconds after posting:
justify-content just needed changed from center to left or removed completely from the following snippet of code:

.grid-item {
  justify-content: center;
  display: grid;
  grid-gap: 10px;
  padding: 10px;
}


问:
Is possible find the value not equal to one in the column and get all position in the same field?
I need to find the value not equal 1 in the column A and get all the position in the same field.

I want to get the all not equal 1 position into the B11.

I want to use the excel formula function and don't use vba or other code. How can I do ? Is possible ?

答:
Since you are working with Excel-2007, unfortunately you won't be able to use the new TEXTJOIN() and CONCAT() functions (nor power query). However you can get quite creative with a function like CONCATENATE(), it will most likely mean at some point you'll have to do some manual 'labour'. Who wants to do manual labour? ;)

So in this case I would prefer to go the UDF way. Below a tested example:

```<code>Function GetPos(RNG As Range, VAL As Double) As String

Dim CL As Range, ARR() As String, X as double

X = 1
For Each CL In RNG
    If CL.Value <> VAL Then
        ReDim Preserve ARR(X)
        ARR(X) = CL.Address(False, False)
        X = X + 1
    End If
Next CL

If IsEmpty(ARR) Then
  GetPos = "No hits"
Else
  GetPos = Join(ARR, ",")
  GetPos = Right(GetPos, Len(GetPos) - 1)
End If

End Function
</code>```

This one takes two criteria, a range and a numeric value indicating what the cells in your range must NOT be. It will return a string value.

Call it from your worksheet through =GETPOS(A1:A10,1) and it should return A2,A7,A9

EDIT

If you are fine using a helper column you could do it like so:

Formula in B1:

```<code>=IF(A1<>1,"A"&ROW()&",","")
</code>```

Formula in B11:

```<code>=LEFT(B1&B2&B3&B4&B5&B6&B7&B8&B9&B10,SUM(LEN(B1:B10))-1)
</code>```

Enter through CtrlShiftEnter

Note: If you don't want to use a helper column you'll have to use TRANSPOSE() to 'load' an array of text values but it involves manual labour and IMO you'll surpass your goal.

Body:
Since you are working with Excel-2007, unfortunately you won't be able to use the new TEXTJOIN() and CONCAT() functions (nor power query). However you can get quite creative with a function like CONCATENATE(), it will most likely mean at some point you'll have to do some manual 'labour'. Who wants to do manual labour? ;)

So in this case I would prefer to go the UDF way. Below a tested example:

Function GetPos(RNG As Range, VAL As Double) As String

Dim CL As Range, ARR() As String, X as double

X = 1
For Each CL In RNG
    If CL.Value <> VAL Then
        ReDim Preserve ARR(X)
        ARR(X) = CL.Address(False, False)
        X = X + 1
    End If
Next CL

If IsEmpty(ARR) Then
  GetPos = "No hits"
Else
  GetPos = Join(ARR, ",")
  GetPos = Right(GetPos, Len(GetPos) - 1)
End If

End Function

This one takes two criteria, a range and a numeric value indicating what the cells in your range must NOT be. It will return a string value.

Call it from your worksheet through =GETPOS(A1:A10,1) and it should return A2,A7,A9

EDIT

If you are fine using a helper column you could do it like so:

Formula in B1:

=IF(A1<>1,"A"&ROW()&",","")

Formula in B11:

=LEFT(B1&B2&B3&B4&B5&B6&B7&B8&B9&B10,SUM(LEN(B1:B10))-1)

Enter through CtrlShiftEnter

Note: If you don't want to use a helper column you'll have to use TRANSPOSE() to 'load' an array of text values but it involves manual labour and IMO you'll surpass your goal.


问:
Wrong Spring AppContext found in EAR
I have an EAR with multiple MDBs in it. Each MDB jar has its own application context. When a message arrives I can see from the logging that the appropriate MDB initialises, but it obtains the application context from different MDB!

I thought each EJB should have it's own classloader. It seems it doesn't. How can I enforce each MDB to load its own app context?

I am using WebSphere 7.

My project structure is:

```<code>META-INF/
META-INF/MANIFEST.MF
topicreader-ejb-mdb01.jar
topicreader-ejb-mdb02.jar
lib/
lib/3rdpartylib01.jar
lib/3rdpartylib02.jar
... etc
</code>```

The content of the mdb jars is:

```<code>applicationContext.xml
com/mycompany/ ... (classes)
META-INF/ejb-jar.xml
META-INF/MANIFEST.MF
</code>```

答: In WAS you can change the classloader order for the WARs!!, I hope you can do the same for the jars. Normaly the class loader order it is "parent first". Try "Parent Last".</p>

ContentLicense: CC BY-SA 3.0

Title: Wrong Spring AppContext found in EAR

Body:
I have an EAR with multiple MDBs in it. Each MDB jar has its own application context. When a message arrives I can see from the logging that the appropriate MDB initialises, but it obtains the application context from different MDB!

I thought each EJB should have it's own classloader. It seems it doesn't. How can I enforce each MDB to load its own app context?

I am using WebSphere 7.

My project structure is:

META-INF/
META-INF/MANIFEST.MF
topicreader-ejb-mdb01.jar
topicreader-ejb-mdb02.jar
lib/
lib/3rdpartylib01.jar
lib/3rdpartylib02.jar
... etc

The content of the mdb jars is:

applicationContext.xml
com/mycompany/ ... (classes)
META-INF/ejb-jar.xml
META-INF/MANIFEST.MF


问:
Trying to insert User defined type of Vector into User defined type Vectors
I'm trying to make a vector of vectors in a spell system for a small RPG battle simulation. The main goal I'm trying to accomplish is have a vector of Spells that the player can access and select what type of Spells they want to cast: Fire, Ice, etc. and then choose the name of the spell: burn, frost, etc.

The code below is what I've declared Spell and FireSpell as. I'm trying to insert a vector of FireSpells into a vector of type vector spells, however, it does not insert.  Is there a way to make it insert?

I've tried the push_back on a FireSpell into a vector of Spells and it works fine, however, it always returns an error when I push_back a FireSpell vector into a vector of type vector Spell.

Magic.h

```<code>struct Fire
{
    int damage;
    int dps;
};

struct Spell
{
    int cost;
    string name;
};

struct FireSpell : Spell, Fire
{

};

</code>```

Magic.cpp

```<code>#include <iostream>
#include "MagicSys.h"
#include <vector>
#include <string>
#include "Magic.h"

using std::cout;
using std::vector;

FireSpell burn;
FireSpell inferno;
FireSpell volcano;

int mainfunc()
{
    vector<vector<Spell>> PlayerSpells;
    vector<FireSpell> PlayerFSpells;
    PlayerFSpells.push_back(burn);
    PlayerFSpells.push_back(inferno);
    PlayerFSpells.push_back(volcano);

 /*Trying to insert FireSpell Vector into the end of the vector of Spell vectors*/

    PlayerSpells.push_back(PlayerFSpells);

    vector<vector<Spell>>::iterator it;
    for (it = PlayerSpells.begin(); it!=PlayerSpells.end(); ++it)
        cout << &it << " ";

    return 0;
}
</code>```

I expected the inner FireSpell vector to insert into the outer Spell vector on the line: PlayerSpells.push_back(PlayerFSpells); , however, it gives me the error message:

```<code>no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back
[with _Ty=std::vector<Spell, std::allocator<Spell>>,
_Alloc=std::allocator<std::vector<Spell, std::allocator<Spell>>>]"
matches the argument list
</code>```

答:
If you come from some other languages, you may be used to treat mutable values as implicit references. In those languages, you typically gain the ability to easily construct collections of different types, which may or may not share an interface, and you may or may not treat them polymorphically (late binding).

In C++, however, objects are not references: they are the actual objects in memory, which requires them to have a compile-time-known size. You can still rather easily create polymorphic collections through a pointer or a reference, though, or even have collections of objects without a common interface; but you have to be explicit about it -- and know the rules of the language to prevent gotchas like slicing (see What is object slicing? for instance).

Body:
I'm trying to make a vector of vectors in a spell system for a small RPG battle simulation. The main goal I'm trying to accomplish is have a vector of Spells that the player can access and select what type of Spells they want to cast: Fire, Ice, etc. and then choose the name of the spell: burn, frost, etc.

The code below is what I've declared Spell and FireSpell as. I'm trying to insert a vector of FireSpells into a vector of type vector spells, however, it does not insert.  Is there a way to make it insert?

I've tried the push_back on a FireSpell into a vector of Spells and it works fine, however, it always returns an error when I push_back a FireSpell vector into a vector of type vector Spell.

Magic.h

struct Fire
{
    int damage;
    int dps;
};

struct Spell
{
    int cost;
    string name;
};

struct FireSpell : Spell, Fire
{

};

Magic.cpp

#include <iostream>
#include "MagicSys.h"
#include <vector>
#include <string>
#include "Magic.h"

using std::cout;
using std::vector;

FireSpell burn;
FireSpell inferno;
FireSpell volcano;

int mainfunc()
{
    vector<vector<Spell>> PlayerSpells;
    vector<FireSpell> PlayerFSpells;
    PlayerFSpells.push_back(burn);
    PlayerFSpells.push_back(inferno);
    PlayerFSpells.push_back(volcano);

 /*Trying to insert FireSpell Vector into the end of the vector of Spell vectors*/

    PlayerSpells.push_back(PlayerFSpells);

    vector<vector<Spell>>::iterator it;
    for (it = PlayerSpells.begin(); it!=PlayerSpells.end(); ++it)
        cout << &it << " ";

    return 0;
}

I expected the inner FireSpell vector to insert into the outer Spell vector on the line: PlayerSpells.push_back(PlayerFSpells); , however, it gives me the error message:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back
[with _Ty=std::vector<Spell, std::allocator<Spell>>,
_Alloc=std::allocator<std::vector<Spell, std::allocator<Spell>>>]"
matches the argument list


问:
string argument in template specialization in C++
In the following code, why the 's' after the string "hello" in the last line is necessary in order to deduce the type of the argument? It is an explicit casting to a string in c++?</p>

```<code>#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>
T addition(T const& a, T const& b){ return a + b;}

template <class T, size_t N>
T reduce(T const (&array)[N], T value = {}, T (*p)(T const&,T const&) = addition<T>)
{
  T res = value;
  for (int i = 0; i < N; i++) {
    res = p(res,array[i]);
  }
  return res;
}

double multiply(double const& lhs, double const& rhs)
{
    return lhs * rhs;
}

int main()
{
    double pi[]{0.0505, 0.0505, 0.0405};
    double factorial[]{1.0, 2.0, 3.0, 4.0, 5.0};
    string concat[]{" ", "world"};
    cout << reduce({1,2,3,4,5}) << endl;
    cout << reduce(pi, 3.0) << endl;
    cout << reduce(factorial, 1.0, multiply) << endl;
    cout << reduce(concat, "hello"s) << endl;
}
</code>```

答:
It's no necessary to deduce the argument, but without the s suffix it would not match.

Because decltype("hello") is const char(&)[6] and that would make T=const char*. But that does not match with the first passed argument concat of type std::string(&)[2] which requires T to be std::string.

The s suffix converts string literal to std::string. So yes, it's an explicit cast to a c++ string because in C/C++ string type is not part of the language and instead it's implemented simply as an array.

Body:
In the following code, why the 's' after the string "hello" in the last line is necessary in order to deduce the type of the argument? It is an explicit casting to a string in c++?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>
T addition(T const& a, T const& b){ return a + b;}

template <class T, size_t N>
T reduce(T const (&array)[N], T value = {}, T (*p)(T const&,T const&) = addition<T>)
{
  T res = value;
  for (int i = 0; i < N; i++) {
    res = p(res,array[i]);
  }
  return res;
}

double multiply(double const& lhs, double const& rhs)
{
    return lhs * rhs;
}

int main()
{
    double pi[]{0.0505, 0.0505, 0.0405};
    double factorial[]{1.0, 2.0, 3.0, 4.0, 5.0};
    string concat[]{" ", "world"};
    cout << reduce({1,2,3,4,5}) << endl;
    cout << reduce(pi, 3.0) << endl;
    cout << reduce(factorial, 1.0, multiply) << endl;
    cout << reduce(concat, "hello"s) << endl;
}


问:
How can I remove unwated query parameters from url that are passed via Model?
I created a simple login page in .net core C# with a model like so:

```<code>
        public string UserEmail { get; set; }

        public string UserPassword { get; set; }
</code>```

and i set it on my razor page like so:

```<code><input type="email" id="email-user" class="form-control mb-4" asp-for="UserEmail" placeholder="E-mail">

<input type="password" id="password-user" class="form-control mb-4" asp-for="UserPassword" placeholder="Password">
</code>```

after user clicks a button, he goes to next page but the url contains his email and password like so:

```<code>https://localhost:44306/User/Welcome?UserEmail=sampleemail%40gmail.com&UserPassword=dasdasdsa
</code>```

答:
I believe you are using a GET request where you would want to use a POST request.

During a GET request, parameters can be sent throw the URL.
In a POST request, you can send your parameters throw the body of the request.

Please consult what-is-the-difference-between-post-and-get and this doc to get more details on HTTP protocol.

Body:
I created a simple login page in .net core C# with a model like so:

        public string UserEmail { get; set; }

        public string UserPassword { get; set; }

and i set it on my razor page like so:

<input type="email" id="email-user" class="form-control mb-4" asp-for="UserEmail" placeholder="E-mail">

<input type="password" id="password-user" class="form-control mb-4" asp-for="UserPassword" placeholder="Password">

after user clicks a button, he goes to next page but the url contains his email and password like so:

https://localhost:44306/User/Welcome?UserEmail=sampleemail%40gmail.com&UserPassword=dasdasdsa


问:
Cannot set headers after they are sent to the client NodeJS
I am writing some Node JS API for login. I have written the logic but I am encountering an issue when I am sending back the response. Here is my code:

```<code>app.post('/API/login', (request, response) => {
    model.findOne({ email: request.body.email }, (err, result) => {
        if (err) throw err;

        if (result) {
            bcrypt.compare(request.body.password, result.password, function (error, hash) {
                if (error) throw err;
                if (hash) {
                    request.session.logged = true;
                    request.session._id = result._id;
                    response.send(result._id);
                }
                else {
                    response.send('Incorrect Username and/or Password!');
                }
            })
        } else {
            response.send('Incorrect Username and/or Password!');
        }
        response.end();
    })
});
</code>```

However, I am encountering a problem. I keep getting the following error:

```<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (node_modules\express\lib\response.js:775:10)
    at ServerResponse.json (node_modules\express\lib\response.js:268:10)
    at ServerResponse.send node_modules\express\lib\response.js:162:21
    at login.js:73:34
    at node_modules\bcryptjs\dist\bcrypt.js:297:21
    at node_modules\bcryptjs\dist\bcrypt.js:1353:21
    at Immediate.next (node_modules\bcryptjs\dist\bcrypt.js:1233:21)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
</code>```

I am not sure what is causing this issue.

答:
You are trying to send a response with response.end() after you've already answered with response.send(...)

You can delete the response.end()statement :

```<code>app.post('/API/login', (request, response) => {
  model.findOne({ email: request.body.email }, (err, result) => {
    if (err) throw err;

    if (result) {
        bcrypt.compare(request.body.password, result.password, function (error, hash) {
            if (error) throw err;
            if (hash) {
                request.session.logged = true;
                request.session._id = result._id;
                response.send(result._id);
            }
            else {
                response.send('Incorrect Username and/or Password!');
            }
        })
    } else {
        response.send('Incorrect Username and/or Password!');
    }
  })
});
</code>```

Body:
I am writing some Node JS API for login. I have written the logic but I am encountering an issue when I am sending back the response. Here is my code:

app.post('/API/login', (request, response) => {
    model.findOne({ email: request.body.email }, (err, result) => {
        if (err) throw err;

        if (result) {
            bcrypt.compare(request.body.password, result.password, function (error, hash) {
                if (error) throw err;
                if (hash) {
                    request.session.logged = true;
                    request.session._id = result._id;
                    response.send(result._id);
                }
                else {
                    response.send('Incorrect Username and/or Password!');
                }
            })
        } else {
            response.send('Incorrect Username and/or Password!');
        }
        response.end();
    })
});

However, I am encountering a problem. I keep getting the following error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (node_modules\express\lib\response.js:775:10)
    at ServerResponse.json (node_modules\express\lib\response.js:268:10)
    at ServerResponse.send node_modules\express\lib\response.js:162:21
    at login.js:73:34
    at node_modules\bcryptjs\dist\bcrypt.js:297:21
    at node_modules\bcryptjs\dist\bcrypt.js:1353:21
    at Immediate.next (node_modules\bcryptjs\dist\bcrypt.js:1233:21)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

I am not sure what is causing this issue.

Body:
You are trying to send a response with response.end() after you've already answered with response.send(...)

You can delete the response.end()statement :

app.post('/API/login', (request, response) => {
  model.findOne({ email: request.body.email }, (err, result) => {
    if (err) throw err;

    if (result) {
        bcrypt.compare(request.body.password, result.password, function (error, hash) {
            if (error) throw err;
            if (hash) {
                request.session.logged = true;
                request.session._id = result._id;
                response.send(result._id);
            }
            else {
                response.send('Incorrect Username and/or Password!');
            }
        })
    } else {
        response.send('Incorrect Username and/or Password!');
    }
  })
});


问:
nn.NLLLoss() target size issue
I have a label of size [32,2,10] and I want to separate this label into label1 and label2, with which I need to compute loss against the input for each label1 and label2.

Model is VGG16 + additional classifier.

output classes = 10

```<code>class cust_vgg():
    def forward(self, images,model):
        out = model.features(images)
        out1 = model.avgpool(out)
        out1 = out1.reshape(out1.size(0), -1)
        return model.classifier(out1), model.classifier1(out1)

out = cust_vgg.forward(images,model)
out_classifier,out_classifier1 = out
labels1,labels2 = labels[0]
loss_classifier = nn.NLLLoss(out_classifier, labels1)
loss_classifier1 = nn.NLLLoss(out_classifier1,labels2)
loss = loss_classifier + loss_classifier1
loss.backward()
opt.step()
</code>```

Input batch_size should match with the target batch_size for
  nn.NLLLoss()

Error: Expected input batch_size (32) to match target batch_size (10).

答:
I am not 100% sure as I do not what the labels mean here. But I think what you want is to pick two different labels from 2nd index. Therefore you should change :

```<code>labels1,labels2 = labels[0]
</code>```

to

```<code>labels1,labels2 = labels[:, 0], labels[:, 1]
</code>```

Also, NLLLoss take class index as input, you do not have to use one-hot encoded labels. However, that problem has already been solved here

Title: nn.NLLLoss() target size issue

Body:
I have a label of size [32,2,10] and I want to separate this label into label1 and label2, with which I need to compute loss against the input for each label1 and label2.

Model is VGG16 + additional classifier.

output classes = 10

class cust_vgg():
    def forward(self, images,model):
        out = model.features(images)
        out1 = model.avgpool(out)
        out1 = out1.reshape(out1.size(0), -1)
        return model.classifier(out1), model.classifier1(out1)

out = cust_vgg.forward(images,model)
out_classifier,out_classifier1 = out
labels1,labels2 = labels[0]
loss_classifier = nn.NLLLoss(out_classifier, labels1)
loss_classifier1 = nn.NLLLoss(out_classifier1,labels2)
loss = loss_classifier + loss_classifier1
loss.backward()
opt.step()

Input batch_size should match with the target batch_size for
  nn.NLLLoss()

Error: Expected input batch_size (32) to match target batch_size (10).

Body:
I am not 100% sure as I do not what the labels mean here. But I think what you want is to pick two different labels from 2nd index. Therefore you should change :

labels1,labels2 = labels[0]

to

labels1,labels2 = labels[:, 0], labels[:, 1]

Also, NLLLoss take class index as input, you do not have to use one-hot encoded labels. However, that problem has already been solved here


问:
Different behavior due to different "looping styles"
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

2)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...

答: Generally, a for x in y type of statement expects y not to change within the loop. You are breaking that contract.

Body:
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

2)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...


问:
Problem with deleting files in Laravel and jquery
I'm beginner with Laravel and JQuery.

I have this code:

```<code><ul>
   <li class="file-id-46">- <a
      href="http://test.test/upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf"
      target="_blank">upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf</a>
      <a href="#" class="red removeThisFile"
         id="46">[delete file]</a>
   </li>
   <li class="file-id-47">- <a
      href="http://test.test/upload/other/65b13b47f09fc785d901e43e7864bab2.pdf"
      target="_blank">upload/other/65b13b47f09fc785d901e43e7864bab2.pdf</a>
      <a href="#" class="red removeThisFile"
         id="47">[delete file]</a>
   </li>
   <li class="file-id-48">- <a
      href="http://test.test/upload/other/19846324513791f79013fb8e5a7854d8.pdf"
      target="_blank">upload/other/19846324513791f79013fb8e5a7854d8.pdf</a>
      <a href="#" class="red removeThisFile"
         id="48">[delete file]</a>
   </li>
   <li class="file-id-49">- <a
      href="http://test.test/upload/other/fca69b7c02ae223cd167202368d3a555.pdf"
      target="_blank">upload/other/fca69b7c02ae223cd167202368d3a555.pdf</a>
      <a href="#" class="red removeThisFile"
         id="49">[delete file]</a>
   </li>
   <li class="file-id-50">- <a
      href="http://test.test/upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf"
      target="_blank">upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf</a>
      <a href="#" class="red removeThisFile"
         id="50">[delete file]</a>
   </li>
   <li class="file-id-51">- <a
      href="http://test.test/upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf"
      target="_blank">upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf</a>
      <a href="#" class="red removeThisFile"
         id="51">[delete file]</a>
   </li>
   <li class="file-id-52">- <a
      href="http://test.test/upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf"
      target="_blank">upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf</a>
      <a href="#" class="red removeThisFile"
         id="52">[delete file]</a>
   </li>
</ul>

$(".removeThisFile").click(function () {
                    var id = $(this).attr("id");
                    $('.file-id-' + id).hide();
                    $.ajax({
                        url: 'http://test.test/psCMS/removeOtherFile?id=52',
                        type: 'get',
                        dataType: 'json',
                        _token: $('meta[name="_token"]').attr('content'),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        cache: false,
                        success: function (response) {
                            $(this).hide();
                        }
                    });
</code>```

Generally, jquery correctly sends a query to php (Laravel).
The problem occurs in deleting files. The first file is deleted correctly. The next file can not be slept.
I suspect that I have an invalid X-CSRF-TOKEN token after deleting the previous file.

How can I fix this problem?

答:
In js code:

```<code>$(".removeThisFile").click(function () {
    var id = $(this).attr("id");
    $('.file-id-' + id).hide();
    $.ajax({
        url: 'http://test.test/psCMS/removeOtherFile/'+id,
        type: 'get',
        dataType: 'json',
        cache: false,
        success: function (response) {
            $(this).hide();
        }
    });
});
</code>```

In route file (web.php):

```<code>Route::get('/psCMS/removeOtherFile/{id}', 'YourController@removeOtherFile');
</code>```

In controller:

```<code>public function removeOtherFile($id){

    $my_id = $id;
    // here is your id
}
</code>```

Body:
I'm beginner with Laravel and JQuery.

I have this code:

- upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf
      [delete file]

- upload/other/65b13b47f09fc785d901e43e7864bab2.pdf
      [delete file]

- upload/other/19846324513791f79013fb8e5a7854d8.pdf
      [delete file]

- upload/other/fca69b7c02ae223cd167202368d3a555.pdf
      [delete file]

- upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf
      [delete file]

- upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf
      [delete file]

- upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf
      [delete file]

$(".removeThisFile").click(function () {
                    var id = $(this).attr("id");
                    $('.file-id-' + id).hide();
                    $.ajax({
                        url: 'http://test.test/psCMS/removeOtherFile?id=52',
                        type: 'get',
                        dataType: 'json',
                        _token: $('meta[name="_token"]').attr('content'),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        cache: false,
                        success: function (response) {
                            $(this).hide();
                        }
                    });

Generally, jquery correctly sends a query to php (Laravel).
The problem occurs in deleting files. The first file is deleted correctly. The next file can not be slept.
I suspect that I have an invalid X-CSRF-TOKEN token after deleting the previous file.

How can I fix this problem?

Body:
In js code:

$(".removeThisFile").click(function () {
    var id = $(this).attr("id");
    $('.file-id-' + id).hide();
    $.ajax({
        url: 'http://test.test/psCMS/removeOtherFile/'+id,
        type: 'get',
        dataType: 'json',
        cache: false,
        success: function (response) {
            $(this).hide();
        }
    });
});

In route file (web.php):

Route::get('/psCMS/removeOtherFile/{id}', 'YourController@removeOtherFile');

In controller:

public function removeOtherFile($id){

    $my_id = $id;
    // here is your id
}


问:
How to return fields of both related models in a Django ManyToMany relation?
I have two models:

class P(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...

class F(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...
    p = models.ManyToManyField(P)
```

<p>I need a query like this:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT p.name, f.name
FROM f
JOIN f_p ON f.id = f_p.f_id
JOIN p ON p.id= f_p.p_id
</code>```

I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names.

In psql the query works like I need. How can I do this in Django?

答:
Use prefetch_related:

F.objects.filter(...).prefetch_related('p')
```

Body:
I have two models:

class P(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...

class F(mdoels.Model):
    name = models.CharField(null=False,max_length=120)
    ...
    p = models.ManyToManyField(P)

I need a query like this:

SELECT p.name, f.name
FROM f
JOIN f_p ON f.id = f_p.f_id
JOIN p ON p.id= f_p.p_id

I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names.

In psql the query works like I need. How can I do this in Django?


问:
Django annotate average query not showing decimal places
I'm working with Django and I'm taking an average for some column values, however the result is rounded up and I'd like to make it one or two decimal places. My goal is to see the result look like 3.5 instead of 4.

My model is named Application and the columns have an IntegerField model type. My database is PostgreSQL.

Here's the query that I'm using to currently take the average of my column values:

```<code>ratings = Application.objects.filter(id = review.id).annotate(rate = (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6)
</code>```

I've already tried playing with FloatFields, but maybe I did it wrong.

Any suggestions?

Thanks in advance!

EDIT: Here is my model for the columns.

```<code>col_1 = models.IntegerField(choices=USER_CHOICE)
...
col_6 = models.IntegerField(choices=USER_CHOICE)
</code>```

答:
You can use an ExpressionWrapper [Django-doc] here to set this to a FloatField [Django-doc] or DecimalField:

```<code>from django.db.models import <b>ExpressionWrapper</b>, FloatField

ratings = Application.objects.filter(id=review.id).annotate(
    rate=<b>ExpressionWrapper(</b>
        (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6,
        <b>output_field=FloatField()</b>
    <b>)</b>
)</code>```

Depending on the situation, it might be better to use a FloatField or a DecimalField [Django-doc].

Body:
I'm working with Django and I'm taking an average for some column values, however the result is rounded up and I'd like to make it one or two decimal places. My goal is to see the result look like 3.5 instead of 4.

My model is named Application and the columns have an IntegerField model type. My database is PostgreSQL.

Here's the query that I'm using to currently take the average of my column values:

ratings = Application.objects.filter(id = review.id).annotate(rate = (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6)

I've already tried playing with FloatFields, but maybe I did it wrong.

Any suggestions?

Thanks in advance!

EDIT: Here is my model for the columns.

col_1 = models.IntegerField(choices=USER_CHOICE)
...
col_6 = models.IntegerField(choices=USER_CHOICE)

Body:
You can use an ExpressionWrapper [Django-doc] here to set this to a FloatField [Django-doc] or DecimalField:

from django.db.models import ExpressionWrapper, FloatField

ratings = Application.objects.filter(id=review.id).annotate(
    rate=ExpressionWrapper(
        (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6,
        output_field=FloatField()
    )
)

Depending on the situation, it might be better to use a FloatField or a DecimalField [Django-doc].


问:
added button to sceneKit view but it has a lag
I added a custom button to the sceneKit view. When it is touched, it plays an animation, indicating that it was clicked. The problem I'm facing is the delay between user touch and start of animation. My scene has 28.1K triangles and 84.4K vertices. Is that to much or do I need to implement buttons differently. The scene renders with 60fps. I added the button via sceneView.addSubview: Thanks for answers

```<code>     viewDidLoad(){
     // relevant code
        starButton = UIButton(type: UIButtonType.Custom)
        starButton.frame = CGRectMake(100, 100, 50, 50)
        starButton.setImage(UIImage(named: "yellowstar.png"), forState: UIControlState.Normal)
        sceneView.addSubview(starButton)
        starButton.addTarget(self, action: "starButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        starButton.adjustsImageWhenHighlighted = false
        }

    func starButtonClicked(){
            animateScaleDown()

        }

    func animateScaleDown(){

        UIView.animateWithDuration(0.1, animations: {
            self.starButton.transform = CGAffineTransformMakeScale(0.8, 0.8)

            }, completion: { _ in
                self.wait()
        })

    }

    func wait(){
        UIView.animateWithDuration(0.2, animations: {}, completion: { _ in
            UIView.animateWithDuration(0.2, animations: {
                self.starButton.transform = CGAffineTransformMakeScale(1, 1)

            })
        })
    }
</code>```

答:
For Swift 5</p>

```<code>var starButton = UIButton()

    func a ()  {

        starButton = UIButton(type: UIButton.ButtonType.custom)
        starButton.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
        starButton.backgroundColor = .blue
        SpielFenster.addSubview(starButton)

        starButton.addTarget(self, action: #selector(starButtonClicked), for: UIControl.Event.touchDown)
        starButton.adjustsImageWhenHighlighted = false
    }
    @objc func starButtonClicked(){
        animateScaleDown()
    }

    func animateScaleDown(){

        UIView.animate(withDuration: 0.1, animations: {
            self.starButton.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

        }, completion: { _ in
            self.wait()
        })

    }

    func wait(){
        UIView.animate(withDuration: 0.2, animations: {}, completion: { _ in
            UIView.animate(withDuration: 0.2, animations: {
                self.starButton.transform = CGAffineTransform(scaleX: 1, y: 1)

            })
        })
    }
</code>```

Body:
I added a custom button to the sceneKit view. When it is touched, it plays an animation, indicating that it was clicked. The problem I'm facing is the delay between user touch and start of animation. My scene has 28.1K triangles and 84.4K vertices. Is that to much or do I need to implement buttons differently. The scene renders with 60fps. I added the button via sceneView.addSubview: Thanks for answers

     viewDidLoad(){
     // relevant code
        starButton = UIButton(type: UIButtonType.Custom)
        starButton.frame = CGRectMake(100, 100, 50, 50)
        starButton.setImage(UIImage(named: "yellowstar.png"), forState: UIControlState.Normal)
        sceneView.addSubview(starButton)
        starButton.addTarget(self, action: "starButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        starButton.adjustsImageWhenHighlighted = false
        }

    func starButtonClicked(){
            animateScaleDown()

        }

    func animateScaleDown(){

        UIView.animateWithDuration(0.1, animations: {
            self.starButton.transform = CGAffineTransformMakeScale(0.8, 0.8)

            }, completion: { _ in
                self.wait()
        })

    }

    func wait(){
        UIView.animateWithDuration(0.2, animations: {}, completion: { _ in
            UIView.animateWithDuration(0.2, animations: {
                self.starButton.transform = CGAffineTransformMakeScale(1, 1)

            })
        })
    }

Body:
For Swift 5

var starButton = UIButton()

    func a ()  {

        starButton = UIButton(type: UIButton.ButtonType.custom)
        starButton.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
        starButton.backgroundColor = .blue
        SpielFenster.addSubview(starButton)

        starButton.addTarget(self, action: #selector(starButtonClicked), for: UIControl.Event.touchDown)
        starButton.adjustsImageWhenHighlighted = false
    }
    @objc func starButtonClicked(){
        animateScaleDown()
    }

    func animateScaleDown(){

        UIView.animate(withDuration: 0.1, animations: {
            self.starButton.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)

        }, completion: { _ in
            self.wait()
        })

    }

    func wait(){
        UIView.animate(withDuration: 0.2, animations: {}, completion: { _ in
            UIView.animate(withDuration: 0.2, animations: {
                self.starButton.transform = CGAffineTransform(scaleX: 1, y: 1)

            })
        })
    }


答:
you are calling postData before to implement the method, as mentioned move your function document.ready or put

```<code>  <script type="text/javascript">
    function postData() {
        return $.ajax({
        var datastring = $("#echo_test").serialize();
        $.ajax({
           type: "POST",
           url: "echo_test.php",
           data: {post: datastring},
        });
    });
    }
</script>
</code>```

in the head of the html file

Title: jQuery onClick function to submit data to php "not defined"

Body:
The following button calls a jQuery function onClick.  However, the Firefox dev console says "postData is not defined."

Here is the button and the jQuery script.

    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button>

function sendReply() {
    // autoresponder
}

postData().done(sendReply);

</script>

</form>

Body:
you are calling postData before to implement the method, as mentioned move your function document.ready or put

  <script type="text/javascript">
    function postData() {
        return $.ajax({
        var datastring = $("#echo_test").serialize();
        $.ajax({
           type: "POST",
           url: "echo_test.php",
           data: {post: datastring},
        });
    });
    }
</script>

in the head of the html file


问:
Angular Material - Chips Autocomplete - how to display required error message & error highlight color
Stackblitz example link

I am using angular material - mat-autocomplete inside form. I want to show red highlight text and border color to the input field  & mat-error message for matAutocomplete input  when form is invalid. Suggestion for reactive or template driven form will work

答:
Add template reference variable to mat-form-field

```<code><mat-form-field #tagsField>
        <mat-label><strong>Tags</strong></mat-label>
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let tag of tags" [selectable]="selectable" [removable]="removable"
            (removed)="remove(tag)" required>
            {{tag}}
            <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
          </mat-chip>
          <input placeholder="eg.(C#,VB)" #tagInput [formControl]="frmAskQuestion.controls['tags']"
            [matAutocomplete]="auto" [matChipInputFor]="chipList"
            [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur"
            (matChipInputTokenEnd)="add($event)" required>
        </mat-chip-list>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)" required>
          <mat-option *ngFor="let tag of filteredTags" [value]="tag">
            {{tag}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
</code>```

and then is ts page

```<code>  if (!this.frmAskQuestion.valid) {
  this.tagsField._elementRef.nativeElement.classList.add("mat-form-field-invalid");
}
else{
  this.tagsField._elementRef.nativeElement.classList.remove("mat-form-field-invalid");
}
</code>```

Note : This not the best way but i couldn't find any other way

Body:
Add template reference variable to mat-form-field

<mat-form-field #tagsField>
        <mat-label><strong>Tags</strong></mat-label>
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let tag of tags" [selectable]="selectable" [removable]="removable"
            (removed)="remove(tag)" required>
            {{tag}}
            <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
          </mat-chip>
          <input placeholder="eg.(C#,VB)" #tagInput [formControl]="frmAskQuestion.controls['tags']"
            [matAutocomplete]="auto" [matChipInputFor]="chipList"
            [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur"
            (matChipInputTokenEnd)="add($event)" required>
        </mat-chip-list>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)" required>
          <mat-option *ngFor="let tag of filteredTags" [value]="tag">
            {{tag}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>

and then is ts page

  if (!this.frmAskQuestion.valid) {
  this.tagsField._elementRef.nativeElement.classList.add("mat-form-field-invalid");
}
else{
  this.tagsField._elementRef.nativeElement.classList.remove("mat-form-field-invalid");
}

Note : This not the best way but i couldn't find any other way


问:
developin web app using .net need Info about Local System
we are devoloping a web application using c#.net,ASP.Net 3.5,in that we need to know the infomation  of local system  like what are the  installed printers? is there any way to get the data using any scripting Languages? Plz let me know if any body knows the answer.

Thanks in advance
Prasad

答:
we are devoloping a web application using c#.net,ASP.Net 3.5,in that we need to know the
  infomation  of local system like what are the installed printers?

Are you? Why do you formulate this as a question. Are you not sure what you are doing?

is there any way to get the data using any scripting Languages?

Maybe, maybe not. Irrelevant, though, as ASP.NET is not using scripting langauges on the server anyway. Your server sidel ogic will be ni C# or VB.NET likely (or any other .NET langauge) and by all means this is not a scripting langauge.

if yuo talk of the client side (i.e. from the browser: no way, and you have no busienss knowing. The internet is not a friendly place. Whatever rights you think you want can be abused by some bad person. And will be.

Plz let me know if any body knows the answer.

Yes, someone knows the answer. Which answers yoru question. Note: you did not ask for an answer, you asked whether anyone knows the answer.

Now, real:

Yes, you can. WMI is your friend. The main problem will be:

Understanding the WMI documentation. WMI is the Windows Management Instrumentation and you can prettya much see everything of any computer you can connect WMI to there.

Configuring IIS to allow you local access.


问:
Why is the core chat script stopping my entire game?
```<code>15:49:30.355 - BackgroundImage is not a valid member of Frame
15:49:30.356 - Stack Begin
15:49:30.357 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsTab', Line 212 - method AnimGuiObjects
15:49:30.357 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsTab', Line 262 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsBar', Line 352 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChatWindow', Line 634 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain', Line 171
15:49:30.359 - Stack End
</code>```

This above was the error I have received

After the error hits, almost all the running scripts freeze and stop working. The script that runs when this occurs is a simple camera manipulation with lerp() and by what I can tell, it only occurs when this script is running, but the thing isI have made a new world, and put everything in there, still didnt work, checked for viruses, not the case, removed all frames in all the GUIs in my game, and it still remains like this.
The line in the chat script thats causing this is:

```<code>self.SelectedFrame.BackgroundImage.BackgroundTransparency = self.AnimParams.Background_CurrentTransparency
</code>```

And I cant simply change it because it only appears in game, or when you press play in studio, so you cant just change it.

答:
This error isn't anything to do with your code. The ChatScript is a script that Roblox has written and provides for free. It looks like they shipped a bug. If you want to disable in-game chat for testing and development try this.

Create a LocalScript in StarterPlayer > StarterPlayerScripts. Add this line :

```<code>game.StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Chat, false)
</code>```

This should prevent the ChatScript from being added to the player when they spawn. Roblox will have to fix this bug.

Body:
15:49:30.355 - BackgroundImage is not a valid member of Frame
15:49:30.356 - Stack Begin
15:49:30.357 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsTab', Line 212 - method AnimGuiObjects
15:49:30.357 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsTab', Line 262 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChannelsBar', Line 352 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain.ChatWindow', Line 634 - method Update
15:49:30.358 - Script 'Players.Crusade_Commander.PlayerScripts.ChatScript.ChatMain', Line 171
15:49:30.359 - Stack End

This above was the error I have received

After the error hits, almost all the running scripts freeze and stop working. The script that runs when this occurs is a simple camera manipulation with lerp() and by what I can tell, it only occurs when this script is running, but the thing isI have made a new world, and put everything in there, still didnt work, checked for viruses, not the case, removed all frames in all the GUIs in my game, and it still remains like this.
The line in the chat script thats causing this is:

self.SelectedFrame.BackgroundImage.BackgroundTransparency = self.AnimParams.Background_CurrentTransparency

And I cant simply change it because it only appears in game, or when you press play in studio, so you cant just change it.

Body:
This error isn't anything to do with your code. The ChatScript is a script that Roblox has written and provides for free. It looks like they shipped a bug. If you want to disable in-game chat for testing and development try this.

Create a LocalScript in StarterPlayer > StarterPlayerScripts. Add this line :

game.StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Chat, false)

This should prevent the ChatScript from being added to the player when they spawn. Roblox will have to fix this bug.


问:
Install specific PHP version for mac
I need a specific version of PHP for magento (7.1.3)

With home brew or curl, I can only specify one decimal (7.1, 7.2 etc).

Running

```<code>brew install php@7.1
</code>```

ultimately gets me

```<code>php -v
PHP 7.1.29 (cli) (built: May 21 2019 20:05:17) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.1.29, Copyright (c) 1999-2018, by Zend
Technologies
</code>```

trying to install a specific version (like you can with node using nvm):

```<code>brew install php@7.1.3
</code>```

gets me

```<code>Error: No available formula with the name "php@7.1.3"
</code>```

I tried using a curl command, same issue:

```<code>https://php-osx.liip.ch/install.sh | bash -s 7.1.3
</code>```

gets me

```<code>Did or could not download package: 7.1.3-frontenddev
</code>```

TL;DR: How do i install exact version of PHP (7.1.3) on mac?

答:
I didn`t find this tagged version on PHP git page, so probably is repacked version for some linux distribution.
If you think that you need ~7.1.3 version because that wrotes on system requirements for magento, you can also use 7.2.0 as they wrote in
https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements-tech.html

so you can use:

```<code>brew install php@7.2
</code>```

Installing old version you miss latest bug fix and security fixes so i recommend to you at least PHP 7.2.

Title: Install specific PHP version for mac

Body:
I need a specific version of PHP for magento (7.1.3)

With home brew or curl, I can only specify one decimal (7.1, 7.2 etc).

Running

brew install php@7.1

ultimately gets me

php -v
PHP 7.1.29 (cli) (built: May 21 2019 20:05:17) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.1.29, Copyright (c) 1999-2018, by Zend
Technologies

trying to install a specific version (like you can with node using nvm):

brew install php@7.1.3

gets me

Error: No available formula with the name "php@7.1.3"

I tried using a curl command, same issue:

https://php-osx.liip.ch/install.sh | bash -s 7.1.3

gets me

Did or could not download package: 7.1.3-frontenddev

TL;DR: How do i install exact version of PHP (7.1.3) on mac?

Body:
I didn`t find this tagged version on PHP git page, so probably is repacked version for some linux distribution.
If you think that you need ~7.1.3 version because that wrotes on system requirements for magento, you can also use 7.2.0 as they wrote in
https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements-tech.html

so you can use:

brew install php@7.2

Installing old version you miss latest bug fix and security fixes so i recommend to you at least PHP 7.2.


问:
Base64 clipping images from database PHP
I am making a website that displays games from a database made in MySQL workbench. I want to have images appear next to the relevant game title of said game. The problem I am having is that I am inserting these images into my database using BLOB and converting them to base64 within the PHP. When I do this and run it, the images come out clipped.

This gets the information from the table that I created in MySQL

```<code>function find_all_games(){
    global $db; //Connects to database
    $sql = 'SELECT * FROM game';
    $result = mysqli_query($db, $sql);
    return $result;
}
</code>```

This is the table that pulls the information that I want from the database and converts the blob to a base64 image, but the images appear clipped.

```<code>'<?php while($game = mysqli_fetch_assoc($get_all_games)) {?>
<table>
    <tr>
      <td><?php
                echo '<img src="data:image/jpeg;base64,'.base64_encode($game['image']).' "height="301" width="220" />'; ?>
      </td>
    </tr>
    <tr>
      <td id="title"><?php echo $game['title']; ?></td>
    </tr>
    <tr>
      <td class="title">Released:</td>
      <td class="data"><?php echo $game['release_date']; ?></td>
    </tr>
    <tr>
      <td class="title">Publisher:</td>
      <td class="data"><?php echo $game['publisher']; ?></td>
    </tr>
</table>
</code>```

'

The image should appear just fine but comes out with a white clip on the bottom that changes for each image even though they are all the same size in pixels.

Evidence that the images display, but are clipped

答:
For anyone who had the same issue as me:
Courtesy of Jeff (https://stackoverflow.com/users/2417483/jeff), I was just being silly, and it turned out all I needed to do was make it a MEDIUMBLOB or LONGBLOB depending on the file sizes of your images.</p>

Body:
I am making a website that displays games from a database made in MySQL workbench. I want to have images appear next to the relevant game title of said game. The problem I am having is that I am inserting these images into my database using BLOB and converting them to base64 within the PHP. When I do this and run it, the images come out clipped.

This gets the information from the table that I created in MySQL

function find_all_games(){
    global $db; //Connects to database
    $sql = 'SELECT * FROM game';
    $result = mysqli_query($db, $sql);
    return $result;
}

This is the table that pulls the information that I want from the database and converts the blob to a base64 image, but the images appear clipped.

'<?php while($game = mysqli_fetch_assoc($get_all_games)) {?>

      <?php
                echo ''; ?>

      <?php echo $game['title']; ?>

      Released:
      <?php echo $game['release_date']; ?>

      Publisher:
      <?php echo $game['publisher']; ?>

'

The image should appear just fine but comes out with a white clip on the bottom that changes for each image even though they are all the same size in pixels.

Evidence that the images display, but are clipped


问:
Behaviour of templated class wrapping a member function call
I have a function of a class I would like to iteratively call inside a loop, and while the loop is fixed, I want to be able to provide different functions (from the given object). To approach this, I created a templated struct MyWrapper to take the object whose function I want to call, the function itself, and data for which to evaluate the function. (In that sense, the member function will always have the same signature)

What I found though, was that using a member function pointer incurs a huge performance cost, even though at compile time, I know the function I want to call. So I was messing around to try and fix this, and (while I'm still unclear why the first situation happens), I've experienced another interesting behaviour.

In the following situation, every call to the wrapper function MyWrapper::eval will actually attempt to copy my whole Grid object into the parameter to the given function it has to wrap, f, even though the call to MyEquation::eval will know not to copy it every time (because of optimization).

template<typename T>
double neighbour_average(T *v, int n)
{
    return v[-n] + v[n] - 2 * v[0];
}

template<typename T>
struct MyEquation
{
    T constant;
    int n;
    T eval(Grid<T, 2> v, int i)
    {
        return rand() / RAND_MAX + neighbour_average(v.values + i, n) + constant;
    }
};

template<typename T, typename R, typename A>
struct MyWrapper
{
    MyWrapper(T &t, R(T::*f)(A, int), A a) : t{ t }, f{ f }, a{ a } {}
    auto eval(int i)
    {
        return (t.*f)(a, i);
    }

protected:
    A a;
    T &t;
    R(T::*f)(A, int);
};

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

    srand((unsigned int)time(NULL));
    for (iter_type i = 0; i < config().len_; ++i)
    {
        op.values[i] = rand() / RAND_MAX;
    }

    srand((unsigned int)time(NULL));
    double constant = rand() / RAND_MAX;
    int n = 2;
    int test_len = 100'000,
    int test_run = 100'000'000;

    Grid<double, 2> arr(100, 1000);
    MyEquation<double> eq{ constant, n };
    MyWrapper weq(eq, &MyEquation<double>::eval, arr); // I'm wrapping what I want to do

    {
        // Time t0("wrapper thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += weq.eval(n + i % (test_len - n)); // a call to the wrapping class to evaluate
        }
    }
    {
        // Time t0("regular thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += rand() / RAND_MAX + neighbour_average(arr.values + n + i % (test_len - n), n) + constant; // a usage of the neighbour function without the wrapping call
        }
    }

    {
        // Time t0("function thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += eq.eval(arr, n + i % (test_len - n)); // raw evaluation of my equation
        }
    }

}

```

Some context:

Grid is just a glorified dynamic array Grid::values with a few helper functions.

I've retained some of the (seemingly unnecessary) templates to my function and object, because it closely parallels how my code is actually set up.

The Time class will give me the duration of the object lifetime, so its a quick and dirty way of measuring certain blocks of code.

So anyways...

If the following code is changed so the signature of the function taken by MyWrapper is R(T::*f)(A&, int), then the execution time of MyWrapper::eval will be almost identical to the other calls (which is what I want anyways).

Why doesn't the compiler (msvc 2017) know it should treat the call weq.eval(n) (and consequently (t.*f)(a, n)) the with the same optimization considerations way as the direct evaluation, if the signature and function is given at compile time?

答:
A function parameter is its own variable, which gets initialized from a function call argument.  So when a function argument in the calling function is an lvalue such as the name of an object previously defined, and the function parameter is an object type, not a reference type, the parameter and the argument are two different objects.  If the parameter has a class type, this means a constructor for that type has to be executed (unless the initialization is an aggregate initialization from a {} initializer list).

In other words, every call to

```<code>T eval(Grid<T, 2> v, int i);
</code>```

needs to create a new Grid<T, 2> object called v, whether it's called via function pointer or by the member name eval.

But in many cases, initialization of a reference doesn't create a new object. It appears your eval doesn't need to modify v or the MyEquation, so it would be better to declare that eval as:

```<code>T eval(const Grid<T, 2> &v, int i) const;
</code>```

This would mean the function pointer in Wrapper needs to be R (T::*f)(const A&, int) const.

But another change you might want to make, especially since Wrapper is already a template: Just make the function used a generic type, so that it can hold non-member function pointers, wrappers to member function pointers with any signature, lambdas, or any other class type with an operator() member.

```<code>#include <utility>

template<typename F, typename A>
struct MyWrapper
{
    MyWrapper(F f, A a) : f{ std::move(f) }, a{ std::move(a) } {}
    auto eval(int i)
    {
        return f(a, i);
    }

protected:
    A a;
    F f;
};
</code>```

Then two ways to create your Wrapper weq; are:

```<code>Wrapper weq([&eq](const auto &arr, int i) {
    return eq.eval(arr, i);
}, arr);
</code>```

or (requires #include <functional>):

```<code>using namespace std::placeholders;
Wrapper weq(
    std::bind(std::mem_fn(&MyEquation<double>::eval), _1, _2),
    arr);
</code>```

Body:
I have a function of a class I would like to iteratively call inside a loop, and while the loop is fixed, I want to be able to provide different functions (from the given object). To approach this, I created a templated struct MyWrapper to take the object whose function I want to call, the function itself, and data for which to evaluate the function. (In that sense, the member function will always have the same signature)

What I found though, was that using a member function pointer incurs a huge performance cost, even though at compile time, I know the function I want to call. So I was messing around to try and fix this, and (while I'm still unclear why the first situation happens), I've experienced another interesting behaviour.

In the following situation, every call to the wrapper function MyWrapper::eval will actually attempt to copy my whole Grid object into the parameter to the given function it has to wrap, f, even though the call to MyEquation::eval will know not to copy it every time (because of optimization).

template<typename T>
double neighbour_average(T *v, int n)
{
    return v[-n] + v[n] - 2 * v[0];
}

template<typename T>
struct MyEquation
{
    T constant;
    int n;
    T eval(Grid<T, 2> v, int i)
    {
        return rand() / RAND_MAX + neighbour_average(v.values + i, n) + constant;
    }
};

template<typename T, typename R, typename A>
struct MyWrapper
{
    MyWrapper(T &t, R(T::*f)(A, int), A a) : t{ t }, f{ f }, a{ a } {}
    auto eval(int i)
    {
        return (t.*f)(a, i);
    }

protected:
    A a;
    T &t;
    R(T::*f)(A, int);
};

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

    srand((unsigned int)time(NULL));
    for (iter_type i = 0; i < config().len_; ++i)
    {
        op.values[i] = rand() / RAND_MAX;
    }

    srand((unsigned int)time(NULL));
    double constant = rand() / RAND_MAX;
    int n = 2;
    int test_len = 100'000,
    int test_run = 100'000'000;

    Grid<double, 2> arr(100, 1000);
    MyEquation<double> eq{ constant, n };
    MyWrapper weq(eq, &MyEquation<double>::eval, arr); // I'm wrapping what I want to do

    {
        // Time t0("wrapper thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += weq.eval(n + i % (test_len - n)); // a call to the wrapping class to evaluate
        }
    }
    {
        // Time t0("regular thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += rand() / RAND_MAX + neighbour_average(arr.values + n + i % (test_len - n), n) + constant; // a usage of the neighbour function without the wrapping call
        }
    }

    {
        // Time t0("function thing");
        for (int i = 0; i < test_run; ++i)
        {
            arr.values[n + i % (test_len - n)] += eq.eval(arr, n + i % (test_len - n)); // raw evaluation of my equation
        }
    }

}

Some context:

Grid is just a glorified dynamic array Grid::values with a few helper functions.

I've retained some of the (seemingly unnecessary) templates to my function and object, because it closely parallels how my code is actually set up.

The Time class will give me the duration of the object lifetime, so its a quick and dirty way of measuring certain blocks of code.

So anyways...

If the following code is changed so the signature of the function taken by MyWrapper is R(T::*f)(A&, int), then the execution time of MyWrapper::eval will be almost identical to the other calls (which is what I want anyways).

Why doesn't the compiler (msvc 2017) know it should treat the call weq.eval(n) (and consequently (t.*f)(a, n)) the with the same optimization considerations way as the direct evaluation, if the signature and function is given at compile time?

Body:
A function parameter is its own variable, which gets initialized from a function call argument.  So when a function argument in the calling function is an lvalue such as the name of an object previously defined, and the function parameter is an object type, not a reference type, the parameter and the argument are two different objects.  If the parameter has a class type, this means a constructor for that type has to be executed (unless the initialization is an aggregate initialization from a {} initializer list).

In other words, every call to

T eval(Grid<T, 2> v, int i);

needs to create a new Grid<T, 2> object called v, whether it's called via function pointer or by the member name eval.

But in many cases, initialization of a reference doesn't create a new object. It appears your eval doesn't need to modify v or the MyEquation, so it would be better to declare that eval as:

T eval(const Grid<T, 2> &v, int i) const;

This would mean the function pointer in Wrapper needs to be R (T::*f)(const A&, int) const.

But another change you might want to make, especially since Wrapper is already a template: Just make the function used a generic type, so that it can hold non-member function pointers, wrappers to member function pointers with any signature, lambdas, or any other class type with an operator() member.

#include <utility>

template<typename F, typename A>
struct MyWrapper
{
    MyWrapper(F f, A a) : f{ std::move(f) }, a{ std::move(a) } {}
    auto eval(int i)
    {
        return f(a, i);
    }

protected:
    A a;
    F f;
};

Then two ways to create your Wrapper weq; are:

Wrapper weq([&eq](const auto &arr, int i) {
    return eq.eval(arr, i);
}, arr);

or (requires #include <functional>):

using namespace std::placeholders;
Wrapper weq(
    std::bind(std::mem_fn(&MyEquation<double>::eval), _1, _2),
    arr);


问:
Why am I getting "runtime error (NZEC)" for this python code?(SPOJ Anti blot system)
I am getting runtime error (NZEC) for this python code even though it returns 0 when I run it on pycharm.

This is my first ever SPOJ problem and I'm new to python and coding in general. So please explain in layman's terms if possible

link to problem:

n=int(input())
for i in range(n):
    s=input().split()
    c=0

    while c<len(s):
        if s[c].find('machula')>=0:
            err=c
        c+=2
    if err==0:
        new=str(int(s[4])-int(s[2]))
    elif err==2:
        new=str(int(s[4])-int(s[0]))
    elif err==4:
        new=str(int(s[0])+int(s[2]))

    s[err]=new
    print(s[0]+" "+s[1]+" "+s[2]+" "+s[3]+" "+s[4])
```

答:
NZEC stands for Non Zero Exit Code, and means your program either did return with a non-zero exit code, or with an exception.

Did you actually test your application with the example input that was provided in the exercise? That's where the examples are intended for. If your program does not yield the correct result for the example input, then there's no point in submitting the solution. It will definitely fail then.

If your Python file is called 'absys.py' you should copy and paste the input (without any modifications) into a file 'input.txt' (for example) and then run:

python absys.py < input.txt
```

<p>If I run your code with the example input I get a Python exception:</p>

<pre class="lang-none prettyprint-override"><code>NameError: name 'err' is not defined
</code>```

which explains the NZEC.

Also note the first comment on the page you linked:

if anyone is getting runtime error try taking two getline() ..... one for line and one for the string.

...and carefully read the Input specification of the problem:

"Each test case is preceded by a blank line."

Your code does not skip the blank lines, and that's what causes the above error. With a simple fix your application returns the correct output for the given example input.

Body:
NZEC stands for Non Zero Exit Code, and means your program either did return with a non-zero exit code, or with an exception.

Did you actually test your application with the example input that was provided in the exercise? That's where the examples are intended for. If your program does not yield the correct result for the example input, then there's no point in submitting the solution. It will definitely fail then.

If your Python file is called 'absys.py' you should copy and paste the input (without any modifications) into a file 'input.txt' (for example) and then run:

python absys.py < input.txt

If I run your code with the example input I get a Python exception:

NameError: name 'err' is not defined

which explains the NZEC.

Also note the first comment on the page you linked:

if anyone is getting runtime error try taking two getline() ..... one for line and one for the string.

...and carefully read the Input specification of the problem:

"Each test case is preceded by a blank line."

Your code does not skip the blank lines, and that's what causes the above error. With a simple fix your application returns the correct output for the given example input.


问:
Mapping Virtual Memory to DRAM
I'm trying to map U-Space allocated virtual memory (shm) to particular DIMM.
I succeed to retrieve the pfns using get_user_pages_remote for the start pointer to vmemory and then converting each page struct to pfn with page_to_pfn(btw these pfns are further used to create scatter-gather table for proprietary frame grabber device and do the job perfectly). However I don't find a way to recognize which physical DIMM (DRAM) each physical address (pfn) is originated from. Internet search yielded some DRAM address mapping schemes but all of them seam to handle inside-the-mmodule navigation i.e.:row, column, bank, channel & rank and all of the former are memory provider architecture dependent e.g.https://www.betriebssysteme.org/wp-content/uploads/2017/04/Hillenbrand.pdf. On the other, side digging into SMBIOS Specification https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.1.pdf, system resident DIMMs properties may be retrieved from /dev/mem (dmidecode -t memory), however I fail to link these two info sources together and finally map the pages.

Any advice will be appreciated.

Thanks,

Yoel.

答:
What you're really asking about is mapping a physical address to DRAM. In general there is no single answer and on a given system, there may be no specific address bit. You will need to know your memory geometry and how your memory controller is configured. On Linux, there's decode-dimms which will query the DRAM chips themselves via an SPD protocol and that may tell you something about the memory geometry but not about the physical  to DRAM address mapping or its configuration. Your memory controller may scramble address bits to achieve more parallelism and to avoid bank thrashing. You have to get into the weeds.

Whereas the TLB hides the complexity of virtual to physical mapping, the DRAM memory controller hides the complexity of physical to DRAM mapping. (And you probably thought physical meant physical!) You need to learn more about physical to DRAM address mapping in general AND your memory controller and how the BIOS configures it in particular. A good tutorial on physical to DRAM address mapping. Another using a particular Sandy Bridge system. A sample Micron data sheet. You'll need to look at the boot logic of your system as it will setup the memory controller. I don't know if there's a way to query the memory controller as to what its configuration is. The OS probably won't touch that configuration and will instead trust that the BIOS has done the right thing. It may be possible to determine these things empirically. RowHammer papers would be a good place to look for that.

Title: Mapping Virtual Memory to DRAM


问:
Regex Replace A Variable Within Brackets, Including Brackets
How do I get rid of a variable within square brackets, including the brackets themselves? E.g. [152] or [153] or [154]. I am using Yahoo Pipes.</p>

答:
You can escape the brackets (like any other character with a special meaning) with \.

```<code>s/\[\d+\]/Replacement/
</code>```

In Yahoo Pipes it should work like: replace \[.+\] with (leave blank). Maybe you have to check the g flag.

Body:
You can escape the brackets (like any other character with a special meaning) with \.

s/\[\d+\]/Replacement/

In Yahoo Pipes it should work like: replace \[.+\] with (leave blank). Maybe you have to check the g flag.


问:
I am getting an JSX error with this code that i am using and i cannot figure it out
I am trying to use a header from a website in HTML  but i am getting a JSX error

```<code><div className="container h-100">
  <div className="row h-100 align-items-center justify-content-center text-center">
    <div className="col-lg-10 align-self-end">
      <h1 className="text-uppercase text-white font-weight-bold">Your Favorite Source of Free Bootstrap Themes</h1>
      <hr className="divider my-4">
    </div>
    <div className="col-lg-8 align-self-baseline">
      <p className="text-white-75 font-weight-light mb-5">Start Bootstrap can help you build better websites using the Bootstrap framework! Just download a theme and start customizing, no strings attached!</p>
      <a className="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a>
    </div>
  </div>
</div>
</code>```

答:
The error is on this line:

```<code> <hr className="divider my-4">
</code>```

It should have a self-closing /

As in

Body:
I am trying to use a header from a website in HTML  but i am getting a JSX error

Your Favorite Source of Free Bootstrap Themes

Start Bootstrap can help you build better websites using the Bootstrap framework! Just download a theme and start customizing, no strings attached!

      Find Out More

Body:
The error is on this line:

 <hr className="divider my-4">

It should have a self-closing /

As in <hr className="divider my-4" />


问:
Adding '£' sign to ggplot axis, when font is defined.
I am trying to add a '£' sign to the below ggplot y axis label. However, when I run the code the £ sign is blank i.e. "Mean cost ( )", instead of "Mean cost (£)". There are no warnings.

I imagine it's because I'm calling a particular font (GoodDog Plain, via extrafont package), because when I remove all themes, the £ sign appears. However, as I need to use this font, does anyone know of a way around this?

```<code>ggplot(FTAt, aes(x=Year, y=FTA_cost, col=Country, group=Country)) +
  geom_line(size=1)+
  ylab("Mean cost (£)") +
  xlab("Year")+
  scale_color_manual(values=c("red2", "royalblue4","forestgreen"))+
  theme(axis.text.x = element_text(family="GoodDog Plain"),
    axis.text.y = element_text(family="GoodDog Plain"),
    axis.title.x = element_text(family="GoodDog Plain"),
    axis.title.y = element_text(family="GoodDog Plain"),
    legend.title = element_text(family="GoodDog Plain"),
    legend.text = element_text(family="GoodDog Plain"))
</code>```

Thanks in advance!

答:
```<code>scale_y_continuous(labels = function(x) paste0(x, "£"))
</code>```

Body:
I am trying to add a '£' sign to the below ggplot y axis label. However, when I run the code the £ sign is blank i.e. "Mean cost ( )", instead of "Mean cost (£)". There are no warnings.

I imagine it's because I'm calling a particular font (GoodDog Plain, via extrafont package), because when I remove all themes, the £ sign appears. However, as I need to use this font, does anyone know of a way around this?

ggplot(FTAt, aes(x=Year, y=FTA_cost, col=Country, group=Country)) +
  geom_line(size=1)+
  ylab("Mean cost (£)") +
  xlab("Year")+
  scale_color_manual(values=c("red2", "royalblue4","forestgreen"))+
  theme(axis.text.x = element_text(family="GoodDog Plain"),
    axis.text.y = element_text(family="GoodDog Plain"),
    axis.title.x = element_text(family="GoodDog Plain"),
    axis.title.y = element_text(family="GoodDog Plain"),
    legend.title = element_text(family="GoodDog Plain"),
    legend.text = element_text(family="GoodDog Plain"))

Thanks in advance!


问:
Is there a faster way to find the highest pair-sum of an int[]?
Is there a different way using the java Collection that makes this code faster ? Is there any another way to make this code faster?
Is ArrayList the right choice for this kind of problem?

```<code>import java.util.*;

class Main{

public static int GetHighestPairSum(int[] L)
{
    int largest = L[0];
    int index = 0;
    int secondlargest = L[0];

    ArrayList<Integer> I = new ArrayList<Integer>();

    for (int i = 0; i<L.length; i++)
    {
        I.add(L[i]);

        if (i == 0)
        {
            largest = L[i];
        }
        else
        {
            if (largest < L[i])
            {
                largest = L[i];
                index = i;
            }
        }
    }

    I.remove(index);
    secondlargest = Collections.max(I);

    return largest + secondlargest;
}

public static void main(String[] args) {

     int[] testarr = new int[] {1,2,3,23,67,100,2,11,3,2,6,7,1,13,4,7,9,34,7,3,2,1,100};
     System.out.println(GetHighestPairSum(testarr));
}
</code>```

}

答:
With this implementation, you'll have to go over the list twice.
A more performant approach would be to hold two variables for the largest and second largest elements, and update them both as you go. Note that this can be done by iterating the array directly, and there's no need to copy it to an ArrayList, as @GBlodgett's answer suggests.

A similar solution which could support any number of elements could use a [PriorityQueue]:

```<code>public static int getHighestTuppleSum(int[] arr, int n) {
    PriorityQueue<Integer> pq = new PriorityQueue(arr.length);
    for (int i : arr) {
        if (pq.size() < n) {
            pq.add(i);
        }
        if (pq.peek() < i) {
            pq.poll();
            pq.add(i);
        }
    }
    return pq.stream().mapToInt(Integer::intValue).sum();
}
</code>```

Body:
Is there a different way using the java Collection that makes this code faster ? Is there any another way to make this code faster?
Is ArrayList the right choice for this kind of problem?

import java.util.*;

class Main{

public static int GetHighestPairSum(int[] L)
{
    int largest = L[0];
    int index = 0;
    int secondlargest = L[0];

    ArrayList<Integer> I = new ArrayList<Integer>();

    for (int i = 0; i<L.length; i++)
    {
        I.add(L[i]);

        if (i == 0)
        {
            largest = L[i];
        }
        else
        {
            if (largest < L[i])
            {
                largest = L[i];
                index = i;
            }
        }
    }

    I.remove(index);
    secondlargest = Collections.max(I);

    return largest + secondlargest;
}

public static void main(String[] args) {

     int[] testarr = new int[] {1,2,3,23,67,100,2,11,3,2,6,7,1,13,4,7,9,34,7,3,2,1,100};
     System.out.println(GetHighestPairSum(testarr));
}

}

Body:
With this implementation, you'll have to go over the list twice.
A more performant approach would be to hold two variables for the largest and second largest elements, and update them both as you go. Note that this can be done by iterating the array directly, and there's no need to copy it to an ArrayList, as @GBlodgett's answer suggests.

A similar solution which could support any number of elements could use a [PriorityQueue]:

public static int getHighestTuppleSum(int[] arr, int n) {
    PriorityQueue<Integer> pq = new PriorityQueue(arr.length);
    for (int i : arr) {
        if (pq.size() < n) {
            pq.add(i);
        }
        if (pq.peek() < i) {
            pq.poll();
            pq.add(i);
        }
    }
    return pq.stream().mapToInt(Integer::intValue).sum();
}