问:
Keeping line breaks when reading a file
I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?</p>

```<code>public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
</code>```

答:
Add the line break at the moment you write each line.
In your case is after the for loop that appends the encrypted characters:

```<code>for (int i = 0; i < newArr.length; i++) {
       convert.append(newArr[i]);
convert.append("\r\n");
</code>```

Adding a new line in Java is as simple as including “\n” or “\r” or “\r\n” at the end of our string depending on the SO you are using. But nowadays the file editors recognise all of them so it might not be a problem whether you chose one or another.

And regarding to why they are 'lost' if you look at the docs of the nextLine() method it says:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

So you have to add the line separators back if you need them.

Title: Keeping line breaks when reading a file

Body:
I want to read a file and modify it but whenever the new file is created everything stays on one line. Therefore, my question is how can I keep line breaks without removing them?

public class JavaProgram {

    public static void main(String[] args) {
        String text = "";
        StringBuilder convert = new StringBuilder();
        Scanner keyboard = new Scanner (System.in);

        File file = new File ("PATH");

            try {
                Scanner input = new Scanner (file);
                while (input.hasNextLine()) {
                        text = input.nextLine();

                        char [] arr = text.toCharArray();
                        char [] newArr = encrypt(3, arr);

                        for (int i = 0; i < newArr.length; i++) {
                            convert.append(newArr[i]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    PrintWriter printer = new PrintWriter (document);

                    printer.append(convert);
                    printer.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

Body:
Add the line break at the moment you write each line.
In your case is after the for loop that appends the encrypted characters:

for (int i = 0; i < newArr.length; i++) {
       convert.append(newArr[i]);
convert.append("\r\n");

Adding a new line in Java is as simple as including “\n” or “\r” or “\r\n” at the end of our string depending on the SO you are using. But nowadays the file editors recognise all of them so it might not be a problem whether you chose one or another.

And regarding to why they are 'lost' if you look at the docs of the nextLine() method it says:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

So you have to add the line separators back if you need them.


来源: stackexchange

问:
How do I reference the output of the previous "pipe" in a Powershell pipeline?
I wrote this code to get some (relative) file path:

```<code>function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"
</code>```

This threw the error:

```<code>Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
</code>```

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

```<code>$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"
</code>```

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

```<code>$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data
</code>```

I'd like to know where I'm going wrong both on a conceptual and a technical level.

答:
Here's a simple example.  Search for "accept pipeline input" in the docs.  Using a scriptblock with get-content's -path parameter is a little advanced.  Most people use a foreach-object instead.  It works because -path accepts pipeline input, but only by property name.  join-path's -path paramaeter can be over the pipe by value, so it's easier.  This will come in handy a lot once you understand it.  Maybe it's easier just to try things sometimes.

```<code>echo '"hi"' > foo.json

'.\' | Join-Path -ChildPath foo.json | Get-Content -Path { $_ } | ConvertFrom-Json

hi
</code>```

Or with foreach, which is short for foreach-object in this case.  But $_ must always be inside the curly braces.

```<code>'.\' | Join-Path -ChildPath foo.json | foreach { Get-Content $_ } | ConvertFrom-Json
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote this code to get some (relative) file path:

function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"

This threw the error:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data

I'd like to know where I'm going wrong both on a conceptual and a technical level.

Body:
Here's a simple example.  Search for "accept pipeline input" in the docs.  Using a scriptblock with get-content's -path parameter is a little advanced.  Most people use a foreach-object instead.  It works because -path accepts pipeline input, but only by property name.  join-path's -path paramaeter can be over the pipe by value, so it's easier.  This will come in handy a lot once you understand it.  Maybe it's easier just to try things sometimes.

echo '"hi"' > foo.json

'.\' | Join-Path -ChildPath foo.json | Get-Content -Path { $_ } | ConvertFrom-Json

hi

Or with foreach, which is short for foreach-object in this case.  But $_ must always be inside the curly braces.

'.\' | Join-Path -ChildPath foo.json | foreach { Get-Content $_ } | ConvertFrom-Json


问:
Pass ID to Modal form box on page
I have read a bunch of SO posts on how to do this but I am unable to get it to work with my script.  Maybe someone smarter than me can see what Im missing here.

I am trying to pass the ID to the modal box. The user will then input notes and it will update in the DB.

```<code>echo "<td>" . $Agent_ID. "<br><a href='' class='btn btn-default btn-rounded mb-4' data-note-id='". $id . "' data-toggle='modal' id='" . $id . "' data-target='#notes'>Add Notes</a></td>";
</code>```

My Modal

```<code><div class="modal fade" id="notes" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
  aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Notes</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <form method="post">
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <i class="fas fa-envelope prefix grey-text"></i>

          <textarea name="note" value="" placeholder="Type Your Note Here" id="defaultForm-email" class="form-control validate"></textarea>

        </div>
      </div>
      <div class="modal-footer d-flex justify-content-center">
        <button type="submit" class="btn btn-default">Submit</button>
      </div>
    </form>

    </div>
  </div>
</div>

</code>```

My JS

```<code><script>

$('#notes').on('show.bs.modal', function(e) {
    var note = $(e.relatedTarget).data('note-id');
    $(e.currentTarget).find('input[name="note"]').val(note);
});

</script>
</code>```

I tried this as well as you can see its very similar
http://jsfiddle.net/k7FC2/

答: Your input box selector is wrong. You changed the <input name="note"> to <textbox name="note">. Update your selector to match. Change input[name="note"] to textarea[name="note"].

Title: Pass ID to Modal form box on page

Body:
I have read a bunch of SO posts on how to do this but I am unable to get it to work with my script.  Maybe someone smarter than me can see what Im missing here.

I am trying to pass the ID to the modal box. The user will then input notes and it will update in the DB.

echo "" . $Agent_ID. "
Add Notes	";

My Modal

Notes

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

      <form method="post">

          <textarea name="note" value="" placeholder="Type Your Note Here" id="defaultForm-email" class="form-control validate"></textarea>

        <button type="submit" class="btn btn-default">Submit</button>

    </form>

My JS

I tried this as well as you can see its very similar
http://jsfiddle.net/k7FC2/


问:
Transpose and create new variables in R
I have a data frame with the following structure:

```<code>study_id date
1        01/01/2011
2        01/01/2012
2        01/01/2013
3        01/01/2014
3        01/01/2015
3        01/01/2016
</code>```

I would like to change the data frame to:

```<code>study_id date_1      date_2    date_3
1        01/01/2011  NA         NA
2        01/01/2012  01/01/2013 NA
3        01/01/2014  01/01/2014 01/01/2016

</code>```

Please note these dates are just examples, the date does not follow this order (01/01/2011 + 1 years and so goes on)

PS: Thanks webprogrammer for editing my question. I deleted before I noticed you fixed it.

答:
Here is a tidyverse approach:

```<code>library(tidyverse)

df %>%
  group_by(study_id) %>%
  mutate(row_id = row_number()) %>%
  pivot_wider(id_cols = study_id, values_from = date, names_from = row_id, names_prefix = "date_")
</code>```

Output

```<code># A tibble: 3 x 4
# Groups:   study_id [3]
  study_id date_1     date_2     date_3
     <int> <chr>      <chr>      <chr>
1        1 01/01/2011 NA         NA
2        2 01/01/2012 01/01/2013 NA
3        3 01/01/2014 01/01/2015 01/01/2016
</code>```

Title: Transpose and create new variables in R

Body:
I have a data frame with the following structure:

study_id date
1        01/01/2011
2        01/01/2012
2        01/01/2013
3        01/01/2014
3        01/01/2015
3        01/01/2016

I would like to change the data frame to:

study_id date_1      date_2    date_3
1        01/01/2011  NA         NA
2        01/01/2012  01/01/2013 NA
3        01/01/2014  01/01/2014 01/01/2016

Please note these dates are just examples, the date does not follow this order (01/01/2011 + 1 years and so goes on)

PS: Thanks webprogrammer for editing my question. I deleted before I noticed you fixed it.

Body:
Here is a tidyverse approach:

library(tidyverse)

df %>%
  group_by(study_id) %>%
  mutate(row_id = row_number()) %>%
  pivot_wider(id_cols = study_id, values_from = date, names_from = row_id, names_prefix = "date_")

Output

# A tibble: 3 x 4
# Groups:   study_id [3]
  study_id date_1     date_2     date_3
     <int> <chr>      <chr>      <chr>
1        1 01/01/2011 NA         NA
2        2 01/01/2012 01/01/2013 NA
3        3 01/01/2014 01/01/2015 01/01/2016


问:
infopath cascaded dropdown displaying lookup field values in 1;#ABC format. Need to format the value as ABC without id
I have a browser enabled infopath form with a dropdown box(cascaded), the data being retreived from an xml document. The data is in the following format-(as the value is retrieved from a lookup field.)

item_number;#item_value

how to show only the item_value in the dropdown box. Can I apply rules to the dropdown box or is there any way through code to achieve this?

Thanks for the help!

I found a similar post here cascaded dropdown look up field but there are no proper solutions

I found a solution but have trouble making it work,
I am using a file query connection to get the data for the dropdown, i will be executing the connection and populating an xml document with the result. I am having trouble writing the content to xmldocument, see my question here-

Infopath FileQueryConnection.Execute(XpathNavigator) throws System.Net.WebException: Attempted to read or write protected memory

I guess if this is solved, everything will be fine.

答: You can try to use an extra calculated column to show clear data.</p>

ContentLicense: CC BY-SA 3.0


问:
Iterate through a list and split into a 1d list
Im trying to loop through a list in python and split words based on characters. I want to return a 1 dimension list as the result.

Example

```<code>wordlist = ['border\collie', 'dog\cat', 'horse\hound'] # slash fix
</code>```

Expected outcome
new_list = ['border', 'collie', 'dog', 'cat', 'horse', 'hound']

Everything that Ive tried results in a 2d list.

```<code>def split_slash_words(text):
    new_list = []
    new_list.append([i.split("\\") for i in text])
    return new_list

</code>```

returned a two dimensional array, and I cannot also resplit the new_list (as it is in a list type)

答: The append method adds a list to the end of new_list. If you use the extend method, each item is added to new_list.</p>

Body:
Im trying to loop through a list in python and split words based on characters. I want to return a 1 dimension list as the result.

Example

wordlist = ['border\collie', 'dog\cat', 'horse\hound'] # slash fix

Expected outcome
new_list = ['border', 'collie', 'dog', 'cat', 'horse', 'hound']

Everything that Ive tried results in a 2d list.

def split_slash_words(text):
    new_list = []
    new_list.append([i.split("\\") for i in text])
    return new_list

returned a two dimensional array, and I cannot also resplit the new_list (as it is in a list type)


问:
Kivy v1.11.1 nested box layout
I created a nesteded box layout with Kivy, which works. But I need to call three classes in my Python code. Is there a more elegant way of doing this? E.g. with just having one class in Python?

Python code:

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class HorizLayout1(BoxLayout):
    pass
class HorizLayout2(BoxLayout):
    pass

class VertLayout(BoxLayout):
    pass

class KivyTestsApp(App):
    def build(self):
        return VertLayout()

if __name__ == '__main__':
    KivyTestsApp().run()
</code>```

kivytests.kv:

```<code><HorizLayout1>:
    orientation: "horizontal"
    Button:
        text: "1"
    Button:
        text: "2"

<HorizLayout2>:
    orientation: "horizontal"
    Button:
        text: "3"
    Button:
        text: "4"

<VertLayout>:
    orientation: "vertical"
    HorizLayout1:
    HorizLayout2:
</code>```

答:
Your py could be this:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class VertLayout(BoxLayout):
    pass

class KivyTestsApp(App):
    def build(self):
        return VertLayout()

if __name__ == '__main__':
    KivyTestsApp().run()
```

<p>... and your <code>kv</code> could be this:</p>

<pre class="lang-py prettyprint-override"><code><VertLayout>:
    orientation: "vertical"
    BoxLayout:
        Button:
            text: "1"
        Button:
            text: "2"
    BoxLayout:
        Button:
            text: "3"
        Button:
            text: "4"
</code>```

Title: Kivy v1.11.1 nested box layout

Body:
I created a nesteded box layout with Kivy, which works. But I need to call three classes in my Python code. Is there a more elegant way of doing this? E.g. with just having one class in Python?

Python code:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class HorizLayout1(BoxLayout):
    pass
class HorizLayout2(BoxLayout):
    pass

class VertLayout(BoxLayout):
    pass

class KivyTestsApp(App):
    def build(self):
        return VertLayout()

if __name__ == '__main__':
    KivyTestsApp().run()

kivytests.kv:

<HorizLayout1>:
    orientation: "horizontal"
    Button:
        text: "1"
    Button:
        text: "2"

<HorizLayout2>:
    orientation: "horizontal"
    Button:
        text: "3"
    Button:
        text: "4"

<VertLayout>:
    orientation: "vertical"
    HorizLayout1:
    HorizLayout2:

Body:
Your py could be this:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class VertLayout(BoxLayout):
    pass

class KivyTestsApp(App):
    def build(self):
        return VertLayout()

if __name__ == '__main__':
    KivyTestsApp().run()

... and your kv could be this:

<VertLayout>:
    orientation: "vertical"
    BoxLayout:
        Button:
            text: "1"
        Button:
            text: "2"
    BoxLayout:
        Button:
            text: "3"
        Button:
            text: "4"


问:
Pandas: How to combine column int values if different given column is duplicated?
There are similar questions on Stack Overflow, but none of them have worked for my situation. I've tried working with a combination of add(...), merge(...), concat(...), drop_duplicates(...) and more, and I just can't seem to figure it out.

I'm handling data prior to this, and now need to combine the A1, A2, B1, B2, B3, B4, B5, and B6 columns (all type int) if ID matches (type str). It does not matter what FavoriteFood or Index the new one "inherits".

Given data:

```<code>Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2
5      Cookie        2330   0    0    6    6    6    6    6    6
6      Pizza         0020   2    2    0    0    0    0    0    0
</code>```

We have the following matches, based on IDs 0054 and 0012:

```<code>Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2
</code>```

Because Index, FavoriteFood, and the order of the DataFrame does not matter, the expected DataFrame is:

```<code>Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   9    9    7    7    7    7    7    7
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   12   12   12   12   12   12
5      Cookie        2330   0    0    6    6    6    6    6    6
6      Pizza         0020   2    2    0    0    0    0    0    0
</code>```

How can I combine those columns like this?

答:
You can try agg with a dictionary:

```<code>agg_dict = {col: 'first' if col in ['FavoriteFood','Index'] else 'sum'
            for col in df.columns if col!='ID'}
df.groupby('ID', as_index=False, sort=False).agg(agg_dict)
</code>```

Output:

```<code>     ID  Index FavoriteFood  A1  A2  B1  B2  B3  B4  B5  B6
0  0054      0        Pizza   9   9   7   7   7   7   7   7
1  0012      1    Hamburger  21  21  12  12  12  12  12  12
2  0101      2    Hamburger  70  70   0   0   0   0   0   0
3  2330      5       Cookie   0   0   6   6   6   6   6   6
4  0020      6        Pizza   2   2   0   0   0   0   0   0
</code>```

Body:
There are similar questions on Stack Overflow, but none of them have worked for my situation. I've tried working with a combination of add(...), merge(...), concat(...), drop_duplicates(...) and more, and I just can't seem to figure it out.

I'm handling data prior to this, and now need to combine the A1, A2, B1, B2, B3, B4, B5, and B6 columns (all type int) if ID matches (type str). It does not matter what FavoriteFood or Index the new one "inherits".

Given data:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2
5      Cookie        2330   0    0    6    6    6    6    6    6
6      Pizza         0020   2    2    0    0    0    0    0    0

We have the following matches, based on IDs 0054 and 0012:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2

Because Index, FavoriteFood, and the order of the DataFrame does not matter, the expected DataFrame is:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   9    9    7    7    7    7    7    7
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   12   12   12   12   12   12
5      Cookie        2330   0    0    6    6    6    6    6    6
6      Pizza         0020   2    2    0    0    0    0    0    0

How can I combine those columns like this?

Body:
You can try agg with a dictionary:

agg_dict = {col: 'first' if col in ['FavoriteFood','Index'] else 'sum'
            for col in df.columns if col!='ID'}
df.groupby('ID', as_index=False, sort=False).agg(agg_dict)

Output:

     ID  Index FavoriteFood  A1  A2  B1  B2  B3  B4  B5  B6
0  0054      0        Pizza   9   9   7   7   7   7   7   7
1  0012      1    Hamburger  21  21  12  12  12  12  12  12
2  0101      2    Hamburger  70  70   0   0   0   0   0   0
3  2330      5       Cookie   0   0   6   6   6   6   6   6
4  0020      6        Pizza   2   2   0   0   0   0   0   0


问:
Are type arguments in interfaces an actual type?
Don't think the title is best wording for this question, I have an interface with two type arguments, and I seem to be able to cast this as both of the types at the same time, see reproducable example:

```<code>interface BaseResult<S : BaseResult<S, E>, E : BaseResult<S, E>> {

    @Suppress("UNCHECKED_CAST")
    fun isSuccess(): Boolean {
        return try {
            val a = this as S //ClassCastException expected
            val b = this as E
            println(a) //com.BaseResultTest$ExampleResult$Error@17d10166
            println(b) //com.BaseResultTest$ExampleResult$Error@17d10166
            true
        } catch (e: Exception) {
            false
        }
    }
}
</code>```

Test:

```<code>class BaseResultTest {

    sealed class ExampleResult: BaseResult<ExampleResult.Success, ExampleResult.Error> {
        object Success: ExampleResult()
        object Error: ExampleResult()
    }

    @Test
    fun test() {
        val error = ExampleResult.Error
        assertEquals(error.isSuccess(), false)
    }
}
</code>```

Am I missing something, or is this a bug in the language? Using v1.3.61

答:
This isn't so much of a bug in the Language, but more of a logic error of the writer. While you can inflect the type of S and E, they're still similar to an Option and it's sub types of Some and None (Some is always typed to the Option<_> whereas None always is empty.

Part of your problem here is that you cannot guarantee the subclass is a type of S or E without explicitly declaring the subtypes for those cases. You can see examples of this in trying to implement Either, and some other examples including this one about Either.

I hope this helps answer the question.

Body:
Don't think the title is best wording for this question, I have an interface with two type arguments, and I seem to be able to cast this as both of the types at the same time, see reproducable example:

interface BaseResult<S : BaseResult<S, E>, E : BaseResult<S, E>> {

    @Suppress("UNCHECKED_CAST")
    fun isSuccess(): Boolean {
        return try {
            val a = this as S //ClassCastException expected
            val b = this as E
            println(a) //com.BaseResultTest$ExampleResult$Error@17d10166
            println(b) //com.BaseResultTest$ExampleResult$Error@17d10166
            true
        } catch (e: Exception) {
            false
        }
    }
}

Test:

class BaseResultTest {

    sealed class ExampleResult: BaseResult<ExampleResult.Success, ExampleResult.Error> {
        object Success: ExampleResult()
        object Error: ExampleResult()
    }

    @Test
    fun test() {
        val error = ExampleResult.Error
        assertEquals(error.isSuccess(), false)
    }
}

Am I missing something, or is this a bug in the language? Using v1.3.61


问:
How to remove element from array when button tapped
I have an add button that adds the current Item object to a finalList array. I am attempting to implement the remove button to remove that current item from the same array if it has already been added. The items are on a full page UICollectionViewCell along with the add and remove buttons.

```<code>   var finalList = [Item]()
    private var hiddenRows = Set<Int>()
@objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false

      let item = itemsArr[indexPath.row]

  //  cell.currentPrice += Float(item.price) ?? 0

    finalList.append(item)
    collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)

       }

@objc func removeButtonTapped(cell: PostCell) {
    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]

  //  finalList.remove(at: item.)
    totalPrice -= Float(item.price) ?? 0
    cell.currentPrice -= Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)
 //   collectionView?.reloadData()
     }

  extension CollectionViewController {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemsArr.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell

            cell.delegate = self

      let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]
    cell.set(name: item.name, brand: item.brand, price: item.price)

    print(finalList)
     if hiddenRows.contains(indexPath.row) {

                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}
</code>```

}

答:
You need a uique key suppose it's name

```<code>finalList.removeAll { $0.name == item.name }
</code>```

In remove don't use insert instead also use

```<code>hiddenRows.removeAll { $0 == indexPath.row }
</code>```

Body:
I have an add button that adds the current Item object to a finalList array. I am attempting to implement the remove button to remove that current item from the same array if it has already been added. The items are on a full page UICollectionViewCell along with the add and remove buttons.

   var finalList = [Item]()
    private var hiddenRows = Set<Int>()
@objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false

      let item = itemsArr[indexPath.row]

  //  cell.currentPrice += Float(item.price) ?? 0

    finalList.append(item)
    collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)

       }

@objc func removeButtonTapped(cell: PostCell) {
    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]

  //  finalList.remove(at: item.)
    totalPrice -= Float(item.price) ?? 0
    cell.currentPrice -= Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)
 //   collectionView?.reloadData()
     }

  extension CollectionViewController {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemsArr.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell

            cell.delegate = self

      let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]
    cell.set(name: item.name, brand: item.brand, price: item.price)

    print(finalList)
     if hiddenRows.contains(indexPath.row) {

                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

}

Body:
You need a uique key suppose it's name

finalList.removeAll { $0.name == item.name }

In remove don't use insert instead also use

hiddenRows.removeAll { $0 == indexPath.row }


问:
How does Youtube control Flash content loading (Chrome 12)
Several days ago my Google Chrome was updated to 12.0.742.53 beta, and I've noticed very interesting change.

When opening a Youtube video page, page loading process does not end even when all the content (text, images) is loaded; loading ends only when video buffering completes! Also, when I interrupt the loading (by pressing Esc, for example) video downloading is also stopped! (Until now I had to right click on the video and press Stop Download to abort buffering).

IMHO that's a great user experience and a big step for making the Flash-based content behave like ordinary web content.

My question is: how this is done?!

I thought they're simulating some loading process until the buffering completes. Also they should have handled the window.onAbort event or something, in order to "tell" the Flash to stop buffering. I tried to catch that event using Chrome's DOM Inspector, but no luck...

Or... do they use some special API that is currently available only in Chrome? There is no such behavior on FF4 right now.

答: It's because flash's net connections are handled via the browser, so requests Flash makes are treated like any other request.</p>


问:
Spring Runtime Error - Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument
I've inherited a legacy Java app require JDK 7.

The app will compile, but I'm getting runtime errors which look like Hibernate entityManagerFactory issues.

The strange part is this app works on another developers machine. He even sent me his Tomcat directory, I have tried it on a Mac and on an Ubuntu machine. No matter where I run it, the runtime errors persist.

I think the problems is an init method in entityManagerFactory class,

```<code>Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
</code>```

pom.xml

PersistenceConfiguration Class:

```<code> * Copyright (c) 2014, German Federal Agency for Cartography and Geodesy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.

 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials
 *       provided with the distribution.

 *     * The names "German Federal Agency for Cartography and Geodesy",
 *       "Bundesamt für Kartographie und Geodäsie", "BKG", "GDI-DE",
 *       "GDI-DE Registry" and the names of other contributors must not
 *       be used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GERMAN
 * FEDERAL AGENCY FOR CARTOGRAPHY AND GEODESY BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package de.geoinfoffm.registry.persistence;

import java.sql.Connection;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.flywaydb.core.api.callback.FlywayCallback;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import de.bespire.LoggerFactory;
import de.geoinfoffm.registry.core.Repository;
import de.geoinfoffm.registry.core.configuration.RegistryConfiguration;
import de.geoinfoffm.registry.persistence.jpa.HibernateConfiguration;

/**
 * Spring configuration class for the persistence layer.
 *
 * @author Florian Esser
 *
 */
@ComponentScan(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" })
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" },
                       repositoryFactoryBeanClass = EntityBackendFactoryBean.class)
public class PersistenceConfiguration
{
    private static final Logger logger = LoggerFactory.make();

    @Autowired
    private Environment env;

    /**
     * Creates a {@link LocalContainerEntityManagerFactoryBean} that will handle the creation
     * of {@link EntityManager}s used by the {@link Repository}s of domain object {@link Repository}s.
     */
    @Autowired
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaManagementService) {
        // Handle schema migration before creating the EntityManagerFactoryBean
        final String flywayMigration = hibernateConfiguration.additionalParameters().getProperty("flyway.migration", "false").toString().toLowerCase();
        if ("true".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.analyze();
            schemaManagementService.migrate();
        }
        else if ("repair".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repair();
        }
        else if ("repairAndMigrate".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repairAndMigrate();
        }

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource(hibernateConfiguration));
        em.setPackagesToScan(registryConfiguration.getBasePackages());
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernateConfiguration.additionalParameters());

        return em;
    }

    @Autowired
    @Bean
    public LocalSessionFactoryBean sessionFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration) {
        LocalSessionFactoryBean result = new LocalSessionFactoryBean();
        result.setDataSource(dataSource(hibernateConfiguration));
        result.setPackagesToScan(registryConfiguration.getBasePackages());

        return result;
    }

    /**
     * @return the {@link DataSource} for the application, based on the connection properties
     */
    @Autowired
    @Bean
    public DataSource dataSource(HibernateConfiguration hibernateConfiguration) {
        return hibernateConfiguration.dataSource();
    }

    /**
     * @return the {@link PlatformTransactionManager} for the application
     */
    @Autowired
    @Bean
    public PlatformTransactionManager transactionManager(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaService) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory(hibernateConfiguration, registryConfiguration, schemaService).getObject());

        return transactionManager;
    }

    /**
     * @return the {@link PersistenceExceptionTranslationPostProcessor} for the application
     */
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Autowired
    @Bean
    public DatabaseSchemaMangementService databaseSchemaMangementService(HibernateConfiguration hibernateConfiguration) {
        return new FlywayDatabaseSchemaManagementService(dataSource(hibernateConfiguration));
    }

}
</code>```

Log file

```<code>INFO: 2 Spring WebApplicationInitializers detected on classpath
Feb 14, 2020 12:28:42 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 14, 2020 12:29:00 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'isoClientConfiguration': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:713)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5195)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5720)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1016)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:992)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:639)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 36 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at
</code>```

Update - Looks like the problem is base packages are not found for this project.

The class that handles getting base packages - getBasePackages()
Of course, I don't know why this project is not finding base packages on my dev instance.

答:
You have a nested NullPointerException in what looks like your PersistenceConfiguration class

```<code>Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
</code>```

Consider posting your code as well if the source of the NPE is not obvious.

Body:
I've inherited a legacy Java app require JDK 7.

The app will compile, but I'm getting runtime errors which look like Hibernate entityManagerFactory issues.

The strange part is this app works on another developers machine. He even sent me his Tomcat directory, I have tried it on a Mac and on an Ubuntu machine. No matter where I run it, the runtime errors persist.

I think the problems is an init method in entityManagerFactory class,

Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException

pom.xml

PersistenceConfiguration Class:

 * Copyright (c) 2014, German Federal Agency for Cartography and Geodesy
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.

 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials
 *       provided with the distribution.

 *     * The names "German Federal Agency for Cartography and Geodesy",
 *       "Bundesamt für Kartographie und Geodäsie", "BKG", "GDI-DE",
 *       "GDI-DE Registry" and the names of other contributors must not
 *       be used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GERMAN
 * FEDERAL AGENCY FOR CARTOGRAPHY AND GEODESY BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package de.geoinfoffm.registry.persistence;

import java.sql.Connection;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationInfoService;
import org.flywaydb.core.api.callback.FlywayCallback;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import de.bespire.LoggerFactory;
import de.geoinfoffm.registry.core.Repository;
import de.geoinfoffm.registry.core.configuration.RegistryConfiguration;
import de.geoinfoffm.registry.persistence.jpa.HibernateConfiguration;

/**
 * Spring configuration class for the persistence layer.
 *
 * @author Florian Esser
 *
 */
@ComponentScan(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" })
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "de.bespire.registry", "de.geoinfoffm.registry" },
                       repositoryFactoryBeanClass = EntityBackendFactoryBean.class)
public class PersistenceConfiguration
{
    private static final Logger logger = LoggerFactory.make();

    @Autowired
    private Environment env;

    /**
     * Creates a {@link LocalContainerEntityManagerFactoryBean} that will handle the creation
     * of {@link EntityManager}s used by the {@link Repository}s of domain object {@link Repository}s.
     */
    @Autowired
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaManagementService) {
        // Handle schema migration before creating the EntityManagerFactoryBean
        final String flywayMigration = hibernateConfiguration.additionalParameters().getProperty("flyway.migration", "false").toString().toLowerCase();
        if ("true".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.analyze();
            schemaManagementService.migrate();
        }
        else if ("repair".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repair();
        }
        else if ("repairAndMigrate".equalsIgnoreCase(flywayMigration)) {
            schemaManagementService.repairAndMigrate();
        }

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource(hibernateConfiguration));
        em.setPackagesToScan(registryConfiguration.getBasePackages());
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernateConfiguration.additionalParameters());

        return em;
    }

    @Autowired
    @Bean
    public LocalSessionFactoryBean sessionFactory(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration) {
        LocalSessionFactoryBean result = new LocalSessionFactoryBean();
        result.setDataSource(dataSource(hibernateConfiguration));
        result.setPackagesToScan(registryConfiguration.getBasePackages());

        return result;
    }

    /**
     * @return the {@link DataSource} for the application, based on the connection properties
     */
    @Autowired
    @Bean
    public DataSource dataSource(HibernateConfiguration hibernateConfiguration) {
        return hibernateConfiguration.dataSource();
    }

    /**
     * @return the {@link PlatformTransactionManager} for the application
     */
    @Autowired
    @Bean
    public PlatformTransactionManager transactionManager(HibernateConfiguration hibernateConfiguration, RegistryConfiguration registryConfiguration, DatabaseSchemaMangementService schemaService) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory(hibernateConfiguration, registryConfiguration, schemaService).getObject());

        return transactionManager;
    }

    /**
     * @return the {@link PersistenceExceptionTranslationPostProcessor} for the application
     */
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Autowired
    @Bean
    public DatabaseSchemaMangementService databaseSchemaMangementService(HibernateConfiguration hibernateConfiguration) {
        return new FlywayDatabaseSchemaManagementService(dataSource(hibernateConfiguration));
    }

}

Log file

INFO: 2 Spring WebApplicationInitializers detected on classpath
Feb 14, 2020 12:28:42 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Feb 14, 2020 12:29:00 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'isoClientConfiguration': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:713)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5195)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5720)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1016)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:992)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:639)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1127)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:2020)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1181)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1075)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 36 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [org/iso/registry/client/configuration/web/IsoClientHibernateConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Unsatisfied dependency expressed through method 'setPermissionEvaluator' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'registryUserRepository': Cannot create inner bean '(inner bean)#7a511d1d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7a511d1d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at

Update - Looks like the problem is base packages are not found for this project.

The class that handles getting base packages - getBasePackages()
Of course, I don't know why this project is not finding base packages on my dev instance.

Body:
You have a nested NullPointerException in what looks like your PersistenceConfiguration class

Error creating bean with name 'entityManagerFactory' defined in de.geoinfoffm.registry.persistence.PersistenceConfiguration: Invocation of init method failed; nested exception is java.lang.NullPointerException

Consider posting your code as well if the source of the NPE is not obvious.


问:
Android Emulator not using webcam in Android Studio
As the title suggests, I'm struggling to get the emulator use the webcam on the laptop. I have enabled the front and back camera to access the webcam. Whenever the emulator boots up it asks for webcam access, which I grant. However the webcam never works when I hit the camera app on the emulator. The camera app just crashes.

Here is an image enabling the cameras:

Based on other posts on StackOverflow, suggesting i add the line: hw.camera=yes. Below is the config file for the avd.

```<code>avd.ini.encoding=UTF-8
AvdId=Nexus_5_API_21_x86
abi.type=x86
avd.ini.displayname=Nexus 5 API 21 x86
disk.dataPartition.size=1G
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.camera=yes
hw.camera.back=webcam0
hw.camera.front=webcam0
hw.cpu.arch=x86
hw.dPad=no
hw.device.hash2=MD5:2fa0e16c8cceb7d385183284107c0c88
hw.device.manufacturer=Google
hw.device.name=Nexus 5
hw.gps=yes
hw.gpu.enabled=yes
hw.keyboard=yes
hw.lcd.density=480
hw.mainKeys=no
hw.ramSize=1536
hw.sdCard=yes
hw.sensors.orientation=yes
hw.sensors.proximity=yes
hw.trackBall=no
image.sysdir.1=system-images\android-21\google_apis\x86\
runtime.network.latency=none
runtime.network.speed=full
runtime.scalefactor=auto
sdcard.path=C:\Users\Roberto\.android\avd\Nexus_5_API_21_x86.avd\sdcard.img
skin.dynamic=no
skin.name=nexus_5
skin.path=C:\Program Files\Android\Android Studio1\plugins\android\lib\device-art-resources\nexus_5
snapshot.present=no
tag.display=Google APIs
tag.id=google_apis
vm.heapSize=64
</code>```

At this stage I'm not sure why this is not working. Any thoughts?

答:
I encountered a similar problem when I tried to use the host system webcam in the Android emulator. I set the webcam settings to webcam0 for the emulator, but the camera’s system application crashed with the error “Unable to access the camera”. An alternative camera application threw an "Unknown camera ID" error.
This will sound ridiculous, but I just forgot to turn on the camera on my laptop using the Fn button and the camera device was not in the Windows device manager. After turning on the camera in the host system with hot keys and rebooting the emulator (with the "Cold Boot" option), the Android camera started working.
Perhaps this answer will help someone as inattentive as I am.

Body:
As the title suggests, I'm struggling to get the emulator use the webcam on the laptop. I have enabled the front and back camera to access the webcam. Whenever the emulator boots up it asks for webcam access, which I grant. However the webcam never works when I hit the camera app on the emulator. The camera app just crashes.

Here is an image enabling the cameras:

Based on other posts on StackOverflow, suggesting i add the line: hw.camera=yes. Below is the config file for the avd.

avd.ini.encoding=UTF-8
AvdId=Nexus_5_API_21_x86
abi.type=x86
avd.ini.displayname=Nexus 5 API 21 x86
disk.dataPartition.size=1G
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.camera=yes
hw.camera.back=webcam0
hw.camera.front=webcam0
hw.cpu.arch=x86
hw.dPad=no
hw.device.hash2=MD5:2fa0e16c8cceb7d385183284107c0c88
hw.device.manufacturer=Google
hw.device.name=Nexus 5
hw.gps=yes
hw.gpu.enabled=yes
hw.keyboard=yes
hw.lcd.density=480
hw.mainKeys=no
hw.ramSize=1536
hw.sdCard=yes
hw.sensors.orientation=yes
hw.sensors.proximity=yes
hw.trackBall=no
image.sysdir.1=system-images\android-21\google_apis\x86\
runtime.network.latency=none
runtime.network.speed=full
runtime.scalefactor=auto
sdcard.path=C:\Users\Roberto\.android\avd\Nexus_5_API_21_x86.avd\sdcard.img
skin.dynamic=no
skin.name=nexus_5
skin.path=C:\Program Files\Android\Android Studio1\plugins\android\lib\device-art-resources\nexus_5
snapshot.present=no
tag.display=Google APIs
tag.id=google_apis
vm.heapSize=64

At this stage I'm not sure why this is not working. Any thoughts?


问:
Filter data frame based on percentile range of one column in pandas
I have a data frame as shown below

```<code>ID     Price
1      5
2      90
3      20
4      40
5      30
6      70
7      60
8      100
9      80
10     50
</code>```

From the above I would like to filter above data frame from 10 percentile to 90 percentile as shown below.

Expected output:

```<code>ID     Price
2      90
3      20
4      40
5      30
6      70
7      60
9      80
10     50
</code>```

Body:
I have a data frame as shown below

ID     Price
1      5
2      90
3      20
4      40
5      30
6      70
7      60
8      100
9      80
10     50

From the above I would like to filter above data frame from 10 percentile to 90 percentile as shown below.

Expected output:

ID     Price
2      90
3      20
4      40
5      30
6      70
7      60
9      80
10     50

Body:
Use between + Series.quantile

df[df['Price'].between(*df['Price'].quantile([0.1, 0.9]))]

   ID  Price
1   2     90
2   3     20
3   4     40
4   5     30
5   6     70
6   7     60
8   9     80
9  10     50


问:
How to retrieve data as File object on flask webserver?
I am currently developing a web interface where you can draw a digit and upload it. The image goes through a machine learning model of digit recognition and return the digit that has been transcribed by the user.

HTML Code :

```<code><canvas id="myCanvas">
        Sorry, your browser does not support HTML5 canvas technology.
</canvas>
<button onclick="clickonbutton()">Upload</button>
</code>```

Canvas is used to draw digit and button to send it to a flask web server.

Javascript Code :

```<code><script type="text/javascript">
function clickonbutton() {
        var canvas = document.getElementById('myCanvas');

        //Convert HTML5 Canvas to bytes-like object then File object
        canvas.toBlob(function(blob) {
                var file = new File([blob], "image.png", { type: "image/png", lastModified : new Date()});

                //Prepare a XMLHttpRequest to send the data with POST method to the server
                var request = new XMLHttpRequest();
                request.open("POST", "/");
                request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                //Sending file...
                request.send(file);
         });
}
</script>
</code>```

When the user click on the button "Upload" after editing the HTML5 canvas, it run this function which send the file to the server.

Python script (server-side) :

```<code>@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #Convert MultiDict to Dict object then string
        data = str(request.form.to_dict())

        #Format string to remove Dict elements
        data = data.replace("{","")
        data = data.replace("}","")
        data = data.replace("'","")
        data = data.replace(": ","")

        #Convert string to bytes-like object
        img_bytes = data.encode()

        #Predict the digit of the user
        _, predicted_class, probabilities = get_prediction(image_bytes=img_bytes)
        predicted_class = int(predicted_class)
        classify(img=_, ps=probabilities)

        #Return the result of the digit prediction
        return render_template('result.html',class_name=predicted_class)
    return render_template('index.html')
</code>```

On server-side, i get the data from request.form but these are in a ImmutableMultiDict object so i converted the data to string then bytes-like object. Unfortunately, conversion using the .replace() method corrupts the PNG file and there's no tool to do that conversion properly...

Is there a solution to get the data directly in a File object without using an ImmutableMultiDict object ?

答:
So with help from this thread on using the Fetch API and this answer on HTML5 canvas drawing I figured this could be done with something like:

```<code><div id='sketch'>
  <canvas id="myCanvas">
  </canvas>
</div>

<button id='btn'>Upload</button>

<div id='result' style='font-size:2em;'></div>
</code>```

Notice I've added a div to output the results (the class name) on the same page.

Then in the Javascript use a FormData object: (I've missed out the drawing function for clarity):

```<code>
// Define the dom elements
const canvas = document.getElementById('myCanvas');
const btn = document.getElementById('btn');
const result = document.getElementById('result');

// This will handle the upload
const upload = (file) => {
  fetch('/', { // Your POST endpoint
    method: 'POST',
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => { result.innerText = success['class_name']; } // Write class_name into results div.
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Listener which handles the button click:
btn.addEventListener('click', function() {

  canvas.toBlob(function(blob) {
    var data = new FormData();
    data.append('file', blob);
    upload(data);
  });

}, false);
</code>```

Now on the server side, this can be handled like a regular Flask file upload:

```<code>@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']

        #Convert string to bytes-like object
        img_bytes = file.read()

        #Predict the digit of the user
        _, predicted_class, probabilities = get_prediction(image_bytes=img_bytes)
        predicted_class = int(predicted_class)
        classify(img=_, ps=probabilities)

        #Return the result of the digit prediction
        return {'class_name': predicted_class}
    return render_template('index.html')
</code>```

Any post request now returns a jsonified dictionary, which is in turn written to the results div on the page.

There's probably room for improvment here, like some validation on the server-side aswell as rate limiting and error handling, but the basic concept works.

Body:
I am currently developing a web interface where you can draw a digit and upload it. The image goes through a machine learning model of digit recognition and return the digit that has been transcribed by the user.

HTML Code :

<canvas id="myCanvas">
        Sorry, your browser does not support HTML5 canvas technology.
</canvas>
<button onclick="clickonbutton()">Upload</button>

Canvas is used to draw digit and button to send it to a flask web server.

Javascript Code :

When the user click on the button "Upload" after editing the HTML5 canvas, it run this function which send the file to the server.

Python script (server-side) :

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        #Convert MultiDict to Dict object then string
        data = str(request.form.to_dict())

        #Format string to remove Dict elements
        data = data.replace("{","")
        data = data.replace("}","")
        data = data.replace("'","")
        data = data.replace(": ","")

        #Convert string to bytes-like object
        img_bytes = data.encode()

        #Predict the digit of the user
        _, predicted_class, probabilities = get_prediction(image_bytes=img_bytes)
        predicted_class = int(predicted_class)
        classify(img=_, ps=probabilities)

        #Return the result of the digit prediction
        return render_template('result.html',class_name=predicted_class)
    return render_template('index.html')

On server-side, i get the data from request.form but these are in a ImmutableMultiDict object so i converted the data to string then bytes-like object. Unfortunately, conversion using the .replace() method corrupts the PNG file and there's no tool to do that conversion properly...

Is there a solution to get the data directly in a File object without using an ImmutableMultiDict object ?

Body:
So with help from this thread on using the Fetch API and this answer on HTML5 canvas drawing I figured this could be done with something like:

<div id='sketch'>
  <canvas id="myCanvas">
  </canvas>
</div>

<button id='btn'>Upload</button>

<div id='result' style='font-size:2em;'></div>

Notice I've added a div to output the results (the class name) on the same page.

Then in the Javascript use a FormData object: (I've missed out the drawing function for clarity):

// Define the dom elements
const canvas = document.getElementById('myCanvas');
const btn = document.getElementById('btn');
const result = document.getElementById('result');

// This will handle the upload
const upload = (file) => {
  fetch('/', { // Your POST endpoint
    method: 'POST',
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => { result.innerText = success['class_name']; } // Write class_name into results div.
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Listener which handles the button click:
btn.addEventListener('click', function() {

  canvas.toBlob(function(blob) {
    var data = new FormData();
    data.append('file', blob);
    upload(data);
  });

}, false);

Now on the server side, this can be handled like a regular Flask file upload:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']

        #Convert string to bytes-like object
        img_bytes = file.read()

        #Predict the digit of the user
        _, predicted_class, probabilities = get_prediction(image_bytes=img_bytes)
        predicted_class = int(predicted_class)
        classify(img=_, ps=probabilities)

        #Return the result of the digit prediction
        return {'class_name': predicted_class}
    return render_template('index.html')

Any post request now returns a jsonified dictionary, which is in turn written to the results div on the page.

There's probably room for improvment here, like some validation on the server-side aswell as rate limiting and error handling, but the basic concept works.


问:
How do I remove a project configuration in Visual Studio 2008?
I have a Visual Studio 2008 solution into which I have imported a number of pre-existing projects.  The projects are mixed-language sample code (C#, VB, C++/CLI).  They currently have multiple configurations, but I want each project only to have only a single "Debug" configuration.

In the configuration manager, I deleted the other configurations (e.g. "Release"), but as I did so there was a warning message to tell me that they would not be deleted from the individual projects.

And indeed when I navigate to an individual project, it still has "Release" and other configurations, even though at the solution level there is only "Debug".

How can I best remove these extra configurations from each project?  Am I overlooking some way to do this in the GUI, or should I just edit the project files directly?

答:
In VS2017/VS2019, if you drop down the "Active solution configuration", there is an <edit> there that lets you remove a configuration from all projects.

Screenshot showing <edit>

OwnerDisplayName: Eric

ContentLicense: CC BY-SA 2.5


问:
Removing pages from search engine results
Hey everyone, I'm a bit new to SEO. I built a one page website that initially utilized several pages (but are now removed), and it looks as if Google has indexed those so that they show up as search results. Is there any way to remove those from the search results? Thanks.</p>

答:
```<code><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
</code>```