问:
How to generate mousedown or keypress event programmatically?
I am developing a chrome extension that runs some javascript on a particular web page.

I want to simulate a click action on the google docs presentation view page's 'prev', 'next' toolbar.
Unfortunately, both are  tags with onmousedown events corresponding to obfuscated javascript.

If they were anchors,
document.getElementById("ToolbarNext").onclick(); works. However, the same for onmousedown does not seem to work, probably because it requires mouse co-ordinates, etc.
How do I generate this event?

An other option is to simulate a keypress 'j' or 'k' on the DOM. I tried a few options but could not figure that out either.

答:
You can collect the function that is attached to the onmousedown and execute it.
However you'll have to re-create the event object if you need it:

```<code><input type="button" onmousedown="console.log('mousedown')" value="click me" />
<script>
    var inp = document.getElementsByTagName('INPUT')[0],
        fn = inp.onmousedown;
        fn({target:inp/*, other properties of the event object if needed */});
</script>
</code>```

Body:
You can collect the function that is attached to the onmousedown and execute it.
However you'll have to re-create the event object if you need it:

<input type="button" onmousedown="console.log('mousedown')" value="click me" />
<script>
    var inp = document.getElementsByTagName('INPUT')[0],
        fn = inp.onmousedown;
        fn({target:inp/*, other properties of the event object if needed */});
</script>


来源: stackexchange

问:
How to check report for all feature files runned under regression?

So I have 6 different feature files that I run from a regression class that has regression tags. Therefore, scripts with the @regression tag will be executed in all feature files in classpath:com.
But my concern that I get 1 report for each function file separately. Is there a way to get all 6 reports of object files in 1 HTML report?

In first screenshot you can see that i have 1 feature file runned, but when I go to cpas feature file scenarios are 39

答:
What you are showing is the JUnit runner, and you seem to have missed the existence of the parallel runner that teams are recommended to use for CI: https://github.com/intuit/karate#parallel-execution

And what most teams do is add the cucumber-html-reports dependency and use that HTML report - which is a single, aggregated one: https://github.com/intuit/karate#test-reports

```<code>Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File("target"), "demo");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
</code>```

P.S. read the docs, totally worth it :P

ContentLicense: CC BY-SA 4.0

Body:
What you are showing is the JUnit runner, and you seem to have missed the existence of the parallel runner that teams are recommended to use for CI: https://github.com/intuit/karate#parallel-execution

And what most teams do is add the cucumber-html-reports dependency and use that HTML report - which is a single, aggregated one: https://github.com/intuit/karate#test-reports

Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File("target"), "demo");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();

P.S. read the docs, totally worth it :P


问:
Can't hide share button in USDZ + QLPreviewController
I got a project that involves a few USDZ files for the augmented reality features embedded in the app. While this works great, and we're really happy with how it performs, the built-in share button of the QLPreviewController is something that we'd like to remove. Subclassing the object doesn't have any effect, and trying to hide the rightBarButtonItem with the controller returned in delegate method still shows the button when a file is selected. The implementation of USDZ + QLPreviewController we're using is pretty basic. Is there a way around this issue?</p>

```<code>func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
      return 1
 }

func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {

     let url = Bundle.main.url(forResource: models[selectedObject], withExtension: "usdz")! controller.navigationItem.rirButtonItems = nil.
// <- no effect return url as QLPreviewItem

}

 @IBAction func userDidSelectARExperience(_ sender: Any) {
     let previewController = QLPreviewController()
     previewController.dataSource = self
     previewController.delegate = self
     present(previewController, animated: true)
}
</code>```

答:
Instead of returning QLPreviewItem, use ARQuickLookPreviewItem which conforms to this protocol.

https://developer.apple.com/documentation/arkit/arquicklookpreviewitem

Then, assign a url that you would want to share (that will appear in share sheet) in canonicalWebPageURL property. By default, this property shares the file url (in this case, the USDZ file url). Doing so would not expose your file URL(s).

Body:
I got a project that involves a few USDZ files for the augmented reality features embedded in the app. While this works great, and we're really happy with how it performs, the built-in share button of the QLPreviewController is something that we'd like to remove. Subclassing the object doesn't have any effect, and trying to hide the rightBarButtonItem with the controller returned in delegate method still shows the button when a file is selected. The implementation of USDZ + QLPreviewController we're using is pretty basic. Is there a way around this issue?

func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
      return 1
 }

func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {

     let url = Bundle.main.url(forResource: models[selectedObject], withExtension: "usdz")! controller.navigationItem.rirButtonItems = nil.
// <- no effect return url as QLPreviewItem

}

 @IBAction func userDidSelectARExperience(_ sender: Any) {
     let previewController = QLPreviewController()
     previewController.dataSource = self
     previewController.delegate = self
     present(previewController, animated: true)
}


问:
Change tag name in SOAP xml response (field in class and tag in response must be different)
I have class like this:

```<code>@Root(name = "address_v1", strict = false)
public class AddressItem {

    @Attribute(name = "idAddress")
    private Long addressId;

    @Attribute(name = "idClient")
    private Long clientId;
...
}
</code>```

And I have response:

```<code>...
<ax23:address xsi:type="ax24:AddressItem">
   <ax24:addressId>1111</ax24:addressId>
   <ax24:clientId>1109</ax24:clientId>
...

</code>```

But I need:

```<code><ax23:address xsi:type="ax24:AddressItem">
   <ax24:idAddress>1111</ax24:idAddress>
   <ax24:idClient>1109</ax24:idClient>
</code>```

Annotation @Attribute(name = "idAddress") doesn't work. (org.simpleframework.xml.Attribute).

I use wsdl2java as wsdl creator.

答:
try with following steps and modify your POJO class as given below,

use @Element annotation for XML Element instead of @Attribute annotation (please refer to documentation for more info)

The Element annotation is used to represent a field or method that
  appears as an XML element.

set the relevant xml element names to @Root and @Element annotations

AddressItem.java

```<code>@Root(name = "ax23:address", strict = false)
public class AddressItem {

    @Element(name = "ax24:addressId")
    private Long addressId;

    @Element(name = "ax24:clientId")
    private Long clientId;
    ...
}
</code>```

Body:
I have class like this:

@Root(name = "address_v1", strict = false)
public class AddressItem {

    @Attribute(name = "idAddress")
    private Long addressId;

    @Attribute(name = "idClient")
    private Long clientId;
...
}

And I have response:

...
<ax23:address xsi:type="ax24:AddressItem">
   <ax24:addressId>1111</ax24:addressId>
   <ax24:clientId>1109</ax24:clientId>
...

But I need:

<ax23:address xsi:type="ax24:AddressItem">
   <ax24:idAddress>1111</ax24:idAddress>
   <ax24:idClient>1109</ax24:idClient>

Annotation @Attribute(name = "idAddress") doesn't work. (org.simpleframework.xml.Attribute).

I use wsdl2java as wsdl creator.

Body:
try with following steps and modify your POJO class as given below,

use @Element annotation for XML Element instead of @Attribute annotation (please refer to documentation for more info)

The Element annotation is used to represent a field or method that
  appears as an XML element.

set the relevant xml element names to @Root and @Element annotations

AddressItem.java

@Root(name = "ax23:address", strict = false)
public class AddressItem {

    @Element(name = "ax24:addressId")
    private Long addressId;

    @Element(name = "ax24:clientId")
    private Long clientId;
    ...
}


问:
weight matrix dimension intuition in a neural network
I have been following a course about neural networks in Coursera and came across this model:

I understand that the values of z1, z2 and so on are the values from the linear regression that will be put into an activation function. The problem that I have is when the author says that there should be one matrix of weights and a vector of the inputs, like this:

I know that the vector of Xs has a dimension of 3 x 1 because there are three inputs, but why the array of Ws is of dimensions 4 x 3?. I can deduct that it has four rows because those are the weights w1, w2, w3 and w4 that they correspond to each ones of the values of a1...a4, but what is inside that array? Its elements are something like:

```<code>w1T w1T w1T
w2T w2T w3T
... ?
</code>```

so when I multiply by x1, for example, I will get:

```<code>w1Tx1+w1Tx2+w1Tx3=w1T(x1+x2+x3)=w1TX
</code>```

I have think about it, but I cannot really get a grasp about what this array contains, even though I know that at the end I will have a vector of 4 x 1 that corresponds to the values of z. Any help?

Thanks

答:
As a thumb rule, weight matrix has following dimensions :

The number of rows must equal the number of neurons in the previous layer. (in this case previous layer is input layer). So 3

The number of columns must match the number of neurons in the next layer. So 4.

Therefore weight matrix = (3X4). If you take the transpose, it becomes (4X3).

Body:
I have been following a course about neural networks in Coursera and came across this model:

I understand that the values of z1, z2 and so on are the values from the linear regression that will be put into an activation function. The problem that I have is when the author says that there should be one matrix of weights and a vector of the inputs, like this:

I know that the vector of Xs has a dimension of 3 x 1 because there are three inputs, but why the array of Ws is of dimensions 4 x 3?. I can deduct that it has four rows because those are the weights w1, w2, w3 and w4 that they correspond to each ones of the values of a1...a4, but what is inside that array? Its elements are something like:

w1T w1T w1T
w2T w2T w3T
... ?

so when I multiply by x1, for example, I will get:

w1Tx1+w1Tx2+w1Tx3=w1T(x1+x2+x3)=w1TX

I have think about it, but I cannot really get a grasp about what this array contains, even though I know that at the end I will have a vector of 4 x 1 that corresponds to the values of z. Any help?

Thanks


问:
PHP login cookie not recognized after a couple hours, but nonetheless remains, and cannot be replaced, even after deleted
I'm new to PHP, but not programming overall, and this has had me stumped for a few weeks now.

I'm working on a website where the login will start to be used by others so I can't use my workaround at that point.

This is the code to set the cookie.

```<code>ob_start();

...

session_register("myusername");

session_register("mypassword");

$cookiename = "loginsuccess";

$ipforcookie = $_SERVER['REMOTE_ADDR'];

$cookiedata = $myusername._.$ipforcookie;

$cookietime = time()+18000;

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

...

ob_end_flush();
</code>```

This is the code I use to check if the cookie is valid.

```<code>if(isset($_COOKIE['loginsuccess'])){

    $arr = explode("_", $_COOKIE['loginsuccess']);

    if(strcmp($arr[1], $_SERVER['REMOTE_ADDR']) == 0){

        require("headerLogged.php");

    }else{

        require("header.php");

    }

}else{

    require("header.php");

}
</code>```

It checks if there is a cookie, and if the IP is match, in case someone tries to copy the cookie over to their computer or basic like that.

The problem is, I can login and the cookie is registered everywhere that i check for it... for about two hours. Then the website stops accepting it, and even after i delete the cookie, it will not create a new cookie unless i change the function call from...

```<code>setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");
</code>```

to

```<code>setcookie($cookiename, $cookiedata, $cookietime, '/');
</code>```

Then the login and validation works again. Repeating as necessary every 2 hours. I can't do this any longer, because others will begin using this login without the knowledge I have of the code, or access to the site.

Edit: When i changed it to the later just now, it could be validated, but only on the part of the site that it was created (somewhat obviously, perhaps).

I hope I've given you enough information, and I appreciate any help you're willing to give me, related to this issue, because I'm sure even the small amount of code I've supplied reveals my novice status. In any case, thank you very much for your time.

答:
Are you actually using PHP sessions? You've got the session_register() calls (which are deprecrated, by the way, and should be avoided), but I don't see a session_start() anywhere.

Your login system is highly flawed, however. Remember that cookies are stored on the client-side of things. Simply embedding an IP address into the cookie doesn't keep anyone out. They can simply edit the cookie on their side to match their IP address and boom, they're into your system.

Use regular PHP sessions instead.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to PHP, but not programming overall, and this has had me stumped for a few weeks now.

I'm working on a website where the login will start to be used by others so I can't use my workaround at that point.

This is the code to set the cookie.

ob_start();

...

session_register("myusername");

session_register("mypassword");

$cookiename = "loginsuccess";

$ipforcookie = $_SERVER['REMOTE_ADDR'];

$cookiedata = $myusername._.$ipforcookie;

$cookietime = time()+18000;

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

...

ob_end_flush();

This is the code I use to check if the cookie is valid.

if(isset($_COOKIE['loginsuccess'])){

    $arr = explode("_", $_COOKIE['loginsuccess']);

    if(strcmp($arr[1], $_SERVER['REMOTE_ADDR']) == 0){

        require("headerLogged.php");

    }else{

        require("header.php");

    }

}else{

    require("header.php");

}

It checks if there is a cookie, and if the IP is match, in case someone tries to copy the cookie over to their computer or basic like that.

The problem is, I can login and the cookie is registered everywhere that i check for it... for about two hours. Then the website stops accepting it, and even after i delete the cookie, it will not create a new cookie unless i change the function call from...

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

to

setcookie($cookiename, $cookiedata, $cookietime, '/');

Then the login and validation works again. Repeating as necessary every 2 hours. I can't do this any longer, because others will begin using this login without the knowledge I have of the code, or access to the site.

Edit: When i changed it to the later just now, it could be validated, but only on the part of the site that it was created (somewhat obviously, perhaps).

I hope I've given you enough information, and I appreciate any help you're willing to give me, related to this issue, because I'm sure even the small amount of code I've supplied reveals my novice status. In any case, thank you very much for your time.


问:
TestNG link broken ? For Eclipse Responsive code 410
ı have a question. First time i install TestNG for JAVA but i have an error. So, Add link afterthat java show me error.  Is the link I added broken? Pls help me... I'm sharing below...

The responsive code 410.
 Some times TestNG freamework is missing in the latest version , also unable to use TestNG old version . use this URL
 http://dl.bintray.com/testng-team/testng-eclipse-release/

答: The installation link has been changed from "http://beust.com/eclipse" to "http://dl.bintray.com/testng-team/testng-eclipse-release/"</p>


问:
How should I read a format string of variable length in C++ from stdin?
sorry for such a stupid question but I couldn't find any obvious answer.

I need to read from stdin first an int n with the size of an array, and then integer values from a string in the format "1 2 3 4 5 6" with n elements.

If I knew the number of parameters at compile time I could use something like a scanf (or the safe alternatives) with a format string like "%d %d %d %d %d %d", but here I will only know that value at run time.

What would be the best way to do this in C++? Performance is important but more than that safety.

答:
Here's a function that does what errorika describes:

```<code>const int SIZE = //as much of your memory as you'd like the user to have access to
***caller function must include this:
   //allocate a string to hold some data;
    char* buffer = NULL;
    buffer = malloc (SIZE * sizeof(char));
    if (buffer == NULL) {
        printf("malloc error terminating\n");
        return;
    }
***
void getEntry(char* buffer) {
    int count = 0;
    int maxlen = SIZE - 1;
    char a = '0';
    for (int i = 0; i < SIZE; i++) {
        buffer[i] = '0';
    }

    while (a != '\n' && count < maxlen) {
            a = fgetc(stdin);
            buffer[count] = a;
            count++;
    }
    if (a == '\n') {
        buffer[count - 1] = '\0';
    }
    else {
        buffer[count] = '\0';
        do {
                a = fgetc(stdin);
        } while (a != '\n');
    }
}
</code>```

This is all basic C code but user entry is evil. Here is what I've come up with for more C++ idiomatic user input functions (query is just the message string you pass in):

```<code>template<typename T>
void getInput(const std::string query, T& entry) {
    std::string input;
    std::cout << query << std::endl;
    getline(std::cin, input);
    std::stringstream buffer{input};
    buffer >> entry;
}
</code>```

OR

```<code>template<typename T>
void getInput2(std::string query, T& entry) {
    bool validInput = false;
    while (validInput == false)
    {
        validInput = true;
        std::cout << query << std::endl;
        std::cin >> entry;
        if (std::cin.fail()) {
            validInput = false;
            std::cout << "Unacceptable entry\n" << std::endl;
        }
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}
</code>```

Body:
Here's a function that does what errorika describes:

const int SIZE = //as much of your memory as you'd like the user to have access to
***caller function must include this:
   //allocate a string to hold some data;
    char* buffer = NULL;
    buffer = malloc (SIZE * sizeof(char));
    if (buffer == NULL) {
        printf("malloc error terminating\n");
        return;
    }
***
void getEntry(char* buffer) {
    int count = 0;
    int maxlen = SIZE - 1;
    char a = '0';
    for (int i = 0; i < SIZE; i++) {
        buffer[i] = '0';
    }

    while (a != '\n' && count < maxlen) {
            a = fgetc(stdin);
            buffer[count] = a;
            count++;
    }
    if (a == '\n') {
        buffer[count - 1] = '\0';
    }
    else {
        buffer[count] = '\0';
        do {
                a = fgetc(stdin);
        } while (a != '\n');
    }
}

This is all basic C code but user entry is evil. Here is what I've come up with for more C++ idiomatic user input functions (query is just the message string you pass in):

template<typename T>
void getInput(const std::string query, T& entry) {
    std::string input;
    std::cout << query << std::endl;
    getline(std::cin, input);
    std::stringstream buffer{input};
    buffer >> entry;
}

OR

template<typename T>
void getInput2(std::string query, T& entry) {
    bool validInput = false;
    while (validInput == false)
    {
        validInput = true;
        std::cout << query << std::endl;
        std::cin >> entry;
        if (std::cin.fail()) {
            validInput = false;
            std::cout << "Unacceptable entry\n" << std::endl;
        }
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}


问:
Through python when connecting MySQL and assign vales to variables, datatype changed from 'int' to 'tuple'
Comparatively new in both python and mysql.

I have solved the issue, but want to know the reason. If I use 'comma' after assigning the values to the variables, then it is changing the next datatype from 'int' to 'tuple'. For sting it is not. If I omit the 'comma' after each line then datatype remains as they are casting. In the both the cases, code exec without 'Exception'.

The DB input datatype are: func_Name as varchar, nbin as int, winWidth as int, ashFilt as varchar etc.

part of the code:-

```<code>cursor.execute("SELECT * FROM func_table;")
tab_funcTab = cursor.fetchall()
    print("parameters in [func_table]: ", cursor.rowcount)
    for row in tab_funcTab:
        funcName =      (str(row['func_Name'])), # <- this commas
        nbin =          (int(row['nbin'])), # <- this commas
        winWid =        (int(row['winWidth'])),
        ashFilt =       (str(row['ashFilt']))

     print(tab_funcTab)
     [{'id': 1, 'func_Name': 'all', 'nbin': 100, 'winWidth': 5, 'ashFilt': 'biweight']

     print(type(funcName), type(nbin), type(winWid), type(ashFilt))
     <class 'str'> <class 'tuple'> <class 'tuple'> <class 'str'>
</code>```

Could someone pl explain the reason?

答: Using comma after value will exactly create a tuple. I have tested your code again with both python2, and 3. You need to check it again.</p>

Body:
Comparatively new in both python and mysql.

I have solved the issue, but want to know the reason. If I use 'comma' after assigning the values to the variables, then it is changing the next datatype from 'int' to 'tuple'. For sting it is not. If I omit the 'comma' after each line then datatype remains as they are casting. In the both the cases, code exec without 'Exception'.

The DB input datatype are: func_Name as varchar, nbin as int, winWidth as int, ashFilt as varchar etc.

part of the code:-

cursor.execute("SELECT * FROM func_table;")
tab_funcTab = cursor.fetchall()
    print("parameters in [func_table]: ", cursor.rowcount)
    for row in tab_funcTab:
        funcName =      (str(row['func_Name'])), # <- this commas
        nbin =          (int(row['nbin'])), # <- this commas
        winWid =        (int(row['winWidth'])),
        ashFilt =       (str(row['ashFilt']))

     print(tab_funcTab)
     [{'id': 1, 'func_Name': 'all', 'nbin': 100, 'winWidth': 5, 'ashFilt': 'biweight']

     print(type(funcName), type(nbin), type(winWid), type(ashFilt))
     <class 'str'> <class 'tuple'> <class 'tuple'> <class 'str'>

Could someone pl explain the reason?


问:
What is the effect of extern "C" in C++?
What exactly does putting extern "C" into C++ code do?

For example:

```<code>extern "C" {
   void foo();
}
</code>```

答:
Without conflicting with other good answers, I will add a bit of my example.

What exactly C++ Compiler does: it mangles the names in the compilation process, hence we require telling the compiler to treat C implementation specially.

When we are making C++ classes and adding extern "C", we're telling our C++ compiler that we are using C calling convention.

Reason (we are calling C implementation from C++):  either we want to call C function from C++ or calling C++ function from C (C++ classes ... etc do not work in C).

Body:
What exactly does putting extern "C" into C++ code do?

For example:

extern "C" {
   void foo();
}


问:
Socket on Android mobile
Can Android Mobile open a socket With Python PC Server Code ?? i did a code but the android code only connect in the Emulator Is this due to i have to change any thing  in my Mobile to be able to connect socket </p>

答:
Can Android Mobile open a socket With Python PC Server Code ??

Android neither knows nor cares what language is used for the server.

i did a code but the android code only connect in the Emulator Is this due to i have to change any thing in my Mobile to be able to connect socket

No. Bear in mind, though, that your phone may or may not be able to talk to the server for other reasons:

If you are on mobile data (e.g., 3G), if the server is not on the public Internet, you will not be able to reach it

If you are on WiFi, and the server is only listening on localhost, you will not be able to reach it

Both of those will be problems with your server implementation and deployment. Android has nothing to do with it.

Title: Socket on Android mobile


问:
Can't run ng serve because of error "Cannot find module '@angular/compiler-cli'"
I have an Angular project, I can't run ng serve because it fails with the error:

```<code>dev@716a5115c45c:~/project$ npx ng serve
Cannot find module '@angular/compiler-cli'
Error: Cannot find module '@angular/compiler-cli'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:12:24)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/index.js:13:10)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
</code>```

Here is my package.json:

```<code>{
  "name": "ruskline-front",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "build-prod": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "tsc": "tsc"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/cdk": "^7.1.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/flex-layout": "^7.0.0-beta.19",
    "@angular/forms": "~7.2.0",
    "@angular/http": "~7.2.0",
    "@angular/material": "^7.1.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "ng2-ckeditor": "1.2.2",
    "rxjs": "~6.3.3",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.12.1",
    "@angular-devkit/build-ng-packagr": "~0.12.1",
    "@angular/cli": "~7.2.1",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/jasmine": "~3.3.5",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~10.12.18",
    "codelyzer": "~4.5.0",
    "css-loader": "^2.1.0",
    "jasmine-core": "~3.3.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^4.2.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tsickle": ">=0.29.0",
    "tslib": "^1.9.0",
    "tslint": "~5.12.1",
    "typescript": "~3.2.2",
    "webpack": "^4.28.4"
  }
}
</code>```

compiler-cli is listed in there

When I run npm i I get a lot of WARN messages, maybe I missed something?

```<code>dev@716a5115c45c:~/project$ npm i
npm WARN @ngtools/webpack@7.2.1 requires a peer of @angular/compiler-cli@>=5.0.0 <8.0.0 || ^7.0.0-beta.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@2.29.0 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/webpack/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/ng-packagr/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/karma/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular/compiler-cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular/cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/core/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/build-ng-packagr/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/build-angular/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

audited 54077 packages in 14.168s
found 0 vulnerabilities
</code>```

UPDATE:
After @Melchia advices i have this error:

```<code>dev@e1f2820d1be5:~/project$ make start
./node_modules/.bin/ng serve --host 0.0.0.0
module.js:550
    throw err;
    ^

Error: Cannot find module 'symbol-observable'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular/cli/lib/init.js:10:1)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
Makefile:5: recipe for target 'start' failed
make: *** [start] Error 1
</code>```

答:
You should try this:</p>

```<code>npm cache clean --force
npm install @angular/cli@latest --save-dev
</code>```

Body:
I have an Angular project, I can't run ng serve because it fails with the error:

dev@716a5115c45c:~/project$ npx ng serve
Cannot find module '@angular/compiler-cli'
Error: Cannot find module '@angular/compiler-cli'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:12:24)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/index.js:13:10)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)

Here is my package.json:

{
  "name": "ruskline-front",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "build-prod": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "tsc": "tsc"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/cdk": "^7.1.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/flex-layout": "^7.0.0-beta.19",
    "@angular/forms": "~7.2.0",
    "@angular/http": "~7.2.0",
    "@angular/material": "^7.1.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "ng2-ckeditor": "1.2.2",
    "rxjs": "~6.3.3",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.12.1",
    "@angular-devkit/build-ng-packagr": "~0.12.1",
    "@angular/cli": "~7.2.1",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/jasmine": "~3.3.5",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~10.12.18",
    "codelyzer": "~4.5.0",
    "css-loader": "^2.1.0",
    "jasmine-core": "~3.3.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "ng-packagr": "^4.2.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tsickle": ">=0.29.0",
    "tslib": "^1.9.0",
    "tslint": "~5.12.1",
    "typescript": "~3.2.2",
    "webpack": "^4.28.4"
  }
}

compiler-cli is listed in there

When I run npm i I get a lot of WARN messages, maybe I missed something?

dev@716a5115c45c:~/project$ npm i
npm WARN @ngtools/webpack@7.2.1 requires a peer of @angular/compiler-cli@>=5.0.0 <8.0.0 || ^7.0.0-beta.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@2.29.0 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/webpack/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/ng-packagr/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/karma/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular/compiler-cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular/cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/core/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/build-ng-packagr/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/@angular-devkit/build-angular/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

audited 54077 packages in 14.168s
found 0 vulnerabilities

UPDATE:
After @Melchia advices i have this error:

dev@e1f2820d1be5:~/project$ make start
./node_modules/.bin/ng serve --host 0.0.0.0
module.js:550
    throw err;
    ^

Error: Cannot find module 'symbol-observable'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/dev/volume/cache/front-node-modules/@angular/cli/lib/init.js:10:1)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
Makefile:5: recipe for target 'start' failed
make: *** [start] Error 1

Body:
You should try this:

npm cache clean --force
npm install @angular/cli@latest --save-dev


问:
Heroku error during deployment of mern application
I just tried to deploy my first heroku application, but unfortunately I am getting an error.

The command heroku logs --tail throws the following error:

```<code>2020-02-14T16:35:34.990792+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"host=agile-wildwood-52268.herokuapp.com request_id=5edfe87f-b4c7-42ee-a856-03ab806613ec fwd="88.68.64.245" dyno= connect= service= status=503 bytes= protocol=https

2020-02-14T16:35:37.110579+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=agile-wildwood-52268.herokuapp.com request_id=4e0aeeee-f828-4f85-a18c-25d54bfe3221 fwd="88.68.64.245" dyno= connect= service= status=503 bytes= protocol=https
</code>```

I don't know where this error might be caused, any help is appreciated. Thank you

答:
So I figured out the problem.
I didn't have my environment variables set on the heroku dashboard.
If you get a similar problem follow those steps:

Go to https://dashboard.heroku.com/apps

Click on your application

Go to settings and click on "reveal config vars"

Enter all your environment variables

Hope it helps

Body:
I just tried to deploy my first heroku application, but unfortunately I am getting an error.

The command heroku logs --tail throws the following error:

2020-02-14T16:35:34.990792+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"host=agile-wildwood-52268.herokuapp.com request_id=5edfe87f-b4c7-42ee-a856-03ab806613ec fwd="88.68.64.245" dyno= connect= service= status=503 bytes= protocol=https

2020-02-14T16:35:37.110579+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=agile-wildwood-52268.herokuapp.com request_id=4e0aeeee-f828-4f85-a18c-25d54bfe3221 fwd="88.68.64.245" dyno= connect= service= status=503 bytes= protocol=https

I don't know where this error might be caused, any help is appreciated. Thank you


问:
How to select hierarchical records from two tables using join
Actually I want to select matched records from two tables with hierarchical data from the first table

I have two tables:

tmpos_category table with columns (category_refid(pk),category_name,parent_ref_id). i am storing hierarchical data in it.

tmpos_menu_child table with columns (id(pk),title,category_ref_ids(fk)). category_ref_ids field from tmpos_menu_child table references the category_refid field of tmpos_category table.

this is a tmpos_category table with hierarchical categories

tmpos_menu_child table with category_ref_ids as fk refrances category(category_refid ) column

SELECT DISTINCT ct.category_name,ct.category_refid,ct.parent_ref_id
from tmpos_category ct
JOIN tmpos_menu_child tmc
ON ct.category_refid = tmc.category_ref_ids
```

Now My Question is when i join tmpos_category table and tmpos_menu_child table i will get all distinct matched category but i also want selected category parent records

答:
If you can only have 2 levels in your hierarchy, i.e. a parent cannot itself have a parent, then two JOINs will do it.

SELECT i.id AS item_id, i.title AS item_title
     , c.category_refid, c.category_name
     , c.parent_ref_id, p.category_name AS parent_name
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
  LEFT JOIN tmpos_category p ON p.category_refid = c.parent_ref_id
```

<p>If the hierarchy can be deep, you should use a hierarchical query, which in most DBMS's are done with a recursive CTE (common table expression).</p>

<pre class="lang-sql prettyprint-override"><code>WITH RECURSIVE Item_and_Cat (item_id, item_title, category_level,
                             category_refid, category_name, parent_ref_id) AS (
   SELECT i.id AS item_id, i.title AS item_title
        , c.category_refid, c.category_name
        , 1 AS category_level, c.parent_ref_id
     FROM tmpos_menu_child i
     JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
   UNION ALL
   SELECT i.item_id, i.item_title
        , p.category_refid, p.category_name
        , i.category_level + 1 AS category_level, p.parent_ref_id
     FROM Item_and_Cat i
     JOIN tmpos_category p ON p.category_refid = i.parent_ref_id
)
SELECT item_id, item_title, category_refid, category_name, category_level
  FROM Item_and_Cat
</code>```

Note: The RECURSIVE keyword is required for PostgreSQL and MySQL, but not allowed for Oracle DB and SQL Server.

UPDATE

From comment:

i want there parents as record(in seperate row)

To get parent records as separate rows, run the query twice and combine with UNION.

SELECT i.id AS item_id, i.title AS item_title
     , c.category_refid, c.category_name, 0 AS is_parent
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
UNION ALL
SELECT i.id AS item_id, i.title AS item_title
     , p.category_refid, p.category_name, 1 AS is_parent
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
  JOIN tmpos_category p ON p.category_refid = c.parent_ref_id
```

Body:
Actually I want to select matched records from two tables with hierarchical data from the first table

I have two tables:

tmpos_category table with columns (category_refid(pk),category_name,parent_ref_id). i am storing hierarchical data in it.

tmpos_menu_child table with columns (id(pk),title,category_ref_ids(fk)). category_ref_ids field from tmpos_menu_child table references the category_refid field of tmpos_category table.

this is a tmpos_category table with hierarchical categories

tmpos_menu_child table with category_ref_ids as fk refrances category(category_refid ) column

SELECT DISTINCT ct.category_name,ct.category_refid,ct.parent_ref_id
from tmpos_category ct
JOIN tmpos_menu_child tmc
ON ct.category_refid = tmc.category_ref_ids

Now My Question is when i join tmpos_category table and tmpos_menu_child table i will get all distinct matched category but i also want selected category parent records

Body:
If you can only have 2 levels in your hierarchy, i.e. a parent cannot itself have a parent, then two JOINs will do it.

SELECT i.id AS item_id, i.title AS item_title
     , c.category_refid, c.category_name
     , c.parent_ref_id, p.category_name AS parent_name
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
  LEFT JOIN tmpos_category p ON p.category_refid = c.parent_ref_id

If the hierarchy can be deep, you should use a hierarchical query, which in most DBMS's are done with a recursive CTE (common table expression).

WITH RECURSIVE Item_and_Cat (item_id, item_title, category_level,
                             category_refid, category_name, parent_ref_id) AS (
   SELECT i.id AS item_id, i.title AS item_title
        , c.category_refid, c.category_name
        , 1 AS category_level, c.parent_ref_id
     FROM tmpos_menu_child i
     JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
   UNION ALL
   SELECT i.item_id, i.item_title
        , p.category_refid, p.category_name
        , i.category_level + 1 AS category_level, p.parent_ref_id
     FROM Item_and_Cat i
     JOIN tmpos_category p ON p.category_refid = i.parent_ref_id
)
SELECT item_id, item_title, category_refid, category_name, category_level
  FROM Item_and_Cat

Note: The RECURSIVE keyword is required for PostgreSQL and MySQL, but not allowed for Oracle DB and SQL Server.

UPDATE

From comment:

i want there parents as record(in seperate row)

To get parent records as separate rows, run the query twice and combine with UNION.

SELECT i.id AS item_id, i.title AS item_title
     , c.category_refid, c.category_name, 0 AS is_parent
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
UNION ALL
SELECT i.id AS item_id, i.title AS item_title
     , p.category_refid, p.category_name, 1 AS is_parent
  FROM tmpos_menu_child i
  JOIN tmpos_category c ON c.category_refid = i.category_ref_ids
  JOIN tmpos_category p ON p.category_refid = c.parent_ref_id


问:
How to find functions which are not executed?
I have a MS Visual Studio 2005 workspace, all C code. I want to find all the functions in that code, which are not called/executed when a certain test case is executed.

What is the way to get that using

1.) MS VS 2005 itself or MSVC6.0 ?

2.) Using some other tool?

-AD

答:
Might want to look into the code coverage tool in VS 2005 Team Edition.  There's an FAQ on it here

There's another tool out there called ncover that looks like it does something similar as well.  Seem's pretty expensive, but they do have a 30 day trial.

I'm sure others will chime in with other tools that might fit the bill as well.

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Eric P


问:
Show information of subclass in list_display django
I have two classes in models.py:

```class ModelOne(models.Model):
   field_one = models.CharField(max_length=100)
   field_two = models.CharField(max_length=200)
   field_three = models.CharField(max_length=300)
   [...] #other fields
   def __unicode__(self):
       return self.field_one

class ModelTwo(models.Model):
   relation_model_one = models.ForeignKey(ModelOne)
   other_field = models.CharField(max_length=50)
   [...]
   def __unicode__(self):
       return self.relation_model_one.field_one
```

And your administration in admin.py is this:

```
class ModelTwoInline(admin.StackedInline):
    model = ModelTwo
    extra = 0

class ModelOneAdmin(admin.ModelAdmin):
    list_display = ('field_one', 'field_two', 'field_three',)
    inlines = [ModelTwoInline]
```

My question is:
Can I display the fields of the ModelTwo in list_display of the ModelOne? (The same for list_filter and search_fields)

I need this because I have many subclasses related to the main class!

答:
You can display anything you want in list_display by writing an instance method with the @property decorator, which then returns whatever you need, and including it in list_display. I don't think that works for list_filter though.

So, let's return to your ModelOne class:

```<code>class ModelOne(models.Model):
    [...]

    def __unicode__(self):
        return self.field_one

    @property
    def model_two_other_field(self):
        return ', '.join([m2.other_field for m2 in self.modeltwo_set.all()])
</code>```

Then, in your ModelOneAdmin:

```<code>class ModelOneAdmin(admin.ModelAdmin):
    list_display = ('field_one', 'field_two', 'field_three', 'model_two_other_field')
    [...]
</code>```

I would note, for the record, that when you do this, you'll be requiring a database hit for every ModelOne instance being displayed. So, if you're listing 50 instances, you're incurring the overhead of 50 separate queries (one for each call of self.modeltwo_set.all()). That doesn't necessarily mean you shouldn't do it -- it might be the right answer, depending on your situation. Just be aware that it could be quite an expensive operation.

Body:
I have two classes in models.py:

class ModelOne(models.Model):
   field_one = models.CharField(max_length=100)
   field_two = models.CharField(max_length=200)
   field_three = models.CharField(max_length=300)
   [...] #other fields
   def __unicode__(self):
       return self.field_one

class ModelTwo(models.Model):
   relation_model_one = models.ForeignKey(ModelOne)
   other_field = models.CharField(max_length=50)
   [...]
   def __unicode__(self):
       return self.relation_model_one.field_one

And your administration in admin.py is this:

class ModelTwoInline(admin.StackedInline):
    model = ModelTwo
    extra = 0

class ModelOneAdmin(admin.ModelAdmin):
    list_display = ('field_one', 'field_two', 'field_three',)
    inlines = [ModelTwoInline]

My question is:
Can I display the fields of the ModelTwo in list_display of the ModelOne? (The same for list_filter and search_fields)

I need this because I have many subclasses related to the main class!

Body:
You can display anything you want in list_display by writing an instance method with the @property decorator, which then returns whatever you need, and including it in list_display. I don't think that works for list_filter though.

So, let's return to your ModelOne class:

class ModelOne(models.Model):
    [...]

    def __unicode__(self):
        return self.field_one

    @property
    def model_two_other_field(self):
        return ', '.join([m2.other_field for m2 in self.modeltwo_set.all()])

Then, in your ModelOneAdmin:

class ModelOneAdmin(admin.ModelAdmin):
    list_display = ('field_one', 'field_two', 'field_three', 'model_two_other_field')
    [...]

I would note, for the record, that when you do this, you'll be requiring a database hit for every ModelOne instance being displayed. So, if you're listing 50 instances, you're incurring the overhead of 50 separate queries (one for each call of self.modeltwo_set.all()). That doesn't necessarily mean you shouldn't do it -- it might be the right answer, depending on your situation. Just be aware that it could be quite an expensive operation.


问:
Using vim, how can I find two words that are in a row and replace it with three words in a row in a txt file?
For instance, I need to find double words like "Saw saw" and replace it with triple words like "Saw saw saw" in a txt file.

I'm thinking I'll be using :%s/pattern/replace/g

There is going to be multiple instances of this in the txt file, so I need to write something that would be universal, or work for different words.

答:
A possible solution is:

```<code>%s/\c\([Ss]aw\) \1/\1 \1 \1/g
</code>```

where \1 is a backreferece for the first capturing group \([Ss]aw\). To force lowercase for second and third occurrences include \l in the replacement string:

```<code>%s/\c\([Ss]aw\) \1/\1 \l\1 \l\1/g
</code>```

Body:
A possible solution is:

%s/\c\([Ss]aw\) \1/\1 \1 \1/g

where \1 is a backreferece for the first capturing group \([Ss]aw\). To force lowercase for second and third occurrences include \l in the replacement string:

%s/\c\([Ss]aw\) \1/\1 \l\1 \l\1/g


问:
BadMethodCallException Method Illuminate\Database\Eloquent\Collection::paginate does not exist
After adding Paginate function I'm getting this error    </p>

```<code>$sub_categories = SubCategory::where('id', $id)->first();
$products = Products::where('subcategory_id', $sub_categories->id)->get()->paginate(10);
</code>```

答:
$sub_categories = SubCategory::where('id', $id)->first(), this will only give you null or one record, not a collection, so you can not use ->paginate(10); chain it. You will only get one record at the most, why you need to paginate?

Update
so first for the sub_categories you do not need to paginate, as you just want one record. so the code should be like this.

$sub_categories = SubCategory::where('id', $id)->first();
```

<p>second, if you want to paginate <code>$products</code> you should do this,</p>

<pre class="lang-php prettyprint-override"><code>if ($sub_categories)
{
    $products = Products::where('subcategory_id', $sub_categories->id)->paginate(10);
}
</code>```

Body:
After adding Paginate function I'm getting this error

$sub_categories = SubCategory::where('id', $id)->first();
$products = Products::where('subcategory_id', $sub_categories->id)->get()->paginate(10);

Body:
$sub_categories = SubCategory::where('id', $id)->first(), this will only give you null or one record, not a collection, so you can not use ->paginate(10); chain it. You will only get one record at the most, why you need to paginate?

Update
so first for the sub_categories you do not need to paginate, as you just want one record. so the code should be like this.

$sub_categories = SubCategory::where('id', $id)->first();

second, if you want to paginate $products you should do this,

if ($sub_categories)
{
    $products = Products::where('subcategory_id', $sub_categories->id)->paginate(10);
}


问:
How to get previous/next row when ordering by date/time then ID in MySQL?
I have table like

```<code>SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...
</code>```

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

答:
Previous:

```<code>SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC LIMIT 1
</code>```

Next:

```<code>SELECT id, name, date FROM `table` ORDER BY `date` ASC, id ASC LIMIT 1
</code>```

If you need both in a single query:

```<code>( SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC LIMIT 1 )
UNION ALL
( SELECT id, name, date FROM `table` ORDER BY `date` ASC, id ASC LIMIT 1 )
</code>```

Body:
I have table like

SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

Body:
Previous:

SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC LIMIT 1

Next:

SELECT id, name, date FROM `table` ORDER BY `date` ASC, id ASC LIMIT 1

If you need both in a single query:

( SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC LIMIT 1 )
UNION ALL
( SELECT id, name, date FROM `table` ORDER BY `date` ASC, id ASC LIMIT 1 )


问:
How to deal with merge/pull in git
I have to use different computers. I updated file A, B and other files in one and B, C and other files in another.

Updates in file B are different part of code.  I have committed in both.
I pushed A and B to the github.

Questions:

Now what should I do in another?

Should I just pull? Or should I push first?

If I push, will file A be overwritten?

If I pull, will file C be overwritten?

What kind of process do I need to take?

What do I need to do with file B which has different version? Can I merge them?

答:
You have to first pull, so that your additions are on top of what is in the server. Once you've pulled (which will merge the previously pushed mods with your local mods), then you can push.
 BTW: This is not github, this is plain git. I suggest the following book to understand git workings:

http://book.git-scm.com/

Title: How to deal with merge/pull in git


问:
Redux Presentational Components Vs Container Component
I'm beginner of react development with redux. I'm wondering what are the Presentational Components and Container Components.

How to categorized components as Presentational or Container ?

What are the difference between these two ?

What are the benefit of categorizing components this way ?

答:
This is how I understand it:

Presentation Components

concern with how things look

Container Components

components with logic involved

However, upon further research, I realised that such separation is sometimes unnecessary as mentioned by Dan Abramov here:
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

You can understand presentation component as something you find in react UI component library. They makes UI component looks pretty. Then, one only have to compose the presentation components in container component as needed.

Having said that, if you're using a component library, then most of the component you coded will be container component. Of course you can make your own react UI component library.

As nothing is hard rules in programming, react UI component library may have some logic tightly coupled with the component (ie how it behaves, such as a drawer component) and still treated to be presentation component.


问:
How to make a server-side loop endless and non-blocking at the same time without using threading/background jobs?
I need an endless loop to run server-side and emit some information per iteration.

Also, I need to make sure it is started only once - preferably on server start-up - and not induced by various users using the app.

Then I would like to avoid additional stack (threading, background jobs etc.) if possible.

Here is the task:

```<code>@app.route('/refresh_games_list_periodically')
def refresh_games_list_periodically():
    while True:
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)
</code>```

It starts whenever 'index.html' is rendered:

```<code>@app.route('/')
def index():
    return render_template('index.html')
</code>```

index.html:

```<code>fetch("{{url_for('refresh_games_list_periodically') }}")
</code>```

Full code:

```<code>import time

from flask import (
    Flask,
    render_template,
    jsonify,
    request,
)
from flask_socketio import SocketIO, emit

from minesweeper import Game, GamesManager

games_manager = GamesManager()

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/refresh_games_list_periodically')
def refresh_games_list_periodically():
    while True:
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')
</code>```

The problem currently is that whenever a new user enters 'index.html', another iteration of the loop will start running besides the old one.

I have tried using some boolean flags to mark the view as already called, but could not get it right in Flask context.

Then I thought I could make refresh_games_list_periodically a normal function, not a view, and just call it in my Flask app before views. But then the while loop will be blocking and no page will be rendered:

```<code>import time

from flask import (
    Flask,
    render_template,
    jsonify,
    request,
)
from flask_socketio import SocketIO, emit

from minesweeper import Game, GamesManager

games_manager = GamesManager()

app = Flask(__name__)
socketio = SocketIO(app)

refresh_games_list_periodically()

def refresh_games_list_periodically():
    while True: # WILL BLOCK
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')
</code>```

How else can I do this?

答:
```<code>thread = threading.Thread(target=refresh_games_list_periodically)
thread.start()
</code>```

I guess ...  I imagine this is not a great idea however and you are probably better off running your socket loop in one process and your flask app seperately

Body:
I need an endless loop to run server-side and emit some information per iteration.

Also, I need to make sure it is started only once - preferably on server start-up - and not induced by various users using the app.

Then I would like to avoid additional stack (threading, background jobs etc.) if possible.

Here is the task:

@app.route('/refresh_games_list_periodically')
def refresh_games_list_periodically():
    while True:
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)

It starts whenever 'index.html' is rendered:

@app.route('/')
def index():
    return render_template('index.html')

index.html:

fetch("{{url_for('refresh_games_list_periodically') }}")

Full code:

import time

from flask import (
    Flask,
    render_template,
    jsonify,
    request,
)
from flask_socketio import SocketIO, emit

from minesweeper import Game, GamesManager

games_manager = GamesManager()

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/refresh_games_list_periodically')
def refresh_games_list_periodically():
    while True:
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

The problem currently is that whenever a new user enters 'index.html', another iteration of the loop will start running besides the old one.

I have tried using some boolean flags to mark the view as already called, but could not get it right in Flask context.

Then I thought I could make refresh_games_list_periodically a normal function, not a view, and just call it in my Flask app before views. But then the while loop will be blocking and no page will be rendered:

import time

from flask import (
    Flask,
    render_template,
    jsonify,
    request,
)
from flask_socketio import SocketIO, emit

from minesweeper import Game, GamesManager

games_manager = GamesManager()

app = Flask(__name__)
socketio = SocketIO(app)

refresh_games_list_periodically()

def refresh_games_list_periodically():
    while True: # WILL BLOCK
        response = {
            'games_list': games_manager.get_nonexpired_games(),
        }
        socketio.emit('games_list_refreshed', response)
        time.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

How else can I do this?

Body:
thread = threading.Thread(target=refresh_games_list_periodically)
thread.start()

I guess ...  I imagine this is not a great idea however and you are probably better off running your socket loop in one process and your flask app seperately


问:
Static Parsing: Tell if Two Javascript Functions are the Same
I am looking for a way, using static analysis of two JavaScript functions, to tell if they are the same. Let me define multiple definitions of "the same".

Level 1: The functions are the same except for possible different whitespace, e.g. TABS, CR, LF and SPACES.

Level 2 The functions may have different whitespace like Level 1, but also may have different variable names.

Level 3 ???

For level one, I think I could just remove all (non-literal, which may be tough) whitespace from each string containing the two JS function definitions, and then compare the strings.

For level two, I think I would need to use something like SpiderMonkey's parser to generate a two parse trees, and then write a comparer which walks the trees and allows variables to have different names.

[Edit] Williham, makes a good point below. I do mean identical. Now, I'm looking for some practical strategies, particularly with regards to using parse trees.

答:
See my company's (Semantic Designs) Smart Differencer tool.  This family of tools parses source code according to compiler-level-detail grammar for the language of interest (in your case, JavaScript), builds ASTs, and then compares the ASTs (which effectively ignores whitespace and comments).  Literal values are normalized, so it doesn't matter how they are "spelled"; 10E17 has the same normalized value as 1E18.

If the two trees are the same, it will tell you "no differences".  If they differ by a consistent renaming of an identifier, the tool will tell you the consisten renaming and the block in which it occurs.   Other differences are reported as language-element (identifier, statement, block, class,...) insertions, deletions, copies, or moves.  The goal is to report the small set of deltas that plausibly explain the differences.  You can see examples for a number of languages at the web site.

You can't in practice go much beyond this; to determine if two functions compute the same answer, in principle you have to solve the halting problem.   You might be able to detect where two language elements that are elements of a commutative list, can be commuted without effect; we're working on this.  You might be able to apply normalization rewrites to canonicalize certain forms (e.g., map all multiple declarations into a sequence of lexically sorted single declarations).  You might be able to convert the source code into its equivalent set of dataflows, and do a graph isomorphism match (the Programmer's Apprentice from MIT back in the 1980's proposed to do this, but I don't think they ever got there).

All of there are more work to do than you might expect.


问:
Vue test watcher change but code inside not response
I'm stuck in this situation where I have a getters from Vuex Store, and whenever that getter change (new value update), the local state data(the 'list') should be reassign .
This is my component, which has 'list' in data

And here is my test Successfully change the getSkills to the getSkillsMock, but there is no response from list, list is still an []

答:
You need to set deep to true when watching an array or object so that
  Vue knows that it should watch the nested data for changes.

```<code>watch: {
 getSkills: {
  handler () {
   this.list = this.getSkills.map(items => {
    return { value: items.id, label: items.name }
   })
  },
  deep: true
 }
}
</code>```

Body:
You need to set deep to true when watching an array or object so that
  Vue knows that it should watch the nested data for changes.

watch: {
 getSkills: {
  handler () {
   this.list = this.getSkills.map(items => {
    return { value: items.id, label: items.name }
   })
  },
  deep: true
 }
}


问:
Angular CLI Proxy: Redirect unsecured local websocket to secured remote websocket
I am trying to establish an MQTT connection via Websockets over a reverse proxy. Is it possible to configure the Angular CLI proxy to forward requests to ws://localhost:4200/mqtt to wss://mqtt.example.com/mqtt?

I have been trying multiple configurations and can't seem to get it to work. Here is what I have in my proxy.conf.json:

```<code>"/mqtt/*": {
  "target": "wss://mqtt.example.com/",
  "secure": false,
  "ws": true,
  "changeOrigin": true,
  "logLevel": "debug"
}
</code>```

I have tried various combinations, using secure and/or changeOrigin to either true or false and I am never able to connect.

Using "secure": false, "ws": true, "changeOrigin": true, or "secure": true, "ws": true, "changeOrigin": true, I always get:

Error during WebSocket handshake: Unexpected response code: 502

Update

I changed the proxy definition to omit the changeOrigin option and append /mqtt to the target:

```<code>"/mqtt": {
  "target": "wss://mqtt.example.com/mqtt",
  "secure": false,
  "ws": true,
  "logLevel": "debug"
},
</code>```

Now get a different error message:

Error during WebSocket handshake: Unexpected response code: 404

My problem is that I cannot see the exact request that the Angular CLI is sending to the remote server, I have already set the logLevel to debug but that does not give any useful output to diagnose the problem. It would be very helpful to debug this if I could see the exact request that the proxy makes to the remote server.

Update 2

Its definitely not necessary to include /mqtt in the target, because then I end up with /mqtt/mqtt in the final request that the proxy makes.

Debugging this further I have discovered the following error message in my Kubernetes Ingress controller:

upstream prematurely closed connection while reading response header from upstream,

However, when I connect directly to the secure websocket using a local MQTT client (MqttBox) then the connection works, so I still think that its not a problem with the upstream configuration but something introduced in to the proxy connection.

Update 3

When I look at the mosquitto broker logs I keep seeing the following output:

1581786178: Socket error on client , disconnecting.

Also I am wondering if my problem might be caused because part of the connection goes via TLS, so the connection chain looks like this:

```<code>Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WSS/HTTPS --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)
</code>```

Inspecting traffic via tcpdump -vvvs 1500 - -i any port 9001 I was able to extract the following header:

```<code>GET /mqtt HTTP/1.1
Host: mqtt.example.com
Upgrade: websocket
Connection: upgrade
X-Request-ID: [...]
X-Real-IP: [...]
X-Forwarded-For: [...]
X-Forwarded-Host: [...]
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Original-URI: /mqtt
X-Scheme: https
sec-websocket-protocol: mqtt
sec-websocket-extensions: permessage-deflate; client_max_window_bits
sec-websocket-key: [...]
accept-language: en-US,en;q=0.9
accept-encoding: gzip, deflate, br
sec-websocket-version: 13
origin: chrome-extension://[...]
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36
cache-control: no-cache
pragma: no-cache
</code>```

Update 4

I have investigated this further. When I disable TLS on the Kubernetes Ingress controller and the whole chain is communicating unsecured, then I have no problems and I can proxy the Websocket connection via the Angular CLI. However, as soon as I enable TLS then I run into the errors that I described above. So to sum up, the following three constellations work fine:

```<code># whole chain unsecured (WORKS OK):
Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WS/HTTP --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)

# wss to public eclipse mqtt broker (WORKS OK):
Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WSS/HTTPS --> MQTT Broker (mqtt.eclipse.org:443)

# secured connection directly from browser/client to broker (WORKS OK):
Browser/Client
  -- WSS/HTTPS --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)
</code>```

答:
This is possible; the following config works with the eclipse test server:

```<code>"/wss": {
    "target": "https://mqtt.eclipse.org:443/mqtt",
    "secure": false,
    "ws": true
},
</code>```

note:  Both https://mqtt.eclipse.org:443/mqtt and wss://mqtt.eclipse.org:443/mqtt work ok.

With that configuration I am able to connect (and subscribe/publish etc) using the Paho JS MQTT Client:

I'm not sure what is wrong with your config but suspect that "target": "wss://mqtt.example.com/" should be "target": "wss://mqtt.example.com/mqtt" (but that might just be due to how you anonymised the data?). Hopefully trying it with the test server will point you in the right direction (I assume you have checked that the proxy works with a standard http page).

Body:
I am trying to establish an MQTT connection via Websockets over a reverse proxy. Is it possible to configure the Angular CLI proxy to forward requests to ws://localhost:4200/mqtt to wss://mqtt.example.com/mqtt?

I have been trying multiple configurations and can't seem to get it to work. Here is what I have in my proxy.conf.json:

"/mqtt/*": {
  "target": "wss://mqtt.example.com/",
  "secure": false,
  "ws": true,
  "changeOrigin": true,
  "logLevel": "debug"
}

I have tried various combinations, using secure and/or changeOrigin to either true or false and I am never able to connect.

Using "secure": false, "ws": true, "changeOrigin": true, or "secure": true, "ws": true, "changeOrigin": true, I always get:

Error during WebSocket handshake: Unexpected response code: 502

Update

I changed the proxy definition to omit the changeOrigin option and append /mqtt to the target:

"/mqtt": {
  "target": "wss://mqtt.example.com/mqtt",
  "secure": false,
  "ws": true,
  "logLevel": "debug"
},

Now get a different error message:

Error during WebSocket handshake: Unexpected response code: 404

My problem is that I cannot see the exact request that the Angular CLI is sending to the remote server, I have already set the logLevel to debug but that does not give any useful output to diagnose the problem. It would be very helpful to debug this if I could see the exact request that the proxy makes to the remote server.

Update 2

Its definitely not necessary to include /mqtt in the target, because then I end up with /mqtt/mqtt in the final request that the proxy makes.

Debugging this further I have discovered the following error message in my Kubernetes Ingress controller:

upstream prematurely closed connection while reading response header from upstream,

However, when I connect directly to the secure websocket using a local MQTT client (MqttBox) then the connection works, so I still think that its not a problem with the upstream configuration but something introduced in to the proxy connection.

Update 3

When I look at the mosquitto broker logs I keep seeing the following output:

1581786178: Socket error on client , disconnecting.

Also I am wondering if my problem might be caused because part of the connection goes via TLS, so the connection chain looks like this:

Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WSS/HTTPS --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)

Inspecting traffic via tcpdump -vvvs 1500 - -i any port 9001 I was able to extract the following header:

GET /mqtt HTTP/1.1
Host: mqtt.example.com
Upgrade: websocket
Connection: upgrade
X-Request-ID: [...]
X-Real-IP: [...]
X-Forwarded-For: [...]
X-Forwarded-Host: [...]
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Original-URI: /mqtt
X-Scheme: https
sec-websocket-protocol: mqtt
sec-websocket-extensions: permessage-deflate; client_max_window_bits
sec-websocket-key: [...]
accept-language: en-US,en;q=0.9
accept-encoding: gzip, deflate, br
sec-websocket-version: 13
origin: chrome-extension://[...]
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36
cache-control: no-cache
pragma: no-cache

Update 4

I have investigated this further. When I disable TLS on the Kubernetes Ingress controller and the whole chain is communicating unsecured, then I have no problems and I can proxy the Websocket connection via the Angular CLI. However, as soon as I enable TLS then I run into the errors that I described above. So to sum up, the following three constellations work fine:

# whole chain unsecured (WORKS OK):
Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WS/HTTP --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)

# wss to public eclipse mqtt broker (WORKS OK):
Browser/Client
  -- WS/HTTP --> Angular CLI Proxy (localhost:4200)
  -- WSS/HTTPS --> MQTT Broker (mqtt.eclipse.org:443)

# secured connection directly from browser/client to broker (WORKS OK):
Browser/Client
  -- WSS/HTTPS --> Ingress Controller (mqtt.example.com:443)
  -- WS/HTTP --> MQTT Broker (port 9001)

Body:
This is possible; the following config works with the eclipse test server:

"/wss": {
    "target": "https://mqtt.eclipse.org:443/mqtt",
    "secure": false,
    "ws": true
},

note:  Both https://mqtt.eclipse.org:443/mqtt and wss://mqtt.eclipse.org:443/mqtt work ok.

With that configuration I am able to connect (and subscribe/publish etc) using the Paho JS MQTT Client:

I'm not sure what is wrong with your config but suspect that "target": "wss://mqtt.example.com/" should be "target": "wss://mqtt.example.com/mqtt" (but that might just be due to how you anonymised the data?). Hopefully trying it with the test server will point you in the right direction (I assume you have checked that the proxy works with a standard http page).


问:
How to change two variables at the same time in flutter?

Goal:

I am trying to create list of items which have a counter to decrement or increase, and at the same time a total is shown with the final price.

Problem:

The problem is that both variables cannot be changed at the same time because they are a setState and I don't know how to do it asynchronously.

I also don't know how to convert this class to a widget that can be called normal to build the list.

```<code>class FlutterExample extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return new Scaffold(
     body: new ListView(
       children: new List.generate(5, (i)=>new ListTileItem(
         title: "Item#$i",
       )),
     ),
   );
 }

}
class ListTileItem extends StatefulWidget {
final  String title;
 ListTileItem({this.title});
 @override
 _ListTileItemState createState() => new _ListTileItemState();
}

class _ListTileItemState extends State<ListTileItem> {
 int _itemCount = 0;
 @override
 Widget build(BuildContext context) {
   return new Container(

     child: new Row(
       children: <Widget>[
          IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),),
           new Text(_itemCount.toString()),
           new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
       ],
     ),
   );
 }
}

</code>```

答:
Keep the state in the upper widget and pass it down the tree so that child widget can always redraw it correctly.

What you need is a StateManagement setup in your project. Read this article for more details.

Body:
Goal:

I am trying to create list of items which have a counter to decrement or increase, and at the same time a total is shown with the final price.

Problem:

The problem is that both variables cannot be changed at the same time because they are a setState and I don't know how to do it asynchronously.

I also don't know how to convert this class to a widget that can be called normal to build the list.

class FlutterExample extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return new Scaffold(
     body: new ListView(
       children: new List.generate(5, (i)=>new ListTileItem(
         title: "Item#$i",
       )),
     ),
   );
 }

}
class ListTileItem extends StatefulWidget {
final  String title;
 ListTileItem({this.title});
 @override
 _ListTileItemState createState() => new _ListTileItemState();
}

class _ListTileItemState extends State<ListTileItem> {
 int _itemCount = 0;
 @override
 Widget build(BuildContext context) {
   return new Container(

     child: new Row(
       children: <Widget>[
          IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),),
           new Text(_itemCount.toString()),
           new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
       ],
     ),
   );
 }
}


问:
Pandas dataframe apply lambda to selected rows only (based on a condition) within the dataframe
In the line of code below, I'm trying to apply a lambda formula only to selected rows based on a condition. I don't want the formula to apply to every row in the dataset. The code seems to be working correctly but I'm getting a warning that says "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame" (not sure why?) so I'm not sure if this is the right way to do it? Also if there's a more efficient/easier way I'll appreciate letting me know about it. Thanks.

I'm basically trying to say if the column GlobalName = '' THEN apply lambda (which has its own if statement)

```<code>df['GlobalName'][df['GlobalName']==''] = df['IsPerson'].apply(lambda x: x if x==True else '')
</code>```

答:
Update: This solution works:

df['GlobalName'] = np.where(df['GlobalName']=='', df['IsPerson'].apply(lambda x: x if x==True else ''), df['GlobalName'])
```

Body:
In the line of code below, I'm trying to apply a lambda formula only to selected rows based on a condition. I don't want the formula to apply to every row in the dataset. The code seems to be working correctly but I'm getting a warning that says "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame" (not sure why?) so I'm not sure if this is the right way to do it? Also if there's a more efficient/easier way I'll appreciate letting me know about it. Thanks.

I'm basically trying to say if the column GlobalName = '' THEN apply lambda (which has its own if statement)

df['GlobalName'][df['GlobalName']==''] = df['IsPerson'].apply(lambda x: x if x==True else '')


问:
Numpy/Scipy : solving several least squares with the same design matrix
I face a least square problem that i solve via scipy.linalg.lstsq(M,b), where :

M has shape (n,n)

b has shape (n,)

The issue is that i have to solve it a bunch of time for different b's. How can i do something more efficient ? I guess that lstsq does a lot of things independently of the value of b.

Ideas ?

答: You can factorize M into either QR or SVD products and find the lsq solution manually.


问:
Counting the number of repeated entries in a file
When I read a file, it gives me an output like this:

```<code>CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749
</code>```

I want to count the total number of CW and CS in the file. The output should look like this:

```<code>3 #For CW
3 #For CS
</code>```

I tried using the following code:

```<code>with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)
</code>```

But it gives me this output

```<code>2
2
2
2
2
2
</code>```

I even tried importing counter, but it gives me output like this:

```<code>C 1
W 1
C 1
W 1
C 1
S 1
</code>```

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

答:
Python 3.8.1
I hope this will help to. I try to make a functional example code with explications in same time to understand what is happen.

```<code># Global variables
file = "lista.txt"
countDictionary = {}

# Logic Read File
def ReadFile(fileName):
    # Try is optional, is used to track error and to prevent them
    # Also except will be optional because is used on try
    try:
        # Open file in read mode
        with open(fileName, mode="r") as f:
            # Define line
            line = f.readline()
            # For every line in this file
            while line:
                # Get out all white spaces (ex: \n, \r)
                # We will call it item (I asume that CW and CS are some data)
                item = line.strip()[:2]

                # Counting logic
                # Dictionary have at least 2 values I call them data and info
                # Data is like key (name/nickname/id) of the information
                # Info is the value (the information) for this data
                # First will check if data is new and will set info = integer 1
                if item not in countDictionary.keys():
                    countDictionary[item] = 1
                # If is not new will update the count number
                else:
                    info = countDictionary[item]    #will get the curent count number
                    countDictionary[item] = info+1  # will increse the count by one

                # Go to next line by defineing the line again
                # With out that this logic will be on infinite loop just for first line
                line = f.readline()

        # This is optional to. Is callet automatical by python to prevent some errors
        # But I like to be shore
        f.close()

    # In case the file do not exist
    except FileNotFoundError:
        print(f"ERROR >> File \"{fileName}\" do not exist!")

# Execut Function
ReadFile(file)

# Testing dictionary count
for k,j in countDictionary.items():
    print(k, ">>", j)
</code>```

Console out put:

```<code>========================= RESTART: D:\Python\StackOverflow\help.py =========================
CW >> 3
CS >> 3
>>>
</code>```

File lista.txt:

```<code>CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042 1
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076 1
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236 1
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213 1
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166 1
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749 1
</code>```

Body:
When I read a file, it gives me an output like this:

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749

I want to count the total number of CW and CS in the file. The output should look like this:

3 #For CW
3 #For CS

I tried using the following code:

with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)

But it gives me this output

2
2
2
2
2
2

I even tried importing counter, but it gives me output like this:

C 1
W 1
C 1
W 1
C 1
S 1

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
Python 3.8.1
I hope this will help to. I try to make a functional example code with explications in same time to understand what is happen.

# Global variables
file = "lista.txt"
countDictionary = {}

# Logic Read File
def ReadFile(fileName):
    # Try is optional, is used to track error and to prevent them
    # Also except will be optional because is used on try
    try:
        # Open file in read mode
        with open(fileName, mode="r") as f:
            # Define line
            line = f.readline()
            # For every line in this file
            while line:
                # Get out all white spaces (ex: \n, \r)
                # We will call it item (I asume that CW and CS are some data)
                item = line.strip()[:2]

                # Counting logic
                # Dictionary have at least 2 values I call them data and info
                # Data is like key (name/nickname/id) of the information
                # Info is the value (the information) for this data
                # First will check if data is new and will set info = integer 1
                if item not in countDictionary.keys():
                    countDictionary[item] = 1
                # If is not new will update the count number
                else:
                    info = countDictionary[item]    #will get the curent count number
                    countDictionary[item] = info+1  # will increse the count by one

                # Go to next line by defineing the line again
                # With out that this logic will be on infinite loop just for first line
                line = f.readline()

        # This is optional to. Is callet automatical by python to prevent some errors
        # But I like to be shore
        f.close()

    # In case the file do not exist
    except FileNotFoundError:
        print(f"ERROR >> File \"{fileName}\" do not exist!")

# Execut Function
ReadFile(file)

# Testing dictionary count
for k,j in countDictionary.items():
    print(k, ">>", j)

Console out put:

========================= RESTART: D:\Python\StackOverflow\help.py =========================
CW >> 3
CS >> 3
>>>

File lista.txt:

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042 1
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076 1
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236 1
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213 1
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166 1
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749 1


问:
Put items in list box- What does it mean to say "opt as opt for opt in months" in Angularjs?
https://angularjsaz.blogspot.com/2015/09/tutorial-28-angularjs-listbox-example.html

That shows:

<select style="width: 100%;" size="7" ng-model="currentItems" multiple
         ng-multiple="true"
         ng-options="opt as opt for opt in months">
</select>
```

<p>This works. I want to understand what does this statement do: <strong>opt as opt for opt in months</strong></p>

<p>I also know that <strong>ng-repeat</strong> takes <strong>car in cars</strong>. Why can't I use such a thing here?</p>

<p>In my case, cars was: </p>

```cars = [
    {make: 'Mazda', model: 'Miata', year: 2001},
    {make: 'Toyota', model: 'Prius', year: 2013},
]
```

<p>In their case, months is:</p>

```months = ['January','February','March','April']
```

答:
According to the documentation, ng-options for iterating an array data source (as in your case) follows the following pattern:

select as label for value in array

Where:

array: an expression which evaluates to an array / object to iterate over.

value: local variable which will refer to each item in the array or each property value of object during iteration.

label: The result of this expression will be the label for  element. The expression will most likely refer to the value variable (e.g. value.propertyName).

select: The result of this expression will be bound to the model of the parent  element. If not specified, select expression will default to value.

This is mainly used for displaying arrays of objects as options in a select list, where you want the object being iterated over, the label, and the value that's bound to the ng-model directive to be 3 different things. In your case, they're just strings, so it just basically is saying stringSelectValue as stringLabel for stringItem in stringArray.

You can simplify this example by saying ng-options="month for month in months". If a select value is not provided, it will use the label value as the select value, too.

Body:
https://angularjsaz.blogspot.com/2015/09/tutorial-28-angularjs-listbox-example.html

That shows:

<select style="width: 100%;" size="7" ng-model="currentItems" multiple
         ng-multiple="true"
         ng-options="opt as opt for opt in months">
</select>

This works. I want to understand what does this statement do: opt as opt for opt in months

I also know that ng-repeat takes car in cars. Why can't I use such a thing here?

In my case, cars was:

cars = [
    {make: 'Mazda', model: 'Miata', year: 2001},
    {make: 'Toyota', model: 'Prius', year: 2013},
]

In their case, months is:

months = ['January','February','March','April']


问:
Vue invalid host header
Don't know why 2 days ago my projects ( created via vue create ) stopped working - in Chrome i get

Invalid Host Header

and

WDS Disconnected

errors. In cmd everything compiles properly( npm run serve )
I don't know webpack, so i have no idea how to fix it.

What i've already done:

reinstalled node

deleted and reinstalled all npm packages

答:
Found this question searching for the same "Invalid Host Header" issue. Here's how I solved it.

I am running Vue dev server npm run serve in Docker on my remote server. Couldn't access it at http://example.com:8080 with the error message above.

Correct and secure way is to add the domain name to the vue.config.js file:

```<code>"devServer": {
  "public": "example.com"
}
</code>```

This is a fresh vue project initiated with Vue Cli command: vue create myproject with Vuetify added via vue add vuetify.  Full content of my vue.config.js after that is:

```<code>module.exports = {
  "transpileDependencies": [
    "vuetify"
  ],
  "devServer": {
    "public": "example.com"
  }
}
</code>```

Title: Vue invalid host header

Body:
Found this question searching for the same "Invalid Host Header" issue. Here's how I solved it.

I am running Vue dev server npm run serve in Docker on my remote server. Couldn't access it at http://example.com:8080 with the error message above.

Correct and secure way is to add the domain name to the vue.config.js file:

"devServer": {
  "public": "example.com"
}

This is a fresh vue project initiated with Vue Cli command: vue create myproject with Vuetify added via vue add vuetify.  Full content of my vue.config.js after that is:

module.exports = {
  "transpileDependencies": [
    "vuetify"
  ],
  "devServer": {
    "public": "example.com"
  }
}