问:
Getting elements in certain range of list
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

```<code>idx = (list > 3) & (list < 7)
list2 = list2[idx]
</code>```

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

答:
You can use zip:

```<code>l1 = [1,2,3,4,5,6,7,8,9]
l2 = ['a','b','c','d','e','f','g','h','j']
result = [a for a, b in zip(l2, l1) if 3 < b < 7]
</code>```

Output:

```<code>['d', 'e', 'f']
</code>```

To get the reduced list as well:

```<code>result, reduced = map(list, zip(*[[a, b] for a, b in zip(l2, l1) if 3 < b < 7]))
</code>```

Output:

```<code>['d', 'e', 'f'] #result
[4, 5, 6] #reduced
</code>```

Body:
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

idx = (list > 3) & (list < 7)
list2 = list2[idx]

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

Body:
You can use zip:

l1 = [1,2,3,4,5,6,7,8,9]
l2 = ['a','b','c','d','e','f','g','h','j']
result = [a for a, b in zip(l2, l1) if 3 < b < 7]

Output:

['d', 'e', 'f']

To get the reduced list as well:

result, reduced = map(list, zip(*[[a, b] for a, b in zip(l2, l1) if 3 < b < 7]))

Output:

['d', 'e', 'f'] #result
[4, 5, 6] #reduced


来源: stackexchange

问:
SSD Inception v2. Is the VGG16 feature extractor replaced by the Inception v2?
In the original SSD paper they used a VGG16 network to the the feature extraction. I am using the SSD Inception v2 model from the TensorFlow model zoo and I do not know what the difference in architecture is. This stack overflow post suggest that for other models like SSD MobileNet the VGG16 feature extractor is replaced by the MobileNet feature extractor.

I thought this would be the same case here with the SSD Inception but this paper has me confused. From here it seems that the Inception is added to the SSD part of the model and the VGG16 feature extractor remains in the beginning of the architecture.

What is the architecture of the SSD Inception v2 model?

答:
In tensorflow object detection api, the ssd_inception_v2 model uses inception_v2 as the feature extractor, namely, the vgg16 part in the first figure (figure (a)) is replaced with inception_v2.

In ssd models, the feature layer extracted by feature extractor (i.e. vgg16, inception_v2, mobilenet) will be further processed to produce extra feature layers of different resolutions. In the above figure (a), there are 6 output feature layers, the first two (19x19) are directly taken from the feature extractor. How are the other 4 layers (10x10, 5x5, 3x3, 1x1) generated?

They are generated by extra convolutional operations (these conv operations are sort of like using very shallow feature extractors, aren't they?). The implementation details are here provided with good documents. In the documentation it says

```<code>Note that the current implementation only supports generating new layers
using convolutions of stride 2 (resulting in a spatial resolution reduction
by a factor of 2)
</code>```

that is how the extra feature map decreases by a factor of 2, and if you read the function multi_resolution_feature_maps, you will find slim.conv2d operations being used, which indicates these extra layers are obtained with extra convolution layer (just one layer each!).

Now we can explain what is improved in the paper you linked. They proposed to replace the extra feature layers with inception block. There is no inception_v2 model but simply a inception block. The paper reported improving classification accuracy by using inception block.

Now it should be clear to the question, ssd model with vgg16, inceptioin_v2 or mobilenet are alright but the inception in the paper only refers to a inception block, not the inception network.

ContentLicense: CC BY-SA 4.0

Body:
In tensorflow object detection api, the ssd_inception_v2 model uses inception_v2 as the feature extractor, namely, the vgg16 part in the first figure (figure (a)) is replaced with inception_v2.

In ssd models, the feature layer extracted by feature extractor (i.e. vgg16, inception_v2, mobilenet) will be further processed to produce extra feature layers of different resolutions. In the above figure (a), there are 6 output feature layers, the first two (19x19) are directly taken from the feature extractor. How are the other 4 layers (10x10, 5x5, 3x3, 1x1) generated?

They are generated by extra convolutional operations (these conv operations are sort of like using very shallow feature extractors, aren't they?). The implementation details are here provided with good documents. In the documentation it says

Note that the current implementation only supports generating new layers
using convolutions of stride 2 (resulting in a spatial resolution reduction
by a factor of 2)

that is how the extra feature map decreases by a factor of 2, and if you read the function multi_resolution_feature_maps, you will find slim.conv2d operations being used, which indicates these extra layers are obtained with extra convolution layer (just one layer each!).

Now we can explain what is improved in the paper you linked. They proposed to replace the extra feature layers with inception block. There is no inception_v2 model but simply a inception block. The paper reported improving classification accuracy by using inception block.

Now it should be clear to the question, ssd model with vgg16, inceptioin_v2 or mobilenet are alright but the inception in the paper only refers to a inception block, not the inception network.


问:
Can't get button to change color based on information in the next page
I'm trying to get the background color of the button to change based on if a sessionStorage item is marked true. On the next page, the Kitchen page, when all the buttons are checked, the sessionStorage item becomes true so when you go back to the "home page",the kitchen is now marked green instead of red. This is the show completion. I think you can use jQuery but I don't really know how to use it.

Home

```<code>function loader(){
        var form = document.getElementById("myForm");

        //error somewhere in here
        for(var i=0;i<form.length;i++){
            if(sessionStorage.getItem(form.elements[i].value) == "true"){
                document.getElementById(form.elements[i].value).style.backgroundColor = "green";
                return true;
            }else{
                document.getElementById(form.elements[i].value).style.backgroundColor = "red";
                return false;
            }
        }
    }

    function initial(){
        if (localStorage.getItem("hasCodeRunBefore") === null) {
                var form = document.forms[0];
                var tot = document.forms[0].length;
                var i;
                for(var i = 0; i < tot ; ++i){
            document.getElementById(form.elements[i].value).style.backgroundColor = "red";
                }
            localStorage.setItem("hasCodeRunBefore", true);
        }
    }

    function start(){
        initial();
        loader();
    }
</code>```

Home HTML

```<code><body onload="start()">
<header align=center>Home Screen</header>
<p align=center id="result"></p>
<script>
    document.getElementById("result").innerHTML = sessionStorage.getItem("currentAddress");
</script>

<ul align=center>
    <form id="myForm">
        <li>
                <input type="button" name="area" id="livingroom" value="Living Room" ><br><br>
                <script type="text/javascript">
                        sessionStorage.setItem("livingroom","false");
                        document.getElementById("livingroom").onclick = function () {
                        location.href = "url";
                    };
                </script>
        </li>
        <li>
                <input type="button" name="area" id="kitchen" value="Kitchen"><br><br>
                <script type="text/javascript">
                        sessionStorage.setItem("kitchen","false");
                        document.getElementById("kitchen").onclick = function () {
                        location.href = "url";
                    };
                </script>
        </li>
        <li>
                <input type="button" name="area" id="bathroom" value="Bathroom" ><br><br>
                <script type="text/javascript">
                        sessionStorage.setItem("bathroom","false");
                        document.getElementById("bathroom").onclick = function () {
                        location.href = "url";
                    };
                </script>
        </li>
        <li>
                <input type="button" name="area" id="dining" value="Dining" ><br><br>
                <script type="text/javascript">
                        sessionStorage.setItem("dining","false");
                        document.getElementById("dining").onclick = function () {
                        location.href = "url";
                    };
                </script>
        </li>
        <li>
                <input type="button" name="area" id="bedroom1" value="Bedroom 1" ><br><br>
                <script type="text/javascript">
                        sessionStorage.setItem("bedroom1","false");
                        document.getElementById("bedroom1").onclick = function () {
                        location.href = "url";
                    };
                </script>
        </li>
    </form>
</ul>
</code>```

Kitchen

```<code>function checkTasks(form){
        var count = 0;
        for(var i=0;i<form.task.length;i++){
            if(form.task[i].checked){
                count++;
            }
        }

        if(count == form.task.length){
            sessionStorage.setItem("kitchen","true");
            window.open("url");
        }else{
            alert("You have not completed all the tasks! Please check all the boxes to indicate you have completed the tasks. If there is an issue, write it in the other box.");
        }
    }
</code>```

Kitchen HTML

```<code><body>
<header align=center>Kitchen To Do List</header>
<form name="todolist" >
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1" ><p>Microwave</p>
        </label>
    </div>
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1"><p>Coffee Maker</p>
        </label>
    </div>
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1"><p>Oven</p>
        </label>
    </div>
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1"><p>Dishwasher</p>
        </label>
    </div>
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1"><p>Stove Top</p>
        </label>
    </div>
    <div id="button">
        <label>
            <input type="checkbox" name="task" value="1"><p>Other</p>
        </label>
    </div>

    <textarea id="other"></textarea><br><br>
    <p align=center>
        <input type="submit" name="box" id="box" value="Complete" onclick="checkTasks(this.form)">
    </p>
</form>

<div class="close">
    <form align=center action="url" target="_self">
        <input type="submit" name="back" value="Back">
    </form>
</div>
</code>```

答: Every time you load the home page you are setting the value to false with those inline scripts. Remove the sessionStorage.setItem("livingroom","false"); calls in home.html and it looks like everything will work.

Body:
I'm trying to get the background color of the button to change based on if a sessionStorage item is marked true. On the next page, the Kitchen page, when all the buttons are checked, the sessionStorage item becomes true so when you go back to the "home page",the kitchen is now marked green instead of red. This is the show completion. I think you can use jQuery but I don't really know how to use it.

Home

function loader(){
        var form = document.getElementById("myForm");

        //error somewhere in here
        for(var i=0;i<form.length;i++){
            if(sessionStorage.getItem(form.elements[i].value) == "true"){
                document.getElementById(form.elements[i].value).style.backgroundColor = "green";
                return true;
            }else{
                document.getElementById(form.elements[i].value).style.backgroundColor = "red";
                return false;
            }
        }
    }

    function initial(){
        if (localStorage.getItem("hasCodeRunBefore") === null) {
                var form = document.forms[0];
                var tot = document.forms[0].length;
                var i;
                for(var i = 0; i < tot ; ++i){
            document.getElementById(form.elements[i].value).style.backgroundColor = "red";
                }
            localStorage.setItem("hasCodeRunBefore", true);
        }
    }

    function start(){
        initial();
        loader();
    }

Home HTML

Home Screen

    <form id="myForm">

                <input type="button" name="area" id="livingroom" value="Living Room" >

                <input type="button" name="area" id="kitchen" value="Kitchen">

                <input type="button" name="area" id="bathroom" value="Bathroom" >

                <input type="button" name="area" id="dining" value="Dining" >

                <input type="button" name="area" id="bedroom1" value="Bedroom 1" >

    </form>

Kitchen

function checkTasks(form){
        var count = 0;
        for(var i=0;i<form.task.length;i++){
            if(form.task[i].checked){
                count++;
            }
        }

        if(count == form.task.length){
            sessionStorage.setItem("kitchen","true");
            window.open("url");
        }else{
            alert("You have not completed all the tasks! Please check all the boxes to indicate you have completed the tasks. If there is an issue, write it in the other box.");
        }
    }

Kitchen HTML

Kitchen To Do List
<form name="todolist" >

            <input type="checkbox" name="task" value="1" >
Microwave

            <input type="checkbox" name="task" value="1">
Coffee Maker

            <input type="checkbox" name="task" value="1">
Oven

            <input type="checkbox" name="task" value="1">
Dishwasher

            <input type="checkbox" name="task" value="1">
Stove Top

            <input type="checkbox" name="task" value="1">
Other

    <textarea id="other"></textarea>

        <input type="submit" name="box" id="box" value="Complete" onclick="checkTasks(this.form)">

</form>

    <form align=center action="url" target="_self">
        <input type="submit" name="back" value="Back">
    </form>


问:
How to search an item in specific folder in one drive?
I am using Microsoft Graph to manipulate files in OneDrive. I need to search for a file in a specific folder, and if the file exists, delete that file.

I am using the following code to search file, it gives the search results for the whole drive.

```<code>var checkIfExists = this.graphClient
 .Me
 .Drive
 .Search(item["FileName"].ToString())
 .Request()
 .GetAsync()
 .Result;
</code>```

I need to search file in specific folder only for example in duplicate folder only.

答:
You can scope the search to any path you like. For example, using the default Graph Explorer dataset, we can search for finance across the entire Drive using this query:

```<code>https://graph.microsoft.com/v1.0/me/drive/root/search(q='finance')?select=name,id,webUrl
</code>```

If we would prefer to only search under a single subfolder (for example /CR-227 Project/), then we can use that Path as the starting point:

```<code>https://graph.microsoft.com/v1.0/me/drive/root:/CR-227 Project:/search(q='finance')?select=name,id,webUrl
</code>```

Additionally, if we know the DriveItem.Id for /CR-227 Project/ (01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU), then we could use that Id instead of the Path:

```<code>https://graph.microsoft.com/v1.0/me/drive/items/01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU/search(q='finance')?select=name,id,webUrl
</code>```

Body:
I am using Microsoft Graph to manipulate files in OneDrive. I need to search for a file in a specific folder, and if the file exists, delete that file.

I am using the following code to search file, it gives the search results for the whole drive.

var checkIfExists = this.graphClient
 .Me
 .Drive
 .Search(item["FileName"].ToString())
 .Request()
 .GetAsync()
 .Result;

I need to search file in specific folder only for example in duplicate folder only.

Body:
You can scope the search to any path you like. For example, using the default Graph Explorer dataset, we can search for finance across the entire Drive using this query:

https://graph.microsoft.com/v1.0/me/drive/root/search(q='finance')?select=name,id,webUrl

If we would prefer to only search under a single subfolder (for example /CR-227 Project/), then we can use that Path as the starting point:

https://graph.microsoft.com/v1.0/me/drive/root:/CR-227 Project:/search(q='finance')?select=name,id,webUrl

Additionally, if we know the DriveItem.Id for /CR-227 Project/ (01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU), then we could use that Id instead of the Path:

https://graph.microsoft.com/v1.0/me/drive/items/01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU/search(q='finance')?select=name,id,webUrl


问:
PDFsharp in C# document has both color modes CMYK and RGB
In a C# project with PDFsharp (WPF build) I save a PDF document setting

```<code>PdfDocument document = new PdfDocument();
document.Options.ColorMode = PdfColorMode.Cmyk;
</code>```

In the document I draw an image stored in another PDF source and a PNG/TIFF image (depends).

When I open the saved document in Adobe Bridge it tells me that both color modes CMYK and RGB are set in the document. How can I make PDFsharp save my document in CMYK only?

答: Make sure that all PDF sources used to create the new PDF are set to CMYK. The setting you use applies to new PDF content, but not to pages imported from external source PDFs.</p>

Body:
In a C# project with PDFsharp (WPF build) I save a PDF document setting

PdfDocument document = new PdfDocument();
document.Options.ColorMode = PdfColorMode.Cmyk;

In the document I draw an image stored in another PDF source and a PNG/TIFF image (depends).

When I open the saved document in Adobe Bridge it tells me that both color modes CMYK and RGB are set in the document. How can I make PDFsharp save my document in CMYK only?


问:
Inspect Realm proxy objects
In javascript I am using this function

```<code>export async function createNewRealm(name) {
  if (process.env.REALM_DISABLED === 'true') return Promise.resolve();
  if (!connectionAdminUser) await establishRealmConnection();
  console.log(`Creating ${name} at realms://${server}/${name}`);
  return Realm.open({
    sync: {
      user: connectionAdminUser,
      url:  `realms://${server}/${name}`
    }
  });
}
</code>```

Upon calling the function like this

```<code>  let test = await realm.createNewRealm('test');
  console.log(test);
  console.log(test.empty);
</code>```

I get following output

```<code>Creating test at realms://:SNIPPED/company-test
Connection[1]: Session[1]: client_reset_config = false, Realm exists = true, async open = false, client reset = false
Connection[1]: Connected to endpoint ':SNIPPED' (from ':SNIPPED')
Connection[1]: Disconnected

Realm {}  <-- THIS being first console.log
true      <-- THIS being second console.log

Connection[2]: Session[2]: client_reset_config = false, Realm exists = true, async open = false, client reset = false
Connection[2]: Connected to endpoint ':SNIPPED' (from ':SNIPPED')
</code>```

Now I get that this is because test in let test = await realm.createNewRealm('test'); is not proper javascript object, but proxy object.

What I would like to know - How can I inspect in code the content or at least see the keys via console.log?

The documentation here can be used, but I did notice that it is not always updated and I would like to avoid context switching by having to look every time if it is user.id or user.identity, etc...

So is there JS way to get those to output via console.log? I don't mind if it ends up being string, or array, just to be able to see the content of various realm objects on demand.

Also bonus question, in the log from realm itself I can see Realm exists = true, but there is nothing in documentation saying if I can see that via object being returned. So far I am checking if it is new by calling test.empty, is there an easier way? (related since this is the reason why I am asking main question)

答:
I dont have right env, but try this code

```<code> let test = await realm.createNewRealm('test');
 console.log(test.__proto__);
</code>```

I think you can print all properties like this

```<code>for(let n in test)  console.log(n,' = ',test[n]);
</code>```

Title: Inspect Realm proxy objects

Body:
In javascript I am using this function

export async function createNewRealm(name) {
  if (process.env.REALM_DISABLED === 'true') return Promise.resolve();
  if (!connectionAdminUser) await establishRealmConnection();
  console.log(`Creating ${name} at realms://${server}/${name}`);
  return Realm.open({
    sync: {
      user: connectionAdminUser,
      url:  `realms://${server}/${name}`
    }
  });
}

Upon calling the function like this

  let test = await realm.createNewRealm('test');
  console.log(test);
  console.log(test.empty);

I get following output

Creating test at realms://:SNIPPED/company-test
Connection[1]: Session[1]: client_reset_config = false, Realm exists = true, async open = false, client reset = false
Connection[1]: Connected to endpoint ':SNIPPED' (from ':SNIPPED')
Connection[1]: Disconnected

Realm {}  <-- THIS being first console.log
true      <-- THIS being second console.log

Connection[2]: Session[2]: client_reset_config = false, Realm exists = true, async open = false, client reset = false
Connection[2]: Connected to endpoint ':SNIPPED' (from ':SNIPPED')

Now I get that this is because test in let test = await realm.createNewRealm('test'); is not proper javascript object, but proxy object.

What I would like to know - How can I inspect in code the content or at least see the keys via console.log?

The documentation here can be used, but I did notice that it is not always updated and I would like to avoid context switching by having to look every time if it is user.id or user.identity, etc...

So is there JS way to get those to output via console.log? I don't mind if it ends up being string, or array, just to be able to see the content of various realm objects on demand.

Also bonus question, in the log from realm itself I can see Realm exists = true, but there is nothing in documentation saying if I can see that via object being returned. So far I am checking if it is new by calling test.empty, is there an easier way? (related since this is the reason why I am asking main question)

Body:
I dont have right env, but try this code

 let test = await realm.createNewRealm('test');
 console.log(test.__proto__);

I think you can print all properties like this

for(let n in test)  console.log(n,' = ',test[n]);


问:
Spring-Boot-Maven-Plugin - Command to Copy Resources into WAR Main Directory
QUESTION

In a Spring Boot Java application built with Maven using the spring-boot-maven-plugin with WAR packaging through Eclipse IDE with M2 with the goal as clean package, I would like to know if there is a command which would allow me to copy the resource folders (css, images, etc) which currently end up in mywar.war/WEB-INF/classes/static/ into the root directory mywar.war, so that I have mywar.war/images/, etc?

I see that with other plugins, there is something like a targetPath, but I can't find anything like that in the documentation for spring-boot-maven-plugin.

EXAMPLE POM

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.myapp</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0.0</version>
    <name>${project.artifactId}</name>
    <description>My Application</description>

    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
        <tomcat.version>7.0.78</tomcat.version>
        <servlet-api.version>3.0.1</servlet-api.version>
        <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
           <scope>provided</scope>
        </dependency>

         <dependency>
            <groupId>test</groupId>
            <artifactId>x</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/MyJar.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

</code>```

答:
Everything will work as expected. Spring Boot will server your static content.

The urls will be

```<code><host>:<port>/<warname>/css
<host>:<port>/<warname>/images
</code>```

etc.

Body:
QUESTION

In a Spring Boot Java application built with Maven using the spring-boot-maven-plugin with WAR packaging through Eclipse IDE with M2 with the goal as clean package, I would like to know if there is a command which would allow me to copy the resource folders (css, images, etc) which currently end up in mywar.war/WEB-INF/classes/static/ into the root directory mywar.war, so that I have mywar.war/images/, etc?

I see that with other plugins, there is something like a targetPath, but I can't find anything like that in the documentation for spring-boot-maven-plugin.

EXAMPLE POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.myapp</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0.0</version>
    <name>${project.artifactId}</name>
    <description>My Application</description>

    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.test.skip>true</maven.test.skip>
        <tomcat.version>7.0.78</tomcat.version>
        <servlet-api.version>3.0.1</servlet-api.version>
        <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>

            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
           <scope>provided</scope>
        </dependency>

         <dependency>
            <groupId>test</groupId>
            <artifactId>x</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/MyJar.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
Everything will work as expected. Spring Boot will server your static content.

The urls will be

<host>:<port>/<warname>/css
<host>:<port>/<warname>/images

etc.


问:
Reg expression in .net to start with 2 specific characters, end with a digit, and at a certain length
Ok Reg ex experts, I am not very good with regex and am hoping for some help. I have a regular expression that I cannot for the life of me figure out. I am looking to create a regular expression that will match the following:

Starts with a "PA" (ingore case)

Ends with a digit

Is 8 characters long (ignoring any trailing white space)

or

Starts with a "WN" (ingore case)

Ends with a digit

Is 10 characters long (ignoring any trailing white space)

答:
```<code>//Trim the whitespace off the ends of your string per requirement
yourString = yourString.Trim();
//Declare regex, the pattern tells it to look for any 7 letter word
//which starts with PA and ends with a digit and is 7 characters long
//OR a word which starts with WN and ends with a digit and is 10 characters long.
Regex regex = new Regex(^PA.+\d${7})|(^WN.+\d${10});
//Set the regex option to ignore case
RegexOptions options = RegexOptions.IgnoreCase;
//Get the match collection by passing your string, the regex pattern and
//the regex options
MatchCollection matches = regex.Matches(yourString, regex, options);

//Do something with captured text
</code>```


问:
How to fix 'IncompatibleClassChangeError: Implementing Class' when importing Cplex library in Maven project?
I'm trying to import Cplex on a Maven project (using Ubuntu 16.04).

So I added cplex.jar to maven repository with this command :
mvn install:install-file -DgroupId=cplex -DartifactId=cplex -Dversion=12.8 -Dpackaging=jar -Dfile=/cplex/install/dir/CPLEX_Studio128/cplex/lib/cplex.jar

I added the dependency to my pom.xml :

<dependency>
    <groupId>cplex</groupId>
    <artifactId>cplex</artifactId>
    <version>12.8</version>
</dependency>
```

<p>I added the link of the Cplex Native Library (.so files) to the LD_LIBRARY_PATH :
<code>export LD_LIBRARY_PATH="/cplex/install/dir/CPLEX_Studio128/cplex/bin/x86-64_linux"</code></p>

<p>But when I'm running my maven project with :
<code>mvn exec:java -Dexec.mainClass="main.main"</code></p>

<p>I got the following error : <strong>java.lang.IncompatibleClassChangeError: Implementing Class</strong></p>

<p>I have already checked this question but I don't understand, in this case, what kind of incompatibles binary changes can be made.</p>

<p>Is it possible that there's some "incompatibles binary changes" ?
And if it's not, is there any other explanation than an "incompatibles binary changes" to this error ?</p>

<h1><strong>Edit</strong></h1>

<p>I also use OPL library (same installation than Cplex library) and I have only the 12.8 version of Cplex and Oplall on my system.</p>

<p>I tried to clean and build again but got the same error.</p>

<p>This is the code I try to run (in ModelFileEvaluator.java) :</p>

<pre class="lang-java prettyprint-override"><code>IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource(fileName);
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();
</code>```

And this is the full backtrace :

```<code>java.lang.IncompatibleClassChangeError: Implementing class
    at java.lang.ClassLoader.defineClass1(java.base@9-internal/Native Method)
    at java.lang.ClassLoader.defineClass(java.base@9-internal/ClassLoader.java:939)
    at java.security.SecureClassLoader.defineClass(java.base@9-internal/SecureClassLoader.java:152)
    at java.net.URLClassLoader.defineClass(java.base@9-internal/URLClassLoader.java:463)
    at java.net.URLClassLoader.access$100(java.base@9-internal/URLClassLoader.java:76)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:371)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:365)
    at java.security.AccessController.doPrivileged(java.base@9-internal/Native Method)
    at java.net.URLClassLoader.findClass(java.base@9-internal/URLClassLoader.java:364)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:486)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:419)
    at java.lang.ClassLoader.defineClass1(java.base@9-internal/Native Method)
    at java.lang.ClassLoader.defineClass(java.base@9-internal/ClassLoader.java:939)
    at java.security.SecureClassLoader.defineClass(java.base@9-internal/SecureClassLoader.java:152)
    at java.net.URLClassLoader.defineClass(java.base@9-internal/URLClassLoader.java:463)
    at java.net.URLClassLoader.access$100(java.base@9-internal/URLClassLoader.java:76)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:371)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:365)
    at java.security.AccessController.doPrivileged(java.base@9-internal/Native Method)
    at java.net.URLClassLoader.findClass(java.base@9-internal/URLClassLoader.java:364)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:486)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:419)
    at ilog.opl.IloOplFactory.createCplex(IloOplFactory.java:227)
    at main.ModelFileEvaluator.testFile(ModelFileEvaluator.java:86)
    at main.ModelFileEvaluator.main(ModelFileEvaluator.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(java.base@9-internal/Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(java.base@9-internal/NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(java.base@9-internal/DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(java.base@9-internal/Method.java:531)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
    at java.lang.Thread.run(java.base@9-internal/Thread.java:804)
</code>```

答: Using OPL requires using oplall.jar. That jar is not compatible with cplex.jar. You can use only one of the two at the same time. Removing cplex.jar from the class path should fix the issue.

Body:
I'm trying to import Cplex on a Maven project (using Ubuntu 16.04).

So I added cplex.jar to maven repository with this command :
mvn install:install-file -DgroupId=cplex -DartifactId=cplex -Dversion=12.8 -Dpackaging=jar -Dfile=/cplex/install/dir/CPLEX_Studio128/cplex/lib/cplex.jar

I added the dependency to my pom.xml :

<dependency>
    <groupId>cplex</groupId>
    <artifactId>cplex</artifactId>
    <version>12.8</version>
</dependency>

I added the link of the Cplex Native Library (.so files) to the LD_LIBRARY_PATH :
export LD_LIBRARY_PATH="/cplex/install/dir/CPLEX_Studio128/cplex/bin/x86-64_linux"

But when I'm running my maven project with :
mvn exec:java -Dexec.mainClass="main.main"

I got the following error : java.lang.IncompatibleClassChangeError: Implementing Class

I have already checked this question but I don't understand, in this case, what kind of incompatibles binary changes can be made.

Is it possible that there's some "incompatibles binary changes" ?
And if it's not, is there any other explanation than an "incompatibles binary changes" to this error ?

Edit

I also use OPL library (same installation than Cplex library) and I have only the 12.8 version of Cplex and Oplall on my system.

I tried to clean and build again but got the same error.

This is the code I try to run (in ModelFileEvaluator.java) :

IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource(fileName);
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();

And this is the full backtrace :

java.lang.IncompatibleClassChangeError: Implementing class
    at java.lang.ClassLoader.defineClass1(java.base@9-internal/Native Method)
    at java.lang.ClassLoader.defineClass(java.base@9-internal/ClassLoader.java:939)
    at java.security.SecureClassLoader.defineClass(java.base@9-internal/SecureClassLoader.java:152)
    at java.net.URLClassLoader.defineClass(java.base@9-internal/URLClassLoader.java:463)
    at java.net.URLClassLoader.access$100(java.base@9-internal/URLClassLoader.java:76)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:371)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:365)
    at java.security.AccessController.doPrivileged(java.base@9-internal/Native Method)
    at java.net.URLClassLoader.findClass(java.base@9-internal/URLClassLoader.java:364)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:486)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:419)
    at java.lang.ClassLoader.defineClass1(java.base@9-internal/Native Method)
    at java.lang.ClassLoader.defineClass(java.base@9-internal/ClassLoader.java:939)
    at java.security.SecureClassLoader.defineClass(java.base@9-internal/SecureClassLoader.java:152)
    at java.net.URLClassLoader.defineClass(java.base@9-internal/URLClassLoader.java:463)
    at java.net.URLClassLoader.access$100(java.base@9-internal/URLClassLoader.java:76)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:371)
    at java.net.URLClassLoader$1.run(java.base@9-internal/URLClassLoader.java:365)
    at java.security.AccessController.doPrivileged(java.base@9-internal/Native Method)
    at java.net.URLClassLoader.findClass(java.base@9-internal/URLClassLoader.java:364)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:486)
    at java.lang.ClassLoader.loadClass(java.base@9-internal/ClassLoader.java:419)
    at ilog.opl.IloOplFactory.createCplex(IloOplFactory.java:227)
    at main.ModelFileEvaluator.testFile(ModelFileEvaluator.java:86)
    at main.ModelFileEvaluator.main(ModelFileEvaluator.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(java.base@9-internal/Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(java.base@9-internal/NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(java.base@9-internal/DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(java.base@9-internal/Method.java:531)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
    at java.lang.Thread.run(java.base@9-internal/Thread.java:804)


问:
Problems when submitting a form in TYPO3 v9.5
In TYPO3 versions before v9, when using the native form, I always disabled the cache of that specific "contact" page (where the form was placed). If I didn't disable the cace, the form wouldn't redirect to my "confirmation" (v6/v7) or "redirect" page (v8), but instead it would simply reload the (filled-out) form (on the same page).

So, to bypass this and to make sure that the form actually got submitted and forwarded to the correct confirmation page, I always disabled the cache (Page Properties -> Page -> Behaviour -> Disable cache).

In TYPO3 v9 however, this option has been removed, and adding config.no_cache = 1 into that specific page (in a TS template), doesn't seem to do the (same) trick.

I would expect that the form, after clicking the submit button, would forward to the confirmation (redirect) page which I configured insde the form itself. That confirmation page isn't usergroup-protected or anything, it's simply a sub-page of the "contact" page (containing the form) itself.

答:
The actual issue in this case is that you are most likely using some kind of autofill for your fields, e.g. from Chrome or using a form filler extension.

This will also fill the honeypot field of your form which then prevents submitting the form.

Right now there is nothing you can do about this except voting for the bug in the Chromium issue tracker.


问:
Where can I find a good NHibernate and ASP.NET MVC Reference Application
Where can I find a good NHibernate and ASP.NET MVC Reference Application? I downloaded S#arp and this seemed to be a lot more than I needed (IOC and CodeGen via T4). I might work my way up to this later, but I need something smaller at first.

Any simple examples? I just want to pick up how NHibernate Session handling works in ASP.NET MVC.  And maybe how some simple query scenarios work. Still trying to grasp how a SELECT DISTINCT would be done in NHibernate and through to the View via the ViewData.

答: Code Camp Server</p>

OwnerDisplayName: Bruno Tyndall

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg

Body: Code Camp Server

OwnerDisplayName: Tim Scott


问:
Sending signal from kernel to user space
How to get signal from kernel space to user space?</p>

答:
Use the kernel API function kill_proc_info(int sig, struct siginfo *info, pid_t pid)

NOTE This is actually a bad answer. The functions does send a signal to user space but the right way to do this, as the asker intended is to use the fasync character device method as documented here: http://www.xml.com/ldd/chapter/book/ch05.html#t4

ContentLicense: CC BY-SA 3.0


问:
Intercepting Boost.Asio HTTP/S request using Fiddler
I'm using Boost:Asio to perform HTTP GET
(Using the example from http://www.boost.org/doc/libs/1_50_0/doc/html/boost_asio/example/http/client/async_client.cpp)

I'm not seeing my requests on fiddler (Only on WireShark)
How can i change it?

答:
I have a similar problem about how to solve it, so I just share my experience. So far as I know, Asio works at the socket level and is not using wininet as @marcinj have pointed out and Fiddler works on wininet, but we are still able to do it by using Fiddler as a proxy.

First, explain why it doesn't work on Boost:Asio like interprecting traffics on IE?

See also how to catch the socket programming's send and receive request in fiddler

Fiddler inserts itself into the stack as an HTTP proxy server. It relies on the web browsers to recognize that there is a proxy configured on the PC and to send through that. Your code does not detect for a proxy to send through - so Fiddler won't be able to monitor your traffic.

You have several options.

Since you are own Windows, just switch from using direct sockets to using the WinInet HTTP API. It will do automatic proxy detection for you without you having to think about it. It will do the proxy authentication as well if its required.

OR. Use Wireshark or NetMon to analyze your traffic instead of Fiddler.

I'd recommend #1 since that means your code will work in the presence of a real proxy server (commonly found on enterprise networks) and Fiddler will just work with it.

I suppose there is a third option where you auto-detect the browser proxy settings, then create a socket to the proxy, speak the HTTP PROXY protocol, etc... but that's not the best practice.

Second, how to do?

There's a good example about passing a proxy address to create a client based on Boost:asio like Socket(java.net.Proxy) or Configure a PHP/cURL Application to Use Fiddler, or the client application is not writen by yourself, but if you can control/configure your client connection endpoint address and port, we can make Fiddler intercept HTTP(s) traffics by in any way (re-route HTTP requests as HTTPS requests or re-route HTTPS requests as HTTPS requests for a HTTPS server) as a reverse proxy (requires one argument).

By default, Fiddler is listening on 8888. If go to http://localhost:8888/ in a browser, it presents a default page like:

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Fiddler Echo Service</title>
Fiddler Echo Service

```GET / HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
DNT: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: _ga=GA9.1.123456789.1234567890

```This page returned a HTTP/200 response
Originating Process Information: chrome:3628

To configure Fiddler as a reverse proxy instead of seeing this page, see Reverse Proxy Setup
You can download the FiddlerRoot certificate

```

<ol>
<li>If the target server is a HTTP server or the target server is a HTTPS server and the client supports for HTTP depending on your configured address, the  just add the following code inside <code>OnBeforeRequest</code> (in Rules -> Customize Rules... Ctrl+R, FiddlerScript), see also Modifying a Request or Response.</li>
</ol>

```//MessageBox.Show(oSession.fullUrl);
// string Session.fullUrl: Retrieves the complete URI, including protocol/scheme, in the form http://www.host.com/filepath?query.
//FiddlerObject.log("Session.fullUrl=" + oSession.fullUrl);
// string Session.url: Gets or sets the URL (without protocol) being requested from the server, in the form www.host.com/filepath?query."
//FiddlerObject.log("Session.url=" + oSession.url);
// string Session.PathAndQuery: Returns the path and query part of the URL. (For a CONNECT request, returns the host:port to be connected.)
//FiddlerObject.log("Session.PathAndQuery=" + oSession.PathAndQuery); // e.g. /filepath?query but host:port for a CONNECT request
// string Session.host: Gets/Sets the host to which this request is targeted. MAY include IPv6 literal brackets. MAY include a trailing port#.
// int Session.port: Returns the server port to which this request is targeted.
//FiddlerObject.log("Session.host=" + oSession.host + ", port=" + oSession.port);
// string Session.hostname: DNS Name of the host server (no port) targeted by this request. Will include IPv6-literal brackets for IPv6-literal addresses
//Gets/Sets the hostname to which this request is targeted; does NOT include any port# but will include IPv6-literal brackets for IPv6 literals.
FiddlerObject.log("Session: hostname=" + oSession.hostname +  ", oRequest.pipeClient.LocalPort=" + oSession.oRequest.pipeClient.LocalPort);

//bool Fiddler.Utilities.isLocalhostname(sHostnameWithoutPort))
// Determines if the specified Hostname is a either 'localhost' or an IPv4 or IPv6 loopback literal
// Returns true if True if the sHostname is 127.0.0.1, 'localhost', or ::1. Note that list is not complete.

// Run Fiddler on your machine, and then add this block of code and test it works on the your same machine:
// Use the `curl http://localhost:8888/get`command  or Using a browser, go to http://localhost:8888/get.
if (Utilities.isLocalhostname(oSession.hostname)) {
    // By default, Fiddler is listening on 8888. Inspect what ports are being listened using proexp or netstat
    // :: Lists the listening ports of a process with the specified image name including extension name(case-insensitive), fiddler.exe
    // for /f "skip=1 tokens=2,9 delims=," %a in ('tasklist /fo csv /fi "IMAGENAME eq fiddler.exe" 2^>NUL') do (netstat -ano | findstr "PID LISTENING" | findstr "PID %a")
    //oSession.host = "httpbin.org:443"; // oSession.oRequest.headers.UriScheme = "https";
    oSession.fullUrl = "https://httpbin.org" + oSession.PathAndQuery;
}
```

<p>You can compare the expected response using the actual url with the above response by the url localhost connecting the Fiddler proxy who forwards the request to the actual url, i.e. httpbin.org.</p>

<ol start="2">
<li>If the target server is a HTTPS server, but the client doesn't support for HTTP, rhe changes above are not enough.</li>
</ol>

<p>Using the command <code>curl -v https://localhost:8888/get</code> (or a browser), we found an error</p>

```* schannel: sent initial handshake data: sent 182 bytes
* schannel: SSL/TLS connection with localhost port 8888 (step 2/3)
* schannel: failed to receive handshake, need more data
```

<p>Inspect the traffic in Wireshark, I found Fiddler didn't perform any HTTPS handshake after the client sent the first TLS request (Client Hello).</p>

<p>Fiddler outputs a log:</p>

<blockquote>
  <p>18:28:44:5960 HTTPSLint> Warning: ClientHello record was 508 bytes long. Some servers have problems with ClientHello's greater than 255 bytes. https://github.com/ssllabs/research/wiki/Long-Handshake-Intolerance</p>
</blockquote>

<p>To solve it, we need to do in addition to the rule script:</p>

<ol>
<li><p>Configure Fiddler as a reverse proxy server, which forwards all request whose destination port equal the second parameter !listen command to the target server. Click Tools > Fiddler Options > Connections. Ensure "Allow remote clients to connect" is checked. It enables fiddler to respond to the SSL/TLS handshake request of HTTPS. This step is a persistent configuration.</p></li>
<li><p>Create a new DWORD named ReverseProxyForPort inside HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to the local port where Fiddler will re-route inbound traffic (usually port 80 for a standard HTTP server).</p></li>
</ol>

```:: reg query HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort
reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort /t REG_DWORD /d 58080 /f && REM /f Force overwriting the existing registry entry without prompt to 58080
:: Deletes the registry key
:: REG DELETE HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort  /f && REM /f Forces the deletion without prompt.
```

<ol start="3">
<li>Restart Fiddler and start a proxy server listening on a specified port by the <code>!listen *PORT [CERTHOSTNAME]*</code> script-command inside Fiddler's <code>QuickExec</code> box at the lower-left corner by typing<code>!listen 443 ServerHostName</code>, where ServerHostName is whatever the server's hostname is; for instance, for https://Fuzzle/ you would use fuzzle for the server name. </li>
</ol>

<p>It doesn't seem necessary to create a new <code>DWORD</code> named <code>ReverseProxyForPort</code> inside <code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2</code> in the windows registry (REGEDIT.exe).</p>

<p>QuickExec - Default commands</p>

<blockquote>
  <p><code>!listen *PORT [CERTHOSTNAME]*</code></p>

  <p>Set up an additional listener on another port, optionally secured by a HTTPS certificate</p>

```!listen 8889
!listen 4443 localhost
!listen 444 secure.example.com
```
</blockquote>

<p><strong>See also</strong></p>

<ul>
<li>Use Fiddler as a Reverse Proxy </li>
<li>WikiPedia Reverse proxy</li>
<li>Difference between proxy server and reverse proxy server?

<blockquote>
  <p>Looking from the perspective of the user, when sending a request to a <em>proxy</em> or <em>reverse proxy</em> server:</p>

  <ul>
  <li><em>proxy</em> - requires <strong>two arguments</strong>:<br>
  1) what to get and 2) which proxy server to use an intermediate  </li>
  <li><em>reverse proxy</em> - requires <strong>one argument</strong>:<br>
  1.) what to get
  reverse proxy fetches contents from another server unbeknowst to user and <strong>returns result as if it originated from reverse proxy server</strong>
  pspi answered Apr 13 at 5:47</li>
  </ul>
</blockquote></li>
<li>Running Fiddler as a Reverse Proxy for HTTPS server</li>
<li>fiddler redirect https to localhost

<blockquote>
  <p>the following code used in <code>static function OnBeforeRequest(oSession:Fiddler.Session) {}</code>:  </p>

  ```if (oSession.HostnameIs("YYYY.azurewebsites.net")) oSession.host = "127.0.0.1:19703";
```
</blockquote></li>
<li>Running Fiddler as HTTP to HTTPS reverse proxy

<blockquote>
  <p>The simplest way of Fiddler converting inbound requests from HTTP to HTTPS would be to add something inside OnBeforeRequest like:  </p>

  ```if (oSession.HostnameIs("myhost") && (oSession.oRequest.pipeClient.LocalPort == 80)) {
  oSession.fullUrl = "https://" + oSession.url;
}
```

This presumes, of course, that Fiddler was configured to run on port 80, the default port for HTTP. You can run it on whatever port you like (e.g. if port 80 were already in use) but you'd need to change the port in the URL that the client requests, and if you could do that, you'd probably be able to change the client to use a HTTPS URL to begin with.

Setting WinINet Proxy Configurations in WinHTTP

MS - How to configure client proxy server settings by using a registry file

Configure Fiddler to Decrypt HTTPS Traffic

Body:
I have a similar problem about how to solve it, so I just share my experience. So far as I know, Asio works at the socket level and is not using wininet as @marcinj have pointed out and Fiddler works on wininet, but we are still able to do it by using Fiddler as a proxy.

First, explain why it doesn't work on Boost:Asio like interprecting traffics on IE?

See also how to catch the socket programming's send and receive request in fiddler

Fiddler inserts itself into the stack as an HTTP proxy server. It relies on the web browsers to recognize that there is a proxy configured on the PC and to send through that. Your code does not detect for a proxy to send through - so Fiddler won't be able to monitor your traffic.

You have several options.

Since you are own Windows, just switch from using direct sockets to using the WinInet HTTP API. It will do automatic proxy detection for you without you having to think about it. It will do the proxy authentication as well if its required.

OR. Use Wireshark or NetMon to analyze your traffic instead of Fiddler.

I'd recommend #1 since that means your code will work in the presence of a real proxy server (commonly found on enterprise networks) and Fiddler will just work with it.

I suppose there is a third option where you auto-detect the browser proxy settings, then create a socket to the proxy, speak the HTTP PROXY protocol, etc... but that's not the best practice.

Second, how to do?

There's a good example about passing a proxy address to create a client based on Boost:asio like Socket(java.net.Proxy) or Configure a PHP/cURL Application to Use Fiddler, or the client application is not writen by yourself, but if you can control/configure your client connection endpoint address and port, we can make Fiddler intercept HTTP(s) traffics by in any way (re-route HTTP requests as HTTPS requests or re-route HTTPS requests as HTTPS requests for a HTTPS server) as a reverse proxy (requires one argument).

By default, Fiddler is listening on 8888. If go to http://localhost:8888/ in a browser, it presents a default page like:

<!doctype html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Fiddler Echo Service</title></head><body style="font-family: arial,sans-serif;"><h1>Fiddler Echo Service</h1><br /><pre>GET / HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
DNT: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: _ga=GA9.1.123456789.1234567890

</pre>This page returned a <b>HTTP/200</b> response <br />Originating Process Information: <code>chrome:3628</code><br /><hr /><ul><li>To configure Fiddler as a reverse proxy instead of seeing this page, see <a href='http://fiddler2.com/r/?REVERSEPROXY'>Reverse Proxy Setup</a><li>You can download the <a href="FiddlerRoot.cer">FiddlerRoot certificate</a></ul></body></html>

If the target server is a HTTP server or the target server is a HTTPS server and the client supports for HTTP depending on your configured address, the  just add the following code inside OnBeforeRequest (in Rules -> Customize Rules... Ctrl+R, FiddlerScript), see also Modifying a Request or Response.

//MessageBox.Show(oSession.fullUrl);
// string Session.fullUrl: Retrieves the complete URI, including protocol/scheme, in the form http://www.host.com/filepath?query.
//FiddlerObject.log("Session.fullUrl=" + oSession.fullUrl);
// string Session.url: Gets or sets the URL (without protocol) being requested from the server, in the form www.host.com/filepath?query."
//FiddlerObject.log("Session.url=" + oSession.url);
// string Session.PathAndQuery: Returns the path and query part of the URL. (For a CONNECT request, returns the host:port to be connected.)
//FiddlerObject.log("Session.PathAndQuery=" + oSession.PathAndQuery); // e.g. /filepath?query but host:port for a CONNECT request
// string Session.host: Gets/Sets the host to which this request is targeted. MAY include IPv6 literal brackets. MAY include a trailing port#.
// int Session.port: Returns the server port to which this request is targeted.
//FiddlerObject.log("Session.host=" + oSession.host + ", port=" + oSession.port);
// string Session.hostname: DNS Name of the host server (no port) targeted by this request. Will include IPv6-literal brackets for IPv6-literal addresses
//Gets/Sets the hostname to which this request is targeted; does NOT include any port# but will include IPv6-literal brackets for IPv6 literals.
FiddlerObject.log("Session: hostname=" + oSession.hostname +  ", oRequest.pipeClient.LocalPort=" + oSession.oRequest.pipeClient.LocalPort);

//bool Fiddler.Utilities.isLocalhostname(sHostnameWithoutPort))
// Determines if the specified Hostname is a either 'localhost' or an IPv4 or IPv6 loopback literal
// Returns true if True if the sHostname is 127.0.0.1, 'localhost', or ::1. Note that list is not complete.

// Run Fiddler on your machine, and then add this block of code and test it works on the your same machine:
// Use the `curl http://localhost:8888/get`command  or Using a browser, go to http://localhost:8888/get.
if (Utilities.isLocalhostname(oSession.hostname)) {
    // By default, Fiddler is listening on 8888. Inspect what ports are being listened using proexp or netstat
    // :: Lists the listening ports of a process with the specified image name including extension name(case-insensitive), fiddler.exe
    // for /f "skip=1 tokens=2,9 delims=," %a in ('tasklist /fo csv /fi "IMAGENAME eq fiddler.exe" 2^>NUL') do (netstat -ano | findstr "PID LISTENING" | findstr "PID %a")
    //oSession.host = "httpbin.org:443"; // oSession.oRequest.headers.UriScheme = "https";
    oSession.fullUrl = "https://httpbin.org" + oSession.PathAndQuery;
}

You can compare the expected response using the actual url with the above response by the url localhost connecting the Fiddler proxy who forwards the request to the actual url, i.e. httpbin.org.

If the target server is a HTTPS server, but the client doesn't support for HTTP, rhe changes above are not enough.

Using the command curl -v https://localhost:8888/get (or a browser), we found an error

* schannel: sent initial handshake data: sent 182 bytes
* schannel: SSL/TLS connection with localhost port 8888 (step 2/3)
* schannel: failed to receive handshake, need more data

Inspect the traffic in Wireshark, I found Fiddler didn't perform any HTTPS handshake after the client sent the first TLS request (Client Hello).

Fiddler outputs a log:

18:28:44:5960 HTTPSLint> Warning: ClientHello record was 508 bytes long. Some servers have problems with ClientHello's greater than 255 bytes. https://github.com/ssllabs/research/wiki/Long-Handshake-Intolerance

To solve it, we need to do in addition to the rule script:

Configure Fiddler as a reverse proxy server, which forwards all request whose destination port equal the second parameter !listen command to the target server. Click Tools > Fiddler Options > Connections. Ensure "Allow remote clients to connect" is checked. It enables fiddler to respond to the SSL/TLS handshake request of HTTPS. This step is a persistent configuration.

Create a new DWORD named ReverseProxyForPort inside HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2. Set the DWORD to the local port where Fiddler will re-route inbound traffic (usually port 80 for a standard HTTP server).

:: reg query HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort
reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort /t REG_DWORD /d 58080 /f && REM /f Force overwriting the existing registry entry without prompt to 58080
:: Deletes the registry key
:: REG DELETE HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 /v ReverseProxyForPort  /f && REM /f Forces the deletion without prompt.

Restart Fiddler and start a proxy server listening on a specified port by the !listen *PORT [CERTHOSTNAME]* script-command inside Fiddler's QuickExec box at the lower-left corner by typing!listen 443 ServerHostName, where ServerHostName is whatever the server's hostname is; for instance, for https://Fuzzle/ you would use fuzzle for the server name.

It doesn't seem necessary to create a new DWORD named ReverseProxyForPort inside HKEY_CURRENT_USER\SOFTWARE\Microsoft\Fiddler2 in the windows registry (REGEDIT.exe).

QuickExec - Default commands

!listen *PORT [CERTHOSTNAME]*

Set up an additional listener on another port, optionally secured by a HTTPS certificate

!listen 8889
!listen 4443 localhost
!listen 444 secure.example.com

See also

Use Fiddler as a Reverse Proxy

WikiPedia Reverse proxy

Difference between proxy server and reverse proxy server?

Looking from the perspective of the user, when sending a request to a proxy or reverse proxy server:

proxy - requires two arguments:

  1) what to get and 2) which proxy server to use an intermediate

reverse proxy - requires one argument:

  1.) what to get
  reverse proxy fetches contents from another server unbeknowst to user and returns result as if it originated from reverse proxy server
  pspi answered Apr 13 at 5:47

Running Fiddler as a Reverse Proxy for HTTPS server

fiddler redirect https to localhost

the following code used in static function OnBeforeRequest(oSession:Fiddler.Session) {}:

if (oSession.HostnameIs("YYYY.azurewebsites.net")) oSession.host = "127.0.0.1:19703";

Running Fiddler as HTTP to HTTPS reverse proxy

The simplest way of Fiddler converting inbound requests from HTTP to HTTPS would be to add something inside OnBeforeRequest like:

if (oSession.HostnameIs("myhost") && (oSession.oRequest.pipeClient.LocalPort == 80)) {
  oSession.fullUrl = "https://" + oSession.url;
}

This presumes, of course, that Fiddler was configured to run on port 80, the default port for HTTP. You can run it on whatever port you like (e.g. if port 80 were already in use) but you'd need to change the port in the URL that the client requests, and if you could do that, you'd probably be able to change the client to use a HTTPS URL to begin with.

Setting WinINet Proxy Configurations in WinHTTP

MS - How to configure client proxy server settings by using a registry file

Configure Fiddler to Decrypt HTTPS Traffic


问:
maven shade not creating fat jar with manifest
I am using maven 3.6.1 and maven shade plugin 2.3.  I have copied the shade plugin part of the pom file below.  The manifest is getting created when the jar is created but it does not reference the main class.  I am creating the jar using the mvn package command.  Any thoughts on how to fix this?

```<code>        <plugin>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>true</createDependencyReducedPom>
                <transformers>
                    <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.abc.someclass</mainClass>
                    </transformer>
                </transformers>
                <!-- exclude signed Manifests -->
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

答:
I had to run the package command as follows (i.e. with shade as target):

```<code>mvn clean package shade:shade
</code>```

Removing the plugin from pluginManagement allows me to create the shaded jar using the following:

```<code>mvn clean package
</code>```

Body:
I am using maven 3.6.1 and maven shade plugin 2.3.  I have copied the shade plugin part of the pom file below.  The manifest is getting created when the jar is created but it does not reference the main class.  I am creating the jar using the mvn package command.  Any thoughts on how to fix this?

        <plugin>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>true</createDependencyReducedPom>
                <transformers>
                    <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer
                            implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.abc.someclass</mainClass>
                    </transformer>
                </transformers>

                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Body:
I had to run the package command as follows (i.e. with shade as target):

mvn clean package shade:shade

Removing the plugin from pluginManagement allows me to create the shaded jar using the following:

mvn clean package


问:
Error in Flutter .DexArchiveMergerException
this is an Issuse

What went wrong:

Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Error while
  merging dex archives

When i Add Finger Local Auth

```<code>  local_auth: ^0.4.0+1
</code>```

with api in gradle

答:
This Error is with AndroidX just be carful to Delete it
from gradle and Change local auth from

local_auth: ^0.4.0+1

To

local_auth: ^0.3.0

Body:
this is an Issuse

What went wrong:

Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Error while
  merging dex archives

When i Add Finger Local Auth

  local_auth: ^0.4.0+1

with api in gradle


问:
Why do I get "overflow evaluating the requirement" when rewriting a function using Diesel's traits into a trait method?
I am trying to add pagination using Diesel. The compiler is able to check bounds on a generic type if I use a function but isn't if I try to do the same as an implementation of a trait.

This is a simple working example:

```<code>use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

pub fn for_page<T>(query: T)
where
    T: OffsetDsl,
    T::Output: LimitDsl,
{
    query.offset(10).limit(10);
}
</code>```

OffsetDsl and
LimitDsl are Diesel's traits which provides the methods offset and limit.

When I try to extract this method as a trait and implement it like this

```<code>use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

trait Paginator {
    fn for_page(self);
}

impl<T> Paginator for T
where
    T: OffsetDsl,
    <T as OffsetDsl>::Output: LimitDsl,
{
    fn for_page(self) {
        self.offset(10).limit(10);
    }
}
</code>```

I get a not very clear error message.

error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
 --> src/main.rs:3:1
  |
3 | / trait Paginator {
4 | |     fn for_page(self);
5 | | }
  | |_^
  |
  = note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
 --> src/main.rs:3:1
  |
3 | trait Paginator {
  | ^^^^^^^^^^^^^^^

error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
 --> src/main.rs:4:5
  |
4 |     fn for_page(self);
  |     ^^^^^^^^^^^^^^^^^^
  |
  = note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
 --> src/main.rs:3:1
  |
3 | trait Paginator {
  | ^^^^^^^^^^^^^^^
```

I understand that this means that the compiler cannot check the condition on T::Output, but it's not clear what is the difference with a simple function with the same condition.

I'm using Rust 1.35.0 and Diesel 1.4.

答:
I cannot answer why they differ. I can say that repeating the bounds on the trait definition compiles:

```<code>use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

trait Paginator
where
    Self: OffsetDsl,
    Self::Output: LimitDsl,
{
    fn for_page(self);
}

impl<T> Paginator for T
where
    T: OffsetDsl,
    T::Output: LimitDsl,
{
    fn for_page(self) {
        self.offset(10).limit(10);
    }
}
</code>```

You may also be interested in the extending Diesel guide, which discusses how best to add a paginate method.

Body:
I am trying to add pagination using Diesel. The compiler is able to check bounds on a generic type if I use a function but isn't if I try to do the same as an implementation of a trait.

This is a simple working example:

use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

pub fn for_page<T>(query: T)
where
    T: OffsetDsl,
    T::Output: LimitDsl,
{
    query.offset(10).limit(10);
}

OffsetDsl and
LimitDsl are Diesel's traits which provides the methods offset and limit.

When I try to extract this method as a trait and implement it like this

use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

trait Paginator {
    fn for_page(self);
}

impl<T> Paginator for T
where
    T: OffsetDsl,
    <T as OffsetDsl>::Output: LimitDsl,
{
    fn for_page(self) {
        self.offset(10).limit(10);
    }
}

I get a not very clear error message.

error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
 --> src/main.rs:3:1
  |
3 | / trait Paginator {
4 | |     fn for_page(self);
5 | | }
  | |_^
  |
  = note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
 --> src/main.rs:3:1
  |
3 | trait Paginator {
  | ^^^^^^^^^^^^^^^

error[E0275]: overflow evaluating the requirement `<Self as diesel::query_dsl::offset_dsl::OffsetDsl>::Output`
 --> src/main.rs:4:5
  |
4 |     fn for_page(self);
  |     ^^^^^^^^^^^^^^^^^^
  |
  = note: required because of the requirements on the impl of `Paginator` for `Self`
note: required by `Paginator`
 --> src/main.rs:3:1
  |
3 | trait Paginator {
  | ^^^^^^^^^^^^^^^

I understand that this means that the compiler cannot check the condition on T::Output, but it's not clear what is the difference with a simple function with the same condition.

I'm using Rust 1.35.0 and Diesel 1.4.

Body:
I cannot answer why they differ. I can say that repeating the bounds on the trait definition compiles:

use diesel::query_dsl::methods::{LimitDsl, OffsetDsl};

trait Paginator
where
    Self: OffsetDsl,
    Self::Output: LimitDsl,
{
    fn for_page(self);
}

impl<T> Paginator for T
where
    T: OffsetDsl,
    T::Output: LimitDsl,
{
    fn for_page(self) {
        self.offset(10).limit(10);
    }
}

You may also be interested in the extending Diesel guide, which discusses how best to add a paginate method.


问:
npm: not found when creating a reactapp using NVM, NPM, in Pycharm
I am trying to create a React project in pycharm. I am using NVM version 0.34.0, and installed node using it.

Here is my pycharm window before starting a project

npm -v return 6.9.0

whereis npm returns  npm: /home/usa/.nvm/versions/node/v12.3.1/bin/npm

Here is the error message

```<code>/home/usa/.nvm/versions/node/v12.3.1/bin/node /home/maged/.nvm/versions/node/v12.3.1/lib/node_modules/create-react-app/index.js .

Creating a new React app in /home/usa/Desktop/ny/untitled1.

/bin/sh: 1: npm: not found
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

events.js:177
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:264:19)
    at onErrorNT (internal/child_process.js:456:16)
    at processTicksAndRejections (internal/process/task_queues.js:84:9)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12)
    at onErrorNT (internal/child_process.js:456:16)
    at processTicksAndRejections (internal/process/task_queues.js:84:9) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'spawn npm',
  path: 'npm',
  spawnargs: [
    'install',
    '--save',
    '--save-exact',
    '--loglevel',
    'error',
    'react',
    'react-dom',
    'react-scripts@0.9.x'
  ]
}
Done
</code>```

答:
You installed npm and you can see its version, but you should add it to PATH variable in your system so other services can find it.
first run this in your terminal

```<code>cat $PATH
</code>```

check the output to see npm path there if it wasn't there run below command and try again

```<code>export PATH=$PATH:/<path-to-npm-bin>/npm/bin
</code>```

Body:
I am trying to create a React project in pycharm. I am using NVM version 0.34.0, and installed node using it.

Here is my pycharm window before starting a project

npm -v return 6.9.0

whereis npm returns  npm: /home/usa/.nvm/versions/node/v12.3.1/bin/npm

Here is the error message

/home/usa/.nvm/versions/node/v12.3.1/bin/node /home/maged/.nvm/versions/node/v12.3.1/lib/node_modules/create-react-app/index.js .

Creating a new React app in /home/usa/Desktop/ny/untitled1.

/bin/sh: 1: npm: not found
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

events.js:177
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:264:19)
    at onErrorNT (internal/child_process.js:456:16)
    at processTicksAndRejections (internal/process/task_queues.js:84:9)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12)
    at onErrorNT (internal/child_process.js:456:16)
    at processTicksAndRejections (internal/process/task_queues.js:84:9) {
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall: 'spawn npm',
  path: 'npm',
  spawnargs: [
    'install',
    '--save',
    '--save-exact',
    '--loglevel',
    'error',
    'react',
    'react-dom',
    'react-scripts@0.9.x'
  ]
}
Done

Body:
You installed npm and you can see its version, but you should add it to PATH variable in your system so other services can find it.
first run this in your terminal

cat $PATH

check the output to see npm path there if it wasn't there run below command and try again

export PATH=$PATH:/<path-to-npm-bin>/npm/bin


问:
What is a Python mapping?
Say I have a function func and an object obj of class Class. I have the following error:

>>> func(**obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class
```

Hence my question: what is a mapping? Are all mappings subclasses of dict? Or is there a list of methods (e.g. __getitem__, __iter__, ...) that Class has to implement to be considered a mapping?

答:
According to Python docs:

A container object that supports arbitrary key lookups and implements the methods specified in the Mapping or MutableMapping abstract base classes.
Examples include:

dict

collections.defaultdict

collections.OrderedDict

collections.Counter.

The class is a mapping if it implements all methods from the Mapping / MutableMapping.

If you will create a Mapping/MutableMapping derived class and implement all of this, you will get a class that is a mapping.

Title: What is a Python mapping?

Body:
Say I have a function func and an object obj of class Class. I have the following error:

>>> func(**obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class

Hence my question: what is a mapping? Are all mappings subclasses of dict? Or is there a list of methods (e.g. __getitem__, __iter__, ...) that Class has to implement to be considered a mapping?


问:
Take tail of variadic template parameters
Given this type:

```<code>template<typename ...As>
struct Base {};
</code>```

I need to implement a function

```<code>template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}
</code>```

which returns an instance of B using the tail of type parameter list from index i.

For example,

```<code>Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert
</code>```

I know how to get the type at index i :

```<code>template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at<i - 1, Ts...>::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};
</code>```

but I can't get a working version for the entire problem.

答:
If you don't mind using C++17. Even static_assert is not needed:

```<code>template<unsigned i, typename T, typename ...Ts>
constexpr auto Tail() {
    if constexpr (i == 0)
        return Base<T, Ts...>();
    else
        return Tail<i - 1, Ts...>();
}

int main(){
    Base<int, double, int> a = Tail<0, int, double, int>();
    Base<double, int> b = Tail<1, int, double, int>();
    Base<int> c = Tail<2, int, double, int>();
    auto d = Tail<3, int, double, int>();
}
</code>```

Btw, changed int to unsigned to avoid possibility of (nearly) infinite recursion for negative numbers.

Body:
Given this type:

template<typename ...As>
struct Base {};

I need to implement a function

template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}

which returns an instance of B using the tail of type parameter list from index i.

For example,

Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert

I know how to get the type at index i :

template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};

but I can't get a working version for the entire problem.

Body:
If you don't mind using C++17. Even static_assert is not needed:

template<unsigned i, typename T, typename ...Ts>
constexpr auto Tail() {
    if constexpr (i == 0)
        return Base<T, Ts...>();
    else
        return Tail<i - 1, Ts...>();
}

int main(){
    Base<int, double, int> a = Tail<0, int, double, int>();
    Base<double, int> b = Tail<1, int, double, int>();
    Base<int> c = Tail<2, int, double, int>();
    auto d = Tail<3, int, double, int>();
}

Btw, changed int to unsigned to avoid possibility of (nearly) infinite recursion for negative numbers.


问:
JSON returning as undefined
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

```<code>$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });
</code>```

答: If you alert is failing then are you sure your json is valid? Can you paste it into your question. You can validate it here online at JsonLint.</p>

Title: JSON returning as undefined

Body:
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });


问:
Using weighted adjacency matrices to calculate global efficiency of said matrix using networkx
I have been trying to study the impact on a network by looking at deletions of different combinations of nodes.

To study this I have used the networkx graph theory metric, global efficiency. But, I figured that the networkx code ignores weight when calculating global efficiency. So, I went in and changed the source code and added weight as a metric. It seems to be working and is giving me different values than the non-weighted approach but is exceptionally slow (about 20 times).

How can I speed up these computations?

```<code>##The code I am running

import networkx
import numpy as np
from networkx import algorithms
from networkx.algorithms import efficiency
from networkx.algorithms.efficiency import global_efficiency
import pandas

data=pandas.read_csv("ones.csv")
lol = data.values.tolist()
data=pandas.read_csv("twos.csv")
lol2 = data.values.tolist()

combo=[["10pp", "10d"]]
GE_list=[]

for row in combo:
    values = row
    datasafe=pandas.read_csv("b1.csv", index_col=0)
    datasafe.loc[values, :] = 0

    datasafe[values] = 0

    g=networkx.from_pandas_adjacency(datasafe)
    ge=global_efficiency(g)
    GE_list.append(ge)

extra=[""]
extra2=["full"]
combo.append(extra)
combo.append(extra2)
datasafe=pandas.read_csv("b1.csv", index_col=0)
g=networkx.from_pandas_adjacency(datasafe)
ge=global_efficiency(g)
GE_list.append(ge)

values = ["s6-8","p9-46v","p47r","p10p","IFSp","IFSa",'IFJp','IFJa','i6-8','a9-46v','a47r','a10p','9p','9a','9-46d','8C','8BL','8AV','8AD','47s','47L','10pp','10d','46','45','44']
datasafe=pandas.read_csv("b1.csv", index_col=0)
datasafe.loc[values, :] = 0

datasafe[values] = 0

g=networkx.from_pandas_adjacency(datasafe)
ge=global_efficiency(g)
GE_list.append(ge)

output=pandas.DataFrame(list(zip(combo, GE_list)))
output.to_csv('delete 1.csv',index=None)

##The change I made to the original networkx code
    try:
        eff = 1 / nx.shortest_path_length(G, u, v)
## changed to
    try:
        eff = 1 / nx.shortest_path_length(G, u, v, weight='weight')
</code>```

Previously with my unweighted graphs I was able to process my data in 2 hours, currently its taking the same time to do a twentieth of the data. Please do suggest any improvements to my code or any other pieces of code that I can run.

Ps-I don't have a great understanding of python, so please do bear with me :)

答:
Using weights, you exchange breadth-first search with Dijkstra algorithm, which increases the runtime by log|V|, see second comment of https://stackoverflow.com/a/25449911

If you have problem with the runtime, you should rather exchange networkx, which is implemented in python, with a C implementation like graph-tool or igraph, see e.g. for a (probably biased) comparison of performance: https://graph-tool.skewed.de/performance

Body:
I have been trying to study the impact on a network by looking at deletions of different combinations of nodes.

To study this I have used the networkx graph theory metric, global efficiency. But, I figured that the networkx code ignores weight when calculating global efficiency. So, I went in and changed the source code and added weight as a metric. It seems to be working and is giving me different values than the non-weighted approach but is exceptionally slow (about 20 times).

How can I speed up these computations?

##The code I am running

import networkx
import numpy as np
from networkx import algorithms
from networkx.algorithms import efficiency
from networkx.algorithms.efficiency import global_efficiency
import pandas

data=pandas.read_csv("ones.csv")
lol = data.values.tolist()
data=pandas.read_csv("twos.csv")
lol2 = data.values.tolist()

combo=[["10pp", "10d"]]
GE_list=[]

for row in combo:
    values = row
    datasafe=pandas.read_csv("b1.csv", index_col=0)
    datasafe.loc[values, :] = 0

    datasafe[values] = 0

    g=networkx.from_pandas_adjacency(datasafe)
    ge=global_efficiency(g)
    GE_list.append(ge)

extra=[""]
extra2=["full"]
combo.append(extra)
combo.append(extra2)
datasafe=pandas.read_csv("b1.csv", index_col=0)
g=networkx.from_pandas_adjacency(datasafe)
ge=global_efficiency(g)
GE_list.append(ge)

values = ["s6-8","p9-46v","p47r","p10p","IFSp","IFSa",'IFJp','IFJa','i6-8','a9-46v','a47r','a10p','9p','9a','9-46d','8C','8BL','8AV','8AD','47s','47L','10pp','10d','46','45','44']
datasafe=pandas.read_csv("b1.csv", index_col=0)
datasafe.loc[values, :] = 0

datasafe[values] = 0

g=networkx.from_pandas_adjacency(datasafe)
ge=global_efficiency(g)
GE_list.append(ge)

output=pandas.DataFrame(list(zip(combo, GE_list)))
output.to_csv('delete 1.csv',index=None)

##The change I made to the original networkx code
    try:
        eff = 1 / nx.shortest_path_length(G, u, v)
## changed to
    try:
        eff = 1 / nx.shortest_path_length(G, u, v, weight='weight')

Previously with my unweighted graphs I was able to process my data in 2 hours, currently its taking the same time to do a twentieth of the data. Please do suggest any improvements to my code or any other pieces of code that I can run.

Ps-I don't have a great understanding of python, so please do bear with me :)


问:
How to prevent 'click' event to fire before 'dblclick' event
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'</p>

```<code>google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });
</code>```

答:
```<code>var clicked = false;
google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng);
   clicked = true;
 });

 google.maps.event.addListener(map, 'click', function(event) {
   if(clicked){
      click_events(map, event.latLng);
   }
 });
</code>```

Body:
I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'

google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });

 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });


问:
How can I get the same piece (duplicate code) of an image from many different photos every time?
From 5000 photos of license plates I want to determine which duplicate code these license plates have.

Here are 2 examples of a duplicate code on a license plate.

In the first example the duplicate code is 2 and in the second example the duplicate code is 1.

With the package Magick and Tesseract, see code below, I was able to retrieve the piece of the photo from the first example where the duplicate code is and to read the duplicate code. Only in the second example and other photos is the photo different.

So I am looking for something that can recognize where the duplicate code is and that will read the duplicate code. Note: The duplicate code is always above the 1st indent mark.

Does someone have an idea how to read the duplicate code automatically from 5000 different photos?

```<code>library(magick)
library(tesseract)

#Load foto:
foto <- image_read("C:/Users/camie/OneDrive/Documenten/kenteken3.jpg")

 #Get piece of photo where duplicate code is retrieved:
foto2 <- image_crop(foto,"10X24-620-170")

#read duplicate code:
cat(ocr(foto3))
</code>```

答:
What with the existance of multiple layouts for Dutch license plates, I'm not sure if you just can hardcode a method to extract a duplication value. Also you don't mention if every image you have always has the same quality and/or orientation/scale/skew/etc.

You could in theory apply a Convolutional Neural Network that categorizes license plates in a several categories. (0 for n/a, 1 for 1, 2 for 2, etc.) However I am not familiar with related packages in R, so I won't be able to point you to some.

Body:
From 5000 photos of license plates I want to determine which duplicate code these license plates have.

Here are 2 examples of a duplicate code on a license plate.

In the first example the duplicate code is 2 and in the second example the duplicate code is 1.

With the package Magick and Tesseract, see code below, I was able to retrieve the piece of the photo from the first example where the duplicate code is and to read the duplicate code. Only in the second example and other photos is the photo different.

So I am looking for something that can recognize where the duplicate code is and that will read the duplicate code. Note: The duplicate code is always above the 1st indent mark.

Does someone have an idea how to read the duplicate code automatically from 5000 different photos?

library(magick)
library(tesseract)

#Load foto:
foto <- image_read("C:/Users/camie/OneDrive/Documenten/kenteken3.jpg")

 #Get piece of photo where duplicate code is retrieved:
foto2 <- image_crop(foto,"10X24-620-170")

#read duplicate code:
cat(ocr(foto3))


问:
Querying based on columns?
A beginner with SQL here - say I have a recipient table and I'm trying to come up with a query and sort the results by ethnicity. Usually I would do

```<code>select abcd
from recipient
where ehthnicity = 'White'
</code>```

but this table has ethnicities listed as fields (attributes) - is this a bad design?

What would be the best way to go about this?

答:
The United States Census Bureau has very well-defined definitions for ethnicity and race (here is a good summary).

You don't say what the source of your data is.  If it is from such a well-defined source, then separate columns can be sensible.  You could also use an association table, although you might find that mildly trickier in practice.

Why are separate columns ok in this case?  Because the columns are well-defined.  Because there are handful of them.  And because they are not changing much over time.  Is an association/junction table also a good solution.  Yes.

What I don't recommend is a list of strings.  For instance, Tiger Woods might have "white,black,indian,asian", and that is troublesome to parse and prone to error (gosh, is "white,black" the same as "black,white"?).

Title: Querying based on columns?

Body:
A beginner with SQL here - say I have a recipient table and I'm trying to come up with a query and sort the results by ethnicity. Usually I would do

select abcd
from recipient
where ehthnicity = 'White'

but this table has ethnicities listed as fields (attributes) - is this a bad design?

What would be the best way to go about this?