问:
The contract name 'x.y.IService' could not be found in the list of contracts implemented by the service 'z.t.MyService'
I'm working on a very simple WCF service.
At the beginning everything was fine, then I moved the service interface in a separated DLL file.
Since that I got this error:

The contract name x.y.IService could
  not be found in the list of contracts
  implemented by the service
  z.t.MyService

My config file looks like this:

```<code>   <endpointBehaviors>
      <behavior name="webHttpBehavior">
         <enableWebScript />
      </behavior>
   </endpointBehaviors>
</behaviors>
<services>
   <service name="z.t.MyService">
      <endpoint address=""
                binding="webHttpBinding"
                behaviorConfiguration="webHttpBehavior"
                contract="x.y.IService" />
   </service>
</services>...
</code>```

and my service looks like this:

```<code>using x.y;

namespace z.y
{
    public class MyService : IService
    {

    }
}
</code>```

Everything else but the service works fine with that namespace.
Where am I wrong?

Thanks in advance.

答:
Everything looks fine assuming the z.t.MyService is a typo.  This is exactly what we do and everything works for our service.

Edit based on comments:
Yes, the interface can be a generic, however you will need to define the type before using it in the service.

You can do the following

```<code>public interface IActualService : IService<MyService>
</code>```

Then you just use IAcutalService as the interface for your service.

Body:
I'm working on a very simple WCF service.
At the beginning everything was fine, then I moved the service interface in a separated DLL file.
Since that I got this error:

The contract name x.y.IService could
  not be found in the list of contracts
  implemented by the service
  z.t.MyService

My config file looks like this:

   <endpointBehaviors>
      <behavior name="webHttpBehavior">
         <enableWebScript />
      </behavior>
   </endpointBehaviors>
</behaviors>
<services>
   <service name="z.t.MyService">
      <endpoint address=""
                binding="webHttpBinding"
                behaviorConfiguration="webHttpBehavior"
                contract="x.y.IService" />
   </service>
</services>...

and my service looks like this:

using x.y;

namespace z.y
{
    public class MyService : IService
    {

    }
}

Everything else but the service works fine with that namespace.
Where am I wrong?

Thanks in advance.

Body:
Everything looks fine assuming the z.t.MyService is a typo.  This is exactly what we do and everything works for our service.

Edit based on comments:
Yes, the interface can be a generic, however you will need to define the type before using it in the service.

You can do the following

public interface IActualService : IService<MyService>

Then you just use IAcutalService as the interface for your service.


来源: stackexchange

问:
Load separate .env from package.json
```<code>"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",
</code>```

I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test

I have searched every where on the Internet, but no help.

Any help is appreciated.

答:
You can only set node env in npm script. to import file you need to write code on your server file.

import dotenv in your server file

```<code>import dotenv from "dotenv";
or
const dotenv = require("dotenv");
</code>```

use below code to import particular env file.

```<code>
let envConfig={}
if (process.env.NODE_ENV === "development") {
  if (fs.existsSync(".env.development")) {
    envConfig = dotenv.parse(fs.readFileSync(".env.development"));
  }

} else if(process.env.NODE_ENV === "testing"){
 if (fs.existsSync(".env.test")) {
    envConfig = dotenv.parse(fs.readFileSync(".env.test"));
  }
}

 for (const k in envConfig) {
    process.env[k] = envConfig[k];
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Load separate .env from package.json

Body:
"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",

I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test

I have searched every where on the Internet, but no help.

Any help is appreciated.

Body:
You can only set node env in npm script. to import file you need to write code on your server file.

import dotenv in your server file

import dotenv from "dotenv";
or
const dotenv = require("dotenv");

use below code to import particular env file.

let envConfig={}
if (process.env.NODE_ENV === "development") {
  if (fs.existsSync(".env.development")) {
    envConfig = dotenv.parse(fs.readFileSync(".env.development"));
  }

} else if(process.env.NODE_ENV === "testing"){
 if (fs.existsSync(".env.test")) {
    envConfig = dotenv.parse(fs.readFileSync(".env.test"));
  }
}

 for (const k in envConfig) {
    process.env[k] = envConfig[k];
  }


问:
the object has type qualifiers that are not compatible with the member function. Why is this error showing up?
```<code>PVector operator + (const PVector& lhs, const PVector& rhs){
    return PVector(lhs.getX() + rhs.getX(), lhs.getY()+ rhs.getY());
}
</code>```

I get an error on the lhs and rhs object when I use the getX() or getY() function. The function does not make any changes to the object, it only returns a private float value. I am wondering why this is happening? I am not that great at programming in c++, but I want to learn.

I can take away the const from the lhs and rhs object but I want to know why I get this error.

Thank you for your assistance.

答:
This compile error indicated that you try to use a (non-const) member function of a const object.

```<code>class A {
    void f();
}

const A a;
A.f(); // <- this will result in a cv qualifier compile error.
</code>```

You can fix this by setting the function to const

```<code>class A {
    void f() const;
}
</code>```

It means, that no member variables are changed by this function call. Thus, it can be applied on a const object.

Most likely your getX and getY functions need to be const.

Body:
PVector operator + (const PVector& lhs, const PVector& rhs){
    return PVector(lhs.getX() + rhs.getX(), lhs.getY()+ rhs.getY());
}

I get an error on the lhs and rhs object when I use the getX() or getY() function. The function does not make any changes to the object, it only returns a private float value. I am wondering why this is happening? I am not that great at programming in c++, but I want to learn.

I can take away the const from the lhs and rhs object but I want to know why I get this error.

Thank you for your assistance.

Body:
This compile error indicated that you try to use a (non-const) member function of a const object.

class A {
    void f();
}

const A a;
A.f(); // <- this will result in a cv qualifier compile error.

You can fix this by setting the function to const

class A {
    void f() const;
}

It means, that no member variables are changed by this function call. Thus, it can be applied on a const object.

Most likely your getX and getY functions need to be const.


问:
Create max character length in UITextField using IBInspectable
I want to create a max length to my textfield with IBInspectable, I see a answer to this on a question here but I'm getting an error saying Expression type '()' is ambiguous without more context,

My code was

import UIKit

private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength)
    }
}
```

and I'm getting an error pointing at textField.text = t?.prefix(maxLength) with an error message saying Expression type '()' is ambiguous without more context,

How can I resolve it?

答:
In Swift 5, String's prefix method returns a value of type String.SubSequence

```<code>func prefix(_ maxLength: Int) -> Substring
</code>```

You'll need to convert this to a String type.

One way to do this might be:

```<code>let s = textField.text!.prefix(maxLength) // though UITextField.text is defined as an optional String, can be safely force-unwrapped as the default value is an empty string even when set to nil
textField.text = String(s)
</code>```

or if you prefer a single-line solution:

```<code>textField.text = String(textField.text!.prefix(maxLength))
</code>```

Body:
I want to create a max length to my textfield with IBInspectable, I see a answer to this on a question here but I'm getting an error saying Expression type '()' is ambiguous without more context,

My code was

import UIKit

private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength)
    }
}

and I'm getting an error pointing at textField.text = t?.prefix(maxLength) with an error message saying Expression type '()' is ambiguous without more context,

How can I resolve it?

Body:
In Swift 5, String's prefix method returns a value of type String.SubSequence

func prefix(_ maxLength: Int) -> Substring

You'll need to convert this to a String type.

One way to do this might be:

let s = textField.text!.prefix(maxLength) // though UITextField.text is defined as an optional String, can be safely force-unwrapped as the default value is an empty string even when set to nil
textField.text = String(s)

or if you prefer a single-line solution:

textField.text = String(textField.text!.prefix(maxLength))


问:
Getting error convert json to java object
My json is : {"language":"English (US)","locale":"en_US","value":"aa"aa"}.
Getting error the json to java object for value , where value is : "aa"aa" .

Please help. Thanks in advance.

答:
You input JSON is wrong. If the value contains " then you need to add escape sequence before the " like this:

```<code>{
   "language":"English (US)",
   "locale":"en_US",
   "value":"aa\"aa"
}
</code>```

Body:
You input JSON is wrong. If the value contains " then you need to add escape sequence before the " like this:

{
   "language":"English (US)",
   "locale":"en_US",
   "value":"aa\"aa"
}


问:
I am getting a different maximum and minimum value here
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done
```

<p>Output: </p>

<p>Invalid Input</p>

<p>Maximum is 10</p>

<p>Minimum is 4</p>

<p><strong>Expected Output:</strong></p>

<p><strong>Invalid Input</strong></p>

<p><strong>Maximum is 11</strong></p>

<p><strong>Minimum is 2</strong></p>

```a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()
```

答:
In these loops:

```<code>        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
</code>```

you have two values, val and largest, when you really only want one (largest).  The idea of finding a maximum value is that you want to be comparing against the largest value you've found so far, and constantly updating it each time you find a larger value.

A much shorter way of writing this code would be:

```<code>a = []
while True:
    val = input()
    if val == "done":
        break
    try:
        a.append(int(val))
    except ValueError:
        print("Invalid")

print(max(a))
print(min(a))
</code>```

Or, if you weren't allowed to use the max and min functions, you could simply maintain largest and smallest as you go, instead of keeping an array at all:

```<code>largest = None
smallest = None
while True:
    val = input()
    if val == "done":
        break
    try:
        num = int(val)
    except ValueError:
        print("Invalid")
        continue
    if (largest, smallest) == (None, None):
        largest, smallest = num, num
    if largest < num:
        largest = num
    if smallest > num:
        smallest = num

print(largest)
print(smallest)
</code>```

Body:
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done

Output:

Invalid Input

Maximum is 10

Minimum is 4

Expected Output:

Invalid Input

Maximum is 11

Minimum is 2

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()

Body:
In these loops:

        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]

you have two values, val and largest, when you really only want one (largest).  The idea of finding a maximum value is that you want to be comparing against the largest value you've found so far, and constantly updating it each time you find a larger value.

A much shorter way of writing this code would be:

a = []
while True:
    val = input()
    if val == "done":
        break
    try:
        a.append(int(val))
    except ValueError:
        print("Invalid")

print(max(a))
print(min(a))

Or, if you weren't allowed to use the max and min functions, you could simply maintain largest and smallest as you go, instead of keeping an array at all:

largest = None
smallest = None
while True:
    val = input()
    if val == "done":
        break
    try:
        num = int(val)
    except ValueError:
        print("Invalid")
        continue
    if (largest, smallest) == (None, None):
        largest, smallest = num, num
    if largest < num:
        largest = num
    if smallest > num:
        smallest = num

print(largest)
print(smallest)


问:
Hide a parent element if ID contains specific text string with vanilla Javascript
I'm wanting to hide a parent
 tag where a grandchild  tag has an ID with a specific string.

Let's say I want to check for the string "test123" in the ID, e.g.

```<code><table>
  <tr id="this_is_a_test456">
    <td>
      <span>
        <span>

        <span>
      </span>
    </td>
  </tr>
  <tr> <<<--- THIS ROW SHOULD BE DELETED
    <td>
      <span>
        <span id="this_is_a_test123">

        <span>
      </span>
    </td>
  </tr>
</table>
</code>```

答:
Find the  within a
 by partial ID and if it exists, select the parent row and remove it

let idPartial = 'test123'
let span = document.querySelector(`tr span[id*="${idPartial}"]`)
if (span) {
  span.closest('tr').remove()
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
  <tr id="this_is_a_test456">
    <td>
      <span>
        <span>My row stays<span>
      </span>
    </td>
  </tr>
  <tr>
    <td>
      <span>
        <span id="this_is_a_test123">My row goes<span>
      </span>
    </td>
  </tr>
</table></code>```

See

Attribute selectors

Element.closest()

ChildNode.remove()

The above finds the first element matching your condition ("id attribute contains"). If you wanted to do this for all matching  elements, use

let idPartial = 'test123'
document.querySelectorAll(`tr span[id*="${idPartial}"]`).forEach(span => {
  span.closest('tr').remove()
})
```

As per Why does jQuery or a DOM method such as getElementById not find the element?, make sure your code runs after the document has loaded.

Body:
I'm wanting to hide a parent
 tag where a grandchild  tag has an ID with a specific string.

Let's say I want to check for the string "test123" in the ID, e.g.

 <<<--- THIS ROW SHOULD BE DELETED

Body:
Find the <span> within a <tr> by partial ID and if it exists, select the parent row and remove it

let idPartial = 'test123'
let span = document.querySelector(`tr span[id*="${idPartial}"]`)
if (span) {
  span.closest('tr').remove()
}

<table border="1">
  <tr id="this_is_a_test456">
    <td>
      <span>
        <span>My row stays<span>
      </span>
    </td>
  </tr>
  <tr>
    <td>
      <span>
        <span id="this_is_a_test123">My row goes<span>
      </span>
    </td>
  </tr>
</table>

See

Attribute selectors

Element.closest()

ChildNode.remove()

The above finds the first element matching your condition ("id attribute contains"). If you wanted to do this for all matching <span> elements, use

let idPartial = 'test123'
document.querySelectorAll(`tr span[id*="${idPartial}"]`).forEach(span => {
  span.closest('tr').remove()
})

As per Why does jQuery or a DOM method such as getElementById not find the element?, make sure your code runs after the document has loaded.


问:
How to show district of india map in python basemap?
I have india basemap in plot result but i want the district / cities of each state also in india map in python. How to show  cities of states of country in python basemap ?

enter image description here

答:
we can do by reading district shape file and then plotting into matplotlib map.
It will work.I have already done.</p>


问:
C - I have a problem with acquiring strings
I wrote a function that reads and checks strings, but something is wrong, it is as if the stdin buffer is not emptying properly.
I thought so because when I insert the first string in output and press enter, the program simply starts a new line, and I have to reinsert the string and press enter again to make it accepted.

Returns 1 if the string is correct, else 0.

The function is:

```<code>int leggiStringhe(char* stringa, int lunghezza_massima, int lunghezza_minima) {

   unsigned int i = 0;
   unsigned int flag = 0;
   char buffer[MAX_LUNGHEZZA_BUFFER];

   while(getchar() != '\n');

   do {

        fgets(buffer, MAX_LUNGHEZZA_BUFFER, stdin);

        while( buffer[i] != '\n'){
            i++;
        }

        if( i > lunghezza_massima){
            printf("\nHai inserito una stringa troppo lunga, riprova:  ");
        } else if(i < lunghezza_minima) {
            printf("\nHai inserito una stringa troppo corta, riprova:  ");
        }
        else { flag = 1; }

   } while( i > lunghezza_massima || i < lunghezza_minima);

    buffer[i]= '\0';
    strcpy(stringa, buffer);

    return flag;
}
</code>```

P.S: I can't use functions like fflush () or others because I use repl.it.

答:
getchar reads a character.  while(getchar() != '\n')     ;  (extra spaces for emphasis) reads an entire line, one character at a time.  If you are running the program with stdin coming from a tty that is echoing its input, then you are seeing the keys you type (including the final newline) be printed on the screen and consumed (and ignored) by your program.  After the first line is ignored, fgets reads the second line.

What are you trying to accomplish with while(getchar() != '\n');?

Body:
I wrote a function that reads and checks strings, but something is wrong, it is as if the stdin buffer is not emptying properly.
I thought so because when I insert the first string in output and press enter, the program simply starts a new line, and I have to reinsert the string and press enter again to make it accepted.

Returns 1 if the string is correct, else 0.

The function is:

int leggiStringhe(char* stringa, int lunghezza_massima, int lunghezza_minima) {

   unsigned int i = 0;
   unsigned int flag = 0;
   char buffer[MAX_LUNGHEZZA_BUFFER];

   while(getchar() != '\n');

   do {

        fgets(buffer, MAX_LUNGHEZZA_BUFFER, stdin);

        while( buffer[i] != '\n'){
            i++;
        }

        if( i > lunghezza_massima){
            printf("\nHai inserito una stringa troppo lunga, riprova:  ");
        } else if(i < lunghezza_minima) {
            printf("\nHai inserito una stringa troppo corta, riprova:  ");
        }
        else { flag = 1; }

   } while( i > lunghezza_massima || i < lunghezza_minima);

    buffer[i]= '\0';
    strcpy(stringa, buffer);

    return flag;
}

P.S: I can't use functions like fflush () or others because I use repl.it.


问:
OpenCV matrix weird behavior of addition, multiplication with float point and 8bit value
I'm using OpenCV version 3.4.5. I tried to understand the behavior of cv::Mat in OpenCV. I multiple some 8bit matrices and add them up. The result seems inconsistent.

Does OpenCV cast the float point result immediately back to 8bit after each multiplication, or after each addition, or maybe some "Fused Multiply Add" happened here ?

#include <iostream>
#include <opencv2/opencv.hpp>

int main() {
    for (int value = 1; value < 10; value++) {
        cv::Mat im(1, 1, CV_8U, value);
        cv::Mat result[10];
        result[0] = im*0.1f;
        result[1] = im*0.1f + im*0.1f;
        result[2] = im*0.1f + im*0.1f + im*0.1f;
        result[3] = im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[4] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[5] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[6] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[7] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[8] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[9] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        std::cout << "base value: " << value << std::endl;
        for (int i = 0; i < 10; i++) {
            std::cout << i + 1 << ": " << int(result[i].at<uint8_t>(0, 0)) << "\t";
        }
        std::cout << std::endl;
    }
    return 0;
}
```

<p>The outputs are:</p>

```base value: 1
1: 0    2: 0    3: 0    4: 0    5: 0    6: 0    7: 0    8: 0    9: 0    10: 0
base value: 2
1: 0    2: 0    3: 0    4: 0    5: 0    6: 0    7: 0    8: 0    9: 0    10: 0
base value: 3
1: 0    2: 1    3: 1    4: 1    5: 1    6: 1    7: 1    8: 1    9: 1    10: 1
base value: 4
1: 0    2: 1    3: 1    4: 1    5: 1    6: 1    7: 1    8: 1    9: 1    10: 1
base value: 5
1: 0    2: 1    3: 2    4: 2    5: 2    6: 2    7: 2    8: 2    9: 2    10: 2
base value: 6
1: 1    2: 1    3: 2    4: 3    5: 4    6: 5    7: 6    8: 7    9: 8    10: 9
base value: 7
1: 1    2: 1    3: 2    4: 3    5: 4    6: 5    7: 6    8: 7    9: 8    10: 9
base value: 8
1: 1    2: 2    3: 3    4: 4    5: 5    6: 6    7: 7    8: 8    9: 9    10: 10
base value: 9
1: 1    2: 2    3: 3    4: 4    5: 5    6: 6    7: 7    8: 8    9: 9    10: 10
```

答:
In OpenCV, the operations between cv::Mat is not evaluated right away for performance reason.
It uses delayed evaluation. If you do A = B*0.1 + C*0.1 (A,B,C is cv::Mat), a cv::MatExpr that holds B,C and their scale value 0.1 and 0.1 is created. And it is evaluated only when the operations are more than 3 or assigned to an actual cv::Mat.

If you don't assign B*0.1 + C*0.1 to an actual cv::Mat, the evaluation will not happen.

If you do A = B*0.1 + C*0.1 + D*0.1, a cv::MatExpr that holds B*0.1 and C*0.1is created, and then another cv::MatExpr is created which holds last cv::MatExpr's evaluation and D*0.1. This is why operations more than 3 is absurd. During evaluation, since the type is not floating-point, the 0.x is lost.

To avoid this problem, just set type to CV_32F or CV_64F.

Your im*0.1f + im*0.1f + im*0.1f + ... is actually working like this.

```<code>result = im*0.1f + im*0.1f + im*0.1f + im*0.1f +   ...
  ∧         │         │         │         │
  │      MatExpr   MatExpr   MatExpr   MatExpr     ...
  │         │         │         │         │
  │         └────┬────┘         │         │
  │           MatExpr           │         │
  │eval          │              │         │
  │              └>────────┬───<┘         │
  │              eval   MatExpr           │
  │                        │              │
  │                        └>────────┬───<┘
  │                        eval   MatExpr
  │                                 ...            ...
  │
  │                                  └>────────┬───<┘
  │                                  eval   MatExpr
  │                                            │
  └<──────────────────────────────────────────<┘
</code>```

matop.cpp

cv::Mat*double

```<code>class MatOp_AddEx : public MatOp
{
public:

    void assign(const MatExpr& expr, Mat& m, int type=-1) const;
    void add(const MatExpr& e1, const Scalar& s, MatExpr& res) const;
    static void makeExpr(MatExpr& res, const Mat& a, const Mat& b, double alpha, double beta, const Scalar& s=Scalar());

    // erased others for clarity
};

static MatOp_AddEx g_MatOp_AddEx; // only visible in matop.cpp
</code>```

```<code>MatExpr operator * (const Mat& a, double s)
{
    MatExpr e;
    MatOp_AddEx::makeExpr(e, a, Mat(), s, 0); // meaning a*s + NULL-mat*0
    return e;
}
</code>```

```<code>inline void MatOp_AddEx::makeExpr(MatExpr& res, const Mat& a, const Mat& b, double alpha, double beta, const Scalar& s)
{
    res = MatExpr(&g_MatOp_AddEx, 0, a, b, Mat(), alpha, beta, s); // MatExpr constructor
}
</code>```

cv::MatExpr + cv::MatExpr

```<code>MatExpr operator + (const MatExpr& e1, const MatExpr& e2)
{
    MatExpr en;
    e1.op->add(e1, e2, en); // MatOp_AddEx inherits MatOp
    return en;
}
</code>```

```<code>void MatOp::add(const MatExpr& e1, const MatExpr& e2, MatExpr& res) const
{
    CV_INSTRUMENT_REGION()

    if( this == e2.op )
    {
        double alpha = 1, beta = 1;
        Scalar s;
        Mat m1, m2;
        if( isAddEx(e1) && (!e1.b.data || e1.beta == 0) )
        {
            m1 = e1.a;
            alpha = e1.alpha;
            s = e1.s;
        }
        else
            e1.op->assign(e1, m1);  // <- Evaluation. Remember that type is set to auto(-1) by default

        if( isAddEx(e2) && (!e2.b.data || e2.beta == 0) )
        {
            m2 = e2.a;
            beta = e2.alpha;
            s += e2.s;
        }
        else
            e2.op->assign(e2, m2);  // <- Evaluation
        MatOp_AddEx::makeExpr(res, m1, m2, alpha, beta, s);
    }
    else
        e2.op->add(e1, e2, res);  // <- Evaluation

}
</code>```

```<code>void MatOp_AddEx::assign(const MatExpr& e, Mat& m, int _type) const
{
    Mat temp, &dst = _type == -1 || e.a.type() == _type ? m : temp;
    if( e.b.data )
    {
        if( e.s == Scalar() || !e.s.isReal() )
        {
            if( e.alpha == 1 )
            {
                if( e.beta == 1 )
                    cv::add(e.a, e.b, dst);
                else if( e.beta == -1 )
                    cv::subtract(e.a, e.b, dst);
                else
                    cv::scaleAdd(e.b, e.beta, e.a, dst);
            }
            else if( e.beta == 1 )
            {
                if( e.alpha == -1 )
                    cv::subtract(e.b, e.a, dst);
                else
                    cv::scaleAdd(e.a, e.alpha, e.b, dst);
            }
            else
                cv::addWeighted(e.a, e.alpha, e.b, e.beta, 0, dst);

            if( !e.s.isReal() )
                cv::add(dst, e.s, dst);
        }
        else
            cv::addWeighted(e.a, e.alpha, e.b, e.beta, e.s[0], dst);
    }
    else if( e.s.isReal() && (dst.data != m.data || fabs(e.alpha) != 1))
    {
        e.a.convertTo(m, _type, e.alpha, e.s[0]);
        return;
    }
    else if( e.alpha == 1 )
        cv::add(e.a, e.s, dst);
    else if( e.alpha == -1 )
        cv::subtract(e.s, e.a, dst);
    else
    {
        e.a.convertTo(dst, e.a.type(), e.alpha);
        cv::add(dst, e.s, dst);
    }

    if( dst.data != m.data )
        dst.convertTo(m, m.type());
}
</code>```

Body:
I'm using OpenCV version 3.4.5. I tried to understand the behavior of cv::Mat in OpenCV. I multiple some 8bit matrices and add them up. The result seems inconsistent.

Does OpenCV cast the float point result immediately back to 8bit after each multiplication, or after each addition, or maybe some "Fused Multiply Add" happened here ?

#include <iostream>
#include <opencv2/opencv.hpp>

int main() {
    for (int value = 1; value < 10; value++) {
        cv::Mat im(1, 1, CV_8U, value);
        cv::Mat result[10];
        result[0] = im*0.1f;
        result[1] = im*0.1f + im*0.1f;
        result[2] = im*0.1f + im*0.1f + im*0.1f;
        result[3] = im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[4] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[5] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[6] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[7] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[8] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        result[9] = im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f + im*0.1f;
        std::cout << "base value: " << value << std::endl;
        for (int i = 0; i < 10; i++) {
            std::cout << i + 1 << ": " << int(result[i].at<uint8_t>(0, 0)) << "\t";
        }
        std::cout << std::endl;
    }
    return 0;
}

The outputs are:

base value: 1
1: 0    2: 0    3: 0    4: 0    5: 0    6: 0    7: 0    8: 0    9: 0    10: 0
base value: 2
1: 0    2: 0    3: 0    4: 0    5: 0    6: 0    7: 0    8: 0    9: 0    10: 0
base value: 3
1: 0    2: 1    3: 1    4: 1    5: 1    6: 1    7: 1    8: 1    9: 1    10: 1
base value: 4
1: 0    2: 1    3: 1    4: 1    5: 1    6: 1    7: 1    8: 1    9: 1    10: 1
base value: 5
1: 0    2: 1    3: 2    4: 2    5: 2    6: 2    7: 2    8: 2    9: 2    10: 2
base value: 6
1: 1    2: 1    3: 2    4: 3    5: 4    6: 5    7: 6    8: 7    9: 8    10: 9
base value: 7
1: 1    2: 1    3: 2    4: 3    5: 4    6: 5    7: 6    8: 7    9: 8    10: 9
base value: 8
1: 1    2: 2    3: 3    4: 4    5: 5    6: 6    7: 7    8: 8    9: 9    10: 10
base value: 9
1: 1    2: 2    3: 3    4: 4    5: 5    6: 6    7: 7    8: 8    9: 9    10: 10

Body:
In OpenCV, the operations between cv::Mat is not evaluated right away for performance reason.
It uses delayed evaluation. If you do A = B*0.1 + C*0.1 (A,B,C is cv::Mat), a cv::MatExpr that holds B,C and their scale value 0.1 and 0.1 is created. And it is evaluated only when the operations are more than 3 or assigned to an actual cv::Mat.

If you don't assign B*0.1 + C*0.1 to an actual cv::Mat, the evaluation will not happen.

If you do A = B*0.1 + C*0.1 + D*0.1, a cv::MatExpr that holds B*0.1 and C*0.1is created, and then another cv::MatExpr is created which holds last cv::MatExpr's evaluation and D*0.1. This is why operations more than 3 is absurd. During evaluation, since the type is not floating-point, the 0.x is lost.

To avoid this problem, just set type to CV_32F or CV_64F.

Your im*0.1f + im*0.1f + im*0.1f + ... is actually working like this.

result = im*0.1f + im*0.1f + im*0.1f + im*0.1f +   ...
  ∧         │         │         │         │
  │      MatExpr   MatExpr   MatExpr   MatExpr     ...
  │         │         │         │         │
  │         └────┬────┘         │         │
  │           MatExpr           │         │
  │eval          │              │         │
  │              └>────────┬───<┘         │
  │              eval   MatExpr           │
  │                        │              │
  │                        └>────────┬───<┘
  │                        eval   MatExpr
  │                                 ...            ...
  │
  │                                  └>────────┬───<┘
  │                                  eval   MatExpr
  │                                            │
  └<──────────────────────────────────────────<┘

matop.cpp

cv::Mat*double

class MatOp_AddEx : public MatOp
{
public:

    void assign(const MatExpr& expr, Mat& m, int type=-1) const;
    void add(const MatExpr& e1, const Scalar& s, MatExpr& res) const;
    static void makeExpr(MatExpr& res, const Mat& a, const Mat& b, double alpha, double beta, const Scalar& s=Scalar());

    // erased others for clarity
};

static MatOp_AddEx g_MatOp_AddEx; // only visible in matop.cpp

MatExpr operator * (const Mat& a, double s)
{
    MatExpr e;
    MatOp_AddEx::makeExpr(e, a, Mat(), s, 0); // meaning a*s + NULL-mat*0
    return e;
}

inline void MatOp_AddEx::makeExpr(MatExpr& res, const Mat& a, const Mat& b, double alpha, double beta, const Scalar& s)
{
    res = MatExpr(&g_MatOp_AddEx, 0, a, b, Mat(), alpha, beta, s); // MatExpr constructor
}

cv::MatExpr + cv::MatExpr

MatExpr operator + (const MatExpr& e1, const MatExpr& e2)
{
    MatExpr en;
    e1.op->add(e1, e2, en); // MatOp_AddEx inherits MatOp
    return en;
}

void MatOp::add(const MatExpr& e1, const MatExpr& e2, MatExpr& res) const
{
    CV_INSTRUMENT_REGION()

    if( this == e2.op )
    {
        double alpha = 1, beta = 1;
        Scalar s;
        Mat m1, m2;
        if( isAddEx(e1) && (!e1.b.data || e1.beta == 0) )
        {
            m1 = e1.a;
            alpha = e1.alpha;
            s = e1.s;
        }
        else
            e1.op->assign(e1, m1);  // <- Evaluation. Remember that type is set to auto(-1) by default

        if( isAddEx(e2) && (!e2.b.data || e2.beta == 0) )
        {
            m2 = e2.a;
            beta = e2.alpha;
            s += e2.s;
        }
        else
            e2.op->assign(e2, m2);  // <- Evaluation
        MatOp_AddEx::makeExpr(res, m1, m2, alpha, beta, s);
    }
    else
        e2.op->add(e1, e2, res);  // <- Evaluation

}

void MatOp_AddEx::assign(const MatExpr& e, Mat& m, int _type) const
{
    Mat temp, &dst = _type == -1 || e.a.type() == _type ? m : temp;
    if( e.b.data )
    {
        if( e.s == Scalar() || !e.s.isReal() )
        {
            if( e.alpha == 1 )
            {
                if( e.beta == 1 )
                    cv::add(e.a, e.b, dst);
                else if( e.beta == -1 )
                    cv::subtract(e.a, e.b, dst);
                else
                    cv::scaleAdd(e.b, e.beta, e.a, dst);
            }
            else if( e.beta == 1 )
            {
                if( e.alpha == -1 )
                    cv::subtract(e.b, e.a, dst);
                else
                    cv::scaleAdd(e.a, e.alpha, e.b, dst);
            }
            else
                cv::addWeighted(e.a, e.alpha, e.b, e.beta, 0, dst);

            if( !e.s.isReal() )
                cv::add(dst, e.s, dst);
        }
        else
            cv::addWeighted(e.a, e.alpha, e.b, e.beta, e.s[0], dst);
    }
    else if( e.s.isReal() && (dst.data != m.data || fabs(e.alpha) != 1))
    {
        e.a.convertTo(m, _type, e.alpha, e.s[0]);
        return;
    }
    else if( e.alpha == 1 )
        cv::add(e.a, e.s, dst);
    else if( e.alpha == -1 )
        cv::subtract(e.s, e.a, dst);
    else
    {
        e.a.convertTo(dst, e.a.type(), e.alpha);
        cv::add(dst, e.s, dst);
    }

    if( dst.data != m.data )
        dst.convertTo(m, m.type());
}


问:
Cannot show json data in dropdown list jquery
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

```<code>jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
</code>```

答:
you need to parse them using $.parseJSON() and to retrieve data.

If you want to do without parsing refer below.

How to access JSON Object name/value?

Body:
I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});


问:
How to like object on index view with AJAX?
I have object that user can like in rails app. It works fine. But I'm trying to add ajax functionality to the like button so when I click it, it updates automatically.

It works on the first object in the index list, but the others do not update via ajax.

I assume this has something to do with the fact that I'm using classes. How would I go about potentially changing this to use ID's to ensure all objects can be updated each. I've tried using ID's but I'm not doing something right here. Any thoughts?

Here's my vote.js.erb file

```<code>    <% if current_user.liked? @candidate %>
         $('.like-btn').removeClass('liked');
     <% else %>
         $('.like-btn').addClass('liked');
    <% end %>
        $('.likes-count').html("<%= @candidate.get_upvotes.size %>")
</code>```

And here is my view

```<code>       <%= link_to like_candidate_path(candidate), class: "like-btn", method:
       :put, remote: :true do %>
       <div>
           <span><p><i class="fa fa-thumbs-up"></i></p></span>
       </div>
       <% end %>
       <span class="likes-count"><%= candidate.get_upvotes.size %></span>
</code>```

答:
In your view,

```<code><%= link_to like_candidate_path(candidate), class: "like-btn",id:"like_button_#{candidate.id}" method:
       :put, remote: :true do %>
<span class="likes-count" id="likes_count#{candidate.id}"><%= candidate.get_upvotes.size %></span>
</code>```

In your controller,

```<code>def vote
   #Your code to udpate here
   respond_to do |format|
      format.js
   end
end
</code>```

In your vote.js.erb

```<code><% if current_user.liked? @candidate %>
  $('#like_button_<%=@candiate.id%>').removeClass('liked');
<% else %>
  $('#like_button_<%=@candiate.id%>').addClass('liked');
<% end %>
$('#like_count_<%=@candiate.id%>').html("<%= @candidate.get_upvotes.size %>")
</code>```

Hope this helps!

Body:
I have object that user can like in rails app. It works fine. But I'm trying to add ajax functionality to the like button so when I click it, it updates automatically.

It works on the first object in the index list, but the others do not update via ajax.

I assume this has something to do with the fact that I'm using classes. How would I go about potentially changing this to use ID's to ensure all objects can be updated each. I've tried using ID's but I'm not doing something right here. Any thoughts?

Here's my vote.js.erb file

    <% if current_user.liked? @candidate %>
         $('.like-btn').removeClass('liked');
     <% else %>
         $('.like-btn').addClass('liked');
    <% end %>
        $('.likes-count').html("<%= @candidate.get_upvotes.size %>")

And here is my view

       <%= link_to like_candidate_path(candidate), class: "like-btn", method:
       :put, remote: :true do %>

       <% end %>
       <%= candidate.get_upvotes.size %>

Body:
In your view,

<%= link_to like_candidate_path(candidate), class: "like-btn",id:"like_button_#{candidate.id}" method:
       :put, remote: :true do %>
<span class="likes-count" id="likes_count#{candidate.id}"><%= candidate.get_upvotes.size %></span>

In your controller,

def vote
   #Your code to udpate here
   respond_to do |format|
      format.js
   end
end

In your vote.js.erb

<% if current_user.liked? @candidate %>
  $('#like_button_<%=@candiate.id%>').removeClass('liked');
<% else %>
  $('#like_button_<%=@candiate.id%>').addClass('liked');
<% end %>
$('#like_count_<%=@candiate.id%>').html("<%= @candidate.get_upvotes.size %>")

Hope this helps!


问:
Given a DateTime object, how do I get an ISO 8601 date in string format?
Given:

```<code>DateTime.UtcNow
</code>```

How do I get a string which represents the same value in an ISO 8601-compliant format?

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

```<code>yyyy-MM-ddTHH:mm:ssZ
</code>```

答:
I would just use XmlConvert:

```<code>XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);
</code>```

It will automatically preserve the time zone.

OwnerDisplayName: Iain

ContentLicense: CC BY-SA 3.0

Body:
Given:

DateTime.UtcNow

How do I get a string which represents the same value in an ISO 8601-compliant format?

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

LastEditorDisplayName: Iain

Body:
I would just use XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

It will automatically preserve the time zone.


问:
Removing extra whitespaces between characters from a string using PHP
After extensive research I'm still puzzled about removing extra white spaces from a string.
My string source is an editable div in Jquery. I pass it via AJAX POST to php script.

```<code>$('#button').on('click', function () {
var text = $('#Editable_DIV').text();
$.ajax({
        url: 'foo.php',
        method: 'POST',
        dataType: 'text',
        data: {characters: text
        },...............

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

My foo.php with '12345     6' string content

```<code>$string = trim(preg_replace('/( )+|\s\K\s+/','', $_POST['characters']));
</code>```

It removes only 2 out of 5 white spaces.

```<code>12345   6
</code>```

But when I hard coded the string like

```<code>$string = trim(preg_replace('/( )+|\s\K\s+/','', '12345     6'));
</code>```

It outputs like expected

```<code>12345 6
</code>```

With only 1 white space between '5' and '6' characters. I tried many Regex expressions combinations, urldecode(), none worked. What's wrong with $_POST['characters']?

UPD.
I include echo and var_dump the content of $_POST['characters'] before any manipulation and string output after manipulation.

```<code>**Before:**

12345     6

C:\xampp\htdocs\foo.php:string '12345     6' (length=15)

**After:**

12345    6

C:\xampp\htdocs\foo.php:string '12345    6' (length=14)
</code>```

答:
I added one more function after it. Please check it.</p>

```<code>$string = trim(preg_replace('/( )+|\s\K\s+/','', $_POST['characters']));
$string = str_replace(' ','',$string);
</code>```

Body:
After extensive research I'm still puzzled about removing extra white spaces from a string.
My string source is an editable div in Jquery. I pass it via AJAX POST to php script.

$('#button').on('click', function () {
var text = $('#Editable_DIV').text();
$.ajax({
        url: 'foo.php',
        method: 'POST',
        dataType: 'text',
        data: {characters: text
        },...............

     )};
 )};

My foo.php with '12345     6' string content

$string = trim(preg_replace('/( )+|\s\K\s+/','', $_POST['characters']));

It removes only 2 out of 5 white spaces.

12345   6

But when I hard coded the string like

$string = trim(preg_replace('/( )+|\s\K\s+/','', '12345     6'));

It outputs like expected

12345 6

With only 1 white space between '5' and '6' characters. I tried many Regex expressions combinations, urldecode(), none worked. What's wrong with $_POST['characters']?

UPD.
I include echo and var_dump the content of $_POST['characters'] before any manipulation and string output after manipulation.

**Before:**

12345     6

C:\xampp\htdocs\foo.php:string '12345     6' (length=15)

**After:**

12345    6

C:\xampp\htdocs\foo.php:string '12345    6' (length=14)

Body:
I added one more function after it. Please check it.

$string = trim(preg_replace('/(&nbsp;)+|\s\K\s+/','', $_POST['characters']));
$string = str_replace(' ','',$string);


问:
Do Timers run on their Own threads in Node.js?
I am a bit confused here I know Javascript is a single-threaded language but while reading about the event loop. I got to know that in case of setTimeout or setInterval javascript calls web API provided by the browser which spawns a new thread to execute timer on that thread. but what happens in the case of node.js environment with timers how do they execute/work?</p>

答:
No threads are used for timers in node.js.

Timers in node.js work in conjunction with the event loop and don't use a thread.  Timers in node.js are stored in a sorted linked list with the next timer to fire at the start of the linked list.  Each time through the event loop, it checks to see if the first timer in the linked list has reached its time.  If so, it fires that timer.  If not, it runs any other events that are waiting in the event loop.

On each subsequent cycle through the event loop, it keeps checking to see if its time for the next timer or not.  When a new timer is added, it is inserted into the linked list in its proper sorted order.  When it fires or is cancelled, it is removed from the linked list.

If the event loop has nothing to do, it may sleep for a brief period of time, but it won't sleep past the timer for the next timer.

Other references on the topic:

How does nodejs manage timers internally

Libuv timer code in nodejs

How many concurrent setTimeouts before performance issues?

Multiple Client Requests in NodeJs

Looking for a solution between setting lots of timers or using a scheduled task queue


问:
Class not found in Tomcat instance, even though every possible artifact that includes it was included as a dependency
```<code>SEVERE: Servlet [com.mycompany.mycms.screport.services.CmsPortfolioConfig] in web application [] threw load() exception
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:540)
    at org.apache.catalina.core.DefaultInstanceManager$PrivilegedLoadClass.run(DefaultInstanceManager.java:835)
    at org.apache.catalina.core.DefaultInstanceManager$PrivilegedLoadClass.run(DefaultInstanceManager.java:823)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:971)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4854)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5170)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:831)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:423)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:928)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:638)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)
</code>```

I have a Tomcat application that mostly provides RESTful api services via Jersey's JAX-RS implementation.  At the some point in startup it decides to throw the above class not found exception. Initially, I started with these dependencies:

```<code>        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>
</code>```

But it did not care, and gave me the same stack trace. So I gave up and in desperation tried all of the remaining:

```<code>        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>
</code>```

I did the build, and asked Eclipse to publish the changes to the Tomcat instance (v9). But I got the above stack trace.  I tried adding this dependency, because search.maven.org reports that it provides the missing class.

```<code>        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>
        <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>2.31</version>
</dependency>
    <dependency>
        <groupId>org.glassfish.jersey.bundles</groupId>
        <artifactId>jaxrs-ri</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.connectors</groupId>
        <artifactId>jersey-helidon-connector</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-wadl-doclet</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-jaxb</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.test-framework.maven</groupId>
        <artifactId>custom-enforcer-rules</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.examples</groupId>
        <artifactId>xml-moxy</artifactId>
        <version>2.31</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.server.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.server.version}</version>
    </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>
</code>```

And it still did not care.  I thought it was complaining because it could not find the class.  I can appreciate that if I did not provide it.  However, I thought the fc: qualifier in the maven search tools allows me to find the artifact that provides the class.  Somehow, this is all incorrect.

Incidentally, I can press Ctrl-Shift-T, type in the fully qualified type and see it in Eclipse, even the source.  I have no idea why it cannot find that class.

Separately, my services all return 404 from Tomcat.  I wonder if it is because of this error or something else.

https://search.maven.org/search?q=fc:org.glassfish.jersey.servlet.ServletContainer%20v:2.31

答: I will suggest, please check your Deployment Assembly in the project. You can do this in eclipse by right-clicking the project and going to properties. Has everything been deployed there? Maybe you have all classes in the source file but it has not been deployed.</p>

Body:
SEVERE: Servlet [com.mycompany.mycms.screport.services.CmsPortfolioConfig] in web application [] threw load() exception
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:540)
    at org.apache.catalina.core.DefaultInstanceManager$PrivilegedLoadClass.run(DefaultInstanceManager.java:835)
    at org.apache.catalina.core.DefaultInstanceManager$PrivilegedLoadClass.run(DefaultInstanceManager.java:823)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:971)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4854)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5170)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:831)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1367)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:902)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:423)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:928)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:638)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)

I have a Tomcat application that mostly provides RESTful api services via Jersey's JAX-RS implementation.  At the some point in startup it decides to throw the above class not found exception. Initially, I started with these dependencies:

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>

But it did not care, and gave me the same stack trace. So I gave up and in desperation tried all of the remaining:

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>

I did the build, and asked Eclipse to publish the changes to the Tomcat instance (v9). But I got the above stack trace.  I tried adding this dependency, because search.maven.org reports that it provides the missing class.

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>
        <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>2.31</version>
</dependency>
    <dependency>
        <groupId>org.glassfish.jersey.bundles</groupId>
        <artifactId>jaxrs-ri</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.connectors</groupId>
        <artifactId>jersey-helidon-connector</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-wadl-doclet</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-jaxb</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.test-framework.maven</groupId>
        <artifactId>custom-enforcer-rules</artifactId>
        <version>2.31</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.examples</groupId>
        <artifactId>xml-moxy</artifactId>
        <version>2.31</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.server.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.server.version}</version>
    </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.server.version}</version>
        </dependency>

And it still did not care.  I thought it was complaining because it could not find the class.  I can appreciate that if I did not provide it.  However, I thought the fc: qualifier in the maven search tools allows me to find the artifact that provides the class.  Somehow, this is all incorrect.

Incidentally, I can press Ctrl-Shift-T, type in the fully qualified type and see it in Eclipse, even the source.  I have no idea why it cannot find that class.

Separately, my services all return 404 from Tomcat.  I wonder if it is because of this error or something else.

https://search.maven.org/search?q=fc:org.glassfish.jersey.servlet.ServletContainer%20v:2.31


问:
How to get enum field value by its index in mysql
I have a table with an enum field. I need to calculate average value of this field and show it as one of enum elements.

I'm getting the average like this: SELECT AVG(val) FROM test; It works fine. But then I need to get one of enum values back by this index. To get index I'm using ROUND. But I don't know what to do next.

Is it possible?

Is there some other approach?

Example

Create a table:

```<code>CREATE TABLE test (
    id INT AUTO_INCREMENT PRIMARY KEY,
    val ENUM('bad', 'good', 'perfect')
);
</code>```

Fill the table:

```<code>INSERT INTO test(val) VALUES('bad'), ('bad'), ('good'), ('bad'), ('perfect'), ('perfect'), ('good');
</code>```

Select query to be fixed somehow:

```<code>SELECT AVG(val) average_value_ind, ROUND(AVG(val)) closest_value_ind FROM test;
</code>```

In this example the average value should be good

答:
While it's easy to convert ENUM values into integers or strings, it's harder to go the other way. You can use the ELT function but that requires enumerating all the ENUM values:

```<code>SELECT AVG(val) average_value_ind,
       ELT(ROUND(AVG(val)), 'bad', 'good', 'perfect') closest_value_ind
FROM test;
</code>```

Output:

```<code>average_value_ind   closest_value_ind
1.8571428571428572  good
</code>```

Demo on dbfiddle

Body:
I have a table with an enum field. I need to calculate average value of this field and show it as one of enum elements.

I'm getting the average like this: SELECT AVG(val) FROM test; It works fine. But then I need to get one of enum values back by this index. To get index I'm using ROUND. But I don't know what to do next.

Is it possible?

Is there some other approach?

Example

Create a table:

CREATE TABLE test (
    id INT AUTO_INCREMENT PRIMARY KEY,
    val ENUM('bad', 'good', 'perfect')
);

Fill the table:

INSERT INTO test(val) VALUES('bad'), ('bad'), ('good'), ('bad'), ('perfect'), ('perfect'), ('good');

Select query to be fixed somehow:

SELECT AVG(val) average_value_ind, ROUND(AVG(val)) closest_value_ind FROM test;

In this example the average value should be good

Body:
While it's easy to convert ENUM values into integers or strings, it's harder to go the other way. You can use the ELT function but that requires enumerating all the ENUM values:

SELECT AVG(val) average_value_ind,
       ELT(ROUND(AVG(val)), 'bad', 'good', 'perfect') closest_value_ind
FROM test;

Output:

average_value_ind   closest_value_ind
1.8571428571428572  good

Demo on dbfiddle


问:
How to display raw HTML code on an HTML page
How can I show HTML snippets on a webpage without needing to replace each < with < and > with >?

In other words, is there a tag for don't render HTML until you hit the closing tag?

答:
This is a bit of a hack, but we can use something like:

body script {
    display: block;
    font-family: monospace;
    white-space: pre;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/html">
<h1>Hello World</h1>

<ul>
    <li>Enjoy this dodgy hack,
    <li>or don't!
</ul>
</script></code>```

With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a  tag.

I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".

There’s some more info in this question When should  tags be visible and why can they?.

Body:
This is a bit of a hack, but we can use something like:

body script {
    display: block;
    font-family: monospace;
    white-space: pre;
}

<script type="text/html">
<h1>Hello World</h1>

<ul>
    <li>Enjoy this dodgy hack,
    <li>or don't!
</ul>
</script>

With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a <script>, unless you want to include a closing </script> tag.

I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".

There’s some more info in this question When should  tags be visible and why can they?.


问:
React Native create class with key-value pair props
```<code>class Adder extends Component {
  constructor(props) {
    super(props)
    this.props.callback(this.props.valueA + this.props.valueB)
  }
}
</code>```

In JSX I can do this:

```<code><Adder callback={this.resultFunc} valueA={4} valueB={2}/>
</code>```

I don't know the syntax in JS, for instance this doesn't work. I only get the first argument passed:

```<code>this.myAdder = new Adder({callback:this.resultFunc},{valueA:4},{valueB:2});
</code>```

Anything but the first KV pair is undefined in the Adder class.
Can anyone please point me right? Thanks!

答:
You should be able to put them all in the same object:</p>

```<code>this.myAdder = new Adder({callback: this.resultFunc, valueA: 4, valueB: 2});
</code>```

Body:
class Adder extends Component {
  constructor(props) {
    super(props)
    this.props.callback(this.props.valueA + this.props.valueB)
  }
}

In JSX I can do this:

<Adder callback={this.resultFunc} valueA={4} valueB={2}/>

I don't know the syntax in JS, for instance this doesn't work. I only get the first argument passed:

this.myAdder = new Adder({callback:this.resultFunc},{valueA:4},{valueB:2});

Anything but the first KV pair is undefined in the Adder class.
Can anyone please point me right? Thanks!

Body:
You should be able to put them all in the same object:

this.myAdder = new Adder({callback: this.resultFunc, valueA: 4, valueB: 2});


问:
Send Nested JSON with file in HttpClient C#
I want to send this object to the server:

```<code>public class Product
    {
        public string name { get; set; }
        public string description { get; set; }
        public ICollection<Photo> photos { get; set; }

    }
</code>```

This object have a collection of other objects:

```<code>public class Photo
    {
        public string url { get; set; }
        public IFormFile file { get; set; }
        public string description { get; set; }
    }
</code>```

How can I send the Product object with its collection of Photo objects? and How can I send a file in the Photo object?(I want to use application/json not form-data)

答:
You should send the file contents as a Base64 string

Create the string like this

```<code>Byte[] bytes = File.ReadAllBytes("path\\to\\file.jpg");
String 64string = Convert.ToBase64String(bytes);
</code>```

Then just update your photo class to have a string for the file, as assign it

```<code>public class Photo
{
    public string url { get; set; }
    public String fileContents { get; set; }
    public string description { get; set; }
}

Photo p = new Photo() { url = "...", fileContents = 64String, ..... }
</code>```

Of course this assumes that your server expect this and can decode accordingly!  I assume you also are writing the server side code.

You can convert it back like this:

```<code>Byte[] bytes = Convert.FromBase64String(64string );
File.WriteAllBytes("path\\to\\file.jpg", bytes);
</code>```

Body:
I want to send this object to the server:

public class Product
    {
        public string name { get; set; }
        public string description { get; set; }
        public ICollection<Photo> photos { get; set; }

    }

This object have a collection of other objects:

public class Photo
    {
        public string url { get; set; }
        public IFormFile file { get; set; }
        public string description { get; set; }
    }

How can I send the Product object with its collection of Photo objects? and How can I send a file in the Photo object?(I want to use application/json not form-data)

Body:
You should send the file contents as a Base64 string

Create the string like this

Byte[] bytes = File.ReadAllBytes("path\\to\\file.jpg");
String 64string = Convert.ToBase64String(bytes);

Then just update your photo class to have a string for the file, as assign it

public class Photo
{
    public string url { get; set; }
    public String fileContents { get; set; }
    public string description { get; set; }
}

Photo p = new Photo() { url = "...", fileContents = 64String, ..... }

Of course this assumes that your server expect this and can decode accordingly!  I assume you also are writing the server side code.

You can convert it back like this:

Byte[] bytes = Convert.FromBase64String(64string );
File.WriteAllBytes("path\\to\\file.jpg", bytes);


问:
how to send html message in gapi.client.gmail.users.messages.send
I tried to send a string as HTML for styling my message in gapi.client.gmail.users.messages.send API, but doenst work. is it possible to send html message for this API?</p>

```<code>sendEmail(res, emailList?) {
   //method one:
    let message = document.createElement('div');
    message.innerHTML = '<label style="color:red">Hello world<label>';

   //method two:
    message = $('<label style="color:red">Hello world<label>');

    let mimeData: any = [
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(this.emailObject.subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/plain; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "" + message];
    mimeData = dest.concat(mimeData).join("\n").trim();
    const raw = window.btoa(unescape(encodeURIComponent(mimeData))).replace(/\+/g, '-').replace(/\//g, '_');
    gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': raw
      }
    }).execute(res => {
      console.log('Email sent result', res);
    });
  }
</code>```

答:
I solved the problem, so with changing content-type to text/html it would work.</p>

```<code>message = '<label style="color:red">Hello world<label>';
  let mimeData: any = [
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(this.emailObject.subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/html; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "" + message];
</code>```

Body:
I tried to send a string as HTML for styling my message in gapi.client.gmail.users.messages.send API, but doenst work. is it possible to send html message for this API?

sendEmail(res, emailList?) {
   //method one:
    let message = document.createElement('div');
    message.innerHTML = 'Hello world';

   //method two:
    message = $('Hello world');

    let mimeData: any = [
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(this.emailObject.subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/plain; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "" + message];
    mimeData = dest.concat(mimeData).join("\n").trim();
    const raw = window.btoa(unescape(encodeURIComponent(mimeData))).replace(/\+/g, '-').replace(/\//g, '_');
    gapi.client.gmail.users.messages.send({
      'userId': 'me',
      'resource': {
        'raw': raw
      }
    }).execute(res => {
      console.log('Email sent result', res);
    });
  }

Body:
I solved the problem, so with changing content-type to text/html it would work.

message = '<label style="color:red">Hello world<label>';
  let mimeData: any = [
      "Subject: =?utf-8?B?" + window.btoa(unescape(encodeURIComponent(this.emailObject.subject))) + "?=",
      "MIME-Version: 1.0",
      "Content-Type: text/html; charset=UTF-8",
      "Content-Transfer-Encoding: 7bit",
      "",
      "" + message];


答:
As you can see the Adder takes only one argument but you are passing three
the props is a single object</p>

```<code>this.myAdder = new Adder({callback:this.resultFunc,valueA:4,valueB:2});
</code>```

Title: React Native create class with key-value pair props

Body:
As you can see the Adder takes only one argument but you are passing three
the props is a single object

this.myAdder = new Adder({callback:this.resultFunc,valueA:4,valueB:2});


问:
Changing image in django user change form
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

```<code>
class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

</code>```

This is my USER CHANGE FORM

```<code>class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```
```

答:
```<code>{% load static %}
{% block content %}

<!-- Inner Page Banner Area Start Here -->
        <div class="inner-page-banner-area" style="background-image: linear-gradient(to bottom,#002147, #fdc800);">
            <div class="container">
                <div class="pagination-area">
                    <h1>Edit Profile</h1>
                </div>
            </div>
        </div>
        <!-- Inner Page Banner Area End Here -->
        <!-- Account Page Start Here -->

<div class="section-space accent-bg">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

                    <div class="profile-details tab-content">
                        <div class="tab-pane fade active in" id="Personal">
                            <h3 class="title-section title-bar-high mb-40">Edit Profile</h3>
                            <form id='login-form' style='text-align:left;' method="post" enctype="multipart/form-data">
                              <div class="form-group mt-1">
                              {% csrf_token %}
                               {% for field in form %}
                                <p>

                                  <div class="mb-n5">{% if field.field.required %}{{ field.label_tag}}<span style='color:red;'>*</span>
                                  {% else %}{{ field.label_tag}}
                                  {% endif %}</div>

                                  {% if field.name == 'password' %}

                                  <a href="{% url 'password_change'%}" class="view-all-primary-btn">Change Password</a>

                                  {% else %}
                                  {{ field }}
                                  {% endif %}
                                  <br>
                                  {% for error in field.errors %}
                                    <p style="color: red">{{ error }}</p>
                                  {% endfor %}
                                </p>
                                </br>
                              {% endfor %}

                            </div>
                              <button class="view-all-primary-btn" type="submit">Save</button>
                            </form>
                        </div>
                    </div>
            </div>
        </div>
    </div>
</div>
{% include 'partials/_footer.html' %}
{% endblock %}
</code>```

Body:
I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed.
This is my USER CREATION FORM:

class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "

    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')

This is my USER CHANGE FORM

class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"

    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```


问:
phpunit, laravel: Cannot use "parent" when current class scope has no parent
I'm using PHPUnit 6.5.13 and Laravel 5.5 on PHP 7.4. I recently upgraded from PHP 7.2 to 7.4. and it seems like that triggered the error.

In my test I use $this->expectsEvents in order to test that an event is fired. The test class looks a little like this:

```<code>namespace Tests\Feature;
use Tests\TestCase;
use App\Events\OrderReSent;

class MyEventTest extends TestCase {
    /** @test */
    public function authenticated_client_can_resend()
    {
        $this->expectsEvents(OrderReSent::class); // there is some more code but this is the line that returns the error
    }
}
</code>```

OrderReSent looks like this (I've tried commenting out broadcastOn and remove InteractsWithSockets use, no change in result):

```<code>namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class OrderReSent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $invoiceId;

    public function __construct($invoiceId)
    {
        $this->invoiceId = $invoiceId;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
</code>```

The only place I see parent::__construct being called is in Illuminate\Broadcasting\PrivateChannel, which extends Illuminate\Broadcasting\Channel (and it is a child class, so I don't understand why it would throw this error):

```<code>namespace Illuminate\Broadcasting;

class PrivateChannel extends Channel
{
    /**
     * Create a new channel instance.
     *
     * @param  string  $name
     * @return void
     */
    public function __construct($name)
    {
        parent::__construct('private-'.$name);
    }
}
</code>```

The stacktrace looks like this and makes me believe Mockery is the culprit:

```<code>1) Tests\Feature\MyEventTest::authenticated_client_can_resend
ErrorException: Cannot use "parent" when current class scope has no parent

/project-root/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php:16
/project-root/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php:16
/project-root/vendor/mockery/mockery/library/Mockery/Container.php:219
/project-root/vendor/mockery/mockery/library/Mockery.php:89
/project-root/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php:99
/project-root/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php:54
/project-root/tests/Feature/MyEventTest.php:29
</code>```

答:
The likely culprit is due to new syntax requirements for setUp and tearDown.
Source

It can be caused by a missing return type, which is void.

For example, change this:

```<code>public function setUp()
{
    parent::setUp();
}

public function tearDown()
{
    parent::tearDown();

}
</code>```

to this:

```<code>public function setUp() : void
{
    parent::setUp();
}

public function tearDown() : void
{
    parent::tearDown();

}
</code>```

Note: I found this question looking for the error message in a unit test, and oddly enough it was related to m::close(), so I'm describing a different problem than the original question, but my answer will be relevant.

Body:
I'm using PHPUnit 6.5.13 and Laravel 5.5 on PHP 7.4. I recently upgraded from PHP 7.2 to 7.4. and it seems like that triggered the error.

In my test I use $this->expectsEvents in order to test that an event is fired. The test class looks a little like this:

namespace Tests\Feature;
use Tests\TestCase;
use App\Events\OrderReSent;

class MyEventTest extends TestCase {
    /** @test */
    public function authenticated_client_can_resend()
    {
        $this->expectsEvents(OrderReSent::class); // there is some more code but this is the line that returns the error
    }
}

OrderReSent looks like this (I've tried commenting out broadcastOn and remove InteractsWithSockets use, no change in result):

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class OrderReSent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $invoiceId;

    public function __construct($invoiceId)
    {
        $this->invoiceId = $invoiceId;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

The only place I see parent::__construct being called is in Illuminate\Broadcasting\PrivateChannel, which extends Illuminate\Broadcasting\Channel (and it is a child class, so I don't understand why it would throw this error):

namespace Illuminate\Broadcasting;

class PrivateChannel extends Channel
{
    /**
     * Create a new channel instance.
     *
     * @param  string  $name
     * @return void
     */
    public function __construct($name)
    {
        parent::__construct('private-'.$name);
    }
}

The stacktrace looks like this and makes me believe Mockery is the culprit:

1) Tests\Feature\MyEventTest::authenticated_client_can_resend
ErrorException: Cannot use "parent" when current class scope has no parent

/project-root/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php:16
/project-root/vendor/mockery/mockery/library/Mockery/Loader/EvalLoader.php:16
/project-root/vendor/mockery/mockery/library/Mockery/Container.php:219
/project-root/vendor/mockery/mockery/library/Mockery.php:89
/project-root/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php:99
/project-root/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php:54
/project-root/tests/Feature/MyEventTest.php:29

Body:
The likely culprit is due to new syntax requirements for setUp and tearDown.
Source

It can be caused by a missing return type, which is void.

For example, change this:

public function setUp()
{
    parent::setUp();
}

public function tearDown()
{
    parent::tearDown();

}

to this:

public function setUp() : void
{
    parent::setUp();
}

public function tearDown() : void
{
    parent::tearDown();

}

Note: I found this question looking for the error message in a unit test, and oddly enough it was related to m::close(), so I'm describing a different problem than the original question, but my answer will be relevant.


问:
I am getting a different maximum and minimum value here
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done
```

<p>Output: </p>

<p>Invalid Input</p>

<p>Maximum is 10</p>

<p>Minimum is 4</p>

<p><strong>Expected Output:</strong></p>

<p><strong>Invalid Input</strong></p>

<p><strong>Maximum is 11</strong></p>

<p><strong>Minimum is 2</strong></p>

```a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()
```

答:
In every iteration you are comparing with first element of list i.e val (val = a[0])
and not updating the val .
Modify

code

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
        print("Appended")
    except:
        print("Invlid")
        continue

    def sml():

        print(a)
        smalles=a[0]
        for i in range(len(a)):
            if smalles > a[i]:
                print(a[i] , end=" ")
                smalles=a[i]
        print()
        print("Minimum is",smalles)

    def lge():
        larges=a[0]
        for i in range(len(a)):
            if a[i]>larges:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()
```

Body:
It is a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered it prints out the largest and smallest of the numbers.

Custom Inputs are given as follow:

7
2
11
flip
10
4
done

Output:

Invalid Input

Maximum is 10

Minimum is 4

Expected Output:

Invalid Input

Maximum is 11

Minimum is 2

a=list()
while True:
    sval=input()
    if sval == "done":
        break
    try:
        value=int(sval)
        a.append(value)
    except:
        print("Invlid")
        continue

    def sml():
        val=a[0]
        for i in range(len(a)):
            if a[i]<val:
                smalles=a[i]
        print("Minimum is",smalles)

    def lge():
        val=a[0]
        for i in range(len(a)):
            if a[i]>val:
                larges=a[i]
        print("Maximum is",larges)

lge()
sml()