问:
HTTP status codes in APIs good practice?
right now I'm building a project with the laravel framework. I'm not a professional or whatever, in the past I built all my applications from scratch without the use of such frameworks.

Right now I'm implenting the Twitch API for certain parts of my website. While doing that I encoutered situations where the Twitch API returns an http error code (40x) even though it provides a "valid" response. Right now I'm using a pretty popular Twitch API package from packagist.org. As soon as I receive an 40x error code an exception will be thrown which would would break my application.

Reason for that is, that the response request looks like this:

```<code>$response = $this->client->send($request);
</code>```

As a workaround I changed this to:

```<code>$response = $this->client->send($request, ['http_errors' => false]);
</code>```

Obviously I could also make use of GuzzleHttp\Exception to handle these errors aswell. But from what I get, all of this would have to happen inside the package I downloaded via composer which means that as soon as the author releases an update and I run a composer update my changes would be overwritten  and my app might be broken until I fix it again.

I guess not everyone is familiar with the Twitch API. An easy example for my question is an API call where you can check wether a specific user is following a a specific channel. When the user does NOT, the response looks like that:

{
      "error": "Not Found",
      "message": "12345 is not following 67890",
      "status": 404 }

So this is a perfectly fine and valid response that would be easy to handle but instead of an 200 http status response the api responds with a 404 http status code  which will throw an exception.

So my question is, is it really good practice in APIs to return a 40x status code even though you send and receive perfectly fine requests? It's not like there's an error like missing parameters, ids or whatever. It's just some kind of "bool" query where return can be true or false and where false will always return a 40x http status code but still contains a valid response.

Thank you

答:
Package that is throwing an exception is the best kind, because you can simply write "global" handler for those exceptions and simply "display" error that is sent along, nevertheless you should not.

You should write an API adaptor for Twitch API package and handle errors / exceptions inside those methods instead of using Twitch package right in controller or model. Further more you should delegate making request to dedicated server (such as Twitch) for queued job.

To answer your question:

Are HTTP status codes in APIs good practice?

Yes, where else would you want to use status codes? API is the perfect place.

Status codes are easy to compare, easy to understand. Messages sent along are just meta information for human to "understand" what is going on.

Part below is way off the scope of the question:

You should never change package code itself (except when testing), instead clone/fork package, make changes you need and use composer to load your version instead.

composer.json

```<code>"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/username/repository"
    }
],
"require": {
    .
    .
    .
    "original-repo-package": "dev-branch-form-your-repo as 1.0.0"
}
</code>```

Body:
right now I'm building a project with the laravel framework. I'm not a professional or whatever, in the past I built all my applications from scratch without the use of such frameworks.

Right now I'm implenting the Twitch API for certain parts of my website. While doing that I encoutered situations where the Twitch API returns an http error code (40x) even though it provides a "valid" response. Right now I'm using a pretty popular Twitch API package from packagist.org. As soon as I receive an 40x error code an exception will be thrown which would would break my application.

Reason for that is, that the response request looks like this:

$response = $this->client->send($request);

As a workaround I changed this to:

$response = $this->client->send($request, ['http_errors' => false]);

Obviously I could also make use of GuzzleHttp\Exception to handle these errors aswell. But from what I get, all of this would have to happen inside the package I downloaded via composer which means that as soon as the author releases an update and I run a composer update my changes would be overwritten  and my app might be broken until I fix it again.

I guess not everyone is familiar with the Twitch API. An easy example for my question is an API call where you can check wether a specific user is following a a specific channel. When the user does NOT, the response looks like that:

{
      "error": "Not Found",
      "message": "12345 is not following 67890",
      "status": 404 }

So this is a perfectly fine and valid response that would be easy to handle but instead of an 200 http status response the api responds with a 404 http status code  which will throw an exception.

So my question is, is it really good practice in APIs to return a 40x status code even though you send and receive perfectly fine requests? It's not like there's an error like missing parameters, ids or whatever. It's just some kind of "bool" query where return can be true or false and where false will always return a 40x http status code but still contains a valid response.

Thank you

Body:
Package that is throwing an exception is the best kind, because you can simply write "global" handler for those exceptions and simply "display" error that is sent along, nevertheless you should not.

You should write an API adaptor for Twitch API package and handle errors / exceptions inside those methods instead of using Twitch package right in controller or model. Further more you should delegate making request to dedicated server (such as Twitch) for queued job.

To answer your question:

Are HTTP status codes in APIs good practice?

Yes, where else would you want to use status codes? API is the perfect place.

Status codes are easy to compare, easy to understand. Messages sent along are just meta information for human to "understand" what is going on.

Part below is way off the scope of the question:

You should never change package code itself (except when testing), instead clone/fork package, make changes you need and use composer to load your version instead.

composer.json

"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/username/repository"
    }
],
"require": {
    .
    .
    .
    "original-repo-package": "dev-branch-form-your-repo as 1.0.0"
}


来源: stackexchange

问:
Find element between two span in selenium
I want to find text between this html using selenium

```<code><span class="value">
Receiver 1
<br>
</span>
</code>```

How can make it maybe something like this  span[class=value]?

答:
Two ways to do that -

By CSS Selector:

```<code>String data = driver.findElement(By.cssSelector("span.value")).getText();
System.out.println(data);
</code>```

Using Xpath:

```<code>String data = driver.findElement(By.xpath("//span[@class,'value']")).getText();
System.out.println(data)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to find text between this html using selenium

Receiver 1

How can make it maybe something like this  span[class=value]?

Body:
Two ways to do that -

By CSS Selector:

String data = driver.findElement(By.cssSelector("span.value")).getText();
System.out.println(data);

Using Xpath:

String data = driver.findElement(By.xpath("//span[@class,'value']")).getText();
System.out.println(data)


问:
How can I make my arduino print "the loop is running for the ....... time"?
i want my arduino to tell me what time running it is E.g. "this is the 22nd time this loop has run." what command/s should i use?
i am currently using this code:

```<code>Serial.print("This loop has run ");
Serial.print(loopsRun);
Serial.println(" times.");
loopsRun++;
</code>```

yes i have declared all variables, i just want to know if there is a way to check the last digit of any int.

答:
22 % 10 = 2 you'd say 22'nd'
1022 % 10 = 2 you'd say 1022 'nd'

27 % 10 = 7 you'd say 7 'th'
457 % 10 = 7 you'd say 457 'th'

Am I getting the pattern right?  If so then you need a switch statement and a % operator

```<code>unsigned int remainder = loopsRun % 10;
switch (remainder)
{
    case 0: suffix = "th"; break;
    case 1: suffix = "st"; break;
    case 2: suffix = "nd"; break;
    <etc>

}
</code>```

Body:
i want my arduino to tell me what time running it is E.g. "this is the 22nd time this loop has run." what command/s should i use?
i am currently using this code:

Serial.print("This loop has run ");
Serial.print(loopsRun);
Serial.println(" times.");
loopsRun++;

yes i have declared all variables, i just want to know if there is a way to check the last digit of any int.

Body:
22 % 10 = 2 you'd say 22'nd'
1022 % 10 = 2 you'd say 1022 'nd'

27 % 10 = 7 you'd say 7 'th'
457 % 10 = 7 you'd say 457 'th'

Am I getting the pattern right?  If so then you need a switch statement and a % operator

unsigned int remainder = loopsRun % 10;
switch (remainder)
{
    case 0: suffix = "th"; break;
    case 1: suffix = "st"; break;
    case 2: suffix = "nd"; break;
    <etc>

}


问:
Searching inside an EAR/WAR file for a jar by jar name
I'm trying to find which command I can use in order to search for a known jar file name, in a specific unknown .ear file (of many) in a specific directory.

Thanks !

答:
The EAR file-format is an extension of the JAR format and thus a simple ZIP container.

You can open it with any program or library that is able to handle the zip format. You can e.g. use java's inbuilt java.util.zip package to load the ear file and then walk its contents until you find what you're looking for.


答:
To search for a jar in a single ear file you can try:

```<code>unzip -l some_file.ear | grep -i known_file.jar
</code>```

If you want to search through more than one ear file, you can feed them one by one to the same command:

```<code>for file in specific/directory/*.ear; do echo "$file: "; unzip -l $file | grep -i known_file.jar; done
</code>```

Which will list all the ear files and any potential matches within them.

Title: Searching inside an EAR/WAR file for a jar by jar name

Body:
I'm trying to find which command I can use in order to search for a known jar file name, in a specific unknown .ear file (of many) in a specific directory.

Thanks !

Body:
To search for a jar in a single ear file you can try:

unzip -l some_file.ear | grep -i known_file.jar

If you want to search through more than one ear file, you can feed them one by one to the same command:

for file in specific/directory/*.ear; do echo "$file: "; unzip -l $file | grep -i known_file.jar; done

Which will list all the ear files and any potential matches within them.


问:
C OVERFLOW! number gets negative
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

```<code>long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}
</code>```

答:
You can use strtol. No need to re invent the wheel.</p>

```<code>long int strtol(const char *str, char **endptr, int base)
</code>```

Title: C OVERFLOW! number gets negative

Body:
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}

Body:
You can use strtol. No need to re invent the wheel.

long int strtol(const char *str, char **endptr, int base)


问:
Full screen Firefox Python Selenium
I'm trying to start a full screen page in Firefox with Selenium in Python 3. The page opening works fine, but when I send the F11 key to the browser (the Full Screen key), anything happens. Here is my code :

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

firefox = webdriver.Firefox()
firefox.get('http://localhost')
firefox.maximize_window()

body = firefox.find_element_by_tag_name('html')
body.send_keys(Keys.F11)
</code>```

Does anyone know how to make my page start in full screen ? I know it's possible with Chrome, but it's harder with Firefox

答:
This is what worked for me.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()

driver.get('http://localhost')
driver.find_element_by_xpath('/html/body').send_keys(Keys.F11)
</code>```

Hope this helps

Just realized I am using Python 2.6 vs your 3. Sorry about that, but at least you know it will work on an older Python version

Title: Full screen Firefox Python Selenium

Body:
I'm trying to start a full screen page in Firefox with Selenium in Python 3. The page opening works fine, but when I send the F11 key to the browser (the Full Screen key), anything happens. Here is my code :

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

firefox = webdriver.Firefox()
firefox.get('http://localhost')
firefox.maximize_window()

body = firefox.find_element_by_tag_name('html')
body.send_keys(Keys.F11)

Does anyone know how to make my page start in full screen ? I know it's possible with Chrome, but it's harder with Firefox

Body:
This is what worked for me.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()

driver.get('http://localhost')
driver.find_element_by_xpath('/html/body').send_keys(Keys.F11)

Hope this helps

Just realized I am using Python 2.6 vs your 3. Sorry about that, but at least you know it will work on an older Python version


问:
Output input if it doesn't contain specific String
I have what seems to be a rather simple problem, but I can't find an answer to it.

I'm working on a travis script which validates files.

I'm using 3rd party software for this and therefore I have no influence on the development.

The Problem:

As you may know travis scripts require non-zero exit codes for the build to fail. Unfortunately the software I'm using only outputs error message in stdout but still exists with code 0.
My idea was to use grep.

Currently I'm using this command:

! echo "SomeInput" | grep -Pzo "\A[^\x{0000}]*error message[^\x{0000}]*\Z"

If the error message is printed, it returns with a non-zero exit code and prints the error message.

As you may have noticed, the output is not being displayed when no errors show up. This is bad if we want to check if a paricular change introduced warnings. Which will then also not be displayed.

Any ideas?

答:
If I understand correctly, you want to detect errors by grep-ing certain patterns in the output, and at the same time you also want to see the entire output. The tricky part is that grep itself would consume the output.

I don't there's an easy clever solution for this. You need to consume the output twice. Once to just print it, and one more time to check for errors.

One solution is to save the output to a file first, and then process it. For example:

```<code>some_command 2>&1 | tee out.log
! grep -Pzo "\A[^\x{0000}]*error message[^\x{0000}]*\Z" out.log
</code>```

Body:
If I understand correctly, you want to detect errors by grep-ing certain patterns in the output, and at the same time you also want to see the entire output. The tricky part is that grep itself would consume the output.

I don't there's an easy clever solution for this. You need to consume the output twice. Once to just print it, and one more time to check for errors.

One solution is to save the output to a file first, and then process it. For example:

some_command 2>&1 | tee out.log
! grep -Pzo "\A[^\x{0000}]*error message[^\x{0000}]*\Z" out.log


问:
Qt android Can't listen to os intents ex.RECEIVE_BOOT_COMPLETED
I have an android service that runs when i open my app, now I want my android service to run at boot time. I tried the bellow code, but the service is not running automatically when i reboot my device. I cannot see it running as a service on my phone! Is there something wrong in my code?

I added these permissions to the manifest:

```<code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.RECEIVE_HEADSET_PLUG"/>
</code>```

Here's my receiver in the manifest:

```<code><receiver android:name="org.qtproject.example.MyBroadcastReceiver">
  <intent-filter>
  <action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED"/>
  <action android:name="android.intent.action.RECEIVE_HEADSET_PLUG"/>
  </intent-filter>
 </receiver>
</code>```

And here's MyBroadcastReceiver.java:

```<code>import android.os.Bundle;
import org.qtproject.qt5.android.bindings.QtActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, org.qtproject.example.MyCustomAppService.class);
        context.startService(startServiceIntent);

    }
}
</code>```

答:
ok so I had 2 problems in my code:

1)Thanks to @kajay, i had to change my action line as he described,
to be:
<action android:name="android.intent.action.BOOT_COMPLETED"/> in the manifest.

2) I was missing defining the package in the MyBroadcastReceiver.java. So, the class couldn't find the startServiceIntent. Of course qt doesn't give any errors or warnings with many java problems.
So, in my case i had to add this to the MyBroadcastReceiver.java :

```<code>package org.qtproject.example;
</code>```

I had to do both of the above steps to fix my problem!
P.S Sometimes the service takes around 45 secs or more to start after booting!

Body:
I have an android service that runs when i open my app, now I want my android service to run at boot time. I tried the bellow code, but the service is not running automatically when i reboot my device. I cannot see it running as a service on my phone! Is there something wrong in my code?

I added these permissions to the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.RECEIVE_HEADSET_PLUG"/>

Here's my receiver in the manifest:

<receiver android:name="org.qtproject.example.MyBroadcastReceiver">
  <intent-filter>
  <action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED"/>
  <action android:name="android.intent.action.RECEIVE_HEADSET_PLUG"/>
  </intent-filter>
 </receiver>

And here's MyBroadcastReceiver.java:

import android.os.Bundle;
import org.qtproject.qt5.android.bindings.QtActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, org.qtproject.example.MyCustomAppService.class);
        context.startService(startServiceIntent);

    }
}

Body:
ok so I had 2 problems in my code:

1)Thanks to @kajay, i had to change my action line as he described,
to be:
<action android:name="android.intent.action.BOOT_COMPLETED"/> in the manifest.

2) I was missing defining the package in the MyBroadcastReceiver.java. So, the class couldn't find the startServiceIntent. Of course qt doesn't give any errors or warnings with many java problems.
So, in my case i had to add this to the MyBroadcastReceiver.java :

package org.qtproject.example;

I had to do both of the above steps to fix my problem!
P.S Sometimes the service takes around 45 secs or more to start after booting!


问:
Regex not matching all hyphens
In the following example, only the third string is matched, even though there are hyphens in all three strings:

```<code>grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3
</code>```

How can I match all three hyphens with grep?

答:
As rightly pointed by @akrun, the other two characters are not hyphens ( they are called EN DASH), if you use Encdoing function you can see what they are like below.

```<code>x <- c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015")
Encoding(x) <- "UTF-8"
print(x)
</code>```

Output:

```<code>[1] "January 7<U+2013>9, 2015" "January a<U+2013>b, 2015"
[3] "Janua-ry 14, 2015"
</code>```

There are lot of ways of matching these encoding patterns, You may use \U followed by the utf encoding numeric counterpart like below to match with your grep.

```<code>grep("-|[\U{2013}]",x )
</code>```

Output:

```<code> grep("-|[\U{2013}]",x )
[1] 1 2 3
</code>```

ContentLicense: CC BY-SA 4.0

Title: Regex not matching all hyphens

Body:
In the following example, only the third string is matched, even though there are hyphens in all three strings:

grep("-", c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015"))
[1] 3

How can I match all three hyphens with grep?

Body:
As rightly pointed by @akrun, the other two characters are not hyphens ( they are called EN DASH), if you use Encdoing function you can see what they are like below.

x <- c("January 7–9, 2015", "January a–b, 2015", "Janua-ry 14, 2015")
Encoding(x) <- "UTF-8"
print(x)

Output:

[1] "January 7<U+2013>9, 2015" "January a<U+2013>b, 2015"
[3] "Janua-ry 14, 2015"

There are lot of ways of matching these encoding patterns, You may use \U followed by the utf encoding numeric counterpart like below to match with your grep.

grep("-|[\U{2013}]",x )

Output:

 grep("-|[\U{2013}]",x )
[1] 1 2 3


问:
How to determine the association between a VB6 app and an exe instanced with CreateObject()
We need to figure out how a service can peek at a running VB6 app and/or its DCOM spawned exe and figure out which VB6 app goes with which DCOM exe. The VB6 app and the spawned exe are both on the same server.

We have a VB6 app that spawns an instance of Bartender (from Seagull Scientific) by way of a CreateObject() call. On a given server, we may have ten or twenty instances of our app, each represents a handheld RF gun client in a warehouse. 95% or more of these VB6 apps will have their own Bartender.

Due to circumstances beyond our control, randomly, one of our VB6 instances will be killed, just as if you killed it using Task Manager. This leaves it's Bartender still alive and consuming resources. After fifty or so have been killed over the course of a few hours or days, these orphaned Bartenders become enough of a resource hog to bring the server to its knees.

We are trying to develop a watcher service to detect which of the Bartenders are still connected, so this new service can kill the orphaned Bartenders. We are trying to accomplish this without changing our VB6 app, but we will modify our app if we have to.

答: I think this routine, aptly named Who's Your Daddy, might be of use to you. It figures out who spawned the process.  It probably won't solve your entire problem, but it's a start.</p>

ContentLicense: CC BY-SA 2.5


问:
For which purpose processRequest method is used in servlet?
How can I handle my requests through processRequest in Servlet?

答:
clic on the sign + right under processRequest
just click on the sign +</p>


问:
Extract image name from "img" tag source
I have html page has images like:

```<code><img src="media/lib/pics/1495343165.jpg" style="width: 600px; height: 400px; margin: 5px;" />
</code>```

I would like to extract the image name only "1495343165.jpg" to replace whole image tag with

```<code><img src="my/new/path/1495343165.jpg"  />
</code>```

How can i do that using regex and php?

Thanks

答:
You can use DOMDocument, and basename():</p>

```<code><?php
$src = '<img src="media/lib/pics/1495343165.jpg" style="width: 600px; height: 400px; margin: 5px;" />';
$doc = new DOMDocument();
$doc->loadHTML($src);

$src = $doc->getElementsByTagName('img')->item(0)->getAttribute('src');

echo '<img src="my/new/path/'.basename($src).'" />';
//<img src="my/new/path/1495343165.jpg" />
?>
</code>```

Body:
I have html page has images like:

I would like to extract the image name only "1495343165.jpg" to replace whole image tag with

How can i do that using regex and php?

Thanks

Body:
You can use DOMDocument, and basename():

<?php
$src = '<img src="media/lib/pics/1495343165.jpg" style="width: 600px; height: 400px; margin: 5px;" />';
$doc = new DOMDocument();
$doc->loadHTML($src);

$src = $doc->getElementsByTagName('img')->item(0)->getAttribute('src');

echo '<img src="my/new/path/'.basename($src).'" />';
//<img src="my/new/path/1495343165.jpg" />
?>


问:
Do I need Azure API Management service to restrict web api endpoints inside an Azure virtual network?
My plan is to have an Azure function using a timer trigger call a REST web API endpoint that is not accessible to the internet - only inside an Azure virtual network.

Is it enough to have both the Azure function and web API inside an Azure virtual network or do I have to use the Azure API Management service in conjunction with the virtual network to restrict the web API endpoint?

答:
If you're using dedicated plan, you can deploy the functions runtime as a site extension with a modified web.config with the ip whitelist you need.

If you are using consumption plan you cannot do that. You need something (like API Management) to front Azure Function and do the filtering.

Another option would be to use Function authorization. Non authorized calls to the function are not billed.


问:
How do I install Pygame with pip in Python 3.4?
I have tried commands like

```<code>pip install pygame
</code>```

or

```<code>pip install 'Pygame == 1.9.1release' --allow-external Pygame --allow-    unverified Pygame
</code>```

suggested in other threads but and similars but they don't seem to work for me. Help me, please.

答:
In Windows

1.open CMD

2.Path should locate where pip is installed   for me it is C:\Users\qwrht\AppData\Local\Programs\Python\Python36-32\Scripts>

if python is in other directory follow steps in link CMD command to change directories

3.getting to the right path where pip is installed use command
**pip install pygame.**in CMD

4.after Downloading pygame current version, Successfully installed pygame message will be displayed

Body:
I have tried commands like

pip install pygame

or

pip install 'Pygame == 1.9.1release' --allow-external Pygame --allow-    unverified Pygame

suggested in other threads but and similars but they don't seem to work for me. Help me, please.


问:
The trait bound `&str: From<MyType>` is not satisfied even though I implemented `From<&str> for MyType`
I tried to implement run length encoding with the help of From and Into. The idea is I am going to implement only from and get into implementation for free.

```<code>extern crate regex;

use regex::Regex;

struct RLE(pub String);

impl<'a> From<&'a str> for RLE {
    fn from(s: &str) -> Self {
        let reg = Regex::new(r"(\d*)([\w\s])").unwrap();
        let mut accum = String::new();
        for c in reg.captures_iter(s) {
            let n = c.get(1).unwrap().as_str().parse::<usize>().unwrap_or(1);
            let c = c.get(2).unwrap().as_str();
            accum.push_str(&c.repeat(n));
        }
        RLE(accum)
    }
}
</code>```

decode("2ab3c") => "aabccc"

```<code>pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}
</code>```

encode("aabccc") => "2ab3c"

```<code>pub fn encode(s: &str) -> String {
    let string: &'static str = RLE(s.to_string()).into();
    string.to_string()
}
</code>```

But I get the following error:

error[E0277]: the trait bound `&str: std::convert::From<RLE>` is not satisfied
  --> src/main.rs:26:51
   |
26 |     let string: &'static str = RLE(s.to_string()).into();
   |                                                   ^^^^ the trait `std::convert::From<RLE>` is not implemented for `&str`
   |
   = note: required because of the requirements on the impl of `std::convert::Into<&str>` for `RLE`
```

What am I doing wrong?

答:
The idea is I am going to implement only from and get into implementation for free...

That works!

You can use From, as in

```<code>pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}
</code>```

and you can use Into, as in

```<code>pub fn decode_using_into(s: &str) -> String {
    let RLE(string) = s.into();
    string
}
</code>```

But I get following error

Well, as DK. said, Rust won't implement one algorithm from another. You'll have to do it yourself.

Body:
I tried to implement run length encoding with the help of From and Into. The idea is I am going to implement only from and get into implementation for free.

extern crate regex;

use regex::Regex;

struct RLE(pub String);

impl<'a> From<&'a str> for RLE {
    fn from(s: &str) -> Self {
        let reg = Regex::new(r"(\d*)([\w\s])").unwrap();
        let mut accum = String::new();
        for c in reg.captures_iter(s) {
            let n = c.get(1).unwrap().as_str().parse::<usize>().unwrap_or(1);
            let c = c.get(2).unwrap().as_str();
            accum.push_str(&c.repeat(n));
        }
        RLE(accum)
    }
}

decode("2ab3c") => "aabccc"

pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}

encode("aabccc") => "2ab3c"

pub fn encode(s: &str) -> String {
    let string: &'static str = RLE(s.to_string()).into();
    string.to_string()
}

But I get the following error:

error[E0277]: the trait bound `&str: std::convert::From<RLE>` is not satisfied
  --> src/main.rs:26:51
   |
26 |     let string: &'static str = RLE(s.to_string()).into();
   |                                                   ^^^^ the trait `std::convert::From<RLE>` is not implemented for `&str`
   |
   = note: required because of the requirements on the impl of `std::convert::Into<&str>` for `RLE`

What am I doing wrong?

Body:
The idea is I am going to implement only from and get into implementation for free...

That works!

You can use From, as in

pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}

and you can use Into, as in

pub fn decode_using_into(s: &str) -> String {
    let RLE(string) = s.into();
    string
}

But I get following error

Well, as DK. said, Rust won't implement one algorithm from another. You'll have to do it yourself.


问:
Will bootloader for armv7 work for armv8?
I am trying to write a bootloader according to armv7 architecture using armv7 assembly instruction set ?
Ex:

Setting cpu to svc mode on reset:

```<code>mrs r0, cpsr
bic r0, r0,#0x1f
orr r0, r0,#0xd3
msr cpsr, r0
mov pc, lr
</code>```

Will the same bootloader work on armv8. As armv8 also supports aarch32 .
But on the other hand it also has many differences.

答:
Not necessarily for a couple of reasons, first off if you are in hyp mode you cant get back from that that easily.  Second, if you are in aarch64 mode then that is a different instruction set.  So in part it depends on where this code is how early in the bootloader is this truly the bootloader or do you have other code that comes before this (that puts you in a state that code like this won't work).

Short answer, no this code not only won't always work for armv8 it won't always work for armv7.

Body:
I am trying to write a bootloader according to armv7 architecture using armv7 assembly instruction set ?
Ex:

Setting cpu to svc mode on reset:

mrs r0, cpsr
bic r0, r0,#0x1f
orr r0, r0,#0xd3
msr cpsr, r0
mov pc, lr

Will the same bootloader work on armv8. As armv8 also supports aarch32 .
But on the other hand it also has many differences.


问:
How to connect vb.net to wamp server?
Do you know of any way on how to connect wampserver or phpmyadmin localhost to vb.net.
I mean adding, searching, deleting, updating, listing of data from the localhost database via vb.net?</p>

答:
First of all install mysql-connector-net-6.0.7 and follow this:

Right click on the program and add reference then browse then mysql.data.dll
then add module

Name it connection and copy this codes

Imports System
Imports System.Data
Imports MySql.Data.MySqlClient
Module connection
    Public conn As New MySqlConnection

```<code>Public Sub ConnectDatabase()

    Try
        If conn.State = ConnectionState.Closed Then
            conn.ConnectionString = "Server=Dell-PC;Data Source=localhost:3306;Database=dbquicklend;User ID=root;"
            conn.Open()
        End If

    Catch myerror As Exception
        MsgBox("Error in Database Connection", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Error")
    End Try
End Sub

Public Sub DisconnectDatabase()
    Try
        conn.Close()
    Catch myerror As MySql.Data.MySqlClient.MySqlException
    End Try
End Sub
</code>```

End Module

just call connectdatabase anywhere in the program you would like to connect or call disconnectdatabase when you need to disconnect

Title: How to connect vb.net to wamp server?

Body:
First of all install mysql-connector-net-6.0.7 and follow this:

Right click on the program and add reference then browse then mysql.data.dll
then add module

Name it connection and copy this codes

Imports System
Imports System.Data
Imports MySql.Data.MySqlClient
Module connection
    Public conn As New MySqlConnection

Public Sub ConnectDatabase()

    Try
        If conn.State = ConnectionState.Closed Then
            conn.ConnectionString = "Server=Dell-PC;Data Source=localhost:3306;Database=dbquicklend;User ID=root;"
            conn.Open()
        End If

    Catch myerror As Exception
        MsgBox("Error in Database Connection", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Error")
    End Try
End Sub

Public Sub DisconnectDatabase()
    Try
        conn.Close()
    Catch myerror As MySql.Data.MySqlClient.MySqlException
    End Try
End Sub

End Module

just call connectdatabase anywhere in the program you would like to connect or call disconnectdatabase when you need to disconnect


问:
Keras forward pass with dropout
I am trying to use dropout to get error estimates for a neural network.

This involves running several forward passes of my network after training, with dropout activated. Dropout does not seem to be activated when calling model.predict() however. Can this be done in Keras or must i take my weights elsewhere?

答:
It is already done in Keras, see e.g. this discussion on the project's page. More on how it works can be found for instance in CS231n: Convolutional Neural Networks for Visual Recognition - AFAIK a very similar implementation is in Keras. Specifically:

(...) Crucially, note that in the predict function we are not dropping
  anymore, but we are performing a scaling of both hidden layer outputs
  by pp. This is important because at test time all neurons see all
  their inputs, so we want the outputs of neurons at test time to be
  identical to their expected outputs at training time.

Title: Keras forward pass with dropout


问:
Does CClientDC guarantee restoring the DC back to its previous state?
I am using a CClientDC object, which serves as a wrapper for functions GetDC and ReleaseDC:

Function GetDC is called from inside the CClientDC constructor

Function ReleaseDC is called from inside the CClientDC destructor

In between, I manipulate the DC (changing pens, brushes, etc).

But I'm pretty sure that the CClientDC object does not restore the DC back to its previous state.

This means I have to make sure of it myself. Is that correct?

Thank you.

答:
Open wingdi.cpp from the MFC source code and look for the implementation of CClientDC:

```<code>CClientDC::~CClientDC()
{
    ASSERT(m_hDC != NULL);
    ::ReleaseDC(m_hWnd, Detach());
}
</code>```

You see that it only calls ReleaseDC, which does not restore the DC to its previous state. There is no way for CClientDC to know which GDI objects you changed.

If you want to save and restore the DC's state, there are special methods for this: CDC::SaveDC and CDC::RestoreDC. These are not called automatically from CDC or CClientDC—you need manually call them yourself.

Or, you can save and restore each individual GDI object that you modify. When you call SelectObject, the original object is returned. You save this, and restore it as you deselect the object you were using.

Body:
Open wingdi.cpp from the MFC source code and look for the implementation of CClientDC:

CClientDC::~CClientDC()
{
    ASSERT(m_hDC != NULL);
    ::ReleaseDC(m_hWnd, Detach());
}

You see that it only calls ReleaseDC, which does not restore the DC to its previous state. There is no way for CClientDC to know which GDI objects you changed.

If you want to save and restore the DC's state, there are special methods for this: CDC::SaveDC and CDC::RestoreDC. These are not called automatically from CDC or CClientDC—you need manually call them yourself.

Or, you can save and restore each individual GDI object that you modify. When you call SelectObject, the original object is returned. You save this, and restore it as you deselect the object you were using.


问:
"trigger insert after" to insert data from another column
here i have table like this

destination:

```<code>  |id_dest | price |
  |     1  |2000   |
  |     2  |100    |
  |     3  |1000   |
</code>```

item:

```<code>   |id_item | weight | id_dest |total(weight*destination.price) |
   |      1 |     3  |      2  |
</code>```

the trigger should make

```<code>   |id_item | weight | id_dest |sum(weight*destination.price) total |
   |      1 |     3  |      2  |300
</code>```

how the query trigger should be?

答:
```<code>CREATE TRIGGER trigger_name
    BEFORE INSERT ON item
    FOR EACH ROW
BEGIN
    UPDATE item
    SET total = (SELECT d.price *, NEW.weight
                 FROM destination d
                 WHERE d.id_dest = NEW.id_dest)
    WHERE id_item = NEW.id_item;
END
</code>```

Body:
here i have table like this

destination:

  |id_dest | price |
  |     1  |2000   |
  |     2  |100    |
  |     3  |1000   |

item:

   |id_item | weight | id_dest |total(weight*destination.price) |
   |      1 |     3  |      2  |

the trigger should make

   |id_item | weight | id_dest |sum(weight*destination.price) total |
   |      1 |     3  |      2  |300

how the query trigger should be?


问:
The correct way to Malloc() space for a pointer to an array of int
Say I have a pointer to an array of int's, like so: int (*x)[3].
What is the correct way to allocate space for such a variable? For example, say I wanted space for 10 items (so that I can store a total of 10 * 3 = 30 values in x):

```<code>/* Is this the correct way? */
x = malloc(sizeof(x) * 10);

/* Will it allow me to do this? */
x[0][0] = 10;
x[0][1] = 20;
x[0][2] = 30;

x[1][0] = 40;
x[1][1] = 50;
x[1][2] = 60;

/* ... etc ... */
</code>```

Or is there some other way to correctly malloc the memory for x (i.e. x = malloc(sizeof(int) * 10) or x = malloc(sizeof(int *) * 10)?

Thanks.

答:
It is also important to not forget to verify the memory of allowance and to not forget to free it after having used it.
However, it is not really the problem. I wonder if the following instructions are valid. Because we could write in the following way "no":</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZEMAX 3
typedef int intTab[SIZEMAX];

int main( void ){

    int i = 0;
    int j = 0;

    intTab *p = NULL;
    extern int errno;

    errno = 0;
    if( NULL == (p = malloc( SIZEMAX * sizeof *p) ) ){
        (void)fprintf( stdout, "(%d)\t:%s\n\t:%s\n", errno,
                      "Erreur alloca mem", strerror(errno) );
        return EXIT_FAILURE;
    }
    memset(p, 0, (SIZEMAX * SIZEMAX * sizeof **p));

    for( i = 0; i < SIZEMAX; i++ ){
        for( j = 0; j < SIZEMAX; j++ )
            (void)fprintf(stdout, "Tab[%d][%d]\t:%d\n",
                          i, j, p[i][j] );
    }

    for( i = 0; i < SIZEMAX; i++ )
        free( p[i] );

    free( p );
    p = NULL;

    return (EXIT_SUCCESS);
}
</code>```

Body:
Say I have a pointer to an array of int's, like so: int (*x)[3].
What is the correct way to allocate space for such a variable? For example, say I wanted space for 10 items (so that I can store a total of 10 * 3 = 30 values in x):

/* Is this the correct way? */
x = malloc(sizeof(x) * 10);

/* Will it allow me to do this? */
x[0][0] = 10;
x[0][1] = 20;
x[0][2] = 30;

x[1][0] = 40;
x[1][1] = 50;
x[1][2] = 60;

/* ... etc ... */

Or is there some other way to correctly malloc the memory for x (i.e. x = malloc(sizeof(int) * 10) or x = malloc(sizeof(int *) * 10)?

Thanks.

Body:
It is also important to not forget to verify the memory of allowance and to not forget to free it after having used it.
However, it is not really the problem. I wonder if the following instructions are valid. Because we could write in the following way "no":

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZEMAX 3
typedef int intTab[SIZEMAX];

int main( void ){

    int i = 0;
    int j = 0;

    intTab *p = NULL;
    extern int errno;

    errno = 0;
    if( NULL == (p = malloc( SIZEMAX * sizeof *p) ) ){
        (void)fprintf( stdout, "(%d)\t:%s\n\t:%s\n", errno,
                      "Erreur alloca mem", strerror(errno) );
        return EXIT_FAILURE;
    }
    memset(p, 0, (SIZEMAX * SIZEMAX * sizeof **p));

    for( i = 0; i < SIZEMAX; i++ ){
        for( j = 0; j < SIZEMAX; j++ )
            (void)fprintf(stdout, "Tab[%d][%d]\t:%d\n",
                          i, j, p[i][j] );
    }

    for( i = 0; i < SIZEMAX; i++ )
        free( p[i] );

    free( p );
    p = NULL;

    return (EXIT_SUCCESS);
}


问:
How do I generate dynamic variable name in my controller and pass the variable to ng-repeat?
How do I generate dynamic variable name in controller and pass the variable to ng-repeat?</p>

答:
You can use math.random, here I'm adding 30 random numbers where each value can have a possibility of being from 0 to 30.</p>

```<code>$scope.randomArrayNumbers = [];

for (i = 0, len = 30; i<len; ++i){

    $scope.randomArrayNumbers.push(Math.floor(Math.random() * 30) + 1);
}

console.log($scope.randomArrayNumbers);
</code>```

Body:
You can use math.random, here I'm adding 30 random numbers where each value can have a possibility of being from 0 to 30.

$scope.randomArrayNumbers = [];

for (i = 0, len = 30; i<len; ++i){

    $scope.randomArrayNumbers.push(Math.floor(Math.random() * 30) + 1);
}

console.log($scope.randomArrayNumbers);


问:
How to absolutely ensure Direct3D9 hook overlay rendering on top
I'm trying to hook IDirect3DDevice9::Present or ::EndScene and render my own overlay (which, for now, is just a simple rectangle) on top of everything else in a D3D9 application, but my overlay seems to be appearing and disappearing quite randomly. The drawing code I'm currently using is:

```<code>typedef struct CUSTOMVERTEX {
    float x, y, z, rwh;
    DWORD color;
};

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

void draw() {
    // the positions are just for testing purposes, so they don't really make sense
    CUSTOMVERTEX vertices[] = {
        { 0, 0, 0, 1.0f, D3DCOLOR_XRGB(255, 255, 255) },
        { 0, cursor_pos.y+500, 0, 1.0f, D3DCOLOR_XRGB(127, 255, 255) },
        { cursor_pos.x, cursor_pos.y, 0, 1.0f, D3DCOLOR_XRGB(255,255, 255) },
        { cursor_pos.x, 600, 0, 1.0f, D3DCOLOR_XRGB(127, 0, 0) }
    };

    if (vBuffer == 0) return;

    VOID* pVoid;

    vBuffer->Lock(0, 0, &pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    vBuffer->Unlock();

    d3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
    d3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

    D3DMATRIX orthographicMatrix;
    D3DMATRIX identityMatrix;

    // MAKE_D3DMATRIX should be equivalent to D3DXMATRIX constructor
    D3DMATRIX viewMatrix = MAKE_D3DMATRIX(
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        ((float)-(get_window_width()/2)), ((float)-(get_window_height()/ 2)), 0, 1
    );
    // MAKE_ORTHO_LH is equivalent to D3DMatrixOrthoLH
    MAKE_ORTHO_LH(&orthographicMatrix, (FLOAT)get_window_width(), (FLOAT)get_window_height(), -1.0, 1.0);

    // and this to D3DMatrixIdentity
    MAKE_IDENTITY(&identityMatrix); // and this to D3DMatrixIdentity

    d3dDevice->SetTransform(D3DTS_PROJECTION, &orthographicMatrix);
    d3dDevice->SetTransform(D3DTS_WORLD, &identityMatrix);
    d3dDevice->SetTransform(D3DTS_VIEW, &viewMatrix);

    d3dDevice->SetRenderState(D3DRS_ZENABLE, false);
    d3dDevice->SetFVF(CUSTOMFVF);
    d3dDevice->SetStreamSource(0, vBuffer, 0, sizeof(CUSTOMVERTEX));
    d3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
    d3dDevice->SetRenderState(D3DRS_ZENABLE, true);
}
</code>```

I can't seem to figure out why this would cause the overlay to pop in and out of existence at seemingly random points in time.. What am I missing?

答:
I found a foolproof method to render my stuff directly to the backbuffer (on CPU):

```<code>IDirect3DSwapChain9 *sc;
if (FAILED(d3dDevice->GetSwapChain(0, &sc))) {
    PRINT("GetSwapChain failed\n");
    return;
}

IDirect3DSurface9 *s;
if (FAILED(sc->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &s))) {
    PRINT("GetBackBuffer failed\n");
    return;
}

D3DLOCKED_RECT r;
if (FAILED(s->LockRect(&r, NULL, D3DLOCK_DONOTWAIT))) {
    PRINT("LockRect failed\n");
    return;
}

// here, find out pixel format and manipulate
// pixel buffer through r->pBits, using r->Pitch accordingly

s->UnlockRect();

s->Release();
sc->Release();
</code>```

Will most probably incur a performance penalty, but in my application this doesn't really make a difference. A more optimal way would be to harness the GPU's hwacceled rendering capabilities, but I currently lack the D3D knowledge to do so.

Body:
I'm trying to hook IDirect3DDevice9::Present or ::EndScene and render my own overlay (which, for now, is just a simple rectangle) on top of everything else in a D3D9 application, but my overlay seems to be appearing and disappearing quite randomly. The drawing code I'm currently using is:

typedef struct CUSTOMVERTEX {
    float x, y, z, rwh;
    DWORD color;
};

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

void draw() {
    // the positions are just for testing purposes, so they don't really make sense
    CUSTOMVERTEX vertices[] = {
        { 0, 0, 0, 1.0f, D3DCOLOR_XRGB(255, 255, 255) },
        { 0, cursor_pos.y+500, 0, 1.0f, D3DCOLOR_XRGB(127, 255, 255) },
        { cursor_pos.x, cursor_pos.y, 0, 1.0f, D3DCOLOR_XRGB(255,255, 255) },
        { cursor_pos.x, 600, 0, 1.0f, D3DCOLOR_XRGB(127, 0, 0) }
    };

    if (vBuffer == 0) return;

    VOID* pVoid;

    vBuffer->Lock(0, 0, &pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    vBuffer->Unlock();

    d3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
    d3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

    D3DMATRIX orthographicMatrix;
    D3DMATRIX identityMatrix;

    // MAKE_D3DMATRIX should be equivalent to D3DXMATRIX constructor
    D3DMATRIX viewMatrix = MAKE_D3DMATRIX(
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        ((float)-(get_window_width()/2)), ((float)-(get_window_height()/ 2)), 0, 1
    );
    // MAKE_ORTHO_LH is equivalent to D3DMatrixOrthoLH
    MAKE_ORTHO_LH(&orthographicMatrix, (FLOAT)get_window_width(), (FLOAT)get_window_height(), -1.0, 1.0);

    // and this to D3DMatrixIdentity
    MAKE_IDENTITY(&identityMatrix); // and this to D3DMatrixIdentity

    d3dDevice->SetTransform(D3DTS_PROJECTION, &orthographicMatrix);
    d3dDevice->SetTransform(D3DTS_WORLD, &identityMatrix);
    d3dDevice->SetTransform(D3DTS_VIEW, &viewMatrix);

    d3dDevice->SetRenderState(D3DRS_ZENABLE, false);
    d3dDevice->SetFVF(CUSTOMFVF);
    d3dDevice->SetStreamSource(0, vBuffer, 0, sizeof(CUSTOMVERTEX));
    d3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2);
    d3dDevice->SetRenderState(D3DRS_ZENABLE, true);
}

I can't seem to figure out why this would cause the overlay to pop in and out of existence at seemingly random points in time.. What am I missing?

Body:
I found a foolproof method to render my stuff directly to the backbuffer (on CPU):

IDirect3DSwapChain9 *sc;
if (FAILED(d3dDevice->GetSwapChain(0, &sc))) {
    PRINT("GetSwapChain failed\n");
    return;
}

IDirect3DSurface9 *s;
if (FAILED(sc->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &s))) {
    PRINT("GetBackBuffer failed\n");
    return;
}

D3DLOCKED_RECT r;
if (FAILED(s->LockRect(&r, NULL, D3DLOCK_DONOTWAIT))) {
    PRINT("LockRect failed\n");
    return;
}

// here, find out pixel format and manipulate
// pixel buffer through r->pBits, using r->Pitch accordingly

s->UnlockRect();

s->Release();
sc->Release();

Will most probably incur a performance penalty, but in my application this doesn't really make a difference. A more optimal way would be to harness the GPU's hwacceled rendering capabilities, but I currently lack the D3D knowledge to do so.


问:
Sticky nav duplicating header background image and making it jump
I am experiencing an issue when I start scrolling down and reach the point when the sticky nav becomes visible, it seems to create a duplicate of the background from header and makes header jump, but it is supposed to move to the next section. Is it CSS or JS related issue?

Please see entire included code:

https://codepen.io/pipistrellonetopier/pen/yXLGjo

CSS code

```<code>.sticky {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.65);
    z-index: 9999;
}

.sticky .main-nav { margin-top: 22px; }

.sticky .main-nav li a:link,
.sticky .main-nav li a:visited {
    padding: 14px 0;
    color: #f0f0f0;
    font-size: 100%;
}

.sticky .logo {
    display: block;
    height: 29px;
    margin: 15px 0;
}
</code>```

Thank you

Peter

答:
Give the following hyperlink display:inline-block and it will stop jumping:

```<code><a href="#" target="_blank" class="app-store-btn"><img src="resources/css/img/app-store-btn.svg" alt="App Store Button"></a>
</code>```

Body:
I am experiencing an issue when I start scrolling down and reach the point when the sticky nav becomes visible, it seems to create a duplicate of the background from header and makes header jump, but it is supposed to move to the next section. Is it CSS or JS related issue?

Please see entire included code:

https://codepen.io/pipistrellonetopier/pen/yXLGjo

CSS code

.sticky {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.65);
    z-index: 9999;
}

.sticky .main-nav { margin-top: 22px; }

.sticky .main-nav li a:link,
.sticky .main-nav li a:visited {
    padding: 14px 0;
    color: #f0f0f0;
    font-size: 100%;
}

.sticky .logo {
    display: block;
    height: 29px;
    margin: 15px 0;
}

Thank you

Peter

Body:
Give the following hyperlink display:inline-block and it will stop jumping:

<a href="#" target="_blank" class="app-store-btn"><img src="resources/css/img/app-store-btn.svg" alt="App Store Button"></a>


问:
Join three entities using spring data
i'm working with spring data in my project herers the entities:

rr:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;
private String model;

@ManyToOne
@JoinColumn( name = "owner" )
private ffperson;
private String constructor;
//getters and setters
</code>```

zaa:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@Column( name = "name" )
private String Name;
//getters and setters
</code>```

gff
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

```<code>@Column( name = "lastname", unique = true )
private String lastName;

@Column( name = "firstname", unique = true )
private String firstName;

@Column( name = "birth_date", unique = true )
private Date   dateOfBirth;
</code>```

gfff:

```<code>@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@ManyToOne
@JoinColumn( name = "dog_id" )
private ffdog;

@ManyToOne
@JoinColumn( name = "person_id" )
private ffperson;
</code>```

i want to write a query with spring data which can fetch all the persons with thier own dogs and cars..Can any body help please

答:
Update your entities like so :

Person

```<code>@Entity
@Table(name = "person")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    Set<Dog> dogs = new HashSet<>();

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    Set<Car> cars = new HashSet<>();

    ...

}
</code>```

Dog

```<code>@Entity
@Table(name="dog")
public class Dog {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

    @Column( name = "name" )
    private String Name;

    @ManyToOne
    private Person person;

    ...

}
</code>```

Car

```<code>@Entity
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private Person person;

    ...

}
</code>```

Now create a PersonRepository and fetch all the person with there dogs and cars

```<code>public interface PersonRepository extends CrudRepository<Person, Long> {

    @Query("select p from Person p join fetch p.dogs join fetch p.cars")
    List<Person> findAll();

}
</code>```

Note: Use Join Fetch to fetch dogs and cars eagerly. Otherwise you may get into n + 1 issue or Lazy fetch issue.

Title: Join three entities using spring data

Body:
i'm working with spring data in my project herers the entities:

rr:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;
private String model;

@ManyToOne
@JoinColumn( name = "owner" )
private ffperson;
private String constructor;
//getters and setters

zaa:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@Column( name = "name" )
private String Name;
//getters and setters

gff
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

@Column( name = "lastname", unique = true )
private String lastName;

@Column( name = "firstname", unique = true )
private String firstName;

@Column( name = "birth_date", unique = true )
private Date   dateOfBirth;

gfff:

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long   id;

@ManyToOne
@JoinColumn( name = "dog_id" )
private ffdog;

@ManyToOne
@JoinColumn( name = "person_id" )
private ffperson;

i want to write a query with spring data which can fetch all the persons with thier own dogs and cars..Can any body help please

Body:
Update your entities like so :

Person

@Entity
@Table(name = "person")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    Set<Dog> dogs = new HashSet<>();

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    Set<Car> cars = new HashSet<>();

    ...

}

Dog

@Entity
@Table(name="dog")
public class Dog {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long   id;

    @Column( name = "name" )
    private String Name;

    @ManyToOne
    private Person person;

    ...

}

Car

@Entity
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private Person person;

    ...

}

Now create a PersonRepository and fetch all the person with there dogs and cars

public interface PersonRepository extends CrudRepository<Person, Long> {

    @Query("select p from Person p join fetch p.dogs join fetch p.cars")
    List<Person> findAll();

}

Note: Use Join Fetch to fetch dogs and cars eagerly. Otherwise you may get into n + 1 issue or Lazy fetch issue.


问:
How to add user to Index Elasticsearch only if one dosen't exist before updating
I'm using elasticsearch , the problem I'm having is sometime the users don't get added to the index , not sure why, only happens sometimes.

1.My set up is when you register to my site a user gets added to the index
2.when a user updates thier profile , the index gets updated with their new info

3.When a user goes to update or edit thier profile, if they weren't added to the index , a error gets thrown.

I want to be able to add them to the index if they aren't added already when they update, in other words if there not already added to the index, then add them before updating

this is how I'm updating

```<code>$client = Clientbuilder::create()->build();
    $response = $client->update([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'doc' => [
                $field => $data,
            ],
        ],

    ]);
}
</code>```

then

```<code>if ($request->has('name')) {
        $user->name = strip_tags($request->input('name'));
        $user->save();

        //update elasticsearch users index
        $user->elasticupdate('name',$user->name);

    }
</code>```

I'm added them to index like so

```<code>$client = Clientbuilder::create()->build();
        $response = $client->index([
            'index' => 'users',
            'type' => 'user',
            'id' => $user->id,
            'body' => [
                'username' => $user->username,
                'name' => $user->name,
                'profession' =>$user->getProfession(),
                'secondary_profession' =>$user->getSecondaryProfession(),
                'genre' => $user->getUserGenre(),
                'subgenre' => $user->getUserSubGenre(),
                'city' => $user->getCity(),
                'profilepic' => 'n026qso2xxztaphbwwey.png', //Default pics
                'backgroundpic' => 'backgrounddefaultpms_oa9mee.png', //Default pics
                // 'profilepic' => $user->getProfilePic(),
                // 'backbroundpic' => $user->getBackroundPic(),
                'country' => $user->country,
                'country_fips_code' => $user->country_fips_code,
                'state' => $user->getState(),
                //'affiliations' => $user->getAffiliations(),
                'affiliation_one' => ' ',
                'affiliation_two' => ' ',
                'affiliation_three' => ' ',
                'affiliation_four' => ' ',
                'affiliation_five' => ' ',
                'credential_one' => ' ',
                'credential_two' => ' ',
                'credential_three' => ' ',
                'credential_four' => ' ',
                'credential_five' => ' ',
                // 'countryAbr' => $countryAbr,
                // 'stateAbr' => $stateAbr,
                'cityGeonameId' => $user->geoname_id,
                'latlong' => [$origin],
            ],

        ]);
</code>```

I thought about just running this everything they update their profile, but what if some of those fields that i have set as defaults are filled with actual data, example if a user was actually added to the index already and everything worked, then this would be overwriting it, any ideas

答:
You should set op_type field to create value like this:

```<code>$client = Clientbuilder::create()->build();
$response = $client->index([
    'index' => 'users',
    'type' => 'user',
    'id' => $user->id,
    'op_type' => 'create',
    'body' => [
        'username' => $user->username,
        'name' => $user->name,
        'profession' =>$user->getProfession(),
        'secondary_profession' =>$user->getSecondaryProfession(),
        'genre' => $user->getUserGenre(),
        'subgenre' => $user->getUserSubGenre(),
        'city' => $user->getCity(),
        'profilepic' => 'n026qso2xxztaphbwwey.png', //Default pics
        'backgroundpic' => 'backgrounddefaultpms_oa9mee.png', //Default pics
        // 'profilepic' => $user->getProfilePic(),
        // 'backbroundpic' => $user->getBackroundPic(),
        'country' => $user->country,
        'country_fips_code' => $user->country_fips_code,
        'state' => $user->getState(),
        //'affiliations' => $user->getAffiliations(),
        'affiliation_one' => ' ',
        'affiliation_two' => ' ',
        'affiliation_three' => ' ',
        'affiliation_four' => ' ',
        'affiliation_five' => ' ',
        'credential_one' => ' ',
        'credential_two' => ' ',
        'credential_three' => ' ',
        'credential_four' => ' ',
        'credential_five' => ' ',
        // 'countryAbr' => $countryAbr,
        // 'stateAbr' => $stateAbr,
        'cityGeonameId' => $user->geoname_id,
        'latlong' => [$origin],
    ],

]);
</code>```

In this case, if user with the same id already exist, request will return an error, and you won't override an existing one. Take look at "Versioning" section here https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html

Body:
I'm using elasticsearch , the problem I'm having is sometime the users don't get added to the index , not sure why, only happens sometimes.

1.My set up is when you register to my site a user gets added to the index
2.when a user updates thier profile , the index gets updated with their new info

3.When a user goes to update or edit thier profile, if they weren't added to the index , a error gets thrown.

I want to be able to add them to the index if they aren't added already when they update, in other words if there not already added to the index, then add them before updating

this is how I'm updating

$client = Clientbuilder::create()->build();
    $response = $client->update([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'doc' => [
                $field => $data,
            ],
        ],

    ]);
}

then

if ($request->has('name')) {
        $user->name = strip_tags($request->input('name'));
        $user->save();

        //update elasticsearch users index
        $user->elasticupdate('name',$user->name);

    }

I'm added them to index like so

$client = Clientbuilder::create()->build();
        $response = $client->index([
            'index' => 'users',
            'type' => 'user',
            'id' => $user->id,
            'body' => [
                'username' => $user->username,
                'name' => $user->name,
                'profession' =>$user->getProfession(),
                'secondary_profession' =>$user->getSecondaryProfession(),
                'genre' => $user->getUserGenre(),
                'subgenre' => $user->getUserSubGenre(),
                'city' => $user->getCity(),
                'profilepic' => 'n026qso2xxztaphbwwey.png', //Default pics
                'backgroundpic' => 'backgrounddefaultpms_oa9mee.png', //Default pics
                // 'profilepic' => $user->getProfilePic(),
                // 'backbroundpic' => $user->getBackroundPic(),
                'country' => $user->country,
                'country_fips_code' => $user->country_fips_code,
                'state' => $user->getState(),
                //'affiliations' => $user->getAffiliations(),
                'affiliation_one' => ' ',
                'affiliation_two' => ' ',
                'affiliation_three' => ' ',
                'affiliation_four' => ' ',
                'affiliation_five' => ' ',
                'credential_one' => ' ',
                'credential_two' => ' ',
                'credential_three' => ' ',
                'credential_four' => ' ',
                'credential_five' => ' ',
                // 'countryAbr' => $countryAbr,
                // 'stateAbr' => $stateAbr,
                'cityGeonameId' => $user->geoname_id,
                'latlong' => [$origin],
            ],

        ]);

I thought about just running this everything they update their profile, but what if some of those fields that i have set as defaults are filled with actual data, example if a user was actually added to the index already and everything worked, then this would be overwriting it, any ideas

Body:
You should set op_type field to create value like this:

$client = Clientbuilder::create()->build();
$response = $client->index([
    'index' => 'users',
    'type' => 'user',
    'id' => $user->id,
    'op_type' => 'create',
    'body' => [
        'username' => $user->username,
        'name' => $user->name,
        'profession' =>$user->getProfession(),
        'secondary_profession' =>$user->getSecondaryProfession(),
        'genre' => $user->getUserGenre(),
        'subgenre' => $user->getUserSubGenre(),
        'city' => $user->getCity(),
        'profilepic' => 'n026qso2xxztaphbwwey.png', //Default pics
        'backgroundpic' => 'backgrounddefaultpms_oa9mee.png', //Default pics
        // 'profilepic' => $user->getProfilePic(),
        // 'backbroundpic' => $user->getBackroundPic(),
        'country' => $user->country,
        'country_fips_code' => $user->country_fips_code,
        'state' => $user->getState(),
        //'affiliations' => $user->getAffiliations(),
        'affiliation_one' => ' ',
        'affiliation_two' => ' ',
        'affiliation_three' => ' ',
        'affiliation_four' => ' ',
        'affiliation_five' => ' ',
        'credential_one' => ' ',
        'credential_two' => ' ',
        'credential_three' => ' ',
        'credential_four' => ' ',
        'credential_five' => ' ',
        // 'countryAbr' => $countryAbr,
        // 'stateAbr' => $stateAbr,
        'cityGeonameId' => $user->geoname_id,
        'latlong' => [$origin],
    ],

]);

In this case, if user with the same id already exist, request will return an error, and you won't override an existing one. Take look at "Versioning" section here https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html


问:
c++ win32 api notify mouse inside button area
I've a Button made using Win32Api that I want to be able to notify whenever the user put the mouse inside the button rectangle.
I noticed that when user does that the WM_NOTIFY is called but I don't know which flag to use for ensure that the user has the mouse inside it's area.

Here is my button:

```<code>HWND Button = CreateWindow("BUTTON", "Test",
        WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
        20, 240, 120, 20,
        hwnd, (HMENU)101, NULL, NULL);
</code>```

And my WndProc:

```<code>LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    switch (msg)
    {
    case WM_NOTIFY:
    {
        //??? Here is where I want to do it
    }
    case WM_CREATE: //On Window Create
    {
        wHWND = hwnd;
        if (onCreate != NULL)
            onCreate(hwnd);
        break;
    }
    case WM_COMMAND: //Command execution
    {
        //...
        break;
    }
    case WM_DESTROY: //Form Destroyed
    {
        if (onDestroy != NULL)
            onDestroy(hwnd);
        PostQuitMessage(0);
        break;
    }
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}
</code>```

I don't know if I'm in the right path using WM_NOTIFY or not, maybe there is an easier way to do that. Thank you!

答:
Try catching the WM_SETFOCUS message instead if you want a generic way of tracking focus.

BN_SETFOCUS is sent as WM_COMMAND in the upper 16 bits of WPARAM (HIWORD):

The parent window of the button receives this notification code through the WM_COMMAND message

If you are not talking about focus but just the mouse position then you can use ChildWindowFromPointEx or RealChildWindowFromPoint and a timer.

Body:
I've a Button made using Win32Api that I want to be able to notify whenever the user put the mouse inside the button rectangle.
I noticed that when user does that the WM_NOTIFY is called but I don't know which flag to use for ensure that the user has the mouse inside it's area.

Here is my button:

HWND Button = CreateWindow("BUTTON", "Test",
        WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
        20, 240, 120, 20,
        hwnd, (HMENU)101, NULL, NULL);

And my WndProc:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    switch (msg)
    {
    case WM_NOTIFY:
    {
        //??? Here is where I want to do it
    }
    case WM_CREATE: //On Window Create
    {
        wHWND = hwnd;
        if (onCreate != NULL)
            onCreate(hwnd);
        break;
    }
    case WM_COMMAND: //Command execution
    {
        //...
        break;
    }
    case WM_DESTROY: //Form Destroyed
    {
        if (onDestroy != NULL)
            onDestroy(hwnd);
        PostQuitMessage(0);
        break;
    }
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

I don't know if I'm in the right path using WM_NOTIFY or not, maybe there is an easier way to do that. Thank you!


问:
Get keys of pandas.Series.value_counts
I use pandas.Series.value_counts to count gender of users. But I also need to get the keys of a result to draw a plot and use keys as a label of the plot.

For example the result of data.gender.value_counts() is:

```<code>female     6700
male       6194
brand      5942
unknown    1117
</code>```

And I need to get a list ['female', 'male', 'brand', 'unknown'] as well and keep the order.

How can I do that?

答:
Demo:

```<code>In [165]: s
Out[165]:
female     6700
male       6194
brand      5942
unknown    1117
Name: value_counts, dtype: int64

In [166]: s.index.tolist()
Out[166]: ['female', 'male', 'brand', 'unknown']
</code>```

Plot:

```<code>In [169]: s.plot.bar(rot=0)
Out[169]: <matplotlib.axes._subplots.AxesSubplot at 0xd659da0>
</code>```

Result:

Title: Get keys of pandas.Series.value_counts

Body:
I use pandas.Series.value_counts to count gender of users. But I also need to get the keys of a result to draw a plot and use keys as a label of the plot.

For example the result of data.gender.value_counts() is:

female     6700
male       6194
brand      5942
unknown    1117

And I need to get a list ['female', 'male', 'brand', 'unknown'] as well and keep the order.

How can I do that?

Body:
Demo:

In [165]: s
Out[165]:
female     6700
male       6194
brand      5942
unknown    1117
Name: value_counts, dtype: int64

In [166]: s.index.tolist()
Out[166]: ['female', 'male', 'brand', 'unknown']

Plot:

In [169]: s.plot.bar(rot=0)
Out[169]: <matplotlib.axes._subplots.AxesSubplot at 0xd659da0>

Result:


问:
What I found so far the blinking text isnt working
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
#google-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
}
#Mail-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
text-decoration:blink;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
</tr>
</table>
<a id="google-link" href="http://www.google.com">Visit Google!</a>
<a id="Mail-link" href="mailto:randywhite30@neb.rr.com"> Contact Me!</a>
</body>
</html>
</code>```

答:
You will find that most HTML clients will not display blinking text, as it's highly visually intrusive.

Even if they did support it, I would strongly encourage you not to avail yourself of the capability for the above reason.

Body:
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

Visit Google!
 Contact Me!


问:
Can't get the browser to read my CSS
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="intro">
   <p>writing</p>
   <p>writing</p>
</div></code>```

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

答:
I registered just now to answer your question,you forgot to add this code in your CSS:

.intro{border-style:solid;}```

border-style is default hidden,you forgot that so you can't see the border.

Title: Can't get the browser to read my CSS

Body:
Can't work out why this code is not working:

CSS then corresponding HTML:

.intro {
  border: 5px
  border-color: rgb(0,0,255);
  text-align: center;
}

writing

writing

No variation seems to work, and I have checked this site, W3C, and seem to be writing the code correctly in the CSS file, but it just is not translating to the browser (Chrome).

Body:
I registered just now to answer your question,you forgot to add this code in your CSS:

.intro{border-style:solid;}

border-style is default hidden,you forgot that so you can't see the border.


问:
Links not working in Full Page Navigation menu for a single page website
The links on this page are not working even though li.a tags target to proper section IDs.

HTML:

```<code><header>
  <a href="#0" class="nav_icon"><i></i></a>
</header>

<nav id="main_nav">
  <ul>
    <li><a href="#red">Red</a></li>
    <li><a href="#green">Green</a></li>
    <li><a href="#blue">Blue</a></li>
    <li><a href="#yellow">Yellow</a></li>
  </ul>
  <a href="#0" class="nav_icon close"><i></i></a>
</nav>

<div id="wrapper">
  <section id="red">Red</section>
  <section id="green">Green</section>
  <section id="blue">Blue</section>
  <section id="yellow">Yellow</section>
</div>
</code>```

Am I missing something here? Codepen:
https://codepen.io/soumyajitn/pen/BZaGmv

答:
Since your script return false after clicking a link, it also cancel the links default behavior, so if you comment out that in your script, it will work

```<code>$( "#main_nav ul li a" ).click(function() {
  $( "#wrapper" ).toggleClass( "hide" );
  $( "#main_nav" ).toggleClass( "show" );
  $('.nav_icon').toggleClass('active');

  //return false;                            comment out this line

});
</code>```

Updated codepen

Body:
The links on this page are not working even though li.a tags target to proper section IDs.

HTML:

Red

Green

Blue

Yellow

Red

Green

Blue

Yellow

Am I missing something here? Codepen:
https://codepen.io/soumyajitn/pen/BZaGmv

Body:
Since your script return false after clicking a link, it also cancel the links default behavior, so if you comment out that in your script, it will work

$( "#main_nav ul li a" ).click(function() {
  $( "#wrapper" ).toggleClass( "hide" );
  $( "#main_nav" ).toggleClass( "show" );
  $('.nav_icon').toggleClass('active');

  //return false;                            comment out this line

});

Updated codepen


问:
CreateFile fails with error ERROR_SHARING_VIOLATION
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

```<code>void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}
</code>```

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE

答:
I mean no disrespect, but I just shot myself in the foot last week on something similar:

Are you sure nothing else has the file open in a way which would prevent the access being requested?

In my case, I had used ctrl-Z in a Linux command window to suspend a program which created a socket connection, then I went to bed.  Next morning after a few simple changes, I kept getting "unable to create socket:  service in use" messages when running the program.  Sadly, I spent hours debugging what I had broken.  Once I killed the offending suspended process, it worked fine.

Body:
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE


问:
Jquery select image then get length undefined
I am trying to make a upload image system using jquery. But I am getting

Uncaught TypeError: Cannot read property 'length' of undefined

The codes I got the error are below. When I click #imageInput button and then I select an image after the clicked ok button I am getting Can not read property 'length' of undefined error from developer console. What I am doing wrong here anyone can help me in this regard?

HTML structure

```<code><li id="box_devstud" class="tab active-chat" client="devstud" style="bottom: 0px; right: 230px;"></li>
<input id="imageInput" type="file" name="file" onchange="uploadimage('devstud');">
<input id="to_id" name="to_id" value="11" type="hidden">
<input id="to_uname" name="to_uname" value="devstud" type="hidden">
<input id="from_uname" name="from_uname" value="Beenny" type="hidden">
</code>```

my javascript code here

```<code>function uploadphoto(thisuser) {

        var file_name=$("#box_"+thisuser+" #imageInput").val();
        var fileName = $("#box_"+thisuser+" #imageInput").val();
        var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

        var toid = $("#box_"+thisuser+" #to_id").val();
        var tun = $("#box_"+thisuser+" #to_uname").val();
        var fun = $("#box_"+thisuser+" #from_uname").val();

        var siteurl = 'requests/postprog.php?toid='+toid+'&tun='+tun+'&fun='+fun;
        var file_data=$("#box_"+thisuser+" #imageInput").prop("files")[0];
        var form_data=new FormData();
        form_data.append("file",file_data);

        $('#loadmsg_'+thisuser).show();      // Loader show

        $.ajax({
            type:"POST",
            url: siteurl,
            cache:false,
            contentType:false,
            processData:false,
            data:form_data,
            success:function(data){
                //alert(data);
                $.each(data.items, function(i,item){
                    if (item)   { // fix strange ie bug
                        chatboxtitle = item.chatboxtitle;
                        filename = item.filename;
                        path = item.path;

                        $('#loadmsg_'+chatboxtitle).hide();     // Loader hide

                        var message_content = "<a url='"+path+"' onclick='trigq(this)'><img src='"+filename+"' style='max-width:156px;min-height:100px;padding: 4px 0 4px 0; border-radius: 7px;cursor: pointer;'/></a>";
                        $("#box_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage direct-chat-msg right"><div class="direct-chat-info clearfix"><span class="direct-chat-name pull-right">'+item.sender+'</span></div><img class="direct-chat-img" src="storage/user_image/'+img+'" alt="message user image"><span class="direct-chat-text">'+message_content+'</span></div>');
                    }

                    setTimeout(scrollDown(chatboxtitle), 5000);
                });
            },
            error:function(){
                //Do something
            }
        });
    }
</code>```

答:
In your fileName variable, You've call your DOM element like this

```<code>function uploadphoto(thisuser) {
    var fileName = $("#box_"+thisuser+" #imageInput").val();
    // Rest of code ....
}
</code>```

From your given html code snippet, You've place your #imageInput input file outside your
 tag(s).

Kindly place your input file inside li tag so that you can call your DOM element now

```<code><li id="box_devstud" class="tab active-chat" client="devstud" style="bottom: 0px; right: 230px;">
    <input id="imageInput" type="file" name="file" onchange="uploadimage('devstud');">
    <input id="to_id" name="to_id" value="11" type="hidden">
    <input id="to_uname" name="to_uname" value="devstud" type="hidden">
    <input id="from_uname" name="from_uname" value="Beenny" type="hidden">
</li>
</code>```

Body:
I am trying to make a upload image system using jquery. But I am getting

Uncaught TypeError: Cannot read property 'length' of undefined

The codes I got the error are below. When I click #imageInput button and then I select an image after the clicked ok button I am getting Can not read property 'length' of undefined error from developer console. What I am doing wrong here anyone can help me in this regard?

HTML structure

<input id="imageInput" type="file" name="file" onchange="uploadimage('devstud');">
<input id="to_id" name="to_id" value="11" type="hidden">
<input id="to_uname" name="to_uname" value="devstud" type="hidden">
<input id="from_uname" name="from_uname" value="Beenny" type="hidden">

my javascript code here

function uploadphoto(thisuser) {

        var file_name=$("#box_"+thisuser+" #imageInput").val();
        var fileName = $("#box_"+thisuser+" #imageInput").val();
        var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

        var toid = $("#box_"+thisuser+" #to_id").val();
        var tun = $("#box_"+thisuser+" #to_uname").val();
        var fun = $("#box_"+thisuser+" #from_uname").val();

        var siteurl = 'requests/postprog.php?toid='+toid+'&tun='+tun+'&fun='+fun;
        var file_data=$("#box_"+thisuser+" #imageInput").prop("files")[0];
        var form_data=new FormData();
        form_data.append("file",file_data);

        $('#loadmsg_'+thisuser).show();      // Loader show

        $.ajax({
            type:"POST",
            url: siteurl,
            cache:false,
            contentType:false,
            processData:false,
            data:form_data,
            success:function(data){
                //alert(data);
                $.each(data.items, function(i,item){
                    if (item)   { // fix strange ie bug
                        chatboxtitle = item.chatboxtitle;
                        filename = item.filename;
                        path = item.path;

                        $('#loadmsg_'+chatboxtitle).hide();     // Loader hide

                        var message_content = "";
                        $("#box_"+chatboxtitle+" .chatboxcontent").append('

'+item.sender+'
'+message_content+'
');
                    }

                    setTimeout(scrollDown(chatboxtitle), 5000);
                });
            },
            error:function(){
                //Do something
            }
        });
    }

Body:
In your fileName variable, You've call your DOM element like this

function uploadphoto(thisuser) {
    var fileName = $("#box_"+thisuser+" #imageInput").val();
    // Rest of code ....
}

From your given html code snippet, You've place your #imageInput input file outside your <li> tag(s).

Kindly place your input file inside li tag so that you can call your DOM element now

<li id="box_devstud" class="tab active-chat" client="devstud" style="bottom: 0px; right: 230px;">
    <input id="imageInput" type="file" name="file" onchange="uploadimage('devstud');">
    <input id="to_id" name="to_id" value="11" type="hidden">
    <input id="to_uname" name="to_uname" value="devstud" type="hidden">
    <input id="from_uname" name="from_uname" value="Beenny" type="hidden">
</li>


问:
Open a pop-up window after selecting files in QFileDialog - Python
I have a main window with upload button, after clicking the upload button a QFileDialog opens to upload the files.
How can I enable a pop-up to appear after selecting the files and clicking open button in the upload dialog?

I tried this one but it closes the program

```<code> def App(Qwidget, self):
    w = QWidget()
    w.resize(320, 240)
    QFileDialog.getOpenFileNames(w, 'Open File', '/')
    w.show()
    self.EWindow = QtWidgets.QWidget()
    self.ui = Ui_Form()
    self.ui.setupUi(self.EWindow)
    self.EWindow.show()
</code>```

答:
Using QPushButton clicked() event

```<code>button = QPushButton('Open', self)
button.clicked.connect(self.on_click)
</code>```

calling QFileDialog and QMessageBox from QPushButton clicked() event

```<code>def on_click(self):
    fileName, _ = QFileDialog.getOpenFileName(self,"Open File", "","All Files (*);;Python Files (*.py)")
    if fileName:
        print(fileName)
    buttonReply = QMessageBox.question(self, 'Message Box', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
    if buttonReply == QMessageBox.Yes:
        print('Yes clicked.')
    else:
        print('No clicked.')
</code>```

Body:
I have a main window with upload button, after clicking the upload button a QFileDialog opens to upload the files.
How can I enable a pop-up to appear after selecting the files and clicking open button in the upload dialog?

I tried this one but it closes the program

 def App(Qwidget, self):
    w = QWidget()
    w.resize(320, 240)
    QFileDialog.getOpenFileNames(w, 'Open File', '/')
    w.show()
    self.EWindow = QtWidgets.QWidget()
    self.ui = Ui_Form()
    self.ui.setupUi(self.EWindow)
    self.EWindow.show()

Body:
Using QPushButton clicked() event

button = QPushButton('Open', self)
button.clicked.connect(self.on_click)

calling QFileDialog and QMessageBox from QPushButton clicked() event

def on_click(self):
    fileName, _ = QFileDialog.getOpenFileName(self,"Open File", "","All Files (*);;Python Files (*.py)")
    if fileName:
        print(fileName)
    buttonReply = QMessageBox.question(self, 'Message Box', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
    if buttonReply == QMessageBox.Yes:
        print('Yes clicked.')
    else:
        print('No clicked.')


问:
Dynamic fields in FieldArray
I've implemented redux-form in my whole app and it's going great. But I'm currently confused on how I would tackle the following case as I can't seem to find the best way to do this.

Case

I'm using a select component in my Field which is working as expected. This Field holds an array of values such as ['NL', 'EN'] and is has a name of languages.

Issue

Based on the values of the languages field, I need to create a FieldArray. How would I programatically create these fields without changing other Fields.

Thoughts

I first thought that I just would use initialize every time the languages field changes but I can't as there will already be information typed in the FieldArray or other Fields of the form.

答: I've switched to the approach of using a FormSection and just using languages.map(language => <Field ... />) inside it. This works fine :)

Title: Dynamic fields in FieldArray


问:
How to send a status 200 answering to a HTTPS POST in python
I am using Flask to create an application that receives some data from a server with an HTTPS POST and process its data. Once i receive the message from the server I need to send a "status = 200" so the server will know that i got the info, and stop re-sending me the information.

Do i have to send a HTTPS GET? It is not really a get as the only thing i need is to notify the server i got the message...

How can i do it in python? I need to do it after processing the data i receive but without return.

```<code>app = Flask(__name__)
@app.route('/webhook', methods=['POST','GET'])``
def webhook():

req = request.form
xml = req['data']
#HOW DO I SEND A CODE 200 NOW???
info = ET.fromstring(xml)
print info[0].text
print info[1].text
print info[2].text
print info[3].text
</code>```

Thanks!

答:
If you want to be sure about the response code, you can send an empty response and only specify the response code like so

```<code>return '', 200
</code>```

The complete answer can be found at Return HTTP status code 201 in flask

UPDATE FOR UPDATED QUESTION:

You could use a Thread for that.

```<code>import threading

app = Flask(__name__)
@app.route('/webhook', methods=['POST','GET'])``

def worker(xml):
  info = ET.fromstring(xml)

  print info[0].text
  print info[1].text
  print info[2].text
  print info[3].text

  return

def webhook():
  req = request.form
  xml = req['data']

  # This executes in background
  t = threading.Thread(target=worker, args=(xml,))
  t.start()

  # So that you can return before worker is done
  return '', 200
</code>```

Body:
I am using Flask to create an application that receives some data from a server with an HTTPS POST and process its data. Once i receive the message from the server I need to send a "status = 200" so the server will know that i got the info, and stop re-sending me the information.

Do i have to send a HTTPS GET? It is not really a get as the only thing i need is to notify the server i got the message...

How can i do it in python? I need to do it after processing the data i receive but without return.

app = Flask(__name__)
@app.route('/webhook', methods=['POST','GET'])``
def webhook():

req = request.form
xml = req['data']
#HOW DO I SEND A CODE 200 NOW???
info = ET.fromstring(xml)
print info[0].text
print info[1].text
print info[2].text
print info[3].text

Thanks!

Body:
If you want to be sure about the response code, you can send an empty response and only specify the response code like so

return '', 200

The complete answer can be found at Return HTTP status code 201 in flask

UPDATE FOR UPDATED QUESTION:

You could use a Thread for that.

import threading

app = Flask(__name__)
@app.route('/webhook', methods=['POST','GET'])``

def worker(xml):
  info = ET.fromstring(xml)

  print info[0].text
  print info[1].text
  print info[2].text
  print info[3].text

  return

def webhook():
  req = request.form
  xml = req['data']

  # This executes in background
  t = threading.Thread(target=worker, args=(xml,))
  t.start()

  # So that you can return before worker is done
  return '', 200


问:
Why is this word boundary regex not matching
This is the sample text:

Item 1 : 1. A method of operating.

This matches 1.:

```<code>\b1\.
</code>```

But this does not match 1.:

```<code>\b1\.\b
</code>```

I need to have an exact match for 1. I am testing it here.

答:
. is not a word character. \b is checking word boundaries, i.e. boundaries between word and characters not considered to be part of words. Therefore you cannot expect . to be inside the "word" 1. because these two characters do not form a word.

Quick reference document describes \b as:

The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character.

And \w is described as:

Matches any word character.

If you check what a Word character is, you will find it includes Unicode classes Ll [Letter, Lowercase];
Lu [Letter, Uppercase];
Lt [Letter, Titlecase];
Lo [Letter, Other];
Lm [Letter, Modifier];
Mn [Mark, Nonspacing];
Nd [Number, Decimal Digit] and
Pc [Punctuation, Connector].

But . has Unicode class Po [Punctuation, Other] which is not listed above.

So if you expect \b to match a word boundary in 1., it is right between 1 and .. This answers your question Why.

Note: .NET regex expressions should be preferably tested on testing sites dedicated to them like for example Regex Storm. If you test your regex using PCRE regex flavour (like on the site you linked), you can get different results from .NET.

Body:
This is the sample text:

Item 1 : 1. A method of operating.

This matches 1.:

\b1\.

But this does not match 1.:

\b1\.\b

I need to have an exact match for 1. I am testing it here.


问:
Lodash vs JavaScript Built In for map,reduce,filter
I was wondering whether it is better to include Lodash for these 3 functions [map(),reduce(),filter()] or just to use the ES6 versions of them.

I prefer using the Lodash functions, it's a little simpler for my use case. However, I am aware there is probably a performance benefit to using the ES6 functions.

Also was wondering whether Lodash is more backwards compatible that ES6?

Suggestions on how to test performance of my implementations?

Suggestions of whether to continue using Lodash or to use ES6?

答:
Lodash is a nice tool to use if you have more complex algorithms, its more readable etc.. It has built in functions for a lot of tasks which are not so easy to implement in native ES6, it is really handy and can save you from a lot of headache. But for simple tasks like you mentioned I would use ES6. As @Mayday said in a comment it is the future.

If you use Lodash only for these tasks I suggest you to get rid of it, that means you have one less dependency which is almost always a good thing (users don't have to download the lodash, because native map,reduce,filter are implemented in the browser). Yes nowadays you may need to use a bundler, or translator to make your code es5 compatible, but that is a dev-dependency which won't be there in production, and also it will be supported in a while and you won't even need these extra steps.

For testing your code see these answers:
How do you performance test JavaScript code?

Also Google Chrome and Firefox have really good profilers: https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference#record

If you want to compare native and lodash functions I suggest you to run the same functions implemented in both a few million times and measure the time between start and end (console.time https://developer.mozilla.org/en-US/docs/Web/API/Console/time), I think you should also make a few measurements of them, since the result can depend on a lot of other things. I think I would also avoid for loops, since they are highly optimized and could distort the results.

EDIT

As @TamasHegedus pointed out in a comment, these functions are in the ES5 specification so you don't even need a bundler, or a translator, it will work natively.