问:
T-SQL: How Can I JOIN Each Row Differently
How can I join two tables together that have dissimilar fields and require different rules to JOIN? An  example:

tb_references               tb_parts
==================          ====================
f_type  |  f_item           f_partID  |  f_partnumber
------------------          --------------------
YY      |  ABC123           1         |  YYABC123
YY      |  ABC124           2         |  YYABC124
NN      |  000111           3         |  YY000111
NN      |  000112           4         |  YY000112
```

<p>To JOIN these, I would normally perform a query like the following</p>

```SELECT *
FROM tb_references
JOIN tb_parts
ON f_type + f_item = f_partnumber
```

<p>However, you can see where the <code>f_type</code> of the <code>NN</code> won't match, so my results would look like the following:</p>

<pre class="lang-none prettyprint-override"><code>RESULTS
=============================================
f_type  | f_item  | f_partID  | f_partnumber
---------------------------------------------
YY      | ABC123  | 1         | YYABC123
YY      | ABC124  | 2         | YYABC124
</code>```

How can I specify an IF statement in the query to allow me to match the broken NN parts as well?

Something like this logic, but I can't figure out how to accomplish it though I've tried various methods without success:

```<code>SELECT *
FROM tb_references
JOIN tb_parts
ON
 IF (
    f_type = 'NN' THEN
      'YY' + f_item = f_partnumber
    )
 ELSE (
    f_type + f_item = f_partnumber
 )
</code>```

My optimal results, then, would be like this:

RESULTS
=============================================
f_type  | f_item  | f_partID  | f_partnumber
---------------------------------------------
YY      | ABC123  | 1         | YYABC123
YY      | ABC124  | 2         | YYABC124
NN      | 000111  | 3         | YY000111
NN      | 000112  | 4         | YY000112
```

I'm open, of course, to other solutions that don't utilize an IF in the JOIN - it is just my way to try to describe the problem I'm facing. Unfortunately, I can't simply update the "f_type" field because it's a third-party database that we cannot control nor edit.

答:
You can use a CASE statement.  Could be a pain performance wise, though:</p>

```<code>SELECT *
FROM tb_references
JOIN tb_parts
ON CASE WHEN f_type='yy' THEN 'zz' ELSE f_type END  + f_item = f_partnumber
</code>```

Body:
How can I join two tables together that have dissimilar fields and require different rules to JOIN? An  example:

tb_references               tb_parts
==================          ====================
f_type  |  f_item           f_partID  |  f_partnumber
------------------          --------------------
YY      |  ABC123           1         |  YYABC123
YY      |  ABC124           2         |  YYABC124
NN      |  000111           3         |  YY000111
NN      |  000112           4         |  YY000112

To JOIN these, I would normally perform a query like the following

SELECT *
FROM tb_references
JOIN tb_parts
ON f_type + f_item = f_partnumber

However, you can see where the f_type of the NN won't match, so my results would look like the following:

RESULTS
=============================================
f_type  | f_item  | f_partID  | f_partnumber
---------------------------------------------
YY      | ABC123  | 1         | YYABC123
YY      | ABC124  | 2         | YYABC124

How can I specify an IF statement in the query to allow me to match the broken NN parts as well?

Something like this logic, but I can't figure out how to accomplish it though I've tried various methods without success:

SELECT *
FROM tb_references
JOIN tb_parts
ON
 IF (
    f_type = 'NN' THEN
      'YY' + f_item = f_partnumber
    )
 ELSE (
    f_type + f_item = f_partnumber
 )

My optimal results, then, would be like this:

RESULTS
=============================================
f_type  | f_item  | f_partID  | f_partnumber
---------------------------------------------
YY      | ABC123  | 1         | YYABC123
YY      | ABC124  | 2         | YYABC124
NN      | 000111  | 3         | YY000111
NN      | 000112  | 4         | YY000112

I'm open, of course, to other solutions that don't utilize an IF in the JOIN - it is just my way to try to describe the problem I'm facing. Unfortunately, I can't simply update the "f_type" field because it's a third-party database that we cannot control nor edit.

Body:
You can use a CASE statement.  Could be a pain performance wise, though:

SELECT *
FROM tb_references
JOIN tb_parts
ON CASE WHEN f_type='yy' THEN 'zz' ELSE f_type END  + f_item = f_partnumber


来源: stackexchange

问:
Identify Parts of the car based on arrow markings
Please excuse me for not posting any code, as I don't think I have reached far enough to be relevant for my question.

I am working on a solution that need to identify the parts of a vehicle being pointed by the customer drawing and extract the Text and the part its referring to as shown in an example below.

I am really new to ML or AI technologies as a result I was looking at using the Azure customvision.ai which allows me to train the model using a bunch of images and object identification and has a nice REST API's to work with. This is somewhat working as I am able to pass the image and it is able to identify the parts of the cars visible on that image.

However I am unable to understand how to how to identify that 9. BXCU12 is actually pointing to Bonnet.

Can someone please help me by pointing to any example or a suitable solution approach for me to solve this problem.

答:
If  I understand correctly, you already can identify parts from your recognition network and also text, and the link between them is given by the arrows in the image that you don't know how to locate. So, the remaining problem here is detecting the arrows and their end-points.

I can think of two solutions right now:

1) Use template matching to identify your arrows. The problem in your case though (from your example image) seems to be that your arrow heads have the same scale but have different lenghts. So, I'd suggest just using the head of the arrow + a very short tail as your template. Then you can rotate this small template N times, obtain N templates and use something like what opencv provides in term of template matching.

2) Train a small convolutional neural network to recognize the arrows. You only want to recognize arrows, so it's rather easy to create a small dataset of rotated arrows of different scales and train the network on them. Note that you should probably be able to add this network as an additional, very shallow head to your recognition network (you'll need to refine jointly though), so the overhead would be minimal.

Hope that helps.

ContentLicense: CC BY-SA 4.0


问:
jQuery: binding a single event listener that can handle events of its children
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

```<code><ul class="myList">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
<li><a href="page6.html">Page 6</a></li>
<!-- ... -->
<li><a href="page1000.html">Page 1000</a></li>
</ul>
</code>```

I want to bind a click event handler to the  tag.  Normally, I would write out

```<code>$('.myList').find('a').click(function() {});  /* Or something similar */
</code>```

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

答:
You can access event.target, which will be the element that started the event.

```<code>$('.myList').click(function(event) {
   var target = $(event.target);
});
</code>```

jsFiddle.

However, Pointy's answer seems to be easier to use.

ContentLicense: CC BY-SA 3.0

Body:
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

Page 1

Page 2

Page 3

Page 4

Page 5

Page 6

Page 1000

I want to bind a click event handler to the  tag.  Normally, I would write out

$('.myList').find('a').click(function() {});  /* Or something similar */

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

Body:
You can access event.target, which will be the element that started the event.

$('.myList').click(function(event) {
   var target = $(event.target);
});

jsFiddle.

However, Pointy's answer seems to be easier to use.


问:
Can Spotfire change data table source directory based on username?
We'd like to distribute a Spotfire dashboard to different users, however the location of the data source file is on Sharepoint and for every user it's mapped to:

C:\Users\myusername\Sharepoint\spotfiretable.csv

Where myusername is the windows login account username and if I gave someone this Spotfire file they'd have to get prompted to re-direct Spotfire to the same folder mapped under their user name. Is there any way to avoid this and have Spotfire recognize the location of the data source automatically by getting the username information from system environment variables?

答:
I would try embedding the data source in the dxp/ analysis with no data just the column names. This way visual ect don't have to be recreated.

Set up a python script to update the data source to the user name path and refresh the table. You can even trigger this event on load so it would be seemless for end user.

Here is a link showing python script to updated data source.
https://spotfired.blogspot.com/2014/05/replace-data-tables-from-file.html?m=1

If you require assistance with the python script post a new question with what code you've tried to implement.


问:
RegExp returning false when it shows true on online tester
```<code>var str = "+9665612345678";
var patt = new RegExp("/\+9665\d{8}/g");
var res = patt.test(str);
console.log(res);
</code>```

Above code returns false while it shows true on online tests

https://regex101.com/r/jb6bwS/1

Why is it returning false when it should be true?

答:
Your use of new Reg Exp is wrong.

It would look like

```<code>var patt = new RegExp("\\+9665\\d{8}",'g');
</code>```

I would skip RegExp and just do

```<code>var patt = /\+9665\d{8}/g;
</code>```

Body:
var str = "+9665612345678";
var patt = new RegExp("/\+9665\d{8}/g");
var res = patt.test(str);
console.log(res);

Above code returns false while it shows true on online tests

https://regex101.com/r/jb6bwS/1

Why is it returning false when it should be true?

Body:
Your use of new Reg Exp is wrong.

It would look like

var patt = new RegExp("\\+9665\\d{8}",'g');

I would skip RegExp and just do

var patt = /\+9665\d{8}/g;


问:
Need to play a mp3 audio over the internet without latency in iOS (Swift)
We are trying to achieve low latency audio streaming(only encoded audio data present, no video data) using AVPlayer.  We have tested audio streaming protocols like HTTP & HLS and have observed a minimum of 3 seconds latency to play.
Does AVPlayer require an input buffer of a minimum of 3 seconds on the device before starting the playback?

Does latency reduction have any correlation with the quality of audio playback?

Can we reduce this latency? If yes, are there any suggestions or recommended practices?

答: You can just observe playerItem.loadedTimeRanges an play pause AVPlayer manually if buffer (aka loadedTimeRanges) enough for you latency conditions


问:
docker push with local notary server returns error: x509: certificate signed by unknown authority
I have been working at setting up a docker notary on a Centos 8 machine. I followed the README.md for the notary project which tells me to use the testing certificate the project
comes with by moving it to the .notary folder in my home directory. My hope here is that when my docker client is setup for it and when I properly tag the image a docker push to my private docker repo (jFrog Artifactory) would result in a published image that is signed by the notary.

My private repo is running on its own machine and not on the machine where the notary server is running.

But every time I go for the push I get this error:

```<code>Signing and pushing trust metadata
Error: error contacting notary server: x509: certificate signed by unknown authority
</code>```

One of the ways I tried to fix this is by copying over the test certificates from fixtures/root-ca.crt to /etc/pki/ca-trust/source/anchors/ after which I ran update-ca-trust.

```<code>$ sudo cp fixtures/root-ca.crt /etc/pki/ca-trust/source/anchors/
$ update-ca-trust
</code>```

But doing this also didn't help. Why is the notary server throwing this error? Help to resolve this would be greatly appreciated.

答:
Rijo my solution is not complete because This doesn’t work on remote server, facing an error

```<code>Error: error contacting notary server: x509: certificate is valid for 127.0.0.1, not xx.xx.xx.xx(notaryIP)
</code>```

Here is my solution where was able to sign image locally on the notary server and push it

```<code>Docker login artifactoryurl
username:
password:
Login successful
docker trust key generate keyname
export DOCKER_CONTENT_TRUST=0
docker build -f Dockerfile -t artrifactoryurl/reponame:tag .
export DOCKER_CONTENT_TRUST_SERVER=http://127.0.0.1:4443
export DOCKER_CONTENT_TRUST=1
docker trust signer add —key keyname.pub name artifactoryurl/repo
docker trust sign artifactoryurl/reponame:tag
docker inspect artifactoryurl/reponame:tag
</code>```

Hope it helps

Body:
I have been working at setting up a docker notary on a Centos 8 machine. I followed the README.md for the notary project which tells me to use the testing certificate the project
comes with by moving it to the .notary folder in my home directory. My hope here is that when my docker client is setup for it and when I properly tag the image a docker push to my private docker repo (jFrog Artifactory) would result in a published image that is signed by the notary.

My private repo is running on its own machine and not on the machine where the notary server is running.

But every time I go for the push I get this error:

Signing and pushing trust metadata
Error: error contacting notary server: x509: certificate signed by unknown authority

One of the ways I tried to fix this is by copying over the test certificates from fixtures/root-ca.crt to /etc/pki/ca-trust/source/anchors/ after which I ran update-ca-trust.

$ sudo cp fixtures/root-ca.crt /etc/pki/ca-trust/source/anchors/
$ update-ca-trust

But doing this also didn't help. Why is the notary server throwing this error? Help to resolve this would be greatly appreciated.

Body:
Rijo my solution is not complete because This doesn’t work on remote server, facing an error

Error: error contacting notary server: x509: certificate is valid for 127.0.0.1, not xx.xx.xx.xx(notaryIP)

Here is my solution where was able to sign image locally on the notary server and push it

Docker login artifactoryurl
username:
password:
Login successful
docker trust key generate keyname
export DOCKER_CONTENT_TRUST=0
docker build -f Dockerfile -t artrifactoryurl/reponame:tag .
export DOCKER_CONTENT_TRUST_SERVER=http://127.0.0.1:4443
export DOCKER_CONTENT_TRUST=1
docker trust signer add —key keyname.pub name artifactoryurl/repo
docker trust sign artifactoryurl/reponame:tag
docker inspect artifactoryurl/reponame:tag

Hope it helps


问:
Python - reset stdout to normal, after previously redirecting it to a file
At the beginning of my python program I have the following line:

```<code>sys.stdout = open('stdout_file', 'w')
</code>```

Halfway through my program I would like to set stdout back to the normal stdout.  How do I do this?

答:
open file and exchange sys variable with file variable

```<code>f = open("sample.txt", "w")

sys.stdout, f = f, sys.stdout
print("sample", flush=True)
</code>```

and take it back

```<code>f, sys.stdout = sys.stdout, f
print("sample")
</code>```

Body:
At the beginning of my python program I have the following line:

sys.stdout = open('stdout_file', 'w')

Halfway through my program I would like to set stdout back to the normal stdout.  How do I do this?

Body:
open file and exchange sys variable with file variable

f = open("sample.txt", "w")

sys.stdout, f = f, sys.stdout
print("sample", flush=True)

and take it back

f, sys.stdout = sys.stdout, f
print("sample")


问:
Is it safe to load HTML and js via ajax?
I'm using the Jquery load function $('#result').load('test.php'); to load a page into another page by clicking a tab. The page I'm loading contains javascript, php, and contains a form. Using the firebug console I saw that there is a GET for all my script sources in the page I'm loading as well. Not sure if that should be a concern..

Can data be hacked via the jquery load? Are there any issues to consider?

note: I'm aware that old browsers don't work with javascript but is there anything else to consider?

答: It really depends on how well you trust the source of the scripts.  If you control them then there's no (additional) issue.  If you're getting them from somewhere else (like jQuery from Google's CDN, for example) you're trusting that source.</p>


问:
Getting invalid attributes error when playing sound with MediaPlayer
suddenly my app doesnt play a sound when I call mediaPlayer.start().

I get following error in log:

```<code>2020-05-29 20:43:57.165 4719-1953/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags:  } when converting to stream
</code>```

I am doing this one when the app starts:

```<code>mMediaPlayer = MediaPlayer.create(context, R.raw.restaurant_order_received)
</code>```

Thanks for help

答:
You need to provide a resourceID. Try this:</p>

```<code>var resID = context?.resources?.getIdentifier("YOUR_FILE_NAME", "raw", context.packageName)

resID?.let {
    // No fike found when it == 0
    if (it == 0) {
        val errorString = "Error occured."
        Snackbar.make(view, errorString, 2000).show()
        return
    }
    mediaPlayer = MediaPlayer.create(context, it)
    mediaPlayer?.start()
    return
}
</code>```

Body:
suddenly my app doesnt play a sound when I call mediaPlayer.start().

I get following error in log:

2020-05-29 20:43:57.165 4719-1953/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags:  } when converting to stream

I am doing this one when the app starts:

mMediaPlayer = MediaPlayer.create(context, R.raw.restaurant_order_received)

Thanks for help

Body:
You need to provide a resourceID. Try this:

var resID = context?.resources?.getIdentifier("YOUR_FILE_NAME", "raw", context.packageName)

resID?.let {
    // No fike found when it == 0
    if (it == 0) {
        val errorString = "Error occured."
        Snackbar.make(view, errorString, 2000).show()
        return
    }
    mediaPlayer = MediaPlayer.create(context, it)
    mediaPlayer?.start()
    return
}


问:
HTTP CURL works - Java Jsoup doesn't
I try to scrape some chat messages from a site (https://bs.to), but I have to login first via HTTP POST. In CURL my code works fine:

```<code>curl -v -X POST ^
-H "Cookie: __bsduid=226mq3kt8oafl5f1le1hv3ognl; " ^
-d "login[user]=RainbowSimon&login[pass]=MY_PASSWORD&security_token=687f7de7247f9a95f7fccc6a" "https://bs.to" ^
--output "out.txt"
</code>```

But then when I tried to get it into Java with JSoup, I get status code 200 and a HTML structure, but I'm not logged in

```<code>Connection.Response loggedIn;
loggedIn = Jsoup.connect("http://bs.to")
    .cookie("__bsduid", cookieUID)
    .data("login[user]", loginUserName)
    .data("login[pass]", loginUserPassword)
    .data("security_token", securityTokenForm)
    .method(Method.POST)
    .execute();

System.out.println(loggedIn.statusCode());
System.out.println(loggedIn.parse());
</code>```

I did even retrieve the security_token and the cookie from the Java application and put them in CURL and it worked too.

Does someone see the mistake I made when trying to implement to Java?

答:
You get different responses because you send different request. The main difference here are headers.

Web browsers and curl are automatically setting for you some basic request headers but Jsoup won't do this. You have to explicitly add them to the connection. You're using curl with -v so they are already visible:

```<code>> POST / HTTP/2
> Host: bs.to
> User-Agent: curl/7.60.0
> Accept: */*
> Cookie: __bsduid=226mq3kt8oafl5f1le1hv3ognl;
> Content-Length: 88
> Content-Type: application/x-www-form-urlencoded
</code>```

Jsoup won't set headers: User-Agent, Accept and Content-Type. Some of them are required by some servers to tell the difference between real web browsers and crawlers. Try to set them to exactly the same values as above using .header(name, value) to simulate the same request.

The other difference between curl and Jsoup is that curl seems to be using HTTP2 but Jsoup uses HTTP1.1 but that shouldn't be the case. To make sure try using curl with --http1.1 switch.

None of the above can be tested by me because your cookies don't work for me so you have to experiment by yourself.

Title: HTTP CURL works - Java Jsoup doesn't

Body:
I try to scrape some chat messages from a site (https://bs.to), but I have to login first via HTTP POST. In CURL my code works fine:

curl -v -X POST ^
-H "Cookie: __bsduid=226mq3kt8oafl5f1le1hv3ognl; " ^
-d "login[user]=RainbowSimon&login[pass]=MY_PASSWORD&security_token=687f7de7247f9a95f7fccc6a" "https://bs.to" ^
--output "out.txt"

But then when I tried to get it into Java with JSoup, I get status code 200 and a HTML structure, but I'm not logged in

Connection.Response loggedIn;
loggedIn = Jsoup.connect("http://bs.to")
    .cookie("__bsduid", cookieUID)
    .data("login[user]", loginUserName)
    .data("login[pass]", loginUserPassword)
    .data("security_token", securityTokenForm)
    .method(Method.POST)
    .execute();

System.out.println(loggedIn.statusCode());
System.out.println(loggedIn.parse());

I did even retrieve the security_token and the cookie from the Java application and put them in CURL and it worked too.

Does someone see the mistake I made when trying to implement to Java?

Body:
You get different responses because you send different request. The main difference here are headers.

Web browsers and curl are automatically setting for you some basic request headers but Jsoup won't do this. You have to explicitly add them to the connection. You're using curl with -v so they are already visible:

> POST / HTTP/2
> Host: bs.to
> User-Agent: curl/7.60.0
> Accept: */*
> Cookie: __bsduid=226mq3kt8oafl5f1le1hv3ognl;
> Content-Length: 88
> Content-Type: application/x-www-form-urlencoded

Jsoup won't set headers: User-Agent, Accept and Content-Type. Some of them are required by some servers to tell the difference between real web browsers and crawlers. Try to set them to exactly the same values as above using .header(name, value) to simulate the same request.

The other difference between curl and Jsoup is that curl seems to be using HTTP2 but Jsoup uses HTTP1.1 but that shouldn't be the case. To make sure try using curl with --http1.1 switch.

None of the above can be tested by me because your cookies don't work for me so you have to experiment by yourself.


问:
python 3.6 bug or i am nuts
checks if items in a list are consecutive.

```<code>[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]
</code>```

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)
</code>```

What am i missing here?

答:
Your list comprehension is doing nested loops, not parallel loops. It's looping over the cross product of the two slices. You can see this if you remove the if and return the values of x and y themselves.

```<code>>>> [(x, y) for x in lst[:-1] for y in lst[1:]]
[(1, 2), (1, 3), (1, 4), (1, 4), (2, 2), (2, 3), (2, 4), (2, 4), (3, 2), (3, 3), (3, 4), (3, 4), (4, 2), (4, 3), (4, 4), (4, 4)]
</code>```

The result contains True whenever the paired elements are consecutive; when they're not consecutive it doesn't add anything to the result. There are 4 pairs that are consecutive, so that's what you get in the result.

If you want to test only adjacent elements, use zip() in the comprehension:

```<code>>>> [True for x, y in zip(lst[:-1], lst[1:]) if x + 1 == y]
[True, True, True]
</code>```

If you want to return both True and False in the list, you shouldn't use if, you should return the result of the test:

```<code>>>> [(x + 1 == y) for x, y in zip(lst[:-1], lst[1:])]
[True, True, True, False]
</code>```

Title: python 3.6 bug or i am nuts

Body:
checks if items in a list are consecutive.

[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)

What am i missing here?

Body:
Your list comprehension is doing nested loops, not parallel loops. It's looping over the cross product of the two slices. You can see this if you remove the if and return the values of x and y themselves.

>>> [(x, y) for x in lst[:-1] for y in lst[1:]]
[(1, 2), (1, 3), (1, 4), (1, 4), (2, 2), (2, 3), (2, 4), (2, 4), (3, 2), (3, 3), (3, 4), (3, 4), (4, 2), (4, 3), (4, 4), (4, 4)]

The result contains True whenever the paired elements are consecutive; when they're not consecutive it doesn't add anything to the result. There are 4 pairs that are consecutive, so that's what you get in the result.

If you want to test only adjacent elements, use zip() in the comprehension:

>>> [True for x, y in zip(lst[:-1], lst[1:]) if x + 1 == y]
[True, True, True]

If you want to return both True and False in the list, you shouldn't use if, you should return the result of the test:

>>> [(x + 1 == y) for x, y in zip(lst[:-1], lst[1:])]
[True, True, True, False]


问:
Rails - Serialize Model to JSON with camelize
I need to serialize a model to json and have all of the keys be camelized.  I see that there's an option in to_xml to allow camel case.  I can't seem to coerce the json serialization into giving me back a camelized hash.  Is this something that's possible in rails?</p>

答:
It seems weird to me to use camelized attribute names in Rails, let alone json. I would stick to the conventions and use underscored variable names.

However, have a look at this gem: RABL. It should be able to help you out.


问:
TypeError: 'int' object is not iterable, don't know why this is happening
```<code>def rectangleArea(l):
    lt = list(l[0])
    l = lt[:3:2]
    l.sort()
    x = l[1] - l[0]
    l = lt[1:4:2]
    l.sort()
    y = l[1] - l[0]
    area = x * y
    return area
l = [(30, 60, 60, 30), (50, 10, 10, 50)]
for i in range(2):
    print("Rectangle")
    la = l[i]
    print(la)
    area = rectangleArea(la)
    print(area)
</code>```

Sorry for my bad english.
As you can see, tuples are in list 'l' and I don't want to edit this.
When I ran it without for loop, it worked well.
And with for loop, "TypeError: 'int' object is not iterable" appears.
The error message looks like this:

```<code>Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 19, in <module>
    area = rectangleArea(la)
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 3, in rectangleArea
    lt = list(l1[0])
</code>```

I searched about it, and my situation isn't like the other.
I guess this is related with la = l[i] but i'm not sure.
What's wrong with this code. Please help me

答:
lt = list(l[0]) replace this with lt = list(l) in your code.

Your code picks rectangle sides one by one and passes into the function. Now inside the function, you just need to convert the tuple into a list but what you are doing is selecting the first element in it.

Body:
def rectangleArea(l):
    lt = list(l[0])
    l = lt[:3:2]
    l.sort()
    x = l[1] - l[0]
    l = lt[1:4:2]
    l.sort()
    y = l[1] - l[0]
    area = x * y
    return area
l = [(30, 60, 60, 30), (50, 10, 10, 50)]
for i in range(2):
    print("Rectangle")
    la = l[i]
    print(la)
    area = rectangleArea(la)
    print(area)

Sorry for my bad english.
As you can see, tuples are in list 'l' and I don't want to edit this.
When I ran it without for loop, it worked well.
And with for loop, "TypeError: 'int' object is not iterable" appears.
The error message looks like this:

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 19, in <module>
    area = rectangleArea(la)
  File "C:/Users/Administrator/Desktop/MP09/help.py", line 3, in rectangleArea
    lt = list(l1[0])

I searched about it, and my situation isn't like the other.
I guess this is related with la = l[i] but i'm not sure.
What's wrong with this code. Please help me


问:
Gap between border and page edge
I have added a border around my page which should stay fixed even when the page scrolls.
How do I remove the small gap between the red border and the edge of page??

body::before {
    content: '';
    position: fixed;
    top: 5px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    border: 15px solid red;
    padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras porttitor, purus non hendrerit bibendum, mauris nisi maximus metus, sit amet commodo augue purus quis lorem. Nullam laoreet nibh nisi, eu suscipit libero varius id. Nunc lobortis odio eu tempor vulputate. Sed placerat nisi gravida lorem laoreet congue. Nam blandit faucibus molestie. Sed tempus mi a arcu eleifend, ut malesuada elit ultricies. Sed odio leo, tempus non accumsan nec, condimentum viverra arcu. Nullam accumsan, elit sed vulputate ultricies, elit lorem interdum lectus, ut feugiat ipsum diam sed nulla. Etiam et pharetra turpis. Duis accumsan quam sit amet interdum blandit. Sed auctor hendrerit mauris ac vestibulum. Nam at dapibus lacus, non mattis turpis. Suspendisse potenti. Quisque vel condimentum enim, quis tincidunt purus. Fusce cursus odio non venenatis dictum. Maecenas felis felis, blandit a dictum ut, blandit sed justo.

Vestibulum placerat placerat elit eget auctor. Suspendisse auctor massa eros, a lobortis leo faucibus a. Pellentesque mi nibh, efficitur vitae dignissim quis, egestas luctus ante. Maecenas at blandit tellus. Sed eleifend, erat commodo sollicitudin egestas, nisl ante sollicitudin sem, eu venenatis nisi mauris at orci. Aliquam erat volutpat. Phasellus nulla augue, dapibus et sem ac, vestibulum ultricies risus. Donec ut lectus risus. Mauris tincidunt, ipsum quis rhoncus scelerisque, quam augue molestie eros, dapibus gravida neque diam in quam. Sed vulputate ante ut tortor rhoncus maximus. Curabitur id facilisis leo, ac suscipit orci. Fusce auctor neque quis fringilla pretium.

Cras nec eros id est ullamcorper consequat. Quisque pellentesque venenatis pretium. Sed a ullamcorper massa. Morbi eget rutrum nisl. Nullam semper tellus ut purus lacinia ornare. Quisque sagittis auctor erat, sed volutpat turpis. Suspendisse vehicula faucibus lectus, nec iaculis turpis mattis ut. Aliquam dapibus felis lectus, sit amet mattis nunc ullamcorper quis. Nam dictum nibh ac pretium vehicula. Cras porta in neque nec convallis. Cras libero tellus, luctus id velit vel, molestie egestas nunc. Morbi vitae dolor metus. Donec vitae interdum sem, vitae condimentum ante. Cras in turpis et nisl tincidunt vehicula.

Sed ut magna commodo, iaculis velit vel, cursus velit. Curabitur nunc sem, maximus et ullamcorper in, venenatis vel sapien. Praesent vulputate, purus sit amet rhoncus lacinia, urna lectus venenatis dui, in elementum velit quam nec urna. Curabitur quis efficitur sem. Proin id feugiat mi. Duis sed diam vitae tortor mollis auctor vitae non erat. Aenean pulvinar accumsan luctus. Fusce at massa suscipit, gravida risus ut, laoreet tortor. Praesent vitae purus elit. Praesent feugiat augue eu tellus scelerisque, vel fringilla ligula suscipit.

Nulla ac elementum neque. Integer tincidunt sollicitudin cursus. Proin a lacus augue. Etiam scelerisque scelerisque commodo. Nulla eros felis, aliquet at tincidunt in, vulputate sit amet libero. Mauris sed vulputate urna, ac consectetur lacus. Duis eget lorem blandit, laoreet velit in, sagittis augue. Vestibulum ut erat quis ipsum aliquam fermentum. Ut varius odio lacus, ut dictum dolor laoreet non. Donec feugiat dictum magna, mollis mattis nibh bibendum quis. Sed ornare risus vel massa tristique, vel iaculis enim aliquet. Sed mauris erat, faucibus sit amet hendrerit eget, suscipit sed neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</code>```

答:
this should work fine !!

body::before {

```<code>content: '';
position: fixed;
top: 0vh;
left: 0vw;
right: 0vw;
bottom:0vh;
border: 15px solid red;
</code>```

}

Title: Gap between border and page edge

Body:
I have added a border around my page which should stay fixed even when the page scrolls.
How do I remove the small gap between the red border and the edge of page??

body::before {
    content: '';
    position: fixed;
    top: 5px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    border: 15px solid red;
    padding: 0px;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras porttitor, purus non hendrerit bibendum, mauris nisi maximus metus, sit amet commodo augue purus quis lorem. Nullam laoreet nibh nisi, eu suscipit libero varius id. Nunc lobortis odio eu tempor vulputate. Sed placerat nisi gravida lorem laoreet congue. Nam blandit faucibus molestie. Sed tempus mi a arcu eleifend, ut malesuada elit ultricies. Sed odio leo, tempus non accumsan nec, condimentum viverra arcu. Nullam accumsan, elit sed vulputate ultricies, elit lorem interdum lectus, ut feugiat ipsum diam sed nulla. Etiam et pharetra turpis. Duis accumsan quam sit amet interdum blandit. Sed auctor hendrerit mauris ac vestibulum. Nam at dapibus lacus, non mattis turpis. Suspendisse potenti. Quisque vel condimentum enim, quis tincidunt purus. Fusce cursus odio non venenatis dictum. Maecenas felis felis, blandit a dictum ut, blandit sed justo.

Vestibulum placerat placerat elit eget auctor. Suspendisse auctor massa eros, a lobortis leo faucibus a. Pellentesque mi nibh, efficitur vitae dignissim quis, egestas luctus ante. Maecenas at blandit tellus. Sed eleifend, erat commodo sollicitudin egestas, nisl ante sollicitudin sem, eu venenatis nisi mauris at orci. Aliquam erat volutpat. Phasellus nulla augue, dapibus et sem ac, vestibulum ultricies risus. Donec ut lectus risus. Mauris tincidunt, ipsum quis rhoncus scelerisque, quam augue molestie eros, dapibus gravida neque diam in quam. Sed vulputate ante ut tortor rhoncus maximus. Curabitur id facilisis leo, ac suscipit orci. Fusce auctor neque quis fringilla pretium.

Cras nec eros id est ullamcorper consequat. Quisque pellentesque venenatis pretium. Sed a ullamcorper massa. Morbi eget rutrum nisl. Nullam semper tellus ut purus lacinia ornare. Quisque sagittis auctor erat, sed volutpat turpis. Suspendisse vehicula faucibus lectus, nec iaculis turpis mattis ut. Aliquam dapibus felis lectus, sit amet mattis nunc ullamcorper quis. Nam dictum nibh ac pretium vehicula. Cras porta in neque nec convallis. Cras libero tellus, luctus id velit vel, molestie egestas nunc. Morbi vitae dolor metus. Donec vitae interdum sem, vitae condimentum ante. Cras in turpis et nisl tincidunt vehicula.

Sed ut magna commodo, iaculis velit vel, cursus velit. Curabitur nunc sem, maximus et ullamcorper in, venenatis vel sapien. Praesent vulputate, purus sit amet rhoncus lacinia, urna lectus venenatis dui, in elementum velit quam nec urna. Curabitur quis efficitur sem. Proin id feugiat mi. Duis sed diam vitae tortor mollis auctor vitae non erat. Aenean pulvinar accumsan luctus. Fusce at massa suscipit, gravida risus ut, laoreet tortor. Praesent vitae purus elit. Praesent feugiat augue eu tellus scelerisque, vel fringilla ligula suscipit.

Nulla ac elementum neque. Integer tincidunt sollicitudin cursus. Proin a lacus augue. Etiam scelerisque scelerisque commodo. Nulla eros felis, aliquet at tincidunt in, vulputate sit amet libero. Mauris sed vulputate urna, ac consectetur lacus. Duis eget lorem blandit, laoreet velit in, sagittis augue. Vestibulum ut erat quis ipsum aliquam fermentum. Ut varius odio lacus, ut dictum dolor laoreet non. Donec feugiat dictum magna, mollis mattis nibh bibendum quis. Sed ornare risus vel massa tristique, vel iaculis enim aliquet. Sed mauris erat, faucibus sit amet hendrerit eget, suscipit sed neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Body:
this should work fine !!

body::before {

content: '';
position: fixed;
top: 0vh;
left: 0vw;
right: 0vw;
bottom:0vh;
border: 15px solid red;

}


问:
Creating classes and objects using bash scripting
I'm trying to use bash scripting to make an script act like a phone book,
so i tried to create classes and objects but unfortunately i couldn't find a way to do that !
so i'm asking how to create a class using bash scripting??</p>

答:
While there's no true way to create classes in Bash, you can get a little creative. I've found over the years that my preferred way to do this is to create a function that returns a command that can be executed to change state or read properties of the instance. The instance data can be stored in an array.

For example, if you wanted to make a class for binary search trees, you could have this in BinarySearchTree.sh:

__BINARYSEARCHTREE_INSTANCE_DATA__=()

__BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__=()
__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__=()

BinarySearchTree()
{
    echo "__BinarySearchTree__ $RANDOM "
}

__BinarySearchTree__()
{
    local id="$1"
    local code="$2"

    case "$code" in
        '.insert' | '[insert]' | "['insert']" | '["insert"]')
            local value="$3"

            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                local length="${__BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]}"
                local new_node="$length"

                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]="$value"

                length=$((length + 1))
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]=''

                length=$((length + 1))
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]=''

                local current_node=0
                local parent

                while [ 1 ]; do
                    parent="$current_node"

                    if [ "$value" -lt "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}" ]; then
                        current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]}"

                        if [ "$current_node" == '' ]; then
                            __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 1))"]="$new_node"

                            break
                        fi
                    else
                        current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]}"

                        if [ "$current_node" == '' ]; then
                            __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 2))"]="$new_node"

                            break
                        fi
                    fi
                done

                __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]="$((length + 1))"
                __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]="$((${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]} + 1))"
            else
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0]="$value"
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 1]=''
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 2]=''
                __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]=3
                __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]=1
            fi;;

        '.has' | '[has]' | "['has']" | '["has"]')
            local value="$3"

            local current_node=0

            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                while [ 1 ]; do
                    local current_value="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}"

                    if [ "$current_value" == "$value" ]; then
                        return 0
                    fi

                    if [ "$value" -lt "$current_value" ]; then
                        current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]}
                    else
                        current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]}
                    fi

                    if [ "$current_node" == '' ]; then
                        return 1
                    fi
                done
            else
                return 1
            fi;;

        '.size' | '[size]' | "['size']" | '["size"]')
            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                echo "${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]}"
            else
                echo 0
            fi;;

        '.empty' | '[empty]' | "['empty']" | '["empty"]')
            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                return 1
            else
                return 0
            fi;;

        '.clear' | '[clear]' | "['clear']" | '["clear"]')
            unset "__BINARYSEARCHTREE_INSTANCE_DATA__[$id, 0]"
    esac
}
```

<p>And then make objects like this:</p>

<pre class="lang-sh prettyprint-override"><code>source './BinarySearchTree.sh'

process()
{
    local tree="$1"

    $tree.insert 52
    $tree.insert -150
    $tree.insert 42

    if $tree.has 42; then
        echo 'Has 42!'
    else
        echo 'Does not have 42!'
    fi

    $tree.clear

    echo "Size: $($tree.size)"
}

main()
{
    local tree=$(BinarySearchTree)

    process "$tree"
}

main "$#" "$@"
</code>```

The advantages of this method are that objects can be passed into other functions and there are no external file operations. Even though this may seem impractical, it actually makes Bash quite a nice language to work in since you can modularize your classes.

Body:
While there's no true way to create classes in Bash, you can get a little creative. I've found over the years that my preferred way to do this is to create a function that returns a command that can be executed to change state or read properties of the instance. The instance data can be stored in an array.

For example, if you wanted to make a class for binary search trees, you could have this in BinarySearchTree.sh:

__BINARYSEARCHTREE_INSTANCE_DATA__=()

__BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__=()
__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__=()

BinarySearchTree()
{
    echo "__BinarySearchTree__ $RANDOM "
}

__BinarySearchTree__()
{
    local id="$1"
    local code="$2"

    case "$code" in
        '.insert' | '[insert]' | "['insert']" | '["insert"]')
            local value="$3"

            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                local length="${__BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]}"
                local new_node="$length"

                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]="$value"

                length=$((length + 1))
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]=''

                length=$((length + 1))
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$length"]=''

                local current_node=0
                local parent

                while [ 1 ]; do
                    parent="$current_node"

                    if [ "$value" -lt "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}" ]; then
                        current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]}"

                        if [ "$current_node" == '' ]; then
                            __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 1))"]="$new_node"

                            break
                        fi
                    else
                        current_node="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]}"

                        if [ "$current_node" == '' ]; then
                            __BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((parent + 2))"]="$new_node"

                            break
                        fi
                    fi
                done

                __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]="$((length + 1))"
                __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]="$((${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]} + 1))"
            else
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0]="$value"
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 1]=''
                __BINARYSEARCHTREE_INSTANCE_DATA__["$id", 2]=''
                __BINARYSEARCHTREE_INSTANCE_DATA_LENGTH__["$id"]=3
                __BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]=1
            fi;;

        '.has' | '[has]' | "['has']" | '["has"]')
            local value="$3"

            local current_node=0

            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                while [ 1 ]; do
                    local current_value="${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node))"]}"

                    if [ "$current_value" == "$value" ]; then
                        return 0
                    fi

                    if [ "$value" -lt "$current_value" ]; then
                        current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 1))"]}
                    else
                        current_node=${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", "$((current_node + 2))"]}
                    fi

                    if [ "$current_node" == '' ]; then
                        return 1
                    fi
                done
            else
                return 1
            fi;;

        '.size' | '[size]' | "['size']" | '["size"]')
            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                echo "${__BINARYSEARCHTREE_INSTANCE_DATA_SIZE__["$id"]}"
            else
                echo 0
            fi;;

        '.empty' | '[empty]' | "['empty']" | '["empty"]')
            if [ "${__BINARYSEARCHTREE_INSTANCE_DATA__["$id", 0] + set}" ]; then
                return 1
            else
                return 0
            fi;;

        '.clear' | '[clear]' | "['clear']" | '["clear"]')
            unset "__BINARYSEARCHTREE_INSTANCE_DATA__[$id, 0]"
    esac
}

And then make objects like this:

source './BinarySearchTree.sh'

process()
{
    local tree="$1"

    $tree.insert 52
    $tree.insert -150
    $tree.insert 42

    if $tree.has 42; then
        echo 'Has 42!'
    else
        echo 'Does not have 42!'
    fi

    $tree.clear

    echo "Size: $($tree.size)"
}

main()
{
    local tree=$(BinarySearchTree)

    process "$tree"
}

main "$#" "$@"

The advantages of this method are that objects can be passed into other functions and there are no external file operations. Even though this may seem impractical, it actually makes Bash quite a nice language to work in since you can modularize your classes.


问:
How to allow ecs private application access to internet if using only aws PrivateLink
I have deployed multiple applications(docker containers) by ECS on private subnet. NAT Gateway is used to allow internet access. Due to active deployment, the images download from ECR by nat gateway is costing too much due to their size.

I am planning on using AWS PrivateLink. But will AWS PrivateLink allow access to internet from my apps or can I use PrivateLink only for ECR image downloads from ECR and natgateway for occasional internet connectivity for my applications.

Thanks for your Valuable time.

答:
You cannot access the internet outside of AWS services in a private instance if you're only using AWS PrivateLink.

You can download ECR images through VPC endpoints instead of a NAT gateway. The following endpoints are required:

```<code>com.amazonaws.region.ecr.dkr
com.amazonaws.region.ecr.api
com.amazonaws.region.ecr.s3
</code>```

Reference: https://docs.aws.amazon.com/AmazonECR/latest/userguide/vpc-endpoints.html

Body:
You cannot access the internet outside of AWS services in a private instance if you're only using AWS PrivateLink.

You can download ECR images through VPC endpoints instead of a NAT gateway. The following endpoints are required:

com.amazonaws.region.ecr.dkr
com.amazonaws.region.ecr.api
com.amazonaws.region.ecr.s3

Reference: https://docs.aws.amazon.com/AmazonECR/latest/userguide/vpc-endpoints.html


问:
Set geom_vline line types and sizes with aes mapping in ggplot2
I'm trying to create a histogram with vertical lines overlaid on top of it. One of the vertical lines shows a target, the rest show percentiles. I would like the line representing the target to be different than the other lines.

I have the data for the lines in a dataframe:

```<code>lines
   qntls        lbs heights    lts lsz
1  29.00      p5=29 32.2400 dashed 0.1
2  45.25     p25=45 33.5296 dashed 0.1
3  79.00     p50=79 30.9504 dashed 0.1
4 128.00    p75=128 32.2400 dashed 0.1
5 249.25    p95=249 33.5296 dashed 0.1
6 120.00 Target=120 30.9504  solid 0.2
</code>```

I then use the lines dataframe to create the geom_vline and geom_label objects:

```<code>ggplot() +
  geom_histogram(
    data = h,
    mapping = aes(
      x = DAYSTODECISION
    ),
    breaks = brks,
    color = clr,
    fill = f
  ) +
  geom_vline(
    data = lines,
    mapping = aes(
      xintercept = qntls,
      color = lbs,
      linetype = lts,
      size = lsz
    ),
    show.legend = FALSE
  ) +
  geom_label(
    data = lines,
    mapping = aes(
      x = qntls,
      y = heights,
      label = lbs,
      hjust = 0 # Label starts on line and extends right
    )
  ) +
  ggtitle(title) +
  labs(
    x = xlab,
    y = ylab
  ) +
  theme_classic()
</code>```

I get this result:

I want the line for the target to be solid and all other lines to be dashed. For some reason this is reversed in the chart compared to the lines dataframe. Additionally, I would expect the target line to be twice as thick as the other lines, but this is not the case.

Any help would be much appreciated!

答:
```<code>  # your plot code ... +
  scale_linetype_identity() +
  scale_size_identity()
</code>```

It's unusual in a ggplot to put the actual colors/sizes/linetypes you want in the data frame (instead of meaningful labels you might want on a legend, like you do for lbs), but if you do the identity scales are your friend.

A more standard approach would have your data set up perhaps like this:

```<code>   qntls        lbs heights is_target
1  29.00      p5=29 32.2400        no
2  45.25     p25=45 33.5296        no
3  79.00     p50=79 30.9504        no
4 128.00    p75=128 32.2400        no
5 249.25    p95=249 33.5296        no
6 120.00 Target=120 30.9504       yes
</code>```

Then map linetype = is_target, size = is_target inside aes(), and use manual scales like this:

```<code>... +
scale_size_manual(values = c("no" = 0.1, "yes" = 0.2)) +
scale_linetype_manual(values = c("no" = "dashed", "yes" = "solid"))
</code>```

This set-up makes it easy to adjust your graph without changing your data.

Body:
I'm trying to create a histogram with vertical lines overlaid on top of it. One of the vertical lines shows a target, the rest show percentiles. I would like the line representing the target to be different than the other lines.

I have the data for the lines in a dataframe:

lines
   qntls        lbs heights    lts lsz
1  29.00      p5=29 32.2400 dashed 0.1
2  45.25     p25=45 33.5296 dashed 0.1
3  79.00     p50=79 30.9504 dashed 0.1
4 128.00    p75=128 32.2400 dashed 0.1
5 249.25    p95=249 33.5296 dashed 0.1
6 120.00 Target=120 30.9504  solid 0.2

I then use the lines dataframe to create the geom_vline and geom_label objects:

ggplot() +
  geom_histogram(
    data = h,
    mapping = aes(
      x = DAYSTODECISION
    ),
    breaks = brks,
    color = clr,
    fill = f
  ) +
  geom_vline(
    data = lines,
    mapping = aes(
      xintercept = qntls,
      color = lbs,
      linetype = lts,
      size = lsz
    ),
    show.legend = FALSE
  ) +
  geom_label(
    data = lines,
    mapping = aes(
      x = qntls,
      y = heights,
      label = lbs,
      hjust = 0 # Label starts on line and extends right
    )
  ) +
  ggtitle(title) +
  labs(
    x = xlab,
    y = ylab
  ) +
  theme_classic()

I get this result:

I want the line for the target to be solid and all other lines to be dashed. For some reason this is reversed in the chart compared to the lines dataframe. Additionally, I would expect the target line to be twice as thick as the other lines, but this is not the case.

Any help would be much appreciated!

Body:
  # your plot code ... +
  scale_linetype_identity() +
  scale_size_identity()

It's unusual in a ggplot to put the actual colors/sizes/linetypes you want in the data frame (instead of meaningful labels you might want on a legend, like you do for lbs), but if you do the identity scales are your friend.

A more standard approach would have your data set up perhaps like this:

   qntls        lbs heights is_target
1  29.00      p5=29 32.2400        no
2  45.25     p25=45 33.5296        no
3  79.00     p50=79 30.9504        no
4 128.00    p75=128 32.2400        no
5 249.25    p95=249 33.5296        no
6 120.00 Target=120 30.9504       yes

Then map linetype = is_target, size = is_target inside aes(), and use manual scales like this:

... +
scale_size_manual(values = c("no" = 0.1, "yes" = 0.2)) +
scale_linetype_manual(values = c("no" = "dashed", "yes" = "solid"))

This set-up makes it easy to adjust your graph without changing your data.


问:
Get Typescript typing of returned object

Challenge

Below is a simplified example of how we control and pass data in an app. It is used in many places and works to translate data between UI, APIs, and a database.
API and UI use camelCase.
Database uses snake_case.

Currently, it's an awkward combination of Partial/Pick types to get some typing where...

```<code>const item = { fooBar: 'something' }
Item.cast(item).value // returns type Partial<ItemModel>
Item.create(item).value // returns type ItemModel
</code>```

The goal is to return the real returned object type.

```<code>// Examples
const item = { fooBar: 'something' }
Item.cast(item).value // returns { fooBar: 'something' }
Item.cast(item).databaseFormat // returns { foo_bar: 'something' }
Item.create(item).value // returns { id: '{uuid}', fooBar: 'something' }
Item.create(item).databaseFormat // returns { id: '{uuid}', foo_bar: 'something' }

const itemFromDatabase = { id: '{uuid}', foo_bar: 'something', baz: null }
Item.cast(itemFromDatabase).value // returns { id: '{uuid}', fooBar: 'something', baz: null }
Item.cast(itemFromDatabase).databaseFormat // returns { id: '{uuid}', foo_bar: 'something', baz: null }
</code>```

Any ideas on this? I would image it's something like the Object.entries() return type but I can't figure out that right T keyof combination.

```<code>// https://mariusschulz.com/blog/keyof-and-lookup-types-in-typescript
interface ObjectConstructor {
  // ...
  entries<T extends { [key: string]: any }, K extends keyof T>(o: T): [keyof T, T[K]][];
  // ...
}
</code>```

Code

```<code>import camelcaseKeys from 'camelcase-keys'
import snakecaseKeys from 'snakecase-keys'

type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>

interface ItemModel {
  id: string
  fooBar: any
  baz?: number
}

interface ItemDatabaseModel {
  id: string
  foo_bar: any
  baz?: number
}

export class Item {

  private _data: Partial<ItemModel>

  public static cast(item: Partial<ItemModel | ItemDatabaseModel>): Item {
    return new this(camelcaseKeys(item))
  }

  public static create(item: Optional<ItemModel | ItemDatabaseModel, 'id'>): Item {
    // Use item.id or add item.id === null to force key
    return new this(camelcaseKeys(item))
  }

  private constructor(input: Partial<ItemModel>) {
    // Validate "input" properties have a Item class property setter, else throw
    // foreach => this[key] = input[key]
  }

  get databaseFormat() { return snakecaseKeys(this._data) }
  get value() { return this._data }

  set id(value: string | null) {
    // automatically generate an ID if null, otherwise validate
    this._data.id = value
  }
  set fooBar(value: any) {
    // validate
    this._data.fooBar = value
  }
  set baz(value: number | null) {
    // validate
    this._data.baz = value
  }
}
</code>```

答:
The best way you could achieve this would be to have some tool which goes through your typescript files looking to type/interface definitions and automatically outputs additional types with the converted keys based on what it finds.

At the moment typescript doesn't support this kind of conversion automatically via a type definition and I'd guess that they'd be quite cautious about adding something like that; concatenating string literals in type definitions is something which has yet to make it into the language, for instance, and what you're looking for here is quite a bit more complex than that, unfortunately.

Body:
Challenge

Below is a simplified example of how we control and pass data in an app. It is used in many places and works to translate data between UI, APIs, and a database.
API and UI use camelCase.
Database uses snake_case.

Currently, it's an awkward combination of Partial/Pick types to get some typing where...

const item = { fooBar: 'something' }
Item.cast(item).value // returns type Partial<ItemModel>
Item.create(item).value // returns type ItemModel

The goal is to return the real returned object type.

// Examples
const item = { fooBar: 'something' }
Item.cast(item).value // returns { fooBar: 'something' }
Item.cast(item).databaseFormat // returns { foo_bar: 'something' }
Item.create(item).value // returns { id: '{uuid}', fooBar: 'something' }
Item.create(item).databaseFormat // returns { id: '{uuid}', foo_bar: 'something' }

const itemFromDatabase = { id: '{uuid}', foo_bar: 'something', baz: null }
Item.cast(itemFromDatabase).value // returns { id: '{uuid}', fooBar: 'something', baz: null }
Item.cast(itemFromDatabase).databaseFormat // returns { id: '{uuid}', foo_bar: 'something', baz: null }

Any ideas on this? I would image it's something like the Object.entries() return type but I can't figure out that right T keyof combination.

// https://mariusschulz.com/blog/keyof-and-lookup-types-in-typescript
interface ObjectConstructor {
  // ...
  entries<T extends { [key: string]: any }, K extends keyof T>(o: T): [keyof T, T[K]][];
  // ...
}

Code

import camelcaseKeys from 'camelcase-keys'
import snakecaseKeys from 'snakecase-keys'

type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>

interface ItemModel {
  id: string
  fooBar: any
  baz?: number
}

interface ItemDatabaseModel {
  id: string
  foo_bar: any
  baz?: number
}

export class Item {

  private _data: Partial<ItemModel>

  public static cast(item: Partial<ItemModel | ItemDatabaseModel>): Item {
    return new this(camelcaseKeys(item))
  }

  public static create(item: Optional<ItemModel | ItemDatabaseModel, 'id'>): Item {
    // Use item.id or add item.id === null to force key
    return new this(camelcaseKeys(item))
  }

  private constructor(input: Partial<ItemModel>) {
    // Validate "input" properties have a Item class property setter, else throw
    // foreach => this[key] = input[key]
  }

  get databaseFormat() { return snakecaseKeys(this._data) }
  get value() { return this._data }

  set id(value: string | null) {
    // automatically generate an ID if null, otherwise validate
    this._data.id = value
  }
  set fooBar(value: any) {
    // validate
    this._data.fooBar = value
  }
  set baz(value: number | null) {
    // validate
    this._data.baz = value
  }
}


问:
Microbial Network Analysis in igraph
I have bacterial OTU table at all taxonomy levels. I want to plot network using igraph (or any other package). I have never created such plot so please if anyone know some tutorial link for beginner? OR If someone guide me with scripts, you time would be really appreciated. Thank you!</p>

答:
I don't understand what data did you have, here an example of routine for small network analysis:

You first have to define what kind of link you want to analyse (e.g., what relationship ? Are the edges directed - and maybe reciprocal - or not ? which caracteristics for nodes and edges are relevant ?).

Then you have to build your edges-list. In my case the most common
way for small network (no need of big performance) is to made a data.frame
with the tidyverse. In every case in network analysis, you want an edges-list. It's usually a data.frame whith the links between 2 entities that you call your network.
Then the analysis:

FOR SMALL GRAPH ONLY, you start by plotting and read the plot. Hereafter, an edges-list sent to igraph and plotted, assuming you require about the tidyverse syntax (%>%):

myedgeslist <- data.frame(from = c('man1', 'man2','man3', 'man3'),
                    to = c('man3','man1','man1', 'man2') )
mygraph <- myedgeslist %>% igraph::graph_from_data_frame(directed = T)
mygraph %>% igraph::plot.igraph()

Which plot a small Directed Network between 3 nodes and with 4 links (Igraph said: IGRAPH DN-- 3 4 -- to indicate DN directed network, 3 nodes and 4 links).

In parallel, you have to made some tidyverse group-statistics, e.g.,

myedgeslist %>% group_by(to) %>% summarise(nlinksto= n(), n_nodes=n_distinct(from)) %>% arrange(desc(n_nodes)) said that 'man1' is the most central nodes, 'cause 2 links go to him (vs. one single link for man3 and man2).

In parallel, like I said above, read some theorical stuff of network analysis and compute indicators for understand the network (centrality, reciprocity . . .). e.g.,

mygraph %>% igraph::edge_density() said that 66 % of the directed links are realized in this network.

PS: it's usually a bad idea to plot large network, you must slice them in several parts or to resume the network  by global/grouped statistics.

Title: Microbial Network Analysis in igraph


问:
How to return routes to views in laravel
I just tried loading a view using a route like so:

```<code>route.php
Route::get("/page", function(){
   return View::make("dir.page");
});

controller.php
View::make("/page");
</code>```

...and an error was  thrown. So my question is:

Is it possible to load a route via a view and if its possible then how?

Thanks.

答:
In laravel 5.8 I had to use this.</p>

```<code>Route::get("/page", function(){
   return \View::make("dir.page");
});
</code>```

Body:
I just tried loading a view using a route like so:

route.php
Route::get("/page", function(){
   return View::make("dir.page");
});

controller.php
View::make("/page");

...and an error was  thrown. So my question is:

Is it possible to load a route via a view and if its possible then how?

Thanks.

Body:
In laravel 5.8 I had to use this.

Route::get("/page", function(){
   return \View::make("dir.page");
});


问:
How to use IUIAutomation::ElementFromPoint to get deeper web elements
I would like to obtain elements on my web browser (Chrome) using the IUIAutomation::ElementFromPoint method.

https://learn.microsoft.com/ja-jp/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomation-elementfrompoint

When I call the ElementFromPoint method with the point shown below, I can only get as far as the Chrome window.
But once I've used the Inspect tool, I can get to the deeper elements when I call the same method.

I am hoping to do the same with my tools.
How do you use the ElementFromPoint method to get the deepest web elements?

Before using inspect tool.

After using inspect tool.

答:
Get from point only returns the topmost window around the cursor.
To go lower you have to drill into the components and check that their bounds contain your cursor position (I know, but it’s not as slow as you’d think).

Make sure you’re using either a raw tree view walker or at least a control tree view walker.

Firefox and chrome (and I guess the new edge) require that your code Is signed to drill into web pages (otherwise you could be building something to steal card info etc) - so triple check what your program performs like when used on a machine that it wasn’t developed on , in release mode, and not on an admin account.


问:
jQuery: binding a single event listener that can handle events of its children
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

```<code><ul class="myList">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
<li><a href="page6.html">Page 6</a></li>
<!-- ... -->
<li><a href="page1000.html">Page 1000</a></li>
</ul>
</code>```

I want to bind a click event handler to the  tag.  Normally, I would write out

```<code>$('.myList').find('a').click(function() {});  /* Or something similar */
</code>```

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

答:
Check out delegate() — it's exactly what you're asking for.

```<code>$('ul.mylist').delegate('a', 'click', function() {
  // ... your code ...
});
</code>```

You get all the benefits of a jQuery handler, without having to do the binding to all those elements.

Body:
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

Page 1

Page 2

Page 3

Page 4

Page 5

Page 6

Page 1000

I want to bind a click event handler to the  tag.  Normally, I would write out

$('.myList').find('a').click(function() {});  /* Or something similar */

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

Body:
Check out delegate() — it's exactly what you're asking for.

$('ul.mylist').delegate('a', 'click', function() {
  // ... your code ...
});

You get all the benefits of a jQuery handler, without having to do the binding to all those elements.


问:
How can I add to the custom listview user control the tasks like editing the items columns groups?
The reason for this control is to make the listview stop flickering when scrolling.
The flickering has stopped and it's working fine but the listview control don't have the same properties like the regular winforms listview.

In this screenshot the listview with the ListView Tasks window is the regular listview and the smaller rectangle the empty one is the custom control.

This is the custom control listview code :

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace FileSearcher
{
    public partial class ListViewCostumControl : UserControl
    {
        public static ListViewControl lvnf;

        public ListViewCostumControl()
        {
            InitializeComponent();

            lvnf = new ListViewControl();
            lvnf.Location = new Point(50, 50);
            lvnf.Size = new Size(50, 50);
            lvnf.View = View.Details;
            lvnf.Dock = DockStyle.Fill;
            lvnf.SuspendLayout();
            lvnf.LabelEdit = true;
            lvnf.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            lvnf.Columns.Add("", 984, HorizontalAlignment.Left);
            lvnf.Sorting = SortOrder.None;
            this.Controls.Add(lvnf);
            lvnf.ResumeLayout(false);
        }

        public class ListViewControl : System.Windows.Forms.ListView
        {
            public ListViewControl()
            {
                //Activate double buffering
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

                //Enable the OnNotifyMessage event so we get a chance to filter out
                // Windows messages before they get to the form's WndProc
                this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            }

            protected override void OnNotifyMessage(System.Windows.Forms.Message m)
            {
                //Filter out the WM_ERASEBKGND message
                if (m.Msg != 0x14)
                {
                    base.OnNotifyMessage(m);
                }
            }
        }

        private void ListViewNFTest_Load(object sender, EventArgs e)
        {

        }
    }
}
</code>```

答:
I added the columns on my own and got the same view as the original list view control.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace FileSearcher
{
    public partial class ListViewCostumControl : UserControl
    {
        public static ListView lvnf;

        public ListViewCostumControl()
        {
            InitializeComponent();

            lvnf = new ListView();
            lvnf.Location = new Point(50, 50);
            lvnf.Size = new Size(50, 50);
            lvnf.View = View.Details;
            lvnf.Dock = DockStyle.Fill;
            lvnf.HideSelection = false;
            lvnf.MultiSelect = false;

            //lvnf.SuspendLayout();
            //lvnf.LabelEdit = true;
            //lvnf.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            lvnf.Columns.Add("Path", 212, HorizontalAlignment.Left);
            lvnf.Columns.Add("Path", 90, HorizontalAlignment.Right);
            lvnf.Columns.Add("Last modified", 120, HorizontalAlignment.Left);
            lvnf.Columns.Add("", 984, HorizontalAlignment.Left);
            lvnf.Sorting = SortOrder.None;
            this.Controls.Add(lvnf);
            lvnf.ResumeLayout(false);
        }

        public class ListView : System.Windows.Forms.ListView
        {
            public ListView()
            {
                //Activate double buffering
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

                //Enable the OnNotifyMessage event so we get a chance to filter out
                // Windows messages before they get to the form's WndProc
                this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            }

            protected override void OnNotifyMessage(System.Windows.Forms.Message m)
            {
                //Filter out the WM_ERASEBKGND message
                if (m.Msg != 0x14)
                {
                    base.OnNotifyMessage(m);
                }
            }
        }

        private void ListViewNFTest_Load(object sender, EventArgs e)
        {

        }
    }
}
</code>```

Working good without any flickers.

Body:
The reason for this control is to make the listview stop flickering when scrolling.
The flickering has stopped and it's working fine but the listview control don't have the same properties like the regular winforms listview.

In this screenshot the listview with the ListView Tasks window is the regular listview and the smaller rectangle the empty one is the custom control.

This is the custom control listview code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace FileSearcher
{
    public partial class ListViewCostumControl : UserControl
    {
        public static ListViewControl lvnf;

        public ListViewCostumControl()
        {
            InitializeComponent();

            lvnf = new ListViewControl();
            lvnf.Location = new Point(50, 50);
            lvnf.Size = new Size(50, 50);
            lvnf.View = View.Details;
            lvnf.Dock = DockStyle.Fill;
            lvnf.SuspendLayout();
            lvnf.LabelEdit = true;
            lvnf.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            lvnf.Columns.Add("", 984, HorizontalAlignment.Left);
            lvnf.Sorting = SortOrder.None;
            this.Controls.Add(lvnf);
            lvnf.ResumeLayout(false);
        }

        public class ListViewControl : System.Windows.Forms.ListView
        {
            public ListViewControl()
            {
                //Activate double buffering
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

                //Enable the OnNotifyMessage event so we get a chance to filter out
                // Windows messages before they get to the form's WndProc
                this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            }

            protected override void OnNotifyMessage(System.Windows.Forms.Message m)
            {
                //Filter out the WM_ERASEBKGND message
                if (m.Msg != 0x14)
                {
                    base.OnNotifyMessage(m);
                }
            }
        }

        private void ListViewNFTest_Load(object sender, EventArgs e)
        {

        }
    }
}

Body:
I added the columns on my own and got the same view as the original list view control.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace FileSearcher
{
    public partial class ListViewCostumControl : UserControl
    {
        public static ListView lvnf;

        public ListViewCostumControl()
        {
            InitializeComponent();

            lvnf = new ListView();
            lvnf.Location = new Point(50, 50);
            lvnf.Size = new Size(50, 50);
            lvnf.View = View.Details;
            lvnf.Dock = DockStyle.Fill;
            lvnf.HideSelection = false;
            lvnf.MultiSelect = false;

            //lvnf.SuspendLayout();
            //lvnf.LabelEdit = true;
            //lvnf.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            lvnf.Columns.Add("Path", 212, HorizontalAlignment.Left);
            lvnf.Columns.Add("Path", 90, HorizontalAlignment.Right);
            lvnf.Columns.Add("Last modified", 120, HorizontalAlignment.Left);
            lvnf.Columns.Add("", 984, HorizontalAlignment.Left);
            lvnf.Sorting = SortOrder.None;
            this.Controls.Add(lvnf);
            lvnf.ResumeLayout(false);
        }

        public class ListView : System.Windows.Forms.ListView
        {
            public ListView()
            {
                //Activate double buffering
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

                //Enable the OnNotifyMessage event so we get a chance to filter out
                // Windows messages before they get to the form's WndProc
                this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            }

            protected override void OnNotifyMessage(System.Windows.Forms.Message m)
            {
                //Filter out the WM_ERASEBKGND message
                if (m.Msg != 0x14)
                {
                    base.OnNotifyMessage(m);
                }
            }
        }

        private void ListViewNFTest_Load(object sender, EventArgs e)
        {

        }
    }
}

Working good without any flickers.


问:
Java Long.parseLong does not give correct value in terms of 2's complement
I have the following codes where I am doing conversion from hex to decimal.
Long.parseLong("FF44C5EC",16).
The output I get is this 4282697196
But by right it should be a negative number. What else should I do to get the correct conversion with 2's complement ?

答:
parseLong returns a signed long, but by "signed" it means that it can handle negative numbers if you pass a string starting with -, not that it knows the 2's complement.

Parses the string argument as a signed long in the radix specified by
  the second argument. The characters in the string must all be digits
  of the specified radix (as determined by whether Character.digit(char,
  int) returns a nonnegative value), except that the first character may
  be an ASCII minus sign '-' ('\u002D') to indicate a negative value or
  an ASCII plus sign '+' ('\u002B') to indicate a positive value. The
  resulting long value is returned.

A solution could be:

```<code>Long.valueOf("FF44C5EC",16).intValue()
</code>```

That prints -12270100 as you expect.

Body:
parseLong returns a signed long, but by "signed" it means that it can handle negative numbers if you pass a string starting with -, not that it knows the 2's complement.

Parses the string argument as a signed long in the radix specified by
  the second argument. The characters in the string must all be digits
  of the specified radix (as determined by whether Character.digit(char,
  int) returns a nonnegative value), except that the first character may
  be an ASCII minus sign '-' ('\u002D') to indicate a negative value or
  an ASCII plus sign '+' ('\u002B') to indicate a positive value. The
  resulting long value is returned.

A solution could be:

Long.valueOf("FF44C5EC",16).intValue()

That prints -12270100 as you expect.


问:
cant connect to mysql database from spring project
I´m having a weird issue with MySQL. When i run my Spring project it throws the exception:

```<code>java.sql.SQLException: Access denied for user 'root     '@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
</code>```

I can connect to MySQL using the command line mysql -u root -p whithout issues

Here´s my application.properties file:

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = admin

spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

spring.thymeleaf.cache = true
</code>```

Here´s the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ernesto</groupId>
    <artifactId>SpringLogInApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringLogInApp</name>
    <description>Login App With Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I´ve tried reinstalling MySQL several times. The project is built with maven. The same happens if i switch user and password in application.properties. The schema "test" is already created. I´ve tried everything i found here at SO with no luck. Need some help.

Thanks in advance

答:
You need to trim your user name mentioned in props files.
Even right now when I am trying to select username its showing lots of extra spaces

Body:
I´m having a weird issue with MySQL. When i run my Spring project it throws the exception:

java.sql.SQLException: Access denied for user 'root     '@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

I can connect to MySQL using the command line mysql -u root -p whithout issues

Here´s my application.properties file:

spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = admin

spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

spring.thymeleaf.cache = true

Here´s the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.ernesto</groupId>
    <artifactId>SpringLogInApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringLogInApp</name>
    <description>Login App With Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I´ve tried reinstalling MySQL several times. The project is built with maven. The same happens if i switch user and password in application.properties. The schema "test" is already created. I´ve tried everything i found here at SO with no luck. Need some help.

Thanks in advance