问:
PKIX path building failed on Kubernetes AutoDevOps
I'm using a custom artifacotry repository on which I deploy my projects.
This is working fine when I'm working on my local machine but I've enable the AutoDevOps feature of Gitlab and integrate my project with a Kubernetes cluster.

The kubernetes cluster is managed by rancher.

The issue is that the build runned on Gitlab is failing with the following error:

Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of
  its dependencies could not be resolved: Failed to read artifact
  descriptor for
  org.apache.maven.plugins:maven-resources-plugin:jar:2.6: Could not
  transfer artifact
  org.apache.maven.plugins:maven-resources-plugin:pom:2.6 from/to
  adibox-snapshots
  (https://artifactory.mydomain.com/artifactory/libs-snapshot): Transfer
  failed for
  https://artifactory.mydomain.com/artifactory/libs-snapshot/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom:
  PKIX path building failed:
  sun.security.provider.certpath.SunCertPathBuilderException: unable to
  find valid certification path to requested target -> [Help 1]

If it was running on a local machine I know I could add the certificate to the java keystore by using keytool command lines. But I do not find where, in case of the AutoDevOps I could add the certificate. My best guess would be to add it on the Runner machine but I do not have any control on it as it's managed by Gitlab.

Any help is welcome.

Thanks.

答:
I fixed it by adding

```<code>before_script:
  - keytool -importcert -file artifactory.cer -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt
</code>```

in my .gitlab-ci.yml file.

It will add the certificate to the Gitlab-Runner.

Body:
I fixed it by adding

before_script:
  - keytool -importcert -file artifactory.cer -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt

in my .gitlab-ci.yml file.

It will add the certificate to the Gitlab-Runner.


来源: stackexchange

问:
jmespath. Change one element in an array depending on type
Im use Ansible filter json_query

data:

```<code>[
  "just_dir",
  {
     "path": "extend_dir",
     "order": "nginx"
  }
]
</code>```

I want to get:

```<code>[
  {
     "path": "just_dir",
  },
  {
     "path": "extend_dir",
     "order": "nginx"
  }
]
</code>```

```<code>merage([?type(@) == `string`].{path: @}, [?type(@) == `object`])
</code>```

does not work.

答:
Unfortunately, it looks like is not possible to merge to 2 arrays

Github issue: jmespath.py#152

Also you need to add a from_json filter before apply it to json_query

```<code>---
- hosts: localhost
  gather_facts: no
  vars:
    data: '[
      "just_dir",
      {
         "path": "extend_dir",
         "order": "nginx"
      }
    ]'
  tasks:
   - name: debug just_dir
     debug: msg="{{ data | from_json  | json_query(jmesquery) }}"
     vars:
       jmesquery: "[?type(@) == `string`].{path: @}"

   - name: debug Other data
     debug: msg="{{ data | from_json  | json_query(jmesquery) }}"
     vars:
       jmesquery: "[?type(@) == `object`]"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im use Ansible filter json_query

data:

[
  "just_dir",
  {
     "path": "extend_dir",
     "order": "nginx"
  }
]

I want to get:

[
  {
     "path": "just_dir",
  },
  {
     "path": "extend_dir",
     "order": "nginx"
  }
]

merage([?type(@) == `string`].{path: @}, [?type(@) == `object`])

does not work.

Body:
Unfortunately, it looks like is not possible to merge to 2 arrays

Github issue: jmespath.py#152

Also you need to add a from_json filter before apply it to json_query

---
- hosts: localhost
  gather_facts: no
  vars:
    data: '[
      "just_dir",
      {
         "path": "extend_dir",
         "order": "nginx"
      }
    ]'
  tasks:
   - name: debug just_dir
     debug: msg="{{ data | from_json  | json_query(jmesquery) }}"
     vars:
       jmesquery: "[?type(@) == `string`].{path: @}"

   - name: debug Other data
     debug: msg="{{ data | from_json  | json_query(jmesquery) }}"
     vars:
       jmesquery: "[?type(@) == `object`]"


问:
Converting arraybuffer to string : Maximum call stack size exceeded
This is my code.

```<code>var xhr = new XMLHttpRequest();
xhr.open('GET',window.location.href, true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
 debugger;
 console.log(" coverting array buffer to string ");
 alert(String.fromCharCode.apply(null, new Uint8Array(this.response)));
};
xhr.send();
</code>```

That request is being made to a PDF URL which is around 3 MB in size. I have read a few threads with same error, Maximum call stack size exceeded, telling me that there must be some recursive call but I do not see any recursive call here. Can anyone help?

答:
```<code>this.response.arrayBuffer()
              .then((buf) => {
                const uint8Array = new Uint8Array(buf);
                const data = uint8Array.reduce((acc, i) => acc += String.fromCharCode.apply(null, [i]), '');
                return data;
              })
</code>```

Body:
This is my code.

var xhr = new XMLHttpRequest();
xhr.open('GET',window.location.href, true);
xhr.responseType = "arraybuffer";
xhr.onload = function(event) {
 debugger;
 console.log(" coverting array buffer to string ");
 alert(String.fromCharCode.apply(null, new Uint8Array(this.response)));
};
xhr.send();

That request is being made to a PDF URL which is around 3 MB in size. I have read a few threads with same error, Maximum call stack size exceeded, telling me that there must be some recursive call but I do not see any recursive call here. Can anyone help?


问:
Use alias in layout templates ruby on rails
I need to use a variable in template.
I have a class call services;
need who this atributes, after iterable, as variable type alias.

In django we use, Example: {% firstof "0" as cont %}. I use the first element as cont.

In ruby on rails templates, how can I do this?

答:
Also, i do this with a variable in controller.

The @aux solve this quest

in controller:
@aux = 0

in my html.erb

do this...

do this...


问:
Python3 and Docker multistage build file not found
I am noob to docker and i am trying to build a multistage dockerfile for python3

```<code>FROM ubuntu:18.04 as base
RUN apt-get -qy update && apt-get install python3 -y
WORKDIR /pydocktest
COPY test.py .

FROM  ubuntu:18.04 AS release
WORKDIR /pytest
COPY --from=base /usr/local/bin/ /usr/local/bin/
COPY --from=base /pydocktest .
CMD ["./test.py"]
</code>```

Then

```<code>docker build -t test .
docker run test
</code>```

Output

```<code>standard_init_linux.go:211: exec user process caused "no such file or directory"
</code>```

but when i run apt -get install python3 in the release part, it works perfect ? so why the need of multistage if i am going to reinstall python sorry if i sound dump

答:
Short answer: there is no need for a multistage if you reinstall Python in the final image.

Long answer: one reason for using a multistage is that you need special applications and files when building your application but don't need them at runtime. In your example, that's not the case.

As a suggestion also, you could use the python3 image instead of installing it yourself. That would simplify your Dockerfile:

```<code>FROM python:3
COPY test.py .
CMD [ "python", "./test.py" ]
</code>```

If you want to learn more about the rationale behind multistage Dockerfiles, my Learn Docker book explains them, and by the way it's a book written for noobs.

Body:
I am noob to docker and i am trying to build a multistage dockerfile for python3

FROM ubuntu:18.04 as base
RUN apt-get -qy update && apt-get install python3 -y
WORKDIR /pydocktest
COPY test.py .

FROM  ubuntu:18.04 AS release
WORKDIR /pytest
COPY --from=base /usr/local/bin/ /usr/local/bin/
COPY --from=base /pydocktest .
CMD ["./test.py"]

Then

docker build -t test .
docker run test

Output

standard_init_linux.go:211: exec user process caused "no such file or directory"

but when i run apt -get install python3 in the release part, it works perfect ? so why the need of multistage if i am going to reinstall python sorry if i sound dump

Body:
Short answer: there is no need for a multistage if you reinstall Python in the final image.

Long answer: one reason for using a multistage is that you need special applications and files when building your application but don't need them at runtime. In your example, that's not the case.

As a suggestion also, you could use the python3 image instead of installing it yourself. That would simplify your Dockerfile:

FROM python:3
COPY test.py .
CMD [ "python", "./test.py" ]

If you want to learn more about the rationale behind multistage Dockerfiles, my Learn Docker book explains them, and by the way it's a book written for noobs.


问:
CakePHP Forgot Password / Ticket component help
I'm using the following tutorial to build a password reset form: http://bakery.cakephp.org/articles/eimermusic/2007/10/23/ticket-component-resetting-user-passwords

However when I submit the form I get the following error: Fatal error: Class 'Ticket' not found in /Users/cameron/Sites/thehive/app/controllers/components/tickets.php on line 60

And Line 60 is this: $ticketObj = new Ticket();

Any ideas what the problem is and how to fix it thanks?

答:
I'm pretty sure you just forgot to create the Ticket model class:

```<code><?php
class Ticket extends AppModel
{
    var $name = 'Ticket';
}
?>
</code>```

Just put this in a file "ticket.php" within your /app/model directory.

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty sure you just forgot to create the Ticket model class:

<?php
class Ticket extends AppModel
{
    var $name = 'Ticket';
}
?>

Just put this in a file "ticket.php" within your /app/model directory.


问:
SSRS Is there a way to set a dropdown null check mark as default?
enter image description hereI have 3 dropdowns and i want 1 dropdown set null check mark by default.
So only when needed to filter with marriedname the check mark can be removed.
Dropdown are Names, Firstnames and Marriedname.

Dataset Marriedname:

Select distinct [Name3]
from Patient
ORDER BY [Name3]

答: Below steps will help you get your desired result.


问:
update database table with button
I'm trying to update my databse with a button to set the visibility from 0 to 1. There isn't any syntax error but for some reason it doesn't change the database value. My database example: (visibility is tinyint with default 0 value)

```<code> id-   name-   visibility
---------------------------
1   -   John    -    1
---------------------------
2   -   Ben     -    1
---------------------------
3   -   Terry   -    0
---------------------------
</code>```

and my php code:

```<code><?php
$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $record = mysqli_fetch_assoc($resultset) ) {
?>
<div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>I want this to be hidden here</div>

<button type="button" class="btn btn-success" name="update">Accept</button>
<?php

if(isset($_POST['update'])){
$allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>
//html stuff here
 <?php }
      ?>
</code>```

答:
You have to wrap your button into a <form> and set its type to submit. Furthermore you need to pass the records id with it. Try this example:

```<code><?php

$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $record = mysqli_fetch_assoc($resultset) ) { ?>

  <div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>

    Record name: <?php echo $record['name']; ?>
    <form action="" method="POST">
      <input value="<?php echo $record['id']; ?>" name="id">
      <button type="submit" class="btn btn-success" name="update">Set visibile</button>
    </form>

  </div>

<?php } ?>

<?php
if(isset($_POST['update'])){
  $id = $_POST['id'];
  $allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>
</code>```

If you get this to work, you should search about prepared statements.

Title: update database table with button

Body:
I'm trying to update my databse with a button to set the visibility from 0 to 1. There isn't any syntax error but for some reason it doesn't change the database value. My database example: (visibility is tinyint with default 0 value)

 id-   name-   visibility
---------------------------
1   -   John    -    1
---------------------------
2   -   Ben     -    1
---------------------------
3   -   Terry   -    0
---------------------------

and my php code:

<?php
$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $record = mysqli_fetch_assoc($resultset) ) {
?>
<div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>I want this to be hidden here

<button type="button" class="btn btn-success" name="update">Accept</button>
<?php

if(isset($_POST['update'])){
$allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>
//html stuff here
 <?php }
      ?>

Body:
You have to wrap your button into a <form> and set its type to submit. Furthermore you need to pass the records id with it. Try this example:

<?php

$sql = "SELECT id, name, image, description, address, phone, phone2, email, job, visibility FROM cards";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
while( $record = mysqli_fetch_assoc($resultset) ) { ?>

  <div class="col-md-4" <?php if ($record['visibility'] == 1) echo " style='display: none';"; ?>>

    Record name: <?php echo $record['name']; ?>
    <form action="" method="POST">
      <input value="<?php echo $record['id']; ?>" name="id">
      <button type="submit" class="btn btn-success" name="update">Set visibile</button>
    </form>

  </div>

<?php } ?>

<?php
if(isset($_POST['update'])){
  $id = $_POST['id'];
  $allowed = mysqli_query($conn," UPDATE cards SET visibility = '1' WHERE id = '$id' ");
}
?>

If you get this to work, you should search about prepared statements.


问:
check for specific key and value pairs in two dictionaries (both dictionary has same key and value pairs)
I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true.
I am new to python, Please help me to write a function for the same.

The dictionaries are

```<code>A: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
B: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
</code>```

Here I want to check if the 'start1', 'end1', 'start2' and 'end2' values are the same are not.

答:
you can use a for loop:

```<code>wanted_keys = {'start1', 'end1', 'start2', 'end2'}

same = True
for k in wanted_keys:
    if A.get(k) != B.get(k):
        same = False
        break
</code>```

one line code:

```<code>all(A.get(k) == B.get(k) for k in wanted_keys)
</code>```

Body:
I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true.
I am new to python, Please help me to write a function for the same.

The dictionaries are

A: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
B: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}

Here I want to check if the 'start1', 'end1', 'start2' and 'end2' values are the same are not.

Body:
you can use a for loop:

wanted_keys = {'start1', 'end1', 'start2', 'end2'}

same = True
for k in wanted_keys:
    if A.get(k) != B.get(k):
        same = False
        break

one line code:

all(A.get(k) == B.get(k) for k in wanted_keys)


问:
How can I suppress java compiler warnings about Sun proprietary API
I'm using the encode() method from the sun.misc.BASE64Encoder package. How do I suppress the compiler warnings that it generates?

sun.misc.BASE64Encoder is Sun proprietary API and may be removed in

And as a followup, why don't I see this warning in Eclipse?

答: The javac option -Xlint:unchecked does do the trick: it disables the warnings, see the javac manual for details

ContentLicense: CC BY-SA 2.5


问:
How can I add line under Row of UICollectionView, Swift 5, Xcode
How can I add line under Row of UICollectionView, Swift 5, Xcode?

I want separate row by line.

答:
As Ayazmon said, you can add UIView to you cell with height of 1.

You can add bottom border to your cell.

```<code>extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case .top:
        border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
    case .bottom:
        border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
    case .left:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
    case .right:
        border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
    default:
        break
    }
    border.backgroundColor = color.cgColor
    addSublayer(border)
    }
}
</code>```

Then

cell.layer.addBorder(edge: .bottom, color: .black, thickness: 1)

Body:
As Ayazmon said, you can add UIView to you cell with height of 1.

You can add bottom border to your cell.

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case .top:
        border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
    case .bottom:
        border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
    case .left:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
    case .right:
        border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
    default:
        break
    }
    border.backgroundColor = color.cgColor
    addSublayer(border)
    }
}

Then

cell.layer.addBorder(edge: .bottom, color: .black, thickness: 1)


问:
C# - Finding a string between two strings
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

```<code>int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);
</code>```

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

答: I believe you can use string.split with ">" as your char array and get the array. Once you get the array you should be able to iterate the array and get the required value</p>

Body:
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.


问:
How to iterate over a nested Ruby hash to add a new key/value pair based on existing key/value data?

I have a nested hash of data:

```<code>munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}
</code>```

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

```<code>ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
</code>```

I would then likely loop though like this:

```<code>age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end
</code>```

For the nested hash, I'm able to access the entire nested hash like this:

```<code>munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end
</code>```

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male
```

答:
The problem with your current attempt is that you try to do something for each key/value-pair of each munster. However you are only interested in the "age" and "age_group". So there is no need to iterate the key/value-pairs of munster. Instead work directly on munster.

Other examples mostly show mutating solution, so let me offer a non-mutating alternative (meaning that munsters doesn't change). I've also removed the if-statement to provide an alternative perspective.

threshholds = { "kid" => 0, "adult" => 18, "senior" => 65 }

age_groups = threshholds.each_key.sort_by(&threshholds)
new_munsters = munsters.transform_values do |munster|
  age_group = age_groups
    .take_while { |age_group| munster["age"] > threshholds[age_group] }
    .last

  munster.merge("age_group" => age_group)
end
#=> {
#   "Herman"=>{"age"=>32, "gender"=>"male", "age_group"=>"adult"},
#   "Lily"=>{"age"=>30, "gender"=>"female", "age_group"=>"adult"},
#   "Grandpa"=>{"age"=>402, "gender"=>"male", "age_group"=>"senior"},
#   "Eddie"=>{"age"=>10, "gender"=>"male", "age_group"=>"kid"},
#   "Marilyn"=>{"age"=>23, "gender"=>"female", "age_group"=>"adult"}
# }
```

This solution uses transform_values to create a new version of munsters, containing new updated versions of munster (created with merge).

Body:
I have a nested hash of data:

munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }

I would then likely loop though like this:

age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end

For the nested hash, I'm able to access the entire nested hash like this:

munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male

Body:
The problem with your current attempt is that you try to do something for each key/value-pair of each munster. However you are only interested in the "age" and "age_group". So there is no need to iterate the key/value-pairs of munster. Instead work directly on munster.

Other examples mostly show mutating solution, so let me offer a non-mutating alternative (meaning that munsters doesn't change). I've also removed the if-statement to provide an alternative perspective.

threshholds = { "kid" => 0, "adult" => 18, "senior" => 65 }

age_groups = threshholds.each_key.sort_by(&threshholds)
new_munsters = munsters.transform_values do |munster|
  age_group = age_groups
    .take_while { |age_group| munster["age"] > threshholds[age_group] }
    .last

  munster.merge("age_group" => age_group)
end
#=> {
#   "Herman"=>{"age"=>32, "gender"=>"male", "age_group"=>"adult"},
#   "Lily"=>{"age"=>30, "gender"=>"female", "age_group"=>"adult"},
#   "Grandpa"=>{"age"=>402, "gender"=>"male", "age_group"=>"senior"},
#   "Eddie"=>{"age"=>10, "gender"=>"male", "age_group"=>"kid"},
#   "Marilyn"=>{"age"=>23, "gender"=>"female", "age_group"=>"adult"}
# }

This solution uses transform_values to create a new version of munsters, containing new updated versions of munster (created with merge).


问:
AVPlayer stops playing and doesn't resume again
In my application I have to play audio files stored on a web server. I'm using AVPlayer for it. I have all the play/pause controls and all delegates and observers there which work perfectly fine. On playing small audio files everything works great.

When a long audio file is played it also starts playing fine but after some seconds the AVPlayer pauses the playing (most probably to buffer it). The issue is it doesn't resume on its own again. It keeps in a pause state and if I manually press the play button again it plays smoothly again.

I want to know why AVPlayer doesn't resume automatically and how can I manage to resume the audio again without user pressing the play button again? Thanks.

答:
In my case,

I was trying to record video with imagePickerController and playback recorded video with AVPlayerController.  But it starts playing video and gets stops after 1 second. Somehow it gets time to save video and if you playback it immediately, it won't play.

So solution is ,

call play video after 0.5 seconds (delay). like below

```<code>    -(void)imagePickerController:(UIImagePickerController *)picker
             didFinishPickingMediaWithInfo:(NSDictionary *)info {
            [self performSelector:@selector(playVideo) withObject:self
            afterDelay:0.5];
      }

-(void) playVideo {

   self.avPlayerViewController = [[AVPlayerViewController alloc] init];
      if(self.avPlayerViewController != nil)
    {
     AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:Vpath];
     AVPlayer* player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
     self.avPlayerViewController.player = player;
     self.avPlayerViewController.showsPlaybackControls = NO;
     [self.avPlayerViewController setVideoGravity:AVLayerVideoGravityResizeAspectFill];
     [self.avPlayerViewController.view setFrame:[[UIScreen mainScreen] bounds]];
     self.avPlayerViewController.view.clipsToBounds = YES;
     self.avPlayerViewController.delegate = self;
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinishPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
     [self.viewVideoHolder addSubview:self.avPlayerViewController.view];
     [self.avPlayerViewController.player play];

 }
</code>```

}

```<code> -(void) playerDidFinishPlaying
  {
    [avPlayer pause];
  }
</code>```

swift  ios

Body:
In my case,

I was trying to record video with imagePickerController and playback recorded video with AVPlayerController.  But it starts playing video and gets stops after 1 second. Somehow it gets time to save video and if you playback it immediately, it won't play.

So solution is ,

call play video after 0.5 seconds (delay). like below

    -(void)imagePickerController:(UIImagePickerController *)picker
             didFinishPickingMediaWithInfo:(NSDictionary *)info {
            [self performSelector:@selector(playVideo) withObject:self
            afterDelay:0.5];
      }

-(void) playVideo {

   self.avPlayerViewController = [[AVPlayerViewController alloc] init];
      if(self.avPlayerViewController != nil)
    {
     AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:Vpath];
     AVPlayer* player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
     self.avPlayerViewController.player = player;
     self.avPlayerViewController.showsPlaybackControls = NO;
     [self.avPlayerViewController setVideoGravity:AVLayerVideoGravityResizeAspectFill];
     [self.avPlayerViewController.view setFrame:[[UIScreen mainScreen] bounds]];
     self.avPlayerViewController.view.clipsToBounds = YES;
     self.avPlayerViewController.delegate = self;
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinishPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
     [self.viewVideoHolder addSubview:self.avPlayerViewController.view];
     [self.avPlayerViewController.player play];

 }

}

 -(void) playerDidFinishPlaying
  {
    [avPlayer pause];
  }

swift  ios


问:
Checking if a string can be converted to float in Python
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible.  Doing this for integers is pretty easy

```<code>if element.isdigit():
  newelement = int(element)
</code>```

Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.

```<code>partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
    or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
    or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
  newelement = float(element)
</code>```

This works, but obviously the if statement for that is a bit of a bear.  The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in this question.

Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?

答:
You can use the try-except-else clause , this will catch any conversion/ value errors raised when the value passed cannot be converted to a float

```<code>  def try_parse_float(item):
      result = None
      try:
        float(item)
      except:
        pass
      else:
        result = float(item)
      return result
</code>```

Body:
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible.  Doing this for integers is pretty easy

if element.isdigit():
  newelement = int(element)

Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.

partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
    or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
    or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
  newelement = float(element)

This works, but obviously the if statement for that is a bit of a bear.  The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in this question.

Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?

Body:
You can use the try-except-else clause , this will catch any conversion/ value errors raised when the value passed cannot be converted to a float

  def try_parse_float(item):
      result = None
      try:
        float(item)
      except:
        pass
      else:
        result = float(item)
      return result


问:
Check if array of objects key is empty and splice it
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]```
</div>
</div>
</p>

<p>In the above array there is an empty string "key" if the key value is <code>false</code> then need to splice the array of objects using index.</p>

<p>Below is the code which I have tried:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}</code>```

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

答:
It works for me, please try it</p>

```<code>var newArr = dataTobeDeleted.filter((val) =>{return val[""] === true});
</code>```

Body:
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.

Below is the code which I have tried:

for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

Body:
It works for me, please try it

var newArr = dataTobeDeleted.filter((val) =>{return val[""] === true});


问:
Can you get Request Headers with python request library?
I am using the python requests library to get all the headers from a website, however requests only seems to be getting the Response Headers and i also need the Request Headers.

Is there a way to get the Request Headers within the requests library or should i use a differant library to get the headers?

my code:

```<code>import requests

r = requests.get("https://google.com", allow_redirects = False)

for key in r.headers:
    print(key, ": ", r.headers[key])
</code>```

output:

```<code>Location :  https://www.google.com/
Content-Type :  text/html; charset=UTF-8
Date :  Wed, 19 Feb 2020 13:08:27 GMT
Expires :  Fri, 20 Mar 2020 13:08:27 GMT
Cache-Control :  public, max-age=2592000
Server :  gws
Content-Length :  220
X-XSS-Protection :  0
X-Frame-Options :  SAMEORIGIN
Alt-Svc :  quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
</code>```

答:
The response object contains a request object that is the request which produced the reponse.

This requests.models.PreparedRequest object is accessible through the request property of the response object, its header are in the property headersof the request object.

See this example:

```<code>>>> import requests
>>> r = requests.get("http://google.com")
>>> r.request.headers
{'Connection': 'keep-alive', 'User-Agent': 'python-requests/2.22.0', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate'}
</code>```

Body:
I am using the python requests library to get all the headers from a website, however requests only seems to be getting the Response Headers and i also need the Request Headers.

Is there a way to get the Request Headers within the requests library or should i use a differant library to get the headers?

my code:

import requests

r = requests.get("https://google.com", allow_redirects = False)

for key in r.headers:
    print(key, ": ", r.headers[key])

output:

Location :  https://www.google.com/
Content-Type :  text/html; charset=UTF-8
Date :  Wed, 19 Feb 2020 13:08:27 GMT
Expires :  Fri, 20 Mar 2020 13:08:27 GMT
Cache-Control :  public, max-age=2592000
Server :  gws
Content-Length :  220
X-XSS-Protection :  0
X-Frame-Options :  SAMEORIGIN
Alt-Svc :  quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000

Body:
The response object contains a request object that is the request which produced the reponse.

This requests.models.PreparedRequest object is accessible through the request property of the response object, its header are in the property headersof the request object.

See this example:

>>> import requests
>>> r = requests.get("http://google.com")
>>> r.request.headers
{'Connection': 'keep-alive', 'User-Agent': 'python-requests/2.22.0', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate'}


Title: R insert rows with sequence

Body:
foo <- data.frame("var1"=c(123,123,123),"var2"=c(45,57,57),"var3"=c(1,3,6),"count"=c(1,1,1))

  var1 var2 var3 count
1  123   45    1     1
2  123   57    3     1
3  123   57    6     1

I want to populate var3 with numbers from 1 to 6 for every obs in var2, retain the data from the original dataframe, and count to be 0.

   var1 var2 var3 count
1   123   45    1     1
2   123   45    2     0
3   123   45    3     0
4   123   45    4     0
5   123   45    5     0
6   123   45    6     0
7   123   57    1     0
8   123   57    2     0
9   123   57    3     1
10  123   57    4     0
11  123   57    5     0
12  123   57    6     0
13  123   57    1     0
14  123   57    2     0
15  123   57    3     0
16  123   57    4     0
17  123   57    5     0
18  123   57    6     1

Body:
One dplyr and tidyr possibility could be:

foo %>%
 rowid_to_column() %>%
 complete(var3 = seq(min(var3), max(var3), 1), nesting(rowid), fill = list(count = 0)) %>%
 arrange(rowid) %>%
 group_by(rowid) %>%
 fill(var1, var2, .direction = "updown")

    var3 rowid  var1  var2 count
   <dbl> <int> <dbl> <dbl> <dbl>
 1     1     1   123    45     1
 2     2     1   123    45     0
 3     3     1   123    45     0
 4     4     1   123    45     0
 5     5     1   123    45     0
 6     6     1   123    45     0
 7     1     2   123    57     0
 8     2     2   123    57     0
 9     3     2   123    57     1
10     4     2   123    57     0
11     5     2   123    57     0
12     6     2   123    57     0
13     1     3   123    57     0
14     2     3   123    57     0
15     3     3   123    57     0
16     4     3   123    57     0
17     5     3   123    57     0
18     6     3   123    57     1


问:
Count values of column A observed only with a single distinct value in columns B and/or C
I'd like to summarise a large dataframe in terms of distinct values of one column with respect to whether they are restricted to occuring with single OR multiple distinct values of other column(s). My current approach for doing this is really convoluted, and I'm looking for a pandas pattern for solving these kinds of problems.

Given the following example dataframe:

```<code>import pandas as pd
pd.DataFrame({'c': ['x', 'x',  'y', 'y',  'z', 'z'],
              's': ['a1', 'a1',  'a1', 'a1',  'a1', 'a2'],
              't': [1, 1,  1, 2,  1, 1]})
</code>```

How may I obtain (and count) the distinct values of column c:

1) that are observed only in conjunction with a single value of columns s and t.

Desired output: set('x') and/or its length: 1

2) that are observed only in conjuction with a single value of column s but >1 values of column t.

Desired output: set('y') and/or its length: 1

3) that are observed in conjuction with >1 values of  columns s and any number of distinct column t values.

Desired output: set('z') and/or its length: 1

Edit:
One more q, using the following revised df!

```<code>df = pd.DataFrame({'c': ['x', 'x', 'y', 'y', 'z', 'z', 'z1', 'z1', 'z2'],
              's': ['a1', 'a1', 'a1', 'a1', 'a1', 'a2', 'a3', 'a3', 'a4'],
              't': [1, 1, 1, 2, 1, 1, 3, 3, 1],
              'cat': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'a']})
</code>```

4) observed twice or more, and only in conjunction with a single value of columns s and t, and also restricted to cat 'a'
Desired output: set('x') and/or its length: 1

Thanks!

答:
Idea is use DataFrame.duplicated by multiple columns with keep=False for all dupes and filtering by boolean indexing:

```<code>m1 = df.duplicated(['c','s','t'], keep=False)
m2 = df.duplicated(['c','s'], keep=False) & ~m1
m3 = df.duplicated(['c','t'], keep=False) & ~m1

a = df.loc[m1, 'c']
print (a)
0    x
1    x
Name: c, dtype: object

b = df.loc[m2, 'c']
print (b)
2    y
3    y
Name: c, dtype: object

c = df.loc[m3, 'c']
print (c)
4    z
5    z
Name: c, dtype: object
</code>```

And then convert columns to sets:

```<code>out1, out2, out3 = set(a['c']), set(b['c']), set(c['c'])
print (out1)
{'x'}
print (out2)
{'y'}
print (out3)
{'z'}
</code>```

And for lengths:

```<code>out11, out21, out31 = len(out1), len(out2), len(out3)
print (out11)
print (out21)
print (out31)
1
1
1
</code>```

Another idea is create new column by concat and DataFrame.dot:

```<code>df1 = pd.concat([m1, m2, m3], axis=1, keys=('s&t','s','t'))
print (df1)
     s&t      s      t
0   True  False  False
1   True  False  False
2  False   True  False
3  False   True  False
4  False  False   True
5  False  False   True

df['new'] = df1.dot(df1.columns)
</code>```

And then aggregate with sets and function nunique:

```<code>df2 = (df.groupby('new')['c']
         .agg([('set', lambda x: set(x)),('count','nunique')])
         .reset_index())
print (df2)
   new  set  count
0    s  {y}      1
1  s&t  {x}      1
2    t  {z}      1
</code>```

Body:
I'd like to summarise a large dataframe in terms of distinct values of one column with respect to whether they are restricted to occuring with single OR multiple distinct values of other column(s). My current approach for doing this is really convoluted, and I'm looking for a pandas pattern for solving these kinds of problems.

Given the following example dataframe:

import pandas as pd
pd.DataFrame({'c': ['x', 'x',  'y', 'y',  'z', 'z'],
              's': ['a1', 'a1',  'a1', 'a1',  'a1', 'a2'],
              't': [1, 1,  1, 2,  1, 1]})

How may I obtain (and count) the distinct values of column c:

1) that are observed only in conjunction with a single value of columns s and t.

Desired output: set('x') and/or its length: 1

2) that are observed only in conjuction with a single value of column s but >1 values of column t.

Desired output: set('y') and/or its length: 1

3) that are observed in conjuction with >1 values of  columns s and any number of distinct column t values.

Desired output: set('z') and/or its length: 1

Edit:
One more q, using the following revised df!

df = pd.DataFrame({'c': ['x', 'x', 'y', 'y', 'z', 'z', 'z1', 'z1', 'z2'],
              's': ['a1', 'a1', 'a1', 'a1', 'a1', 'a2', 'a3', 'a3', 'a4'],
              't': [1, 1, 1, 2, 1, 1, 3, 3, 1],
              'cat': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'a']})

4) observed twice or more, and only in conjunction with a single value of columns s and t, and also restricted to cat 'a'
Desired output: set('x') and/or its length: 1

Thanks!

Body:
Idea is use DataFrame.duplicated by multiple columns with keep=False for all dupes and filtering by boolean indexing:

m1 = df.duplicated(['c','s','t'], keep=False)
m2 = df.duplicated(['c','s'], keep=False) & ~m1
m3 = df.duplicated(['c','t'], keep=False) & ~m1

a = df.loc[m1, 'c']
print (a)
0    x
1    x
Name: c, dtype: object

b = df.loc[m2, 'c']
print (b)
2    y
3    y
Name: c, dtype: object

c = df.loc[m3, 'c']
print (c)
4    z
5    z
Name: c, dtype: object

And then convert columns to sets:

out1, out2, out3 = set(a['c']), set(b['c']), set(c['c'])
print (out1)
{'x'}
print (out2)
{'y'}
print (out3)
{'z'}

And for lengths:

out11, out21, out31 = len(out1), len(out2), len(out3)
print (out11)
print (out21)
print (out31)
1
1
1

Another idea is create new column by concat and DataFrame.dot:

df1 = pd.concat([m1, m2, m3], axis=1, keys=('s&t','s','t'))
print (df1)
     s&t      s      t
0   True  False  False
1   True  False  False
2  False   True  False
3  False   True  False
4  False  False   True
5  False  False   True

df['new'] = df1.dot(df1.columns)

And then aggregate with sets and function nunique:

df2 = (df.groupby('new')['c']
         .agg([('set', lambda x: set(x)),('count','nunique')])
         .reset_index())
print (df2)
   new  set  count
0    s  {y}      1
1  s&t  {x}      1
2    t  {z}      1


问:
How do I truncate a file in Visual C++?
I have the following case. I have a big file say 1 KB. I want to read the first 100 bytes and then delete the 100 bytes read data from the file and then read next 100 bytes. To read 100 bytes is ok, but how do I delete 100 bytes from the file?</p>

答:
This is commonly done as a multiple-step process:

Rename the original file.

Write the data you want into a new file with the original file name.

Delete the old file with the temporary name that contains the data you no longer want.

That way, if something were to go wrong, you could simply restore the original file that you renamed. Moving a file from one place to another is implemented this way, as well.

However, if you don't want to do this, the SetEndOfFile function is another viable option to truncate the contents of a file in-place. From the documentation:

Sets the physical file size for the specified file to the current position of the file pointer.

The physical file size is also referred to as the end of the file. The SetEndOfFile function can be used to truncate or extend a file.

Title: How do I truncate a file in Visual C++?


问:
Showing "unexpected token admin" error although admin is declared
I'm trying to do some sequential asynchronous operation. But getting error:

Parsing error: Unexpected token admin

Although I've declared this variable. Here is my code

```<code>const admin = require('firebase-admin')
module.exports = {
   notificationCount: async (change, context) => {
    countRef.collection("notification").doc(context.params.reqID).get().then((requestDoc) => {
      console.log("Request Info " + requestDoc.data().reqUserName)
      return requestDoc.data();
    }).then((requestDocData) => {

      const token = await admin.database().ref("/UserInfo/" + notifiedUserID + "/token").once('value');
      console.log("UserInfo "+token);
      return null;

    }).catch((error) => {
      console.log("Loading failed: ", error);
    });
  }
}
</code>```

答:
This is not the issue of the firebase-admin, the issues are:

you are using await without async

using function expression syntax instead of arrow-callback

then() should return a value or throw

use catch preceding to then

Body:
I'm trying to do some sequential asynchronous operation. But getting error:

Parsing error: Unexpected token admin

Although I've declared this variable. Here is my code

const admin = require('firebase-admin')
module.exports = {
   notificationCount: async (change, context) => {
    countRef.collection("notification").doc(context.params.reqID).get().then((requestDoc) => {
      console.log("Request Info " + requestDoc.data().reqUserName)
      return requestDoc.data();
    }).then((requestDocData) => {

      const token = await admin.database().ref("/UserInfo/" + notifiedUserID + "/token").once('value');
      console.log("UserInfo "+token);
      return null;

    }).catch((error) => {
      console.log("Loading failed: ", error);
    });
  }
}


问:
How to return LocalDateTime from REST controller endpoint?
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

```<code>@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}
</code>```

This is the client request:

```<code>ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);
</code>```

I get the following excepation on my client side:

```<code>org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]
</code>```

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

答:
Problem solved!
In general- I should've added this configuration to my app:

```<code>@Configuration
public class MvcConfig {
    @Configuration
    @EnableWebMvc
    public class MessageConvertersConfiguration implements WebMvcConfigurer {
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
        }

        @Bean
        public ObjectMapper objectMapper() {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss");
            SimpleModule localDateModule = new SimpleModule();
            localDateModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
            localDateModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));

            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModules(localDateModule);

            return mapper;
        }
    }
}
</code>```

* IMPORTANT!!! - In Tests add this to your rest template: *

```<code>restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(objectMapper())));
</code>```

Body:
I'm writing a REST controller in Spring- java, and one of my endpoints should return a LocalDateTime variable.

@GetMapping(path = "/lastDateTimeOfReset")
LocalDateTime fetchLastDateTimeOfReset() {
   return mongoManagerService.fetchLastDateTimeOfReset();
}

This is the client request:

ResponseEntity<LocalDateTime> lastDateEntity = restTemplate.getForEntity(url, LocalDateTime.class);

I get the following excepation on my client side:

org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.time.LocalDateTime] and content type [application/json;charset=UTF-8];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Expected array or string.;
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
at [Source: (PushbackInputStream); line: 1, column: 1]

I checked the return value on debug mode and it is a valid LocalDateTime.
Why is this exception thrown and how to overcome it?

Body:
Problem solved!
In general- I should've added this configuration to my app:

@Configuration
public class MvcConfig {
    @Configuration
    @EnableWebMvc
    public class MessageConvertersConfiguration implements WebMvcConfigurer {
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
        }

        @Bean
        public ObjectMapper objectMapper() {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss");
            SimpleModule localDateModule = new SimpleModule();
            localDateModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
            localDateModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));

            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModules(localDateModule);

            return mapper;
        }
    }
}

* IMPORTANT!!! - In Tests add this to your rest template: *

restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(objectMapper())));


问:
Icon corrupted with Powershell exe to ico converter
i'm looking for a powershell script to extract the .ico of an executable.

I found some tools that seems to work like this one:

```<code>[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')  | Out-Null

$folder = "C:\TMP_7423\icons"
md $folder -ea 0 | Out-Null

dir $env:windir *.exe -ea 0 -rec |
  ForEach-Object {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_.FullName)
    Write-Progress "Extracting Icon" $baseName
    [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName).ToBitmap().Save("$folder\$BaseName.ico")
}
</code>```

But the problem is, that I want to use a powershell to exe converter for another tool that have a function to directly put an icon in the generated .exe. And I wanna use the extracted ico for the generated executable.
The problem is that the ps1 to exe converter do not work with any icon generated by the ico extractor.
But, the thing is that the ps1 to exe converter work when I use .ico that I found on the internet.

So, do you have any executable .ico extractor that do not extract corrupted ico but normal .ico that we could find on the internet ?

Thank you in advance ! :)

答:
I wrote a Powershell utility using Windows Forms for precisely this purpose:

Available here: IconTool

Body:
i'm looking for a powershell script to extract the .ico of an executable.

I found some tools that seems to work like this one:

[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')  | Out-Null

$folder = "C:\TMP_7423\icons"
md $folder -ea 0 | Out-Null

dir $env:windir *.exe -ea 0 -rec |
  ForEach-Object {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_.FullName)
    Write-Progress "Extracting Icon" $baseName
    [System.Drawing.Icon]::ExtractAssociatedIcon($_.FullName).ToBitmap().Save("$folder\$BaseName.ico")
}

But the problem is, that I want to use a powershell to exe converter for another tool that have a function to directly put an icon in the generated .exe. And I wanna use the extracted ico for the generated executable.
The problem is that the ps1 to exe converter do not work with any icon generated by the ico extractor.
But, the thing is that the ps1 to exe converter work when I use .ico that I found on the internet.

So, do you have any executable .ico extractor that do not extract corrupted ico but normal .ico that we could find on the internet ?

Thank you in advance ! :)


问:
Add item(row) from a table to another table row
I have two tables. The first one contains database entries. Its last column holds a button. When I'm searching for the item in the table and I find it I will insert the quantity and I'll click the button. Then the function will copy all td of the row and append it in the new table.

My problem is that only the first two columns of the second table  contains the same value (COD and DESC) but N.ITEM should be the input Quantity and DISCOUNT should be the input #discount and the last TOT should be [(€*Quantity)/100] * discount.

Obviously I also need to update Num of item in the first table with Num of item - Quantity. I hope someone can help me.

$(document).ready(function() {
  $(".use-button").click(function() {
    var html = $(this).closest("tr").clone().find('td:last').remove().end().prop('outerHTML');
    $("#pdfTab").append(html);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr class="header">
      <th style="width:20%;">Cod</th>
      <th style="width:30%;">Desc</th>
      <th style="width:20%">Num of item</th>
      <th style="width:10%">€</th>
      <th style="width:10%">Quantity</th>
      <th style="width:10%"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="cod">1101</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1102</td>
      <td>bbb</td>
      <td>25</td>
      <td>13</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1103</td>
      <td>ccc</td>
      <td>25</td>
      <td>20</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1104</td>
      <td>ddd</td>
      <td>25</td>
      <td>35</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1201</td>
      <td>RRTT</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1301</td>
      <td>BBFF</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1901</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1651</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1231</td>
      <td>AAA</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
  </tbody>
</table>
<input type="text" id="discount" name="% of discount">

<table id="pdfTab" class="w3-table-all w3-small" style="width:92%;margin-bottom:10px;margin-left:23px">
  <tr>
    <th style="width:20%;">COD</th>
    <th style="width:30%;">DESC</th>
    <th style="width:20%;">N.ITEM</th>
    <th style="width:20%;">DISCOUNT</th>
    <th style="width:10%;">TOT</th>
  </tr>
</table></code>```

答:
Some dirty code but it should give you an idea.

Read each column's value separately, perform your calculation then manually create a row and append it to the second table. You can add further validation of the entered amounts to check if they are valid numbers. I've defaulted the discount value to 10. Your formula seems wrong but maybe I'm just too tired to think.

$(document).ready(function () {
    $(".use-button").click(function () {
        var row = $(this).closest("tr");

        //Get Values from each Column
        var code     = row.find('td')[0].textContent;
        var desc     = row.find('td')[1].textContent;
        var nItem    = parseInt(row.find('td')[2].textContent);
        var price    = parseFloat(row.find('td')[3].textContent);
        var quantity = parseInt(row.find('input')[0].value);
        var discount = parseFloat($('#discount').val());

        //Calculate your total. N.B. Your formula looks wrong but I kept it the same
        var total = ((price * quantity) / 100) * discount;

        //Update the "Num of item" column on the row you clicked
        nItem = nItem - quantity;
        row.find('td')[2].textContent = nItem;

        //Manually add each amount to the relevant column and append the row to the table
        var newRow = '
' + code + '	' + desc + '	' + nItem + '	' + discount + '	' + total + '
';
        $("#pdfTab").append(newRow);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr class="header">
      <th style="width:20%;">Cod</th>
      <th style="width:30%;">Desc</th>
      <th style="width:20%">Num of item</th>
      <th style="width:10%">€</th>
      <th style="width:10%">Quantity</th>
      <th style="width:10%"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="cod">1101</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1102</td>
      <td>bbb</td>
      <td>25</td>
      <td>13</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1103</td>
      <td>ccc</td>
      <td>25</td>
      <td>20</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1104</td>
      <td>ddd</td>
      <td>25</td>
      <td>35</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1201</td>
      <td>RRTT</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1301</td>
      <td>BBFF</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1901</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1651</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1231</td>
      <td>AAA</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
  </tbody>
</table>
<b>Discount: </b><input type="text" id="discount" name="% of discount" value="10">

<table id="pdfTab" class="w3-table-all w3-small" style="width:92%;margin-bottom:10px;margin-left:23px">
  <tr>
    <th style="width:20%;">COD</th>
    <th style="width:30%;">DESC</th>
    <th style="width:20%;">N.ITEM</th>
    <th style="width:20%;">DISCOUNT</th>
    <th style="width:10%;">TOT</th>
  </tr>
</table></code>```

Body:
I have two tables. The first one contains database entries. Its last column holds a button. When I'm searching for the item in the table and I find it I will insert the quantity and I'll click the button. Then the function will copy all td of the row and append it in the new table.

My problem is that only the first two columns of the second table  contains the same value (COD and DESC) but N.ITEM should be the input Quantity and DISCOUNT should be the input #discount and the last TOT should be [(€*Quantity)/100] * discount.

Obviously I also need to update Num of item in the first table with Num of item - Quantity. I hope someone can help me.

$(document).ready(function() {
  $(".use-button").click(function() {
    var html = $(this).closest("tr").clone().find('td:last').remove().end().prop('outerHTML');
    $("#pdfTab").append(html);
  });
});

      Cod
      Desc
      Num of item
      €
      Quantity

      1101
      aaa
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1102
      bbb
      25
      13
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1103
      ccc
      25
      20
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1104
      ddd
      25
      35
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1201
      RRTT
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1301
      BBFF
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1901
      aaa
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1651
      aaa
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

      1231
      AAA
      25
      9
      <input type="text" id="Quantity" value="0" />
      <button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button>

<input type="text" id="discount" name="% of discount">

    COD
    DESC
    N.ITEM
    DISCOUNT
    TOT

Body:
Some dirty code but it should give you an idea.

Read each column's value separately, perform your calculation then manually create a row and append it to the second table. You can add further validation of the entered amounts to check if they are valid numbers. I've defaulted the discount value to 10. Your formula seems wrong but maybe I'm just too tired to think.

$(document).ready(function () {
    $(".use-button").click(function () {
        var row = $(this).closest("tr");

        //Get Values from each Column
        var code     = row.find('td')[0].textContent;
        var desc     = row.find('td')[1].textContent;
        var nItem    = parseInt(row.find('td')[2].textContent);
        var price    = parseFloat(row.find('td')[3].textContent);
        var quantity = parseInt(row.find('input')[0].value);
        var discount = parseFloat($('#discount').val());

        //Calculate your total. N.B. Your formula looks wrong but I kept it the same
        var total = ((price * quantity) / 100) * discount;

        //Update the "Num of item" column on the row you clicked
        nItem = nItem - quantity;
        row.find('td')[2].textContent = nItem;

        //Manually add each amount to the relevant column and append the row to the table
        var newRow = '<tr><td>' + code + '</td><td>' + desc + '</td><td>' + nItem + '</td><td>' + discount + '</td><td>' + total + '</td><tr>';
        $("#pdfTab").append(newRow);
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr class="header">
      <th style="width:20%;">Cod</th>
      <th style="width:30%;">Desc</th>
      <th style="width:20%">Num of item</th>
      <th style="width:10%">€</th>
      <th style="width:10%">Quantity</th>
      <th style="width:10%"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="cod">1101</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1102</td>
      <td>bbb</td>
      <td>25</td>
      <td>13</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1103</td>
      <td>ccc</td>
      <td>25</td>
      <td>20</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1104</td>
      <td>ddd</td>
      <td>25</td>
      <td>35</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1201</td>
      <td>RRTT</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1301</td>
      <td>BBFF</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1901</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1651</td>
      <td>aaa</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
    <tr>
      <td id="cod">1231</td>
      <td>AAA</td>
      <td>25</td>
      <td>9</td>
      <td><input type="text" id="Quantity" value="0" /></td>
      <td><button id="addButton" class="use-button w3-button w3-circle w3-amber">+</button></td>
    </tr>
  </tbody>
</table>
<b>Discount: </b><input type="text" id="discount" name="% of discount" value="10">

<table id="pdfTab" class="w3-table-all w3-small" style="width:92%;margin-bottom:10px;margin-left:23px">
  <tr>
    <th style="width:20%;">COD</th>
    <th style="width:30%;">DESC</th>
    <th style="width:20%;">N.ITEM</th>
    <th style="width:20%;">DISCOUNT</th>
    <th style="width:10%;">TOT</th>
  </tr>
</table>


问:
Treating warnings as errors in Visual Studio 2019 for build but NOT intellisense
I've just started using <TreatWarningsAsErrors>true</TreatWarningsAsErrors> in my csproj files, and when messing up a bit of code, I've found myself taking quite a bit of extra time hovering over all the different red lines to find the one that's actually an error, as I want to prioritse fixing the errors over the warnings. It would be great if the intellisense warnings could still show as green lines in the text editor, but also cause the build to fail.

I think that I could make the test/staging/production builds fail by passing /warnaserror to MSBuild, but I do want the development build in VS to fail as well if there are any warnings.

Does anyone know if this is possible? I'm using .NET Framework 4.8 (but would also be interested to know if it's possible in .NET Core) in Visual Studio 2019.

Thanks very much!

答:
I've found myself taking quite a bit of extra time hovering over all
  the different red lines to find the one that's actually an error, as I
  want to prioritse fixing the errors over the warnings. It would be
  great if the intellisense warnings could still show as green lines in
  the text editor, but also cause the build to fail.

As far as l know, Intellisense is very sensitive to catching errors, and once the built warnings are turned into errors, intellisense will catch them as errors.

Does anyone know if this is possible? I'm using .NET Framework 4.8
  (but would also be interested to know if it's possible in .NET Core)
  in Visual Studio 2019.

Edit 1

So it is impossible to distinguish between warnings and real errors in this state. And in this state, Intellisense doesn't discriminate between them.

As an alternative, you can try my suggestion:

Suggestion

You can create a new configuration called Production which differ from Debug or Release. In this solution, the first step is to find the real error, and the second step is to turn the warning into an error so that you can optimize the code.

First, you can use Debug or Release to build your project in this mode, it can catch the real build error so that you can fix these errors preferentially.

Second, change Configuration to Production. This phase is often referred to as the final production release phase, and the build process will turn warnings into errors so you can spot bad code and optimize it.

The real question is how to create the Production Configuration:

Step

1) click menu Build-->Configuration Manager-->click new in Active solution configuration-->create a new configuration called Production.

2) unload the project and add <TreatWarningsAsErrors>true</TreatWarningsAsErrors> under Production like this:

```<code><PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Production|AnyCPU'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\Production\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <LangVersion>7.3</LangVersion>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
    <Prefer32Bit>true</Prefer32Bit>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
</code>```

In a word, first, change Configuration to Debug or Release, then build the project to find the real errors to fix them. Second, change change Configuration to Production, build the project to find the warning errors to fix them.

Hope it could help you.

Body:
I've found myself taking quite a bit of extra time hovering over all
  the different red lines to find the one that's actually an error, as I
  want to prioritse fixing the errors over the warnings. It would be
  great if the intellisense warnings could still show as green lines in
  the text editor, but also cause the build to fail.

As far as l know, Intellisense is very sensitive to catching errors, and once the built warnings are turned into errors, intellisense will catch them as errors.

Does anyone know if this is possible? I'm using .NET Framework 4.8
  (but would also be interested to know if it's possible in .NET Core)
  in Visual Studio 2019.

Edit 1

So it is impossible to distinguish between warnings and real errors in this state. And in this state, Intellisense doesn't discriminate between them.

As an alternative, you can try my suggestion:

Suggestion

You can create a new configuration called Production which differ from Debug or Release. In this solution, the first step is to find the real error, and the second step is to turn the warning into an error so that you can optimize the code.

First, you can use Debug or Release to build your project in this mode, it can catch the real build error so that you can fix these errors preferentially.

Second, change Configuration to Production. This phase is often referred to as the final production release phase, and the build process will turn warnings into errors so you can spot bad code and optimize it.

The real question is how to create the Production Configuration:

Step

1) click menu Build-->Configuration Manager-->click new in Active solution configuration-->create a new configuration called Production.

2) unload the project and add <TreatWarningsAsErrors>true</TreatWarningsAsErrors> under Production like this:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Production|AnyCPU'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\Production\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <LangVersion>7.3</LangVersion>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
    <Prefer32Bit>true</Prefer32Bit>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>

In a word, first, change Configuration to Debug or Release, then build the project to find the real errors to fix them. Second, change change Configuration to Production, build the project to find the warning errors to fix them.

Hope it could help you.


问:
Rails Joins Select Associated Columns not working
I am working on a Ruby on Rails application there,

AnalyticsPage has the below relations. Many to Many relations with the users.

```<code>class AnalyticsPage < ApplicationRecord
  belongs_to :graph_page_layout
  has_many :analytics_pages_users
  has_many :users, through: :analytics_pages_users
  has_many :graph_sections
end

##### query #####
I need to write query where I need to fetch the columns from both of the tables.
analytics_pages = AnalyticsPage.select('users.first_name, users.last_name, analytics_pages.title').joins([:users])
</code>```

The above query is not giving users first name and last name.The other point is that when I am running the SQL query it is running in mysql admin.

答:
try with pluck

Pod.pluck('users.first_name, users.last_name').joins(:users)

Body:
I am working on a Ruby on Rails application there,

AnalyticsPage has the below relations. Many to Many relations with the users.

class AnalyticsPage < ApplicationRecord
  belongs_to :graph_page_layout
  has_many :analytics_pages_users
  has_many :users, through: :analytics_pages_users
  has_many :graph_sections
end

##### query #####
I need to write query where I need to fetch the columns from both of the tables.
analytics_pages = AnalyticsPage.select('users.first_name, users.last_name, analytics_pages.title').joins([:users])

The above query is not giving users first name and last name.The other point is that when I am running the SQL query it is running in mysql admin.


问:
How to write nested if in makefile?
How do I use multiple nested if-then blocks in a Makefile?

E.g.

```<code>$(NAMING_SCHEME).$(COMPRESS_TYPE):
ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        @echo hi \
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            @echo hi again \
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                @echo hi for the last time!!! \
            fi; \
        fi; \
    fi;
endif
</code>```

This results in

```<code>bin/sh: -c: line 2: syntax error near unexpected token 'then'
/bin/sh: -c: line 0: 'ifeq (1, 1)'
make: *** [Makefile:22: program_name.1.2.3.lz4] Error 1
</code>```

What am I doing incorrectly?

答:
As per beta and vonbrand's suggestions I was able to make it work, thanks a million!

```<code>ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        echo 111 ${LOG_LEVEL} ;\
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            echo 222 ${LOG_LEVEL} ;\
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                echo 333 ${LOG_LEVEL} ;\
            fi \
        fi \
    fi
endif
</code>```

This outputs (in Windows cmd):

```<code>if [ 2 -gt 0 ] ; then \
        echo 111 2 ;\
        if [ 2 -gt 1 ] ; then \
                echo 222 2 ;\
                if [ 2 -gt 2 ] ; then \
                        echo 333 2 ;\
                fi \
        fi \
fi
111 2
222 2
</code>```

Title: How to write nested if in makefile?

Body:
How do I use multiple nested if-then blocks in a Makefile?

E.g.

$(NAMING_SCHEME).$(COMPRESS_TYPE):
ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        @echo hi \
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            @echo hi again \
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                @echo hi for the last time!!! \
            fi; \
        fi; \
    fi;
endif

This results in

bin/sh: -c: line 2: syntax error near unexpected token 'then'
/bin/sh: -c: line 0: 'ifeq (1, 1)'
make: *** [Makefile:22: program_name.1.2.3.lz4] Error 1

What am I doing incorrectly?

Body:
As per beta and vonbrand's suggestions I was able to make it work, thanks a million!

ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        echo 111 ${LOG_LEVEL} ;\
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            echo 222 ${LOG_LEVEL} ;\
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                echo 333 ${LOG_LEVEL} ;\
            fi \
        fi \
    fi
endif

This outputs (in Windows cmd):

if [ 2 -gt 0 ] ; then \
        echo 111 2 ;\
        if [ 2 -gt 1 ] ; then \
                echo 222 2 ;\
                if [ 2 -gt 2 ] ; then \
                        echo 333 2 ;\
                fi \
        fi \
fi
111 2
222 2


问:
CORS Error in Angular BotDetect with ASP.NET WebApi2 backend
I use Botdetect in angular 8 project and ASPNET WebApi2 Backend.

but this error

Access to XMLHttpRequest at 'http://localhost:29739/simple-captcha-endpoint.ashx?get=html&c=yourFirstCaptchaStyle' from origin 'http://localhost:4500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I use EnableCors

```<code> config.EnableCors();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*")
        {
            SupportsCredentials = true,

        });
</code>```

and added botdetect.xml file

```<code><captchaEndpoint>
 <accessControlAllowOriginHeaderEnabled>true</accessControlAllowOriginHeaderEnabled>
 <accessControlAllowOriginHeaderValue>http://localhost:4500</accessControlAllowOriginHeaderValue>
</captchaEndpoint>
</code>```

答:
If you work on local application, you can just install extension.

If you want a real solution you have to add a proxy config, please check this link

This happens becuase your front and back have not the same URL and port, it's a cross-domain request.

Body:
I use Botdetect in angular 8 project and ASPNET WebApi2 Backend.

but this error

Access to XMLHttpRequest at 'http://localhost:29739/simple-captcha-endpoint.ashx?get=html&c=yourFirstCaptchaStyle' from origin 'http://localhost:4500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I use EnableCors

 config.EnableCors();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*")
        {
            SupportsCredentials = true,

        });

and added botdetect.xml file

<captchaEndpoint>
 <accessControlAllowOriginHeaderEnabled>true</accessControlAllowOriginHeaderEnabled>
 <accessControlAllowOriginHeaderValue>http://localhost:4500</accessControlAllowOriginHeaderValue>
</captchaEndpoint>


问:
gmock - how to mock function with noexcept specifier
I need to mock the following function:

```<code> virtual void fun() noexcept = 0;
</code>```

Is it possible using gmock ?

Gmock has the following macro:#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) but there is a comment: // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! Moreover I don't know how to use that macro (what the parameters tn and ct means) ?

Edit

The following mock:

```<code>GMOCK_METHOD0_(, noexcept, ,fun, void());
</code>```

compiles with gmock 1.7.0 but when I compile it using gmock 1.8.1 I get the compilation errors:

```<code>main.cpp:17: error: expected identifier before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:17: error: expected ‘,’ or ‘...’ before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:-1: In member function ‘testing::internal::MockSpec<void()> MockX::gmock_fun(const testing::internal::WithoutMatchers&, int) const’:

gmock-generated-function-mockers.h:154: error: ‘AdjustConstness_noexcept’ is not a member of ‘testing::internal’
     return ::testing::internal::AdjustConstness_##constness(this)-> \
            ^
main.cpp:17: in expansion of macro ‘GMOCK_METHOD0_’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
 ^
</code>```

答:
On older mock versions one may workaround such a c++-decoration by simple trick:

Create mock method without noexcept

Create proxy method with right signature, which will call mocked method

In your example it would be

```<code>class Mock : public MyInterface
{
public:
  MOCK_METHOD0(funImpl, void());
  virtual void fun() noexcept
  {
    funImpl();
  }
};
</code>```

Using the same pattern you may mock methods taking non-gmock-friendly arguments like auto_ptr. You also create wrapper function and change arguments to gmock-friendly ones inside wrapper (like shared_ptr).

Body:
I need to mock the following function:

 virtual void fun() noexcept = 0;

Is it possible using gmock ?

Gmock has the following macro:#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) but there is a comment: // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! Moreover I don't know how to use that macro (what the parameters tn and ct means) ?

Edit

The following mock:

GMOCK_METHOD0_(, noexcept, ,fun, void());

compiles with gmock 1.7.0 but when I compile it using gmock 1.8.1 I get the compilation errors:

main.cpp:17: error: expected identifier before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:17: error: expected ‘,’ or ‘...’ before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:-1: In member function ‘testing::internal::MockSpec<void()> MockX::gmock_fun(const testing::internal::WithoutMatchers&, int) const’:

gmock-generated-function-mockers.h:154: error: ‘AdjustConstness_noexcept’ is not a member of ‘testing::internal’
     return ::testing::internal::AdjustConstness_##constness(this)-> \
            ^
main.cpp:17: in expansion of macro ‘GMOCK_METHOD0_’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
 ^

Body:
On older mock versions one may workaround such a c++-decoration by simple trick:

Create mock method without noexcept

Create proxy method with right signature, which will call mocked method

In your example it would be

class Mock : public MyInterface
{
public:
  MOCK_METHOD0(funImpl, void());
  virtual void fun() noexcept
  {
    funImpl();
  }
};

Using the same pattern you may mock methods taking non-gmock-friendly arguments like auto_ptr. You also create wrapper function and change arguments to gmock-friendly ones inside wrapper (like shared_ptr).


问:
How do we iterate through muliple list and call a setter method using java streams
I have 2 lists.

```<code>List<Email> emailList emailList = getEmails();
List<FileData> fileList = getFileList();
</code>```

```<code>public class Email {

    private String email;
    private String name;
    private String type;
    private Set<Permissions>;

    //getter and setter
}
</code>```

```<code>public class Permissions {

    private String permissionType;
    private String level;

    //getter and setter
}
</code>```

```<code>public class FileData {

    private String email;
    private String type;

    //getter and setter
}
</code>```

I need to iterate through the list match the email from both list and call setPermissionType() method and if there is no match with the Email it needs to throw NotFoundException. How can we do this with Java streams?

The logic I have at the moment is.

```<code>for (final FileData fileData: fileList ) {
    Email email= emailDao.findByEmail(fileData.getEmail()); //throws NotFoundException
    final Set<Permissions> permissions = email.getPermissions();
    permissions.removeIf(p -> p.getPermissionType() == fileData.getType());
    email.setPermissions(permissions);
}
</code>```

In the above logic I'm making DB calls in a for loop. I need to avoid that by using IN clause.

```<code>List<String> emailStringList = fileList.stream()
                                       .map(file -> Objects.toString(file.getEmail()))
                                       .collect(Collectors.toList());
List<Email> emailList= emailDao.findByEmailIn(emailStringList);
</code>```

答:
First of all, I would suggest to remove emailDao.findByEmail() inside a loop, this costs you a huge cost and technical debt

First of all, create a list of emails

List<String> emailIds = fileList.stream().map(fileData->FileData::getEmail).collect(Collectors.toList());

Create a new method findByEmails(List emails) to find by multiple emails.

List<Email> emails = emailDao.findByEmails(emailIds);

I think, Something like this would work

emails.forEach(email->
 email.setPermissions(email.getPermissions().stream().fiter(permission -> !permission.getType().equals(fileList.stream().filter(file-> file.getEmail().equals(email.getEmail()).findFirst().orElse(new Permission())).getType()))))

Also, I think this will eliminate the NotFoundException as we're iterating only on the already existing emails.

Body:
I have 2 lists.

List<Email> emailList emailList = getEmails();
List<FileData> fileList = getFileList();

public class Email {

    private String email;
    private String name;
    private String type;
    private Set<Permissions>;

    //getter and setter
}

public class Permissions {

    private String permissionType;
    private String level;

    //getter and setter
}

public class FileData {

    private String email;
    private String type;

    //getter and setter
}

I need to iterate through the list match the email from both list and call setPermissionType() method and if there is no match with the Email it needs to throw NotFoundException. How can we do this with Java streams?

The logic I have at the moment is.

for (final FileData fileData: fileList ) {
    Email email= emailDao.findByEmail(fileData.getEmail()); //throws NotFoundException
    final Set<Permissions> permissions = email.getPermissions();
    permissions.removeIf(p -> p.getPermissionType() == fileData.getType());
    email.setPermissions(permissions);
}

In the above logic I'm making DB calls in a for loop. I need to avoid that by using IN clause.

List<String> emailStringList = fileList.stream()
                                       .map(file -> Objects.toString(file.getEmail()))
                                       .collect(Collectors.toList());
List<Email> emailList= emailDao.findByEmailIn(emailStringList);