问:
why openpyxl creating worksheet with name"Sheet1"?
openpyxl creates spreadsheet with name "Sheet1" by default
even though I'm specifying that the sheet should be created with index 0.
I'm sure it's not a duplicate question.
Documentation says openpyxl supports 2010 MS Office version but I'm using office365 pro.
Could you provide any help or suggestions?

Please note that standalone code is working fine for me but when the same code is being integrated with other code I experience the problem described below.
I have tried many things. Since I'm new to Python it looks like there's something I'm not aware of.
If I specify index 1 there are two worksheets created: one with name Sheet and the other one with name I'm providing. If I provide Index 0 there is only one Sheet with name Sheet1 created.

The code below should create worksheet at index 0 with name test.

```<code>            for r in range(3, rowcount + 1):
                for c in range(1, columncount + 1):
                    final_path = first_part + str(r) + second_part + str(c) + third_part
                    table_data = self.driver.find_element_by_xpath(final_path).text

                    fname = r"{}_{}.xlsx".format(str(i[1]), str(i[2]))
                    if (os.path.exists(fname)):
                        workbook = openpyxl.load_workbook(fname)
                        worksheet = workbook[fname]
                    else:
                        workbook = Workbook()
                        worksheet= workbook.create_sheet(fname,0)
                        #worksheet = workbook.active
                        #worksheet.title = fname
                    worksheet.cell(row=r,column=c).value = table_data
                    workbook.save(fname)
</code>```

答:
openpyxl creates a single sheet called "Sheet" when you first call the Workbook() function. It's just a kind of annoying quirk of the module.. The cleanest way I found to deal with it is to just rename that sheet instead of attempting to make a new one

```<code>from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
wb.save("Test.xlsx")
</code>```

Will create an xlsx file with a single worksheet called "My sheet name".
When you call create_sheet with index 0, you just insert a new sheet before this original sheet.

```<code>from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
ws2 = wb.create_sheet("Another Name", 0)
wb.save("Test.xlsx")
</code>```

Will create an xlsx where the first sheet is called "Another name" and the second sheet is called "My sheet name". If you're dealing with one sheet workbooks it's easiest to just use title.

Body:
openpyxl creates spreadsheet with name "Sheet1" by default
even though I'm specifying that the sheet should be created with index 0.
I'm sure it's not a duplicate question.
Documentation says openpyxl supports 2010 MS Office version but I'm using office365 pro.
Could you provide any help or suggestions?

Please note that standalone code is working fine for me but when the same code is being integrated with other code I experience the problem described below.
I have tried many things. Since I'm new to Python it looks like there's something I'm not aware of.
If I specify index 1 there are two worksheets created: one with name Sheet and the other one with name I'm providing. If I provide Index 0 there is only one Sheet with name Sheet1 created.

The code below should create worksheet at index 0 with name test.

            for r in range(3, rowcount + 1):
                for c in range(1, columncount + 1):
                    final_path = first_part + str(r) + second_part + str(c) + third_part
                    table_data = self.driver.find_element_by_xpath(final_path).text

                    fname = r"{}_{}.xlsx".format(str(i[1]), str(i[2]))
                    if (os.path.exists(fname)):
                        workbook = openpyxl.load_workbook(fname)
                        worksheet = workbook[fname]
                    else:
                        workbook = Workbook()
                        worksheet= workbook.create_sheet(fname,0)
                        #worksheet = workbook.active
                        #worksheet.title = fname
                    worksheet.cell(row=r,column=c).value = table_data
                    workbook.save(fname)

Body:
openpyxl creates a single sheet called "Sheet" when you first call the Workbook() function. It's just a kind of annoying quirk of the module.. The cleanest way I found to deal with it is to just rename that sheet instead of attempting to make a new one

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
wb.save("Test.xlsx")

Will create an xlsx file with a single worksheet called "My sheet name".
When you call create_sheet with index 0, you just insert a new sheet before this original sheet.

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
ws2 = wb.create_sheet("Another Name", 0)
wb.save("Test.xlsx")

Will create an xlsx where the first sheet is called "Another name" and the second sheet is called "My sheet name". If you're dealing with one sheet workbooks it's easiest to just use title.


来源: stackexchange

问:
why no tailOption in Scala?
Why is no tailOption in Scala, if there is headOption ?

This is an old question, found no answer on google.

答: Actually, there is lastOption which does exactly what you want

ContentLicense: CC BY-SA 3.0

Title: why no tailOption in Scala?

ContentLicense: CC BY-SA 4.0


问:
Oracle query to filter and sort table based on values in child table
I am using Oracle 11g, and I have tables with data and structure as follows:

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 2 | Jane   | 40  |
 3 | Agatha | 45  |
-------------------

TABLE2_CHILD
==============================================
CID | Name       | Age | Class | House | PID |
----------------------------------------------
 1 | John        | 7  |    3   | Red   |  1  |
 2 | Marie       | 5  |    1   | Yellow|  2  |
 3 | Petra       | 6  |    2   | Green |  3  |
 4 | Taylor      | 8  |    4   | Blue  |  2  |
 5 | Lean        | 9  |    5   | Red   |  2  |
 6 | Justin      | 7  |    3   | Yellow|  3  |
 7 | Arianna     | 5  |    1   | Blue  |  3  |
 8 | Brendon     | 6  |    2   | Green |  3  |
 9 | Shawn       | 7  |    3   | Red   |  1  |
----------------------------------------------
</code>```

For a single condition, the query is simple:

```<code>SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);
</code>```

which will result in the following result:

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 3 | Agatha | 45  |
-------------------
</code>```

However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:

```<code>SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');
</code>```

I would get no results.

I am expecting the result to be :

```<code>TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 3 | Agatha | 45  |
-------------------
</code>```

since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.

I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.

```<code>List<Parent> filteredParents = parents.stream()
                .filter(parent -> parent.getChildren().stream()
                        .anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
                        .anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
                .collect(Collectors.toList());

</code>```

I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.

Any help would be great. Thanks!

答:
You are not getting output because in your TABLE2_CHILD, there is no child whose age is 7 in the green house. For your expected result, the query should be:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7) AND PID IN (SELECT PID FROM TABLE2_CHILD WHERE house='GREEN');

Body:
I am using Oracle 11g, and I have tables with data and structure as follows:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 2 | Jane   | 40  |
 3 | Agatha | 45  |
-------------------

TABLE2_CHILD
==============================================
CID | Name       | Age | Class | House | PID |
----------------------------------------------
 1 | John        | 7  |    3   | Red   |  1  |
 2 | Marie       | 5  |    1   | Yellow|  2  |
 3 | Petra       | 6  |    2   | Green |  3  |
 4 | Taylor      | 8  |    4   | Blue  |  2  |
 5 | Lean        | 9  |    5   | Red   |  2  |
 6 | Justin      | 7  |    3   | Yellow|  3  |
 7 | Arianna     | 5  |    1   | Blue  |  3  |
 8 | Brendon     | 6  |    2   | Green |  3  |
 9 | Shawn       | 7  |    3   | Red   |  1  |
----------------------------------------------

For a single condition, the query is simple:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7);

which will result in the following result:

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 1 | Mark   | 35  |
 3 | Agatha | 45  |
-------------------

However, if I want to fetch the list of parents whose children are of age=7 and belong to house='GREEN', if I write a query as below:

SELECT * FROM TABLE1_PARENT WHERE PID IN (SELECT PID FROM TABLE2_CHILD WHERE AGE=7 AND house='GREEN');

I would get no results.

I am expecting the result to be :

TABLE1_PARENT:
-------------------
PID | Name  | Age |
-------------------
 3 | Agatha | 45  |
-------------------

since Agatha has a child belonging to age=7, and a child belonging to house='GREEN'.

I was able to come up with a solution for a similar data structure using Java streams. I am trying to do the same using Oracle SQL.

List<Parent> filteredParents = parents.stream()
                .filter(parent -> parent.getChildren().stream()
                        .anyMatch(child -> child.getAge().equals("7")) && parent.getChildren().stream()
                        .anyMatch(child -> child.getHouse().equalsIgnoreCase("Green")))
                .collect(Collectors.toList());

I am expecting the query to give me a result where the conditions could match any of the children. Because, the filtering is happening at the Parent level.

Any help would be great. Thanks!


问:
Simple CRUD examples for alpha driver from MongoDB
I want to test the Golang MongoDB driver from MongoDB
(https://github.com/mongodb/mongo-go-driver, currently in alpha state).

The example in the package documentation (https://godoc.org/github.com/mongodb/mongo-go-driver/mongo) isn't very help for me. What I'm looking for are simple (but complete) examples for the basic CRUD operations.

答:
I wrote code like this in my recent project and it worked well. Request you to kindly try it out.

FYI : I am using official Go - Mongo DB driver.

```<code>import "go.mongodb.org/mongo-driver/bson/primitive"
</code>```

and

```<code>type Item struct {

    OID  primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
    Item string
    Qty  int
    Tags []string
    Size Size
}
</code>```

Body:
I wrote code like this in my recent project and it worked well. Request you to kindly try it out.

FYI : I am using official Go - Mongo DB driver.

import "go.mongodb.org/mongo-driver/bson/primitive"

and

type Item struct {

    OID  primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
    Item string
    Qty  int
    Tags []string
    Size Size
}


问:
Match a string that doesn't contain another string in Bash?
I want to match a string that contains some text in the beginning and end but doesn't contain a different text in the middle. For example: starts with a word (\w+) and ends with another one but doesn't contain NOT in between:

```<code>some_YES_text   // ok
other_COOL_string  // also ok
some_NOT_string   // don't want to match this
</code>```

Normally, I could do that with negative lookahead:

```<code>\w+_(?!NOT)\w+_\w+
</code>```

But I'm writing a script in Bash which doesn't support it. What is the easiest way to achieve the same effect?

Edit: I wasn't precise before - I still need to use regex, not just plain text matching.

答:
You may match abc_NOT_def or abc_anywordhere_def and capture one of them, or part of them, and upon a match, check if that capture is not empty. Then, just implement the logic you need:

```<code>s="other_NOT_string"
rx='^([[:alnum:]_]+_(NOT)_[[:alnum:]_]+|[[:alnum:]_]+_[[:alnum:]_]+_[[:alnum:]_]+)$'
if [[ "$s" =~ $rx ]]; then
 if [ -z ${BASH_REMATCH[2]} ]; then
   echo "MATCH: ${BASH_REMATCH[0]}"
 else
   echo "No match"
 fi;
else
 echo "No match"
fi;
</code>```

Details

^ - start of string

( - Start of Group 1:

[[:alnum:]_]+_ - 1+ word chars (POSIX ERE \w equivalent) and a _

(NOT) - Group 2: NOT

_[[:alnum:]_]+  - _ and 1+ word chars

| - or

[[:alnum:]_]+_[[:alnum:]_]+_[[:alnum:]_]+ - 1+ word chars, _, 1+ word chars, _ and again 1+ word chars

) - end of Group 1.

$ - end of string

With [ -z ${BASH_REMATCH[2]} ] condition, we check if NOT was matched. If it was, there is no valid match, else, there is one.

Body:
I want to match a string that contains some text in the beginning and end but doesn't contain a different text in the middle. For example: starts with a word (\w+) and ends with another one but doesn't contain NOT in between:

some_YES_text   // ok
other_COOL_string  // also ok
some_NOT_string   // don't want to match this

Normally, I could do that with negative lookahead:

\w+_(?!NOT)\w+_\w+

But I'm writing a script in Bash which doesn't support it. What is the easiest way to achieve the same effect?

Edit: I wasn't precise before - I still need to use regex, not just plain text matching.

Body:
You may match abc_NOT_def or abc_anywordhere_def and capture one of them, or part of them, and upon a match, check if that capture is not empty. Then, just implement the logic you need:

s="other_NOT_string"
rx='^([[:alnum:]_]+_(NOT)_[[:alnum:]_]+|[[:alnum:]_]+_[[:alnum:]_]+_[[:alnum:]_]+)$'
if [[ "$s" =~ $rx ]]; then
 if [ -z ${BASH_REMATCH[2]} ]; then
   echo "MATCH: ${BASH_REMATCH[0]}"
 else
   echo "No match"
 fi;
else
 echo "No match"
fi;

Details

^ - start of string

( - Start of Group 1:

[[:alnum:]_]+_ - 1+ word chars (POSIX ERE \w equivalent) and a _

(NOT) - Group 2: NOT

_[[:alnum:]_]+  - _ and 1+ word chars

| - or

[[:alnum:]_]+_[[:alnum:]_]+_[[:alnum:]_]+ - 1+ word chars, _, 1+ word chars, _ and again 1+ word chars

) - end of Group 1.

$ - end of string

With [ -z ${BASH_REMATCH[2]} ] condition, we check if NOT was matched. If it was, there is no valid match, else, there is one.


问:
apache-camel put bulk messages into JMS
Am setting up a project where bulk commit of JMS has to be done in a single shot. Using the transaction for restarting the message processing, so need thoughts on how to push "x" number of messages onto a JMS Queue and do JMS commit.

What am currently doing is creating a JMS message which a long string appended with the message which I wish to commit in one shot.
Then use a Splitter to split the message into multiple in another route.
Finally, use another route to send the messages onto JMS (as a bulk commit).

```<code>    <route>
        <from uri="file:sample"/>
        <split streaming="true">
            <tokenize token="\n"/>
            <to uri="activemq:queue:dest"/>
        </split>
    </route>
</code>```

I wish to construct a route that controls when the JMS commit is issued.

The use case is am trying to read a message from Queue A and create many messages (let that number be "x"). And push them to Queue B. However, I wish to do a bulk commit (or batch commit) like DB. Am trying to be efficient not to create connections to JMS and do individual commits.

答:
I don't fully see your problem. Perhaps it is just a matter of what error handling to use.

Setup: You have a Camel route with a transacted JMS consumer and in this route you send multiple messages to one or different queues.

Good case: The route is successfully completed and all JMS messages are delivered.

Error case: If your route encounters an error, let's say in the middle of processing, some JMS messages are already "sent", some are not.

In this case no messages are sent at all because Camel does a rollback and the already "sent" JMS messages are not really sent or, to be more precise, they are not yet committed and they will not get committed.

Important detail: Camel must not handle the error. If it does, the error is not propagated to the broker and therefore the consumed message is committed and so is the JMS transaction.

Title: apache-camel put bulk messages into JMS

Body:
Am setting up a project where bulk commit of JMS has to be done in a single shot. Using the transaction for restarting the message processing, so need thoughts on how to push "x" number of messages onto a JMS Queue and do JMS commit.

What am currently doing is creating a JMS message which a long string appended with the message which I wish to commit in one shot.
Then use a Splitter to split the message into multiple in another route.
Finally, use another route to send the messages onto JMS (as a bulk commit).

    <route>
        <from uri="file:sample"/>
        <split streaming="true">
            <tokenize token="\n"/>
            <to uri="activemq:queue:dest"/>
        </split>
    </route>

I wish to construct a route that controls when the JMS commit is issued.

The use case is am trying to read a message from Queue A and create many messages (let that number be "x"). And push them to Queue B. However, I wish to do a bulk commit (or batch commit) like DB. Am trying to be efficient not to create connections to JMS and do individual commits.


问:
how to correctly extend form_for / ActionView::Helpers::FormBuilder?
This is similiar to Trying to extend ActionView::Helpers::FormBuilder but I don't want to use :builder => MyThing.

I want to extend form builder to add custom methods. This is the current situation:

```<code>module ActsAsTreeHelpers
  def acts_as_tree_block(method, &block)
    yield if block_given?
  end

end

ActionView::Helpers::FormBuilder.send :include, ::ActsAsTreeHelpers
</code>```

Console:

```<code>ruby-1.9.2-p180 :004 > ActionView::Helpers::FormBuilder.included_modules
=> [ActsAsTreeHelpers, ...]
</code>```

But the following gives me: undefined method acts_as_tree_block for #<ActionView::Helpers::FormBuilder:0xae114dc>

```<code><%= form_for thing do |form| %>
  <%= form.acts_as_tree_block :parent_id, {"test"} %>
<% end %>
</code>```

What am I missing here?

答:
The accepted answer no longer worked for me (Rails 5+)

Here is the changes I made to get it to work (Rails 5.2.3) :

```<code># config/initializers/custom_form_builder.rb
class ActionView::Helpers::FormBuilder
  def my_custom_text_field_with_only_letters(method, options = {})
    options[:pattern] = "^[A-Za-z]+$"
    options[:title] = "Only letters please"
    text_field(method, options)
  end

  field_helpers << :my_custom_text_field_with_only_letters
end
</code>```

field_helpers << :my_custom_text_field_with_only_letters makes sure your new method is available natively in all your application forms.

According to the doc, another possibility is to extend FormBuilder , add your custom method, and then specify in each of your wanted forms which FormBuilder to use :

```<code>class MyFormBuilder < ActionView::Helpers::FormBuilder
 def div_radio_button(method, tag_value, options = {})
...

<%= form_for @person, :builder => MyFormBuilder do |f| %>
<%= f.div_radio_button(:admin, "child") %>
</code>```

Body:
This is similiar to Trying to extend ActionView::Helpers::FormBuilder but I don't want to use :builder => MyThing.

I want to extend form builder to add custom methods. This is the current situation:

module ActsAsTreeHelpers
  def acts_as_tree_block(method, &block)
    yield if block_given?
  end

end

ActionView::Helpers::FormBuilder.send :include, ::ActsAsTreeHelpers

Console:

ruby-1.9.2-p180 :004 > ActionView::Helpers::FormBuilder.included_modules
=> [ActsAsTreeHelpers, ...]

But the following gives me: undefined method acts_as_tree_block for #<ActionView::Helpers::FormBuilder:0xae114dc>

<%= form_for thing do |form| %>
  <%= form.acts_as_tree_block :parent_id, {"test"} %>
<% end %>

What am I missing here?

Body:
The accepted answer no longer worked for me (Rails 5+)

Here is the changes I made to get it to work (Rails 5.2.3) :

# config/initializers/custom_form_builder.rb
class ActionView::Helpers::FormBuilder
  def my_custom_text_field_with_only_letters(method, options = {})
    options[:pattern] = "^[A-Za-z]+$"
    options[:title] = "Only letters please"
    text_field(method, options)
  end

  field_helpers << :my_custom_text_field_with_only_letters
end

field_helpers << :my_custom_text_field_with_only_letters makes sure your new method is available natively in all your application forms.

According to the doc, another possibility is to extend FormBuilder , add your custom method, and then specify in each of your wanted forms which FormBuilder to use :

class MyFormBuilder < ActionView::Helpers::FormBuilder
 def div_radio_button(method, tag_value, options = {})
...

<%= form_for @person, :builder => MyFormBuilder do |f| %>
<%= f.div_radio_button(:admin, "child") %>


问:
How can i use recursion properly on javascript for making license plates?
I want to know all the combinations for Costa Rica alphanumeric license plates, the format of these license plates are 3 consonants a dash and another 3 numbers (xxx-xxx)

I have already made some outputs of license plates, but I don't know if what I have done is okay

```<code>var letra = "";
var numLetra = 0;
var letras = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"];
var tempPlaca = [];
var placas = [];
var placa = "";
function getRndInteger() {
    num = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
}
function getRndLetra() {
    numLetra = Math.floor(Math.random() * (21 - 0 + 1)) + 0;
}
generatePlaca();

function generatePlaca() {
    // Genera las letras
    for (var u = 0; u < 3; u++) {
        getRndLetra();
        letra = letras[numLetra];
        tempPlaca.push(letra);
        letra = "";
    }
    tempPlaca.push("-");
    // Genera los numeros
    for (var i = 0; i < 3; i++) {
        getRndInteger();
        tempPlaca.push(num);
    }
    placa = tempPlaca.join("");
    if (findInArray(placas, placa) == false) {
        placas.push(placa);
        tempPlaca = [];
        placa = "";
        generatePlaca();
    }
}
console.log(JSON.stringify(placas));
function findInArray(ar, val) {
    for (var i = 0, len = ar.length; i < len; i++) {
        if (ar[i] === val) {
            return true;
        }
    }
    return false;
}

</code>```

My output:

```<code>["GCT-381","BYG-097","KMV-305","PRZ-046","HFC-147","LQC-268","MZL-631","NVH-843"....
</code>```

And I don't know why in some cases the license plate is not in the right format like this:

```<code>"PB-557","JT-536"
</code>```

答:
Because your letter random index is incorrect. It should only be from 0-20, since your array size is 21;

Change your getRndLetra function to this:

```<code>function getRndLetra() {
    numLetra = Math.floor(Math.random() * letras.length);
}
</code>```

Problem: when random returns 21, you get letras[21] which is undefined thats why it sometimes appears that it's missing 1 letter.

Body:
I want to know all the combinations for Costa Rica alphanumeric license plates, the format of these license plates are 3 consonants a dash and another 3 numbers (xxx-xxx)

I have already made some outputs of license plates, but I don't know if what I have done is okay

var letra = "";
var numLetra = 0;
var letras = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"];
var tempPlaca = [];
var placas = [];
var placa = "";
function getRndInteger() {
    num = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
}
function getRndLetra() {
    numLetra = Math.floor(Math.random() * (21 - 0 + 1)) + 0;
}
generatePlaca();

function generatePlaca() {
    // Genera las letras
    for (var u = 0; u < 3; u++) {
        getRndLetra();
        letra = letras[numLetra];
        tempPlaca.push(letra);
        letra = "";
    }
    tempPlaca.push("-");
    // Genera los numeros
    for (var i = 0; i < 3; i++) {
        getRndInteger();
        tempPlaca.push(num);
    }
    placa = tempPlaca.join("");
    if (findInArray(placas, placa) == false) {
        placas.push(placa);
        tempPlaca = [];
        placa = "";
        generatePlaca();
    }
}
console.log(JSON.stringify(placas));
function findInArray(ar, val) {
    for (var i = 0, len = ar.length; i < len; i++) {
        if (ar[i] === val) {
            return true;
        }
    }
    return false;
}

My output:

["GCT-381","BYG-097","KMV-305","PRZ-046","HFC-147","LQC-268","MZL-631","NVH-843"....

And I don't know why in some cases the license plate is not in the right format like this:

"PB-557","JT-536"

Body:
Because your letter random index is incorrect. It should only be from 0-20, since your array size is 21;

Change your getRndLetra function to this:

function getRndLetra() {
    numLetra = Math.floor(Math.random() * letras.length);
}

Problem: when random returns 21, you get letras[21] which is undefined thats why it sometimes appears that it's missing 1 letter.


问:
create an array from JSON in swift
I am trying to convert JSON data into an array but I do not really have any idea how to do it.

I get the data and save it in strings and I can also show it on display.

```<code>struct User_Hosting: Codable {
    let company_name: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String

    enum CodingKeys: String, CodingKey {
        case company_name = "company_name"
        case website = "website"
        case street = "street"
        case housenumber = "housenumber"
        case zip = "zip"
        case city = "city"
    }
}
</code>```

And here some other codes:

```<code>let url = URL(string: "myURL.com")

        URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "An error occurred")
                return
            }
            DispatchQueue.main.async {
                self?.dataSource = try! JSONDecoder().decode([User_Hosting].self, from: data)
            }
        }).resume()
    }
</code>```

答:
Your CodingKeys match the property names, so you can get rid of the enum at all

```<code>struct UserHosting: Codable {
    let companyName: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String
}
</code>```

Since you have a some snake case keys in JSON, you can change the JSONDecoder.keyDecodingStrategy to convertFromSnakeCase, like so

```<code>let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
</code>```

Above decoder will treat keys such as company_name to be assigned to companyName property of your struct.

Finally you can decode your JSON in a do-catch block, so in case of an error we will have a message as to what went wrong.

```<code>do {
    self.dataSource = try decoder.decode([UserHosting].self, from: data)
} catch {
    print("JSON Decoding Error \(error)")
}
</code>```

Title: create an array from JSON in swift

Body:
I am trying to convert JSON data into an array but I do not really have any idea how to do it.

I get the data and save it in strings and I can also show it on display.

struct User_Hosting: Codable {
    let company_name: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String

    enum CodingKeys: String, CodingKey {
        case company_name = "company_name"
        case website = "website"
        case street = "street"
        case housenumber = "housenumber"
        case zip = "zip"
        case city = "city"
    }
}

And here some other codes:

let url = URL(string: "myURL.com")

        URLSession.shared.dataTask(with: url!, completionHandler: { [weak self] (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "An error occurred")
                return
            }
            DispatchQueue.main.async {
                self?.dataSource = try! JSONDecoder().decode([User_Hosting].self, from: data)
            }
        }).resume()
    }

Body:
Your CodingKeys match the property names, so you can get rid of the enum at all

struct UserHosting: Codable {
    let companyName: String
    let website: String
    let street: String
    let housenumber: String
    let zip: String
    let city: String
}

Since you have a some snake case keys in JSON, you can change the JSONDecoder.keyDecodingStrategy to convertFromSnakeCase, like so

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

Above decoder will treat keys such as company_name to be assigned to companyName property of your struct.

Finally you can decode your JSON in a do-catch block, so in case of an error we will have a message as to what went wrong.

do {
    self.dataSource = try decoder.decode([UserHosting].self, from: data)
} catch {
    print("JSON Decoding Error \(error)")
}


问:
end condition of for i in range(n)
I have to work with an almost 1:1 Python translation of some existing (very old) C library and found a problem.

The original code was:

```<code>int i, n;
//...
for (i = 0; i < n; i++)
    if (someCondition(i))
        doSomething();
        break;
if (i == n)
    doSomeOtherStuff();
</code>```

It was translated to

```<code>for i in range(n):
    if someCondition(i):
        doSomething()
        break
if i == n:
    doSomeOtherStuff()
</code>```

The problem is that i is equal to n - 1 after the loop if someCondtion(i) is never true.

My solution is

```<code>found = False
for i in range(n):
    if someCondition(i):
        doSomething()
        found = True
        break
if not found:
    doSomeOtherStuff()
</code>```

Is there a better solution? I would prefer a solution with a minimal code change to still be able to compare the C and the Python implementation. The Python code is only for testing, the C implementation is the production code. So, there are no performance requirements, just readability.

答:
A Python for statement has an optional else suite, which is executed if the items are exhausted, but not if you break or otherwise exit the loop early. So you could write that code as:

```<code>for i in range(n):
    if someCondition(i):
        doSomething()
        break
else:
    doSomeOtherStuff()
</code>```

Title: end condition of for i in range(n)

Body:
I have to work with an almost 1:1 Python translation of some existing (very old) C library and found a problem.

The original code was:

int i, n;
//...
for (i = 0; i < n; i++)
    if (someCondition(i))
        doSomething();
        break;
if (i == n)
    doSomeOtherStuff();

It was translated to

for i in range(n):
    if someCondition(i):
        doSomething()
        break
if i == n:
    doSomeOtherStuff()

The problem is that i is equal to n - 1 after the loop if someCondtion(i) is never true.

My solution is

found = False
for i in range(n):
    if someCondition(i):
        doSomething()
        found = True
        break
if not found:
    doSomeOtherStuff()

Is there a better solution? I would prefer a solution with a minimal code change to still be able to compare the C and the Python implementation. The Python code is only for testing, the C implementation is the production code. So, there are no performance requirements, just readability.

Body:
A Python for statement has an optional else suite, which is executed if the items are exhausted, but not if you break or otherwise exit the loop early. So you could write that code as:

for i in range(n):
    if someCondition(i):
        doSomething()
        break
else:
    doSomeOtherStuff()


问:
how to sort array pointers of struct by name?
I'm trying to sort struct by field 'name', but It don't works :/
Can you show or explain me the problem that i didn't see?

```<code>struct clients {
int id;
char name[27];
};

int comparator(const void* p, const void* q){
return strcmp(((struct list_node*)p)->name,
              ((struct list_node*)q)->name);
}

void sort_by_name(struct list_node *node){

const int length = count_list(node);
struct list_node *arr[length];
int i=0;
while (node)
{
    arr[i]=node;
    node = node->next;
    i++;
}

printf("Before sort:\n");
for (i = 0; i < length; i++) {
    printf("Id = %d, Name = %s\n",
           arr[i]->id, arr[i]->name);
}

qsort(arr, length, sizeof(struct list_node), comparator);

printf("After sort:\n");
for (i = 0; i < length; i++) {
    printf("Id = %d, Name = %s\n",
           arr[i]->id, arr[i]->name);
}

}
</code>```

Result:

```<code> Before sort:
 Id = 11, Name = adam
 Id = 20, Name = mati
 Id = 25, Name = zenek
 Id = 28, Name = mat

Process finished with exit code -1073741819 (0xC0000005).
</code>```

I use the function in main menu - user have to decide print sorted or not sorted list

答:
Your problem is:

```<code>qsort(arr, length, sizeof(struct list_node), comparator);
</code>```

You tell qsort the array has list nodes, but the array has only pointers to list nodes, so:

```<code>qsort(arr, length, sizeof(struct list_node *), comparator);
</code>```

Body:
I'm trying to sort struct by field 'name', but It don't works :/
Can you show or explain me the problem that i didn't see?

struct clients {
int id;
char name[27];
};

int comparator(const void* p, const void* q){
return strcmp(((struct list_node*)p)->name,
              ((struct list_node*)q)->name);
}

void sort_by_name(struct list_node *node){

const int length = count_list(node);
struct list_node *arr[length];
int i=0;
while (node)
{
    arr[i]=node;
    node = node->next;
    i++;
}

printf("Before sort:\n");
for (i = 0; i < length; i++) {
    printf("Id = %d, Name = %s\n",
           arr[i]->id, arr[i]->name);
}

qsort(arr, length, sizeof(struct list_node), comparator);

printf("After sort:\n");
for (i = 0; i < length; i++) {
    printf("Id = %d, Name = %s\n",
           arr[i]->id, arr[i]->name);
}

}

Result:

 Before sort:
 Id = 11, Name = adam
 Id = 20, Name = mati
 Id = 25, Name = zenek
 Id = 28, Name = mat

Process finished with exit code -1073741819 (0xC0000005).

I use the function in main menu - user have to decide print sorted or not sorted list

Body:
Your problem is:

qsort(arr, length, sizeof(struct list_node), comparator);

You tell qsort the array has list nodes, but the array has only pointers to list nodes, so:

qsort(arr, length, sizeof(struct list_node *), comparator);


问:
use qt table with buttons
I have a table with some data. However since not all the information fits into the table, the user should have the option to get further information on the line by pressing a button in this line. I currently add the buttons in the following way:

int lastRow = table->rowCount();
table->insertRow(lastRow);

QWidget* pWidget = new QWidget();
pWidget->setFixedWidth(30);
LdtButton* btn_help = new LdtButton();
btn_help->addInactiveIcon(QPixmap(":/icons/help_inactive.png"));
btn_help->addHoverIcon(QPixmap(":/icons/help_hovered.png"));
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(btn_help);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
table->setCellWidget(lastRow, 1, pWidget);
```

However I do not really have a idea how to connect these buttons, so I get the row the button was in when it gets pressed, so I can output the appropriate informations. (not every row has a button)

答:
Use the signal QPushButton::clicked and a lambda to call the right method (use the capture to pass the row).

```<code>QTableWidget* table = new QTableWidget(0, 2);
QStringList values = {"foo", "bar", "spam"};
for (QString const& value : values)
{
    int lastRow = table->rowCount();
    table->insertRow(lastRow);
    table->setItem(lastRow, 0, new QTableWidgetItem(value));
    QWidget* pWidget = new QWidget();
    QPushButton* btn_help = new QPushButton("help");
    QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
    pLayout->addWidget(btn_help);
    pLayout->setAlignment(Qt::AlignCenter);
    pLayout->setContentsMargins(0, 0, 0, 0);
    pWidget->setLayout(pLayout);
    table->setCellWidget(lastRow, 1, pWidget);

    // Call your method in the lambda
    QObject::connect(btn_help, &QPushButton::clicked, [lastRow]() {qDebug() << "Show help for " << lastRow; });

}
table->show();
</code>```

It will display:

```<code>Show help for  0
Show help for  1
Show help for  2
</code>```

Title: use qt table with buttons

Body:
I have a table with some data. However since not all the information fits into the table, the user should have the option to get further information on the line by pressing a button in this line. I currently add the buttons in the following way:

int lastRow = table->rowCount();
table->insertRow(lastRow);

QWidget* pWidget = new QWidget();
pWidget->setFixedWidth(30);
LdtButton* btn_help = new LdtButton();
btn_help->addInactiveIcon(QPixmap(":/icons/help_inactive.png"));
btn_help->addHoverIcon(QPixmap(":/icons/help_hovered.png"));
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(btn_help);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
table->setCellWidget(lastRow, 1, pWidget);

However I do not really have a idea how to connect these buttons, so I get the row the button was in when it gets pressed, so I can output the appropriate informations. (not every row has a button)

Body:
Use the signal QPushButton::clicked and a lambda to call the right method (use the capture to pass the row).

QTableWidget* table = new QTableWidget(0, 2);
QStringList values = {"foo", "bar", "spam"};
for (QString const& value : values)
{
    int lastRow = table->rowCount();
    table->insertRow(lastRow);
    table->setItem(lastRow, 0, new QTableWidgetItem(value));
    QWidget* pWidget = new QWidget();
    QPushButton* btn_help = new QPushButton("help");
    QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
    pLayout->addWidget(btn_help);
    pLayout->setAlignment(Qt::AlignCenter);
    pLayout->setContentsMargins(0, 0, 0, 0);
    pWidget->setLayout(pLayout);
    table->setCellWidget(lastRow, 1, pWidget);

    // Call your method in the lambda
    QObject::connect(btn_help, &QPushButton::clicked, [lastRow]() {qDebug() << "Show help for " << lastRow; });

}
table->show();

It will display:

Show help for  0
Show help for  1
Show help for  2


问:
How to fix ERR_EMPTY_RESPONSE on Chrome? (PHP cURL)
I have problem only on Chrome. On Firefox working very well.

```<code>define('USER_AGENT', 'Mozilla/5.0 (Windows NT 5.1)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36');
$curl = curl_init(); // CURL BAŞLATTIK
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
//curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_REFERER, 'https://www.google.com');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
$veri = curl_exec($curl);
</code>```

... continue ...

```<code>foreach($data as $dataa){
    echo $dataa;
}
</code>```

This problem have only on Chrome: "ERR_EMPTY_RESPONSE".

This codes working on Firefox very well.

How can I fix this problem?

答:
I fixed. I am using VPN on my browser. The connection over time of VPN is 30 seconds. Thats why when I using this page, after 30 seconds page said me: "ERR_EMPTY_RESPONSE".

First Way: Close VPN on your browser and computer.
Second Way: Increase execution time on your server with php.ini.

Body:
I have problem only on Chrome. On Firefox working very well.

define('USER_AGENT', 'Mozilla/5.0 (Windows NT 5.1)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36');
$curl = curl_init(); // CURL BAŞLATTIK
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CURLOPT_COOKIEJAR, "cookies.txt");
//curl_setopt($curl, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_REFERER, 'https://www.google.com');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
$veri = curl_exec($curl);

... continue ...

foreach($data as $dataa){
    echo $dataa;
}

This problem have only on Chrome: "ERR_EMPTY_RESPONSE".

This codes working on Firefox very well.

How can I fix this problem?


问:
Class method decorator with self arguments?
How do I pass a class field to a decorator on a class method as an argument?  What I want to do is something like:

```<code>class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()
</code>```

It complains that self does not exist for passing self.url to the decorator.  Is there a way around this?

答:
Another option would be to abandon the syntactic sugar and decorate in the __init__ of the class.

```<code>def countdown(number):
    def countdown_decorator(func):
        def func_wrapper():
            for index in reversed(range(1, number+1)):
                print(index)
            func()
        return func_wrapper
    return countdown_decorator

class MySuperClass():
    def __init__(self, number):
        self.number = number
        self.do_thing = countdown(number)(self.do_thing)

    def do_thing(self):
        print('im doing stuff!')

myclass = MySuperClass(3)

myclass.do_thing()
</code>```

which would print

```<code>3
2
1
im doing stuff!
</code>```

Body:
How do I pass a class field to a decorator on a class method as an argument?  What I want to do is something like:

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()

It complains that self does not exist for passing self.url to the decorator.  Is there a way around this?

Body:
Another option would be to abandon the syntactic sugar and decorate in the __init__ of the class.

def countdown(number):
    def countdown_decorator(func):
        def func_wrapper():
            for index in reversed(range(1, number+1)):
                print(index)
            func()
        return func_wrapper
    return countdown_decorator

class MySuperClass():
    def __init__(self, number):
        self.number = number
        self.do_thing = countdown(number)(self.do_thing)

    def do_thing(self):
        print('im doing stuff!')

myclass = MySuperClass(3)

myclass.do_thing()

which would print

3
2
1
im doing stuff!


问:
SQL issue - how do I select all tuples which contain all references in a second table?
Heres the deal - I have three tables here:

```<code>Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID
</code>```

Using a nested query I can retrieve all companies that are tagged by tags in a certain set i.e:

```<code>select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))
</code>```

The above query returns all companies that have an either tag id 12, 43 or 67 but I need to retrieve all companies who are tagged 12 AND 43 AND 67

How would I redo my query here? I'm using MySQL

答:
Not too efficient but works:

```<code>select c.*
from companies c
where c.id in (select t.company_id from tags_companies t where t.tagid = 12)
and c.id in (select t.company_id from tags_companies t where t.tagid = 43)
and c.id in (select t.company_id from tags_companies t where t.tagid = 67)
</code>```

Another possibility using a HAVING clause:

```<code>select c.id, c.name, c.details
from companies c join tags_companies t on c.id = t.company_id
where t.tagid in (12, 43, 67)
group by c.id, c.name, c.details
having count(distinct t.tagid) = 3
</code>```

Body:
Heres the deal - I have three tables here:

Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID

Using a nested query I can retrieve all companies that are tagged by tags in a certain set i.e:

select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))

The above query returns all companies that have an either tag id 12, 43 or 67 but I need to retrieve all companies who are tagged 12 AND 43 AND 67

How would I redo my query here? I'm using MySQL

Body:
Not too efficient but works:

select c.*
from companies c
where c.id in (select t.company_id from tags_companies t where t.tagid = 12)
and c.id in (select t.company_id from tags_companies t where t.tagid = 43)
and c.id in (select t.company_id from tags_companies t where t.tagid = 67)

Another possibility using a HAVING clause:

select c.id, c.name, c.details
from companies c join tags_companies t on c.id = t.company_id
where t.tagid in (12, 43, 67)
group by c.id, c.name, c.details
having count(distinct t.tagid) = 3


答:
Use more pythonic idioms, like for..else:

```<code>for i in range(n):
    if some_condition(i):
        do_something()
        break
else:
    do_something_else()
</code>```

The else is executed if the loop is not broken.

Or, even better:

```<code>if any(map(some_condition, range(n))):
    do_something()
else:
    do_something_else()
</code>```

See: any, map

Title: end condition of for i in range(n)

Body:
Use more pythonic idioms, like for..else:

for i in range(n):
    if some_condition(i):
        do_something()
        break
else:
    do_something_else()

The else is executed if the loop is not broken.

Or, even better:

if any(map(some_condition, range(n))):
    do_something()
else:
    do_something_else()

See: any, map


问:
How to fix UnsatisfiedDependencyException in spring boot with mongodb application?
I'm trying to change my spring boot application DB from H2 to MongoDB.
I have updated the application.properties file
and removed any "@Entity" and "@Column"
and added "@Document" instead.
The error I'm getting is:

Description:

Parameter 0 of constructor in smartspace.dao.rdb.RdbActionDao required a bean named 'mongoTemplate' that could not be found.

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

The full Console log:

```<code>2019-05-13 12:48:55.477  INFO 15596 --- [           main] smartspace.Application                   : Starting Application on LAPTOP-E00E1JFN with PID 15596 (D:\git\2019b.giron.aptik.smartspace\bin started by Lael in D:\git\2019b.giron.aptik.smartspace)
2019-05-13 12:48:55.480  INFO 15596 --- [           main] smartspace.Application                   : The following profiles are active: production,default
2019-05-13 12:48:56.313  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-05-13 12:48:56.316  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-13 12:48:56.354  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.ActionCrud.
2019-05-13 12:48:56.356  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.ElementCrud.
2019-05-13 12:48:56.475  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.UserCrud.
2019-05-13 12:48:56.503  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 180ms. Found 1 repository interfaces.
2019-05-13 12:48:56.517  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-05-13 12:48:56.518  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-13 12:48:56.533  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data MongoDB - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.GenericIdGeneratorCrud.
2019-05-13 12:48:56.542  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23ms. Found 3 repository interfaces.
2019-05-13 12:48:56.947  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2019-05-13 12:48:56.952  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2019-05-13 12:48:56.956  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2019-05-13 12:48:57.078  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$14f03da7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.093  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$94708ad9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.104  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type [org.springframework.integration.config.IntegrationManagementConfiguration$$EnhancerBySpringCGLIB$$7fe1f8d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.117  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.721  INFO 15596 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8089 (http)
2019-05-13 12:48:57.746  INFO 15596 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-13 12:48:57.746  INFO 15596 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-05-13 12:48:57.757  INFO 15596 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\integrationcourse\jdk8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Lael\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Python27\python.exe;;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\;C:\Users\Lael\AppData\Local\Microsoft\WindowsApps;C:\Users\Lael\AppData\Roaming\npm;C:\Program Files\MongoDB\Server\4.0\bin;;C:\Program Files\JetBrains\WebStorm 2018.3.1\bin;;C:\Program Files\heroku\bin;.]
2019-05-13 12:48:57.855  INFO 15596 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-13 12:48:57.856  INFO 15596 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2335 ms
2019-05-13 12:48:58.157  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-13 12:48:58.265  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-13 12:48:58.332  INFO 15596 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-05-13 12:48:58.388  INFO 15596 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-05-13 12:48:58.389  INFO 15596 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-05-13 12:48:58.506  INFO 15596 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-05-13 12:48:58.645  INFO 15596 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:

    drop table generic_id_generator if exists
Hibernate:

    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:

    create table generic_id_generator (
       id bigint not null,
        primary key (id)
    )
2019-05-13 12:48:59.321  INFO 15596 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@1d6713dd'
2019-05-13 12:48:59.323  INFO 15596 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-05-13 12:48:59.356  WARN 15596 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rdbActionDao' defined in file [D:\git\2019b.giron.aptik.smartspace\bin\smartspace\dao\rdb\RdbActionDao.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'actionCrud': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
2019-05-13 12:48:59.356  INFO 15596 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-05-13 12:48:59.356  INFO 15596 --- [           main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
Hibernate:

    drop table generic_id_generator if exists
Hibernate:

    drop sequence if exists hibernate_sequence
2019-05-13 12:48:59.363  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-05-13 12:48:59.365  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2019-05-13 12:48:59.368  INFO 15596 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-13 12:48:59.378  INFO 15596 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-13 12:48:59.422 ERROR 15596 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in smartspace.dao.rdb.RdbActionDao required a bean named 'mongoTemplate' that could not be found.

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

</code>```

This is my smartspace.dao.rdb.RdbActionDao:

```<code>package smartspace.dao.rdb;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import smartspace.dao.EnhancedActionDao;
import smartspace.data.ActionEntity;

@Repository
public class RdbActionDao implements EnhancedActionDao{
    private ActionCrud actionCrud;
    private GenericIdGeneratorCrud genericIdGeneratorCrud;
    @Value("${smartspace.name}")
    private String ourSmartspaceName;
    @Autowired
    public RdbActionDao(
            ActionCrud actionCrud,
            GenericIdGeneratorCrud genericIdGeneratorCrud) {
        super();
        this.actionCrud = actionCrud;
        this.genericIdGeneratorCrud = genericIdGeneratorCrud;
    }

    @Override
    @Transactional
    public ActionEntity create(ActionEntity actionEntity) {
        // SQL: INSERT INTO ACTION (ID, NAME) VALUES (?,?);

        GenericIdGenerator nextId =
            this.genericIdGeneratorCrud.save(new GenericIdGenerator());
        if(actionEntity.getActionSmartspace() == null) {
            actionEntity.setKey(Long.toString(nextId.getId()) +"#"+ ourSmartspaceName);
            this.genericIdGeneratorCrud.delete(nextId);
        }
        if (!this.actionCrud.existsById(actionEntity.getKey())) {
            ActionEntity rv = this.actionCrud.save(actionEntity);
            return rv;
        }else {
            throw new RuntimeException("Action already exists with key: " + actionEntity.getKey());
        }
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readAll() {
        List<ActionEntity> rv = new ArrayList<>();
        // SQL: SELECT
        this.actionCrud.findAll()
            .forEach(rv::add);

        return rv;
    }

    @Override
    @Transactional
    public void deleteAll() {
        // SQL: DELETE
        this.actionCrud.deleteAll();
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readAll(int size, int page) {
        return this.actionCrud
            .findAll(PageRequest.of(page, size))
            .getContent();
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readActionWithElementIdContaining(
            String elementId,
            int size,
            int page) {

        return this.actionCrud
                .findAllByElementId(
                        elementId,
                        PageRequest.of(page, size));
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readActionAvaiable(
            Date fromDate,
            Date toDate,
            int size, int page) {
        return this.actionCrud
                .findAllByCreationTimestampBetween(
                        fromDate, toDate,
                        PageRequest.of(page, size));
    }

    @Override
    public List<ActionEntity> readAll(String sortBy, int size, int page) {
        return this.actionCrud
            .findAll(PageRequest.of(
                    page, size,
                    Direction.ASC, sortBy))
            .getContent();
    }

    @Override
    @Transactional(readOnly=true)
    public Optional<ActionEntity> readById(String actionKey) {
        return this.actionCrud.findById(actionKey);
    }
}

</code>```

This is my EnhancedActionDao:

```<code>package smartspace.dao;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import smartspace.data.ActionEntity;

public interface EnhancedActionDao extends ActionDao{
    public List<ActionEntity> readAll(int size, int page);
    public List<ActionEntity> readAll(String sortBy, int size, int page);
    public List<ActionEntity> readActionWithElementIdContaining (String text, int size, int page);
    public List<ActionEntity> readActionAvaiable (
            Date fromDate, Date toDate,
            int size, int page);
    Optional<ActionEntity> readById(String actionKey);

}

</code>```

This is my ActionDao:

```<code>package smartspace.dao;

import smartspace.data.ActionEntity;

public interface ActionDao {

    public ActionEntity create(ActionEntity actionEntity);
    public java.util.List<ActionEntity> readAll();
    public void deleteAll();
}

</code>```

This is my Application.java:

```<code>package smartspace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
}

</code>```

And this is my application.properties:

```<code>smartspace.name =2019B.giron.aptik.smartspace

name.for.user.generator=World

spring.profiles.active=production,default

spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

server.port = 8089

spring.data.mongodb.uri=mongodb://laelav:laelav1@integrationcourse-shard-00-00-7bsmm.mongodb.net:27017,integrationcourse-shard-00-01-7bsmm.mongodb.net:27017,integrationcourse-shard-00-02-7bsmm.mongodb.net:27017/test?ssl=true&replicaSet=integrationcourse-shard-0&authSource=admin&retryWrites=true
spring.data.mongodb.host=integrationcourse-shard-00-01-7bsmm.mongodb.net
spring.data.mongodb.repositories.enabled=true
spring.data.mongodb.port=27017
spring.data.mongodb.database=course
spring.data.mongodb.username=laelav
spring.data.mongodb.password=laelav1

</code>```

Thanks for the help in advance!

```<code>EDIT:
After adding the MongoTemplate Bean I have a new error:

>Description:

>The dependencies of some of the beans in the application context form a cycle:

>???????
>|  rdbActionDao defined in file [D:\git\2019b.giron.aptik.smartspace\bin\smartspace\dao\rdb\RdbActionDao.class]
>?     ?
>|  actionCrud
>???????
</code>```

答: The problem was fixed by importing the right libraries and using ID annotation by spring.data.... and not from javax. one.</p>

Body:
I'm trying to change my spring boot application DB from H2 to MongoDB.
I have updated the application.properties file
and removed any "@Entity" and "@Column"
and added "@Document" instead.
The error I'm getting is:

Description:

Parameter 0 of constructor in smartspace.dao.rdb.RdbActionDao required a bean named 'mongoTemplate' that could not be found.

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

The full Console log:

2019-05-13 12:48:55.477  INFO 15596 --- [           main] smartspace.Application                   : Starting Application on LAPTOP-E00E1JFN with PID 15596 (D:\git\2019b.giron.aptik.smartspace\bin started by Lael in D:\git\2019b.giron.aptik.smartspace)
2019-05-13 12:48:55.480  INFO 15596 --- [           main] smartspace.Application                   : The following profiles are active: production,default
2019-05-13 12:48:56.313  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-05-13 12:48:56.316  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-13 12:48:56.354  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.ActionCrud.
2019-05-13 12:48:56.356  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.ElementCrud.
2019-05-13 12:48:56.475  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.UserCrud.
2019-05-13 12:48:56.503  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 180ms. Found 1 repository interfaces.
2019-05-13 12:48:56.517  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-05-13 12:48:56.518  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-13 12:48:56.533  INFO 15596 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data MongoDB - Could not safely identify store assignment for repository candidate interface smartspace.dao.rdb.GenericIdGeneratorCrud.
2019-05-13 12:48:56.542  INFO 15596 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23ms. Found 3 repository interfaces.
2019-05-13 12:48:56.947  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2019-05-13 12:48:56.952  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2019-05-13 12:48:56.956  INFO 15596 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2019-05-13 12:48:57.078  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$14f03da7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.093  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$94708ad9] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.104  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type [org.springframework.integration.config.IntegrationManagementConfiguration$$EnhancerBySpringCGLIB$$7fe1f8d6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.117  INFO 15596 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 12:48:57.721  INFO 15596 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8089 (http)
2019-05-13 12:48:57.746  INFO 15596 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-13 12:48:57.746  INFO 15596 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-05-13 12:48:57.757  INFO 15596 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\integrationcourse\jdk8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\WINDOWS\System32\OpenSSH\;C:\Users\Lael\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Python27\python.exe;;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\;C:\Users\Lael\AppData\Local\Microsoft\WindowsApps;C:\Users\Lael\AppData\Roaming\npm;C:\Program Files\MongoDB\Server\4.0\bin;;C:\Program Files\JetBrains\WebStorm 2018.3.1\bin;;C:\Program Files\heroku\bin;.]
2019-05-13 12:48:57.855  INFO 15596 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-13 12:48:57.856  INFO 15596 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2335 ms
2019-05-13 12:48:58.157  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-13 12:48:58.265  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-13 12:48:58.332  INFO 15596 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-05-13 12:48:58.388  INFO 15596 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-05-13 12:48:58.389  INFO 15596 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-05-13 12:48:58.506  INFO 15596 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-05-13 12:48:58.645  INFO 15596 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:

    drop table generic_id_generator if exists
Hibernate:

    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate:

    create table generic_id_generator (
       id bigint not null,
        primary key (id)
    )
2019-05-13 12:48:59.321  INFO 15596 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@1d6713dd'
2019-05-13 12:48:59.323  INFO 15596 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-05-13 12:48:59.356  WARN 15596 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rdbActionDao' defined in file [D:\git\2019b.giron.aptik.smartspace\bin\smartspace\dao\rdb\RdbActionDao.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'actionCrud': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
2019-05-13 12:48:59.356  INFO 15596 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-05-13 12:48:59.356  INFO 15596 --- [           main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
Hibernate:

    drop table generic_id_generator if exists
Hibernate:

    drop sequence if exists hibernate_sequence
2019-05-13 12:48:59.363  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-05-13 12:48:59.365  INFO 15596 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2019-05-13 12:48:59.368  INFO 15596 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-13 12:48:59.378  INFO 15596 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-13 12:48:59.422 ERROR 15596 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in smartspace.dao.rdb.RdbActionDao required a bean named 'mongoTemplate' that could not be found.

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

This is my smartspace.dao.rdb.RdbActionDao:

package smartspace.dao.rdb;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import smartspace.dao.EnhancedActionDao;
import smartspace.data.ActionEntity;

@Repository
public class RdbActionDao implements EnhancedActionDao{
    private ActionCrud actionCrud;
    private GenericIdGeneratorCrud genericIdGeneratorCrud;
    @Value("${smartspace.name}")
    private String ourSmartspaceName;
    @Autowired
    public RdbActionDao(
            ActionCrud actionCrud,
            GenericIdGeneratorCrud genericIdGeneratorCrud) {
        super();
        this.actionCrud = actionCrud;
        this.genericIdGeneratorCrud = genericIdGeneratorCrud;
    }

    @Override
    @Transactional
    public ActionEntity create(ActionEntity actionEntity) {
        // SQL: INSERT INTO ACTION (ID, NAME) VALUES (?,?);

        GenericIdGenerator nextId =
            this.genericIdGeneratorCrud.save(new GenericIdGenerator());
        if(actionEntity.getActionSmartspace() == null) {
            actionEntity.setKey(Long.toString(nextId.getId()) +"#"+ ourSmartspaceName);
            this.genericIdGeneratorCrud.delete(nextId);
        }
        if (!this.actionCrud.existsById(actionEntity.getKey())) {
            ActionEntity rv = this.actionCrud.save(actionEntity);
            return rv;
        }else {
            throw new RuntimeException("Action already exists with key: " + actionEntity.getKey());
        }
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readAll() {
        List<ActionEntity> rv = new ArrayList<>();
        // SQL: SELECT
        this.actionCrud.findAll()
            .forEach(rv::add);

        return rv;
    }

    @Override
    @Transactional
    public void deleteAll() {
        // SQL: DELETE
        this.actionCrud.deleteAll();
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readAll(int size, int page) {
        return this.actionCrud
            .findAll(PageRequest.of(page, size))
            .getContent();
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readActionWithElementIdContaining(
            String elementId,
            int size,
            int page) {

        return this.actionCrud
                .findAllByElementId(
                        elementId,
                        PageRequest.of(page, size));
    }

    @Override
    @Transactional(readOnly=true)
    public List<ActionEntity> readActionAvaiable(
            Date fromDate,
            Date toDate,
            int size, int page) {
        return this.actionCrud
                .findAllByCreationTimestampBetween(
                        fromDate, toDate,
                        PageRequest.of(page, size));
    }

    @Override
    public List<ActionEntity> readAll(String sortBy, int size, int page) {
        return this.actionCrud
            .findAll(PageRequest.of(
                    page, size,
                    Direction.ASC, sortBy))
            .getContent();
    }

    @Override
    @Transactional(readOnly=true)
    public Optional<ActionEntity> readById(String actionKey) {
        return this.actionCrud.findById(actionKey);
    }
}

This is my EnhancedActionDao:

package smartspace.dao;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import smartspace.data.ActionEntity;

public interface EnhancedActionDao extends ActionDao{
    public List<ActionEntity> readAll(int size, int page);
    public List<ActionEntity> readAll(String sortBy, int size, int page);
    public List<ActionEntity> readActionWithElementIdContaining (String text, int size, int page);
    public List<ActionEntity> readActionAvaiable (
            Date fromDate, Date toDate,
            int size, int page);
    Optional<ActionEntity> readById(String actionKey);

}

This is my ActionDao:

package smartspace.dao;

import smartspace.data.ActionEntity;

public interface ActionDao {

    public ActionEntity create(ActionEntity actionEntity);
    public java.util.List<ActionEntity> readAll();
    public void deleteAll();
}

This is my Application.java:

package smartspace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

    }
}

And this is my application.properties:

smartspace.name =2019B.giron.aptik.smartspace

name.for.user.generator=World

spring.profiles.active=production,default

spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

server.port = 8089

spring.data.mongodb.uri=mongodb://laelav:laelav1@integrationcourse-shard-00-00-7bsmm.mongodb.net:27017,integrationcourse-shard-00-01-7bsmm.mongodb.net:27017,integrationcourse-shard-00-02-7bsmm.mongodb.net:27017/test?ssl=true&replicaSet=integrationcourse-shard-0&authSource=admin&retryWrites=true
spring.data.mongodb.host=integrationcourse-shard-00-01-7bsmm.mongodb.net
spring.data.mongodb.repositories.enabled=true
spring.data.mongodb.port=27017
spring.data.mongodb.database=course
spring.data.mongodb.username=laelav
spring.data.mongodb.password=laelav1

Thanks for the help in advance!

EDIT:
After adding the MongoTemplate Bean I have a new error:

>Description:

>The dependencies of some of the beans in the application context form a cycle:

>???????
>|  rdbActionDao defined in file [D:\git\2019b.giron.aptik.smartspace\bin\smartspace\dao\rdb\RdbActionDao.class]
>?     ?
>|  actionCrud
>???????


问:
Aspx content page, unable to execute send email code
I'm using an asp content page that uses site master file. I'm particularly confused about the runat=server with the labels and getting the vb.net to execute. I tried this but its not working:

```<code><div class="card-body">
    <asp:Label ID="Label1" runat="server" />
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name" required>
    </div>
    <div class="form-group" runat="server">
        <asp:Label for="email" runat="server" Text="Email address"></asp:Label>
        <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" required>
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
        <label for="message">Message</label>
        <textarea class="form-control" id="message" rows="6" required></textarea>
    </div>
    <div class="mx-auto">
        <asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit"></asp:Button>
    </div>
</code>```

I tried putting the html code in a form but errors saying cannot have nested form, so confused as to how to send the html to the vb.net code

VB.NET code:

```<code>Protected Sub Btn_SendMessage_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim Email As String = FindControl("email").ToString
    Dim Name As String = FindControl("name").ToString
    Dim Message As String = FindControl("message").ToString
    Dim Mail As New MailMessage
    Dim SMTP As New SmtpClient("smtp.gmail.com")

    Mail.Subject = Name
    Mail.From = New MailAddress(Email)
    SMTP.Credentials = New System.Net.NetworkCredential("xxxx@gmail.com", "xxxxxxxx") '<-- Password Here

    Mail.To.Add("xxxxxxx@gmail.com")

    Mail.Body = Message

    SMTP.EnableSsl = True
    SMTP.Port = "587"

    Try
        SMTP.Send(Mail)
        Label1.Text = "Message sent"
    Catch ex As Exception
        Label1.Text = ex.ToString
    End Try
End Sub
</code>```

The page refreshes and nothing happens, I don't even think the VB.NET executes.

答:
Here's a working sample based on your code:

ASPX

```<code><%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div class="card-body">
            <asp:Label ID="Label1" runat="server" />
            <div class="form-group">
                <label for="name">Name</label>
                <asp:Label ID="Label4" runat="server" AssociatedControlID="TextBoxName" Text="Name"></asp:Label>
                <asp:TextBox ID="TextBoxName" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ErrorMessage="*" ControlToValidate="TextBoxName"></asp:RequiredFieldValidator>
            </div>
            <div class="form-group" runat="server">
                <asp:Label ID="Label3" runat="server" AssociatedControlID="TextBoxEmail" Text="Email address"></asp:Label>
                <asp:TextBox ID="TextBoxEmail" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" runat="server" ErrorMessage="*" ControlToValidate="TextBoxEmail"></asp:RequiredFieldValidator>
                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
            </div>
            <div class="form-group">
                <asp:Label ID="Label2" runat="server" AssociatedControlID="TextBoxMessage" Text="Message"></asp:Label>
                <asp:TextBox ID="TextBoxMessage" runat="server" TextMode="MultiLine" CssClass="form-control" Rows="6"></asp:TextBox>
            </div>
            <div class="mx-auto">
                <asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit" OnClick="Btn_SendMessage_Click"></asp:Button>
            </div>
        </div>
    </form>
</body>
</html>
</code>```

Code behind

```<code>Protected Sub Btn_SendMessage_Click(sender As Object, e As EventArgs) Handles Btn_SendMessage.Click
    Dim Mail As New MailMessage
    Dim SMTP As New SmtpClient("smtp.gmail.com")

    Mail.Subject = TextBoxName.Text
    Mail.From = New MailAddress(TextBoxEmail.Text)
    SMTP.Credentials = New System.Net.NetworkCredential("xxxx@gmail.com", "xxxxxxxx") '<-- Password Here

    Mail.To.Add("xxxxxxx@gmail.com")

    Mail.Body = TextBoxMessage.Text

    SMTP.EnableSsl = True
    SMTP.Port = "587"

    Try
        SMTP.Send(Mail)
        Label1.Text = "Message sent"
    Catch ex As Exception
        Label1.Text = ex.ToString
    End Try
End Sub
</code>```

Tags with the runat="server" attribute are ASP.NET server side controls which render as their HTML counterparts in the resulting web page sent to the browser. During the server side processing of the page you can access them in your code directly using their IDs.

Please note that I've used server side validation controls for the required fields. You may need to add the following setting in the Web.config file in case you receive a runtime error about Unobtrusive Validation:

```<code><appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</code>```

Hope it helps. I am using Visual Studio 2017 and the target framework is .NET 4.6.1.

Body:
I'm using an asp content page that uses site master file. I'm particularly confused about the runat=server with the labels and getting the vb.net to execute. I tried this but its not working:

    <asp:Label ID="Label1" runat="server" />

        Name
        <input type="text" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name" required>

        <asp:Label for="email" runat="server" Text="Email address"></asp:Label>
        <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" required>
        We'll never share your email with anyone else.

        Message
        <textarea class="form-control" id="message" rows="6" required></textarea>

        <asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit"></asp:Button>

I tried putting the html code in a form but errors saying cannot have nested form, so confused as to how to send the html to the vb.net code

VB.NET code:

Protected Sub Btn_SendMessage_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim Email As String = FindControl("email").ToString
    Dim Name As String = FindControl("name").ToString
    Dim Message As String = FindControl("message").ToString
    Dim Mail As New MailMessage
    Dim SMTP As New SmtpClient("smtp.gmail.com")

    Mail.Subject = Name
    Mail.From = New MailAddress(Email)
    SMTP.Credentials = New System.Net.NetworkCredential("xxxx@gmail.com", "xxxxxxxx") '<-- Password Here

    Mail.To.Add("xxxxxxx@gmail.com")

    Mail.Body = Message

    SMTP.EnableSsl = True
    SMTP.Port = "587"

    Try
        SMTP.Send(Mail)
        Label1.Text = "Message sent"
    Catch ex As Exception
        Label1.Text = ex.ToString
    End Try
End Sub

The page refreshes and nothing happens, I don't even think the VB.NET executes.

Body:
Here's a working sample based on your code:

ASPX

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div class="card-body">
            <asp:Label ID="Label1" runat="server" />
            <div class="form-group">
                <label for="name">Name</label>
                <asp:Label ID="Label4" runat="server" AssociatedControlID="TextBoxName" Text="Name"></asp:Label>
                <asp:TextBox ID="TextBoxName" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ErrorMessage="*" ControlToValidate="TextBoxName"></asp:RequiredFieldValidator>
            </div>
            <div class="form-group" runat="server">
                <asp:Label ID="Label3" runat="server" AssociatedControlID="TextBoxEmail" Text="Email address"></asp:Label>
                <asp:TextBox ID="TextBoxEmail" runat="server" CssClass="form-control" placeholder="Enter name"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" runat="server" ErrorMessage="*" ControlToValidate="TextBoxEmail"></asp:RequiredFieldValidator>
                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
            </div>
            <div class="form-group">
                <asp:Label ID="Label2" runat="server" AssociatedControlID="TextBoxMessage" Text="Message"></asp:Label>
                <asp:TextBox ID="TextBoxMessage" runat="server" TextMode="MultiLine" CssClass="form-control" Rows="6"></asp:TextBox>
            </div>
            <div class="mx-auto">
                <asp:Button type="submit" class="btn btn-primary text-right" ID="Btn_SendMessage" runat="server" Text="Submit" OnClick="Btn_SendMessage_Click"></asp:Button>
            </div>
        </div>
    </form>
</body>
</html>

Code behind

Protected Sub Btn_SendMessage_Click(sender As Object, e As EventArgs) Handles Btn_SendMessage.Click
    Dim Mail As New MailMessage
    Dim SMTP As New SmtpClient("smtp.gmail.com")

    Mail.Subject = TextBoxName.Text
    Mail.From = New MailAddress(TextBoxEmail.Text)
    SMTP.Credentials = New System.Net.NetworkCredential("xxxx@gmail.com", "xxxxxxxx") '<-- Password Here

    Mail.To.Add("xxxxxxx@gmail.com")

    Mail.Body = TextBoxMessage.Text

    SMTP.EnableSsl = True
    SMTP.Port = "587"

    Try
        SMTP.Send(Mail)
        Label1.Text = "Message sent"
    Catch ex As Exception
        Label1.Text = ex.ToString
    End Try
End Sub

Tags with the runat="server" attribute are ASP.NET server side controls which render as their HTML counterparts in the resulting web page sent to the browser. During the server side processing of the page you can access them in your code directly using their IDs.

Please note that I've used server side validation controls for the required fields. You may need to add the following setting in the Web.config file in case you receive a runtime error about Unobtrusive Validation:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Hope it helps. I am using Visual Studio 2017 and the target framework is .NET 4.6.1.


问:
How to scale an image inside a container
Hey guys I have been running into this problem where I create a container box but the image I put inside is either being stretch or some parts of the image is not showing up

I've tried to make the box bigger at that works to some extent but it is still cutting off parts of the image. I have also tried object-fit but it doesn't seem to work

<!DOCTYPE html>

    <title>Example-1</title>
    <link rel="stylesheet" href="Example.css" type="text/css">

```

<pre class="lang-css prettyprint-override"><code>.img-box {
  width: 1200px;
  height: 600px;
  padding: 20px;
  margin: 100px auto;
  box-shadow: 0px 0px 10px grey;
  background: url(about.jpg);
  background-size: cover;
  background-repeat: no-repeat;
}
</code>```

I expected the image to scale when I used object-fit but it doesn't seem to be the case. Any ideas?

答:
use width:100% to prevent the stretched images, and below code may you on second case. </p>

```<code>.img-box {
  width: 100%;
  height: 600px;
  padding: 20px;
  margin: 100px auto;
  box-shadow: 0px 0px 10px grey;
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Flag_of_Pakistan.svg/800px-Flag_of_Pakistan.svg.png);
  background-size: cover;
  background-repeat: no-repeat;
}
.text{
  height:100%
}
</code>```

Body:
Hey guys I have been running into this problem where I create a container box but the image I put inside is either being stretch or some parts of the image is not showing up

I've tried to make the box bigger at that works to some extent but it is still cutting off parts of the image. I have also tried object-fit but it doesn't seem to work

<!DOCTYPE html>

    <title>Example-1</title>
    <link rel="stylesheet" href="Example.css" type="text/css">

.img-box {
  width: 1200px;
  height: 600px;
  padding: 20px;
  margin: 100px auto;
  box-shadow: 0px 0px 10px grey;
  background: url(about.jpg);
  background-size: cover;
  background-repeat: no-repeat;
}

I expected the image to scale when I used object-fit but it doesn't seem to be the case. Any ideas?

Body:
use width:100% to prevent the stretched images, and below code may you on second case.

.img-box {
  width: 100%;
  height: 600px;
  padding: 20px;
  margin: 100px auto;
  box-shadow: 0px 0px 10px grey;
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Flag_of_Pakistan.svg/800px-Flag_of_Pakistan.svg.png);
  background-size: cover;
  background-repeat: no-repeat;
}
.text{
  height:100%
}