问:
How to send a KeyValue list to Kafka?
I am trying to send a List[KeyValue] to the topic, in a Kafka Streams app. But the stream expects a single KeyValue. How I can send the KeyValues to the stream, instead of the whole list?

```<code>class MainTopology {

  val createTopology = (sourceTopic: String, sinkTopic: String) => {
    val builder = new StreamsBuilder()
    builder.stream(sourceTopic)
      .map[String, Option[JsonMessage]]((key, value) => toJsonEvent(key, value))
      .map[String, String]((key, value) => toFormattedEvents(key, value))
      .to(sinkTopic)
    builder.build()
  }

  private val toJsonEvent = (key: String, value: String) => {
    println(value)
    val jsonEventsAsCaseClasses = jsonToClass(value)
    new KeyValue(key, jsonEventsAsCaseClasses)
  }

  private val toFormattedEvents = (key: String, value: Option[JsonMessage]) => {
    val jsonEvents: List[String] = formatEvents(value)
    jsonEvents.map(event => new KeyValue(key,event))
  }

}
</code>```

The second map is not compiling due to this.

Expression of type List[KeyValue[String, String]] doesn't conform to expected type KeyValue[_ <: String, _ <: String]

I update my code, but now it is throwing another error:

```<code>    val builder = new StreamsBuilder()
    builder.stream(sourceTopic)
      .map[String, Option[JsonMessage]]((key, value) => toJsonEvent(key, value))
      .flatMap(
      (key, value) => toFormattedEvents(key, value)
    )
      .to(sinkTopic)
    builder.build()
  }

  private val toJsonEvent = (key: String, value: String) => {
    println(value)
    val jsonEventsAsCaseClasses = jsonToClass(value)
    new KeyValue(key, jsonEventsAsCaseClasses)
  }

  private val toFormattedEvents = (key: String, value: Option[JsonMessage]) => {
    val jsonEvents: List[String] = formatEvents(value)
    jsonEvents.map(event => new KeyValue(key,event)).toIterable.asJava
  }
</code>```

```<code>Error:(15, 8) inferred type arguments [?1,?0] do not conform to method flatMap's type parameter bounds [KR,VR]
      .flatMap(
Error:(16, 20) type mismatch;
 found   : org.apache.kafka.streams.kstream.KeyValueMapper[String,Option[org.minsait.streams.model.JsonMessage],Iterable[org.apache.kafka.streams.KeyValue[String,String]]]
 required: org.apache.kafka.streams.kstream.KeyValueMapper[_ >: String, _ >: Option[org.minsait.streams.model.JsonMessage], _ <: Iterable[_ <: org.apache.kafka.streams.KeyValue[_ <: KR, _ <: VR]]]
      (key, value) => toFormattedEvents(key, value)
</code>```

答:
Take a look at flatMap() and flatMapValues() to replace the second map().
https://kafka.apache.org/22/javadoc/org/apache/kafka/streams/kstream/KStream.html

For example:

.flatMap[String, Long]((key, value) => Seq(("foo", 1L), ("bar", 2L)))
```

<p>If you do intent to keep using <code>map</code> for some reason, then see below.</p>

<blockquote>
  <p>The second map is not compiling due to this.</p>

```Expression of type List[KeyValue[String, String]] doesn't conform to expected type KeyValue[_ <: String, _ <: String]
```
</blockquote>

<p>The corresponding code, for reference:</p>

<pre class="lang-scala prettyprint-override"><code>.map[String, String]((key, value) => toFormattedEvents(key, value))
</code>```

What you need is something like:

.map[String, List[KeyValue[KR, VR]]]((key, value) => toFormattedEvents(key, value))
```

<p>where <code>KR</code> and <code>VR</code> are the key and value types, respectively, as returned by <code>toFormattedEvents()</code> (the actual return types are not clear from your question). For this to work you must also have <code>Serde</code> for the <code>List[KeyValue[KR, VR]]</code> type.</p>

<p>Let me illustrate this with a few different types so it's easier to understand which part of the method call refers to which type. Assume we want to the map output to have a key type of <code>Integer</code> and a value type of <code>List[KeyValue[String, Long]]</code>:</p>

<pre class="lang-scala prettyprint-override"><code>.map[Integer, List[KeyValue[String, Long]]]((key, value) => (5, List(KeyValue.pair("foo", 1L), KeyValue.pair("bar", 2L))))
</code>```

Note that this example assigns the same values to every mapped record, but it's not the point of the example.

Title: How to send a KeyValue list to Kafka?

Body:
I am trying to send a List[KeyValue] to the topic, in a Kafka Streams app. But the stream expects a single KeyValue. How I can send the KeyValues to the stream, instead of the whole list?

class MainTopology {

  val createTopology = (sourceTopic: String, sinkTopic: String) => {
    val builder = new StreamsBuilder()
    builder.stream(sourceTopic)
      .map[String, Option[JsonMessage]]((key, value) => toJsonEvent(key, value))
      .map[String, String]((key, value) => toFormattedEvents(key, value))
      .to(sinkTopic)
    builder.build()
  }

  private val toJsonEvent = (key: String, value: String) => {
    println(value)
    val jsonEventsAsCaseClasses = jsonToClass(value)
    new KeyValue(key, jsonEventsAsCaseClasses)
  }

  private val toFormattedEvents = (key: String, value: Option[JsonMessage]) => {
    val jsonEvents: List[String] = formatEvents(value)
    jsonEvents.map(event => new KeyValue(key,event))
  }

}

The second map is not compiling due to this.

Expression of type List[KeyValue[String, String]] doesn't conform to expected type KeyValue[_ <: String, _ <: String]

I update my code, but now it is throwing another error:

    val builder = new StreamsBuilder()
    builder.stream(sourceTopic)
      .map[String, Option[JsonMessage]]((key, value) => toJsonEvent(key, value))
      .flatMap(
      (key, value) => toFormattedEvents(key, value)
    )
      .to(sinkTopic)
    builder.build()
  }

  private val toJsonEvent = (key: String, value: String) => {
    println(value)
    val jsonEventsAsCaseClasses = jsonToClass(value)
    new KeyValue(key, jsonEventsAsCaseClasses)
  }

  private val toFormattedEvents = (key: String, value: Option[JsonMessage]) => {
    val jsonEvents: List[String] = formatEvents(value)
    jsonEvents.map(event => new KeyValue(key,event)).toIterable.asJava
  }

Error:(15, 8) inferred type arguments [?1,?0] do not conform to method flatMap's type parameter bounds [KR,VR]
      .flatMap(
Error:(16, 20) type mismatch;
 found   : org.apache.kafka.streams.kstream.KeyValueMapper[String,Option[org.minsait.streams.model.JsonMessage],Iterable[org.apache.kafka.streams.KeyValue[String,String]]]
 required: org.apache.kafka.streams.kstream.KeyValueMapper[_ >: String, _ >: Option[org.minsait.streams.model.JsonMessage], _ <: Iterable[_ <: org.apache.kafka.streams.KeyValue[_ <: KR, _ <: VR]]]
      (key, value) => toFormattedEvents(key, value)

Body:
Take a look at flatMap() and flatMapValues() to replace the second map().
https://kafka.apache.org/22/javadoc/org/apache/kafka/streams/kstream/KStream.html

For example:

.flatMap[String, Long]((key, value) => Seq(("foo", 1L), ("bar", 2L)))

If you do intent to keep using map for some reason, then see below.

The second map is not compiling due to this.

Expression of type List[KeyValue[String, String]] doesn't conform to expected type KeyValue[_ <: String, _ <: String]

The corresponding code, for reference:

.map[String, String]((key, value) => toFormattedEvents(key, value))

What you need is something like:

.map[String, List[KeyValue[KR, VR]]]((key, value) => toFormattedEvents(key, value))

where KR and VR are the key and value types, respectively, as returned by toFormattedEvents() (the actual return types are not clear from your question). For this to work you must also have Serde for the List[KeyValue[KR, VR]] type.

Let me illustrate this with a few different types so it's easier to understand which part of the method call refers to which type. Assume we want to the map output to have a key type of Integer and a value type of List[KeyValue[String, Long]]:

.map[Integer, List[KeyValue[String, Long]]]((key, value) => (5, List(KeyValue.pair("foo", 1L), KeyValue.pair("bar", 2L))))

Note that this example assigns the same values to every mapped record, but it's not the point of the example.


来源: stackexchange

问:
Pagination in wordpress posts
I have been given this post template to work with, I am trying to get the posts to paginate, how would I go about achieving this? Apologies if I am asking about this/approaching this in a naive way.

I've tried following the WordPress guides but they don't seem to match up with what I've got and I'm struggling to extrapolate.

Hope this all makes sense, many thanks.

```<code><?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<?php $postLoops = 0 ?>

<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php $postLoops++;
if ($postLoops == 2) {
    echo '<div class="post-right-half">';
}
if ($postLoops == 1) {
    echo '<div class="post-left-half">';
}

?>
<div class="post-square">
    <div class="post-thumbnail" style="background-image: url(<?php the_post_thumbnail_url(); ?>);"><br></div>
    <div class="content-half">
        <h2 class="post-title"><?php the_title(); ?></h2>
        <p class="post-content"><?php the_excerpt(__('(more…)')); ?</p>
        <a class="read-more" href="<?php the_permalink() ?>">Read More <i class="fa fa-angle-right" aria-hidden="true"></i></a>
    </div>
</div>

<?php
if ($postLoops == 3) {
    echo '</div>';
}
if ($postLoops == 1) {
    echo '</div>';
}
?>

<?php
endwhile;
wp_reset_postdata();
?>
</code>```

答:
So I dont know how universal this is, but from a combination of the commented doc links and some further research this is the solution I arrived at:

The top two lines became this:

```<code><?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ?>
<?php $the_query = new WP_Query( array('posts_per_page' => 12,'paged' => $paged) ); ?>
<?php $postLoops = 0 ?>
</code>```

It's a bit complicated but I think the core of it is that I had to turn the query settings into an array, which includes the paged variable which is defined above (not sure I totally understand that bit yet but I'm working on it).

Then at the bottom of my page where I want my links to appear, I put in this crazy array that we modified to suit what we needed it to do, which looks complicated but essentially just includes all the settings you might need, including setting the previous and next buttons as font awesome buttons:

```<code><?php
    echo paginate_links( array(
        'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
        'total'        => $the_query->max_num_pages,
        'current'      => max( 1, get_query_var( 'paged' ) ),
        'format'       => '?paged=%#%',
        'show_all'     => false,
        'type'         => 'plain',
        'end_size'     => 2,
        'mid_size'     => 1,
        'prev_next'    => true,
        'prev_text'    => sprintf( '<i></i> %1$s', __( '<i class="fa fa-angle-left" aria-hidden="true"></i>', 'text-domain' ) ),
        'next_text'    => sprintf( '%1$s <i></i>', __( '<i class="fa fa-angle-right" aria-hidden="true"></i>', 'text-domain' ) ),
        'add_args'     => false,
        'add_fragment' => '',
    ) );
?>
</code>```

I think that's everything, I'll add more description if I understand it a bit more but it seems to work for now.

Many thanks.

ContentLicense: CC BY-SA 4.0

Title: Pagination in wordpress posts

Body:
I have been given this post template to work with, I am trying to get the posts to paginate, how would I go about achieving this? Apologies if I am asking about this/approaching this in a naive way.

I've tried following the WordPress guides but they don't seem to match up with what I've got and I'm struggling to extrapolate.

Hope this all makes sense, many thanks.

<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<?php $postLoops = 0 ?>

<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php $postLoops++;
if ($postLoops == 2) {
    echo '
';
}
if ($postLoops == 1) {
    echo '
';
}

?>

    <div class="post-thumbnail" style="background-image: url(<?php the_post_thumbnail_url(); ?>);">

<?php the_title(); ?>

<?php the_excerpt(__('(more…)')); ?

        <a class="read-more" href="<?php the_permalink() ?>">Read More

<?php
if ($postLoops == 3) {
    echo '
';
}
if ($postLoops == 1) {
    echo '
';
}
?>

<?php
endwhile;
wp_reset_postdata();
?>

Body:
So I dont know how universal this is, but from a combination of the commented doc links and some further research this is the solution I arrived at:

The top two lines became this:

<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ?>
<?php $the_query = new WP_Query( array('posts_per_page' => 12,'paged' => $paged) ); ?>
<?php $postLoops = 0 ?>

It's a bit complicated but I think the core of it is that I had to turn the query settings into an array, which includes the paged variable which is defined above (not sure I totally understand that bit yet but I'm working on it).

Then at the bottom of my page where I want my links to appear, I put in this crazy array that we modified to suit what we needed it to do, which looks complicated but essentially just includes all the settings you might need, including setting the previous and next buttons as font awesome buttons:

<?php
    echo paginate_links( array(
        'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
        'total'        => $the_query->max_num_pages,
        'current'      => max( 1, get_query_var( 'paged' ) ),
        'format'       => '?paged=%#%',
        'show_all'     => false,
        'type'         => 'plain',
        'end_size'     => 2,
        'mid_size'     => 1,
        'prev_next'    => true,
        'prev_text'    => sprintf( '<i></i> %1$s', __( '<i class="fa fa-angle-left" aria-hidden="true"></i>', 'text-domain' ) ),
        'next_text'    => sprintf( '%1$s <i></i>', __( '<i class="fa fa-angle-right" aria-hidden="true"></i>', 'text-domain' ) ),
        'add_args'     => false,
        'add_fragment' => '',
    ) );
?>

I think that's everything, I'll add more description if I understand it a bit more but it seems to work for now.

Many thanks.


问:
How to connect MySQL with Docker using Navicat or MySQL Workbench?
I am using the MySQL Docker images, and I can connect to this Docker with mysqli_connect('mysql', 'docker', 'docker'); in php

Here is docker ps:

```<code>CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                          NAMES
c271f8e68378        afraidjpg/nginx:nginx   "nginx -g 'daemon of…"   2 hours ago         Up 2 hours          0.0.0.0:80->80/tcp, 0.0.0.0:10086->10086/tcp   nginx
92d7c923f777        afraidjpg/php:php56     "docker-php-entrypoi…"   2 hours ago         Up 2 hours          0.0.0.0:9000->9000/tcp                         php
68b818bd68c4        afraidjpg/mysql:mysql   "docker-entrypoint.s…"   2 hours ago         Up 2 hours          0.0.0.0:3306->3306/tcp, 33060/tcp              mysql
</code>```

I use --link mysql option when starting PHP Docker.

IP of MySQL Docker is 172.17.0.2.

My mac's IP is 192.168.1.50

here is user in mysql:

```<code>mysql> select User, Host from mysql.user;
+--------+-----------+
| User   | Host      |
+--------+-----------+
| docker | %         |
| root   | localhost |
+--------+-----------+
2 rows in set (0.00 sec)
</code>```

then I tried to connect mysql with navicat and mysql-workbench

host:192.168.1.50, user:docker, pass:docker Access denied for user 'docker'@'%%' (using password: YES)

host:127.0.0.1, user:docker, pass:docker Access denied for user 'docker'@'%%' (using password: YES)

host:172.17.0.2, user:docker, pass:docker Can't connect to MySQL server on '172.17.0.2

all get the error with Access denied for user 'docker'@'%%' (using password: YES)

if l tried to change user from docker to root, error become Access denied for user 'docker'@'172.17.0.1' (using password: YES)

I found some article before, and followed their step, but always failed. I don't where I was wrong

here are some screenshot

update
I cannot ping from local to docker, and there is no ping command in docker so I cannot do the test to ping from docker to local

```<code>zk ~/Documents/PHP/www/docker $ ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3
</code>```

more update

I can connect to mysql with command in terminal with mysql -udocker -p --portocol=tcp

more details

error message is Access denied for user 'docker'@'%%' (using password: YES), It said @'%%', I know what the '%' is, but what's mean of '%%'?

答:
Do try host as mysql instead of localhost from the connected container. If you are on windows try 192.168.99.100 as host.

If still having issue try retest with mysql-compose.yml

```<code>version: "3.1"
services:

  mysql:
    image: mysql:5.7.22
    command: "--innodb_use_native_aio=0"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
    env_file:
      - .env
    ports:
      - "3306:3306"
    volumes:
      - /var/database/docker/common:/var/lib/mysql
    networks:
      - mysqlnet
      - mysqlnetfpm

networks:
  mysqlnet:
    driver: bridge
  mysqlnetfpm:
    driver: bridge
</code>```

Note: Before running new mysql container don't forgot to delete the older mysqldata files.

Now you can use the username as root, password as root and for the internal containers(attached containers) use the host as mysql.

If you are try to connect from outside the docker do try with host as localhost or 127.0.0.1 or your public docker ip.

Body:
I am using the MySQL Docker images, and I can connect to this Docker with mysqli_connect('mysql', 'docker', 'docker'); in php

Here is docker ps:

CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                          NAMES
c271f8e68378        afraidjpg/nginx:nginx   "nginx -g 'daemon of…"   2 hours ago         Up 2 hours          0.0.0.0:80->80/tcp, 0.0.0.0:10086->10086/tcp   nginx
92d7c923f777        afraidjpg/php:php56     "docker-php-entrypoi…"   2 hours ago         Up 2 hours          0.0.0.0:9000->9000/tcp                         php
68b818bd68c4        afraidjpg/mysql:mysql   "docker-entrypoint.s…"   2 hours ago         Up 2 hours          0.0.0.0:3306->3306/tcp, 33060/tcp              mysql

I use --link mysql option when starting PHP Docker.

IP of MySQL Docker is 172.17.0.2.

My mac's IP is 192.168.1.50

here is user in mysql:

mysql> select User, Host from mysql.user;
+--------+-----------+
| User   | Host      |
+--------+-----------+
| docker | %         |
| root   | localhost |
+--------+-----------+
2 rows in set (0.00 sec)

then I tried to connect mysql with navicat and mysql-workbench

host:192.168.1.50, user:docker, pass:docker Access denied for user 'docker'@'%%' (using password: YES)

host:127.0.0.1, user:docker, pass:docker Access denied for user 'docker'@'%%' (using password: YES)

host:172.17.0.2, user:docker, pass:docker Can't connect to MySQL server on '172.17.0.2

all get the error with Access denied for user 'docker'@'%%' (using password: YES)

if l tried to change user from docker to root, error become Access denied for user 'docker'@'172.17.0.1' (using password: YES)

I found some article before, and followed their step, but always failed. I don't where I was wrong

here are some screenshot

update
I cannot ping from local to docker, and there is no ping command in docker so I cannot do the test to ping from docker to local

zk ~/Documents/PHP/www/docker $ ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
Request timeout for icmp_seq 3

more update

I can connect to mysql with command in terminal with mysql -udocker -p --portocol=tcp

more details

error message is Access denied for user 'docker'@'%%' (using password: YES), It said @'%%', I know what the '%' is, but what's mean of '%%'?

Body:
Do try host as mysql instead of localhost from the connected container. If you are on windows try 192.168.99.100 as host.

If still having issue try retest with mysql-compose.yml

version: "3.1"
services:

  mysql:
    image: mysql:5.7.22
    command: "--innodb_use_native_aio=0"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
    env_file:
      - .env
    ports:
      - "3306:3306"
    volumes:
      - /var/database/docker/common:/var/lib/mysql
    networks:
      - mysqlnet
      - mysqlnetfpm

networks:
  mysqlnet:
    driver: bridge
  mysqlnetfpm:
    driver: bridge

Note: Before running new mysql container don't forgot to delete the older mysqldata files.

Now you can use the username as root, password as root and for the internal containers(attached containers) use the host as mysql.

If you are try to connect from outside the docker do try with host as localhost or 127.0.0.1 or your public docker ip.


问:
How do I pause or delay blinking text animation, so my text displays for a short period of time?
I have a button with some text that blinks, however I want to delay it for a short time when the text is visible, giving the user enough time to read the text before it fades to transparent.</p>

```<code>.btn-blink{
 border: 2px solid #4aa570;
 margin-bottom:20px;
 color:#fff;background:#4aa570;
 animation:blinkingText 3.2s infinite;
}

@keyframes blinkingText{
    0%{ color: #fff;    }
    25%{color: transparent; }
    50%{color: #fff;    }
    75%{color: transparent;}
    100%{color: #fff;   }
    }
</code>```

答:
I hope below code will be helpful.Below is HTML code.

```<code>//HTML CODE
<button>
  <span class="blinking">HELLO THERE</span>
</button>
</code>```

Write CSS code as below using keyframes:

```<code>//CSS
.blinking{
   animation:blinkingText 0.8s infinite;
}

@keyframes blinkingText{
 0%{ color: #000;}
 49%{ color: transparent; }
 50%{ color: transparent; }
 99%{ color:transparent; }
 100%{ color: #000; }
}
</code>```

I hope you will find your answer.

Body:
I have a button with some text that blinks, however I want to delay it for a short time when the text is visible, giving the user enough time to read the text before it fades to transparent.

.btn-blink{
 border: 2px solid #4aa570;
 margin-bottom:20px;
 color:#fff;background:#4aa570;
 animation:blinkingText 3.2s infinite;
}

@keyframes blinkingText{
    0%{ color: #fff;    }
    25%{color: transparent; }
    50%{color: #fff;    }
    75%{color: transparent;}
    100%{color: #fff;   }
    }

Body:
I hope below code will be helpful.Below is HTML code.

//HTML CODE
<button>
  <span class="blinking">HELLO THERE</span>
</button>

Write CSS code as below using keyframes:

//CSS
.blinking{
   animation:blinkingText 0.8s infinite;
}

@keyframes blinkingText{
 0%{ color: #000;}
 49%{ color: transparent; }
 50%{ color: transparent; }
 99%{ color:transparent; }
 100%{ color: #000; }
}

I hope you will find your answer.


问:
VBA: How to Automatically Include Cell Borders Without Error (Runtime 1004) Line Style
So this a question about the same big project my others are.

I am now just tidying up some formatting and essentially want a sub (that I can call from another) which will automatically add the borders I need around the new data being posted to the sheet.

I recorded the macro of adding the borders (and changed the range to one that is variable - RowToPasteTo) and all was working well.

I tried to call it from another piece of code and it went haywire, now giving me an error of:

Run-Time error '1004':

Unable to set the LineStyle Property of the Borders class

As the error mentions, it seems to be an error with the .LineStyle but I am using the same style as what their recorder gave me.

How can I get this working again so that is completes all borders?

EDIT: Forgot to add the code - sorry!

```<code>Sub Borders()

Dim RowToPasteTo As Long

With Sheets(4)

 RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
 Range("B" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Select
  With Selection.Borders
    .LineStyle = xlContinuous
    .ThemeColor = 3
    .TintAndShade = -9.99786370433668E-02
    .Weight = xlThin
    End With
End With

End Sub
</code>```

EDIT 2: This piece of code is to insert the borders when each new row of data is moved to this sheet (grid marks are off, as the borders are only to be shown on the lines with data.

I have tried all amendments so far suggested and am still receiving errors when running the above code alone.

I have now also created a blank sheet (and adjusted the sheets number accordingly) and I receive a different error there.

The (minimised) code that will later call this piece if as follows:

```<code>Sub ToTank()
Dim RowToPasteTo As Long
        RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1

        Sheets(4).Unprotect
        .Range("A" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Locked = False
Call Borders()

End Sub
</code>```

答:
I think there is something going on from the main sub calling the border sub. To avoid these kind of problems you need to full qualify all your ranges, another way is to do this:

```<code>Option Explicit
Sub ToTank()

    Dim RowToPasteTo As Long

    With ThisWorkbook.Sheets(4) 'If the code runs for the same workbook the code is in
        RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
        .Unprotect
        Borders .Range("B" & RowToPasteTo & ":" & "Z" & RowToPasteTo) 'call the procedure inserting the borders passing the range you need
    End With

End Sub
Sub Borders(MyRange As Range)

    With MyRange.Borders
        .LineStyle = xlContinuous
        .ThemeColor = 3
        .TintAndShade = -9.99786370433668E-02
        .Weight = xlThin
    End With

End Sub
</code>```

This way you can always call the Borders sub giving the range you want without any modifications. You could also make variables the LineStyle and all the properties you need by passing more arguments.

Body:
So this a question about the same big project my others are.

I am now just tidying up some formatting and essentially want a sub (that I can call from another) which will automatically add the borders I need around the new data being posted to the sheet.

I recorded the macro of adding the borders (and changed the range to one that is variable - RowToPasteTo) and all was working well.

I tried to call it from another piece of code and it went haywire, now giving me an error of:

Run-Time error '1004':

Unable to set the LineStyle Property of the Borders class

As the error mentions, it seems to be an error with the .LineStyle but I am using the same style as what their recorder gave me.

How can I get this working again so that is completes all borders?

EDIT: Forgot to add the code - sorry!

Sub Borders()

Dim RowToPasteTo As Long

With Sheets(4)

 RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
 Range("B" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Select
  With Selection.Borders
    .LineStyle = xlContinuous
    .ThemeColor = 3
    .TintAndShade = -9.99786370433668E-02
    .Weight = xlThin
    End With
End With

End Sub

EDIT 2: This piece of code is to insert the borders when each new row of data is moved to this sheet (grid marks are off, as the borders are only to be shown on the lines with data.

I have tried all amendments so far suggested and am still receiving errors when running the above code alone.

I have now also created a blank sheet (and adjusted the sheets number accordingly) and I receive a different error there.

The (minimised) code that will later call this piece if as follows:

Sub ToTank()
Dim RowToPasteTo As Long
        RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1

        Sheets(4).Unprotect
        .Range("A" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Locked = False
Call Borders()

End Sub

Body:
I think there is something going on from the main sub calling the border sub. To avoid these kind of problems you need to full qualify all your ranges, another way is to do this:

Option Explicit
Sub ToTank()

    Dim RowToPasteTo As Long

    With ThisWorkbook.Sheets(4) 'If the code runs for the same workbook the code is in
        RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
        .Unprotect
        Borders .Range("B" & RowToPasteTo & ":" & "Z" & RowToPasteTo) 'call the procedure inserting the borders passing the range you need
    End With

End Sub
Sub Borders(MyRange As Range)

    With MyRange.Borders
        .LineStyle = xlContinuous
        .ThemeColor = 3
        .TintAndShade = -9.99786370433668E-02
        .Weight = xlThin
    End With

End Sub

This way you can always call the Borders sub giving the range you want without any modifications. You could also make variables the LineStyle and all the properties you need by passing more arguments.


问:
C++ Bind failure due to unable to resolve overloaded function
```<code>void printVector(vector<int> &data){
        for(auto i : data){
                cout<< i << " ";
        }
        cout<<endl;
}

int main(){
    std::vector<int> data {0,1,2,3,4,5,6,7,8,9};
    vector<int> result;
    result.resize(data.size());
    transform(data.begin(),data.end(),result,bind(std::pow,_1,2));
    return 0;
}
</code>```

The error thrown is:

```<code>stlalgo.cpp:22:61: error: no matching function for call to ‘bind(<unresolved overloaded function type>, const std::_Placeholder<1>&, int)’
</code>```

How do i hint which overloaded function needs to be used in bind?

Cheers!

答:
You can't pass a function name that designates an overload set as a function pointer. There are several ways to mitigate this. One is a lambda:

```<code>transform(data.cbegin(),data.cend(),result.begin(),
    [](int d){ return std::pow(d, 2); });
</code>```

Another one is to explicitly cast the overload set to the specific function you intend to invoke:

```<code>transform(data.cbegin(),data.cend(),result.begin(),
    bind(static_cast<double(*)(double, int)>(std::pow),_1,2));
</code>```

A third way is to use one of the "lift" macros available, that wrap overload sets into lambdas.

```<code>#include <boost/hof/lift.hpp>

transform(data.cbegin(),data.cend(),result.begin(),
    bind(BOOST_HOF_LIFT(std::pow),_1,2));
</code>```

Note that in all snippets, I have changed the third parameter into result.begin(), as std::transform needs an output iterator there, and the first and second to act on const_iterators.

Body:
void printVector(vector<int> &data){
        for(auto i : data){
                cout<< i << " ";
        }
        cout<<endl;
}

int main(){
    std::vector<int> data {0,1,2,3,4,5,6,7,8,9};
    vector<int> result;
    result.resize(data.size());
    transform(data.begin(),data.end(),result,bind(std::pow,_1,2));
    return 0;
}

The error thrown is:

stlalgo.cpp:22:61: error: no matching function for call to ‘bind(<unresolved overloaded function type>, const std::_Placeholder<1>&, int)’

How do i hint which overloaded function needs to be used in bind?

Cheers!

Body:
You can't pass a function name that designates an overload set as a function pointer. There are several ways to mitigate this. One is a lambda:

transform(data.cbegin(),data.cend(),result.begin(),
    [](int d){ return std::pow(d, 2); });

Another one is to explicitly cast the overload set to the specific function you intend to invoke:

transform(data.cbegin(),data.cend(),result.begin(),
    bind(static_cast<double(*)(double, int)>(std::pow),_1,2));

A third way is to use one of the "lift" macros available, that wrap overload sets into lambdas.

#include <boost/hof/lift.hpp>

transform(data.cbegin(),data.cend(),result.begin(),
    bind(BOOST_HOF_LIFT(std::pow),_1,2));

Note that in all snippets, I have changed the third parameter into result.begin(), as std::transform needs an output iterator there, and the first and second to act on const_iterators.


问:
lucene 3.0.3 | searching problem with *.docx file
I am creating index with help of StandardAnalyzer for *.docx file it's fine. But at the time of searching it do not gives result for these *.docx file.

any help or suggestion will be appreciated!!!

答:
How do you convert the *.docx file to an indexable (text) format?

We use Apache POI to get our *.docx (and other office formats) indexed and this works pretty fine!

You can have a look at the Implementation here: http://code.google.com/p/gtxcontentconnector/source/browse/#svn%2Ftrunk%2Fcontentconnector-poi-transformer%2Fsrc%2Fmain%2Fjava%2Fcom%2Fgentics%2Fcr%2Flucene%2Findexer%2Ftransformer

ContentLicense: CC BY-SA 3.0


问:
Stack sticky element after other sticky element with dynamic height
I need to stack few sticky header elements like this:
https://webthemez.com/demo/sticky-multi-header-scroll/index.html

There are solutions for this question in stackover in here. But in my case my sticky headers have dynamic heights. Therefore not possible to hard code top position for stick headers. My code is like below:

html

```<code><div class="sticky-header1">
    Header 1 with dynamic height
</div>
<div>
    Header 1 content
</div>

<div class="sticky-header2">
    Header 2 with dynamic height
</div>
<div>
    Header 2 content
</div>
</code>```

css

```<code>.sticky-header1,
.sticky-header2
{
    position: sticky;
}
</code>```

Is it possible to set stacked sticky header in this scenario? Pure CSS solution is preferred.

答:
maybe u need to use javascript like this:

firstdiv =document.querySelector(".first");
secondiv =document.querySelector(".second");
thirdiv = document.querySelector(".third");
const fheight = firstdiv.offsetHeight;
const sheight = secondiv.offsetHeight;
secondiv.style.top= `${fheight}px`;
thirdiv.style.top= `${fheight+sheight}px`;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin:0;
  min-height:200vh;
  border:2px solid;
}
.first {
  height:50px;
  background:red;
  position:sticky;
  top:0;
}

.second {
  height:60px;
  background:blue;
  position:sticky;
}
.third {
  height:80px;
  background:green;
  position:sticky;

}</code>```

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
```

Body:
I need to stack few sticky header elements like this:
https://webthemez.com/demo/sticky-multi-header-scroll/index.html

There are solutions for this question in stackover in here. But in my case my sticky headers have dynamic heights. Therefore not possible to hard code top position for stick headers. My code is like below:

html

    Header 1 with dynamic height

    Header 1 content

    Header 2 with dynamic height

    Header 2 content

css

.sticky-header1,
.sticky-header2
{
    position: sticky;
}

Is it possible to set stacked sticky header in this scenario? Pure CSS solution is preferred.

Body:
maybe u need to use javascript like this:

firstdiv =document.querySelector(".first");
secondiv =document.querySelector(".second");
thirdiv = document.querySelector(".third");
const fheight = firstdiv.offsetHeight;
const sheight = secondiv.offsetHeight;
secondiv.style.top= `${fheight}px`;
thirdiv.style.top= `${fheight+sheight}px`;

body {
  margin:0;
  min-height:200vh;
  border:2px solid;
}
.first {
  height:50px;
  background:red;
  position:sticky;
  top:0;
}

.second {
  height:60px;
  background:blue;
  position:sticky;
}
.third {
  height:80px;
  background:green;
  position:sticky;

}

<div class="first"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
<div class="second"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
<div class="third"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>


问:
First gradient descent : how to normalize X and Y?
I'm doing my first gradient descent ever , following a course about Machine Learning.

But it doesn't seem to work correctly as it oscillates (converges then diverges then converges ... ) and at the end , the result is not appreciate.

Maybe it's because I did'nt normalize my X and Y but I don't know how to do it ...
I've tried  a way with  sklearn StandardScaler , but got an error.
I don't know what is going wrong.

I'm using Tensorflow 1.3.0  and jupyter.

Here's my code :

    #from sklearn.preprocessing import StandardScaler
    #scaler=StandardScaler()

    n_epochs=1000
    learning_rate=0.01
    X=tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
    #X_norm=scaler.fit_transform(X)
    Y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="Y")
    theta=tf.Variable(tf.random_uniform([n+1,1],-1.0,1.0),name="theta")
    y_pred=tf.matmul(X,theta,name="predictions")  #eq 1.4
    error=y_pred - Y

    mse=tf.reduce_mean(tf.square(error),name="mse") #eq 1.5
    gradients= (2/(m*mse) ) * tf.matmul(tf.transpose(X),error)
    training_op = tf.assign(theta,theta - learning_rate * gradients)

    init=tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        print("   Y   ")
        print(Y.eval())
        print("   X   ")
        print(X.eval())
        for epoch in range(n_epochs):
            if epoch%100==0:
                print("Epoch",epoch,"MSE =",mse.eval())
            sess.run(training_op)

        best_theta=theta.eval()
```

<p>and Here's what I get :</p>

```Y
[[4.526]
 [3.585]
 [3.521]
 ...
 [0.923]
 [0.847]
 [0.894]]
   X
[[   1.           8.3252      41.        ...    2.5555556   37.88
  -122.23     ]
 [   1.           8.3014      21.        ...    2.1098418   37.86
  -122.22     ]
 [   1.           7.2574      52.        ...    2.80226     37.85
  -122.24     ]
 ...
 [   1.           1.7         17.        ...    2.3256352   39.43
  -121.22     ]
 [   1.           1.8672      18.        ...    2.1232092   39.43
  -121.32     ]
 [   1.           2.3886      16.        ...    2.616981    39.37
  -121.24     ]]
Epoch 0 MSE = 511820.7
Epoch 100 MSE = 775760.0
Epoch 200 MSE = 2181710.8
Epoch 300 MSE = 115924.266
Epoch 400 MSE = 7663049.0
Epoch 500 MSE = 2283198.2
Epoch 600 MSE = 586127.75
Epoch 700 MSE = 7143360.5
Epoch 800 MSE = 15567712.0
Epoch 900 MSE = 2333040.0
```

But what's going wrong?
I thought that normalize will only allow to converge faster.

答:
From the looks of your code, you aren't using an optimizer for the Gradient Descent algorithm. I suggest to use an optimizer and then check the MSE again. Theoretically, it should improve. Here is an example of one Gradient Descent optimizer,

```<code>n_epochs=1000
learning_rate=0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) # Play around with learning rates and check the accuracy
X=tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
#X_norm=scaler.fit_transform(X)
Y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="Y")
theta=tf.Variable(tf.random_uniform([n+1,1],-1.0,1.0),name="theta")
y_pred=tf.matmul(X,theta,name="predictions")  #eq 1.4
error=y_pred - Y

mse=tf.reduce_mean(tf.square(error),name="mse") #eq 1.5
training_op = optimizer.minimize(mse)
</code>```

This is using a built in Optimizer from TensorFlow. You can opt to manually code the optimizer for your gradient descent algorithm.

Here is a link to blog site which explains different optimizers and Gradient descent in detail, http://ruder.io/optimizing-gradient-descent/

Body:
I'm doing my first gradient descent ever , following a course about Machine Learning.

But it doesn't seem to work correctly as it oscillates (converges then diverges then converges ... ) and at the end , the result is not appreciate.

Maybe it's because I did'nt normalize my X and Y but I don't know how to do it ...
I've tried  a way with  sklearn StandardScaler , but got an error.
I don't know what is going wrong.

I'm using Tensorflow 1.3.0  and jupyter.

Here's my code :

    #from sklearn.preprocessing import StandardScaler
    #scaler=StandardScaler()

    n_epochs=1000
    learning_rate=0.01
    X=tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
    #X_norm=scaler.fit_transform(X)
    Y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="Y")
    theta=tf.Variable(tf.random_uniform([n+1,1],-1.0,1.0),name="theta")
    y_pred=tf.matmul(X,theta,name="predictions")  #eq 1.4
    error=y_pred - Y

    mse=tf.reduce_mean(tf.square(error),name="mse") #eq 1.5
    gradients= (2/(m*mse) ) * tf.matmul(tf.transpose(X),error)
    training_op = tf.assign(theta,theta - learning_rate * gradients)

    init=tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)
        print("   Y   ")
        print(Y.eval())
        print("   X   ")
        print(X.eval())
        for epoch in range(n_epochs):
            if epoch%100==0:
                print("Epoch",epoch,"MSE =",mse.eval())
            sess.run(training_op)

        best_theta=theta.eval()

and Here's what I get :

Y
[[4.526]
 [3.585]
 [3.521]
 ...
 [0.923]
 [0.847]
 [0.894]]
   X
[[   1.           8.3252      41.        ...    2.5555556   37.88
  -122.23     ]
 [   1.           8.3014      21.        ...    2.1098418   37.86
  -122.22     ]
 [   1.           7.2574      52.        ...    2.80226     37.85
  -122.24     ]
 ...
 [   1.           1.7         17.        ...    2.3256352   39.43
  -121.22     ]
 [   1.           1.8672      18.        ...    2.1232092   39.43
  -121.32     ]
 [   1.           2.3886      16.        ...    2.616981    39.37
  -121.24     ]]
Epoch 0 MSE = 511820.7
Epoch 100 MSE = 775760.0
Epoch 200 MSE = 2181710.8
Epoch 300 MSE = 115924.266
Epoch 400 MSE = 7663049.0
Epoch 500 MSE = 2283198.2
Epoch 600 MSE = 586127.75
Epoch 700 MSE = 7143360.5
Epoch 800 MSE = 15567712.0
Epoch 900 MSE = 2333040.0

But what's going wrong?
I thought that normalize will only allow to converge faster.

Body:
From the looks of your code, you aren't using an optimizer for the Gradient Descent algorithm. I suggest to use an optimizer and then check the MSE again. Theoretically, it should improve. Here is an example of one Gradient Descent optimizer,

n_epochs=1000
learning_rate=0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) # Play around with learning rates and check the accuracy
X=tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
#X_norm=scaler.fit_transform(X)
Y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="Y")
theta=tf.Variable(tf.random_uniform([n+1,1],-1.0,1.0),name="theta")
y_pred=tf.matmul(X,theta,name="predictions")  #eq 1.4
error=y_pred - Y

mse=tf.reduce_mean(tf.square(error),name="mse") #eq 1.5
training_op = optimizer.minimize(mse)

This is using a built in Optimizer from TensorFlow. You can opt to manually code the optimizer for your gradient descent algorithm.

Here is a link to blog site which explains different optimizers and Gradient descent in detail, http://ruder.io/optimizing-gradient-descent/


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
First convert strings to datetime, then calculate difference in days.</p>

```<code>df['start_date'] = pd.to_datetime(df['start_date'], format='%Y-%m-%d')
df['end_date'] = pd.to_datetime(df['end_date'], format='%Y-%m-%d')
df['time_diff'] = (df.end_date - df.start_date).dt.days
</code>```

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
First convert strings to datetime, then calculate difference in days.

df['start_date'] = pd.to_datetime(df['start_date'], format='%Y-%m-%d')
df['end_date'] = pd.to_datetime(df['end_date'], format='%Y-%m-%d')
df['time_diff'] = (df.end_date - df.start_date).dt.days


问:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product
I am working on Spring Data MongoDB Aggregation framework.

Error:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aggregationBasicApplication': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at xpadro.spring.data.AggregationBasicApplication.main(AggregationBasicApplication.java:15) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:94) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:382) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:358) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:311) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:324) ~[na:1.8.0_171]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:293) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:276) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:250) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_171]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:251) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:380) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_171]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:381) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:93) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:64) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:193) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:566) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:559) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_171]
    at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049) ~[na:1.8.0_171]
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:561) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:551) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_171]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:551) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:211) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:119) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 29 common frames omitted
</code>```

Product.java

```<code>@Document
public class Product {
    @Id
    private final String id;
    private final String warehouse;
    private final float price;

    public Product(String id, String warehouse, float price) {
        this.id = id;
        this.warehouse = warehouse;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public String getWarehouse() {
        return warehouse;
    }

    public float getPrice() {
        return price;
    }
}
</code>```

ProductRepository.java

```<code>@Repository
public interface ProductRepository extends MongoRepository<Product, String>, ProductRepositoryCustom {

}
</code>```

WarehouseSummary.java

```<code>@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WarehouseSummary {
    private String warehouse;
    private List<String> productIds;
    private float averagePrice;
    private float totalRevenue;
}
</code>```

ProductRepositoryCustom.java

```<code>public interface ProductRepositoryCustom {
    List<WarehouseSummary> aggregate(float minPrice, float maxPrice);
}
</code>```

ProductRepositoryImpl.java

```<code>public class ProductRepositoryImpl implements ProductRepositoryCustom {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<WarehouseSummary> aggregate(float minPrice, float maxPrice) {
        // Match ==> filter
        Criteria priceCriteria = where("price").gt(minPrice).andOperator(where("price").lt(maxPrice));
        MatchOperation matchOperation = match(priceCriteria);

        // Group
        GroupOperation groupOperation = group("warehouse").last("warehouse").as("warehouse")
                .addToSet("id").as("productIds")
                .avg("price").as("averagePrice")
                .sum("price").as("totalRevenue");

        // Project
        ProjectionOperation projectionOperation = project("productIds", "averagePrice", "totalRevenue").and("warehouse")
                .previousOperation();

        Aggregation aggregation = Aggregation.newAggregation(matchOperation, groupOperation, projectionOperation);

        AggregationResults<WarehouseSummary> aggregationResults = mongoTemplate.aggregate(aggregation, Product.class, WarehouseSummary.class);

        List<WarehouseSummary> warehouseSummaries = aggregationResults.getMappedResults();
        return warehouseSummaries;
    }
}
</code>```

AggregationBasicApplication.java

```<code>@SpringBootApplication
public class AggregationBasicApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(AggregationBasicApplication.class, args);
    }

    @Autowired
    private ProductRepository productRepository;

    private void saveProducts() {
        productRepository.save(new Product("NW1", "Norwich", 3.0f));
        productRepository.save(new Product("LN1", "London", 25.0f));
        productRepository.save(new Product("LN2", "London", 35.0f));
        productRepository.save(new Product("LV1", "Liverpool", 15.2f));
        productRepository.save(new Product("MN1", "Manchester", 45.5f));
        productRepository.save(new Product("LV2", "Liverpool", 23.9f));
        productRepository.save(new Product("LN3", "London", 55.5f));
        productRepository.save(new Product("LD1", "Leeds", 87.0f));
    }

    @Override
    public void run(String... args) throws Exception {
        saveProducts();
    }
}
</code>```

答:
After spending many hour, I did not found the solution, why thin things are breaking. I put all these 3 classes in the same package: xpadro.spring.data.repository. Now its working fine. Anyone knows what's causing the real issue ?

ProductRepository.java

ProductRepositoryCustom.java

ProductRepositoryImpl.java

Body:
I am working on Spring Data MongoDB Aggregation framework.

Error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aggregationBasicApplication': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at xpadro.spring.data.AggregationBasicApplication.main(AggregationBasicApplication.java:15) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property aggregate found for type Product!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:94) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:382) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:358) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:311) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:324) ~[na:1.8.0_171]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:293) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:276) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:250) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_171]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:251) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:380) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_171]
    at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:381) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:93) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.query.PartTreeMongoQuery.<init>(PartTreeMongoQuery.java:64) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:193) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:566) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:559) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_171]
    at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_171]
    at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049) ~[na:1.8.0_171]
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_171]
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_171]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_171]
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_171]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:561) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:551) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_171]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:551) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:211) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:119) ~[spring-data-mongodb-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 29 common frames omitted

Product.java

@Document
public class Product {
    @Id
    private final String id;
    private final String warehouse;
    private final float price;

    public Product(String id, String warehouse, float price) {
        this.id = id;
        this.warehouse = warehouse;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public String getWarehouse() {
        return warehouse;
    }

    public float getPrice() {
        return price;
    }
}

ProductRepository.java

@Repository
public interface ProductRepository extends MongoRepository<Product, String>, ProductRepositoryCustom {

}

WarehouseSummary.java

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WarehouseSummary {
    private String warehouse;
    private List<String> productIds;
    private float averagePrice;
    private float totalRevenue;
}

ProductRepositoryCustom.java

public interface ProductRepositoryCustom {
    List<WarehouseSummary> aggregate(float minPrice, float maxPrice);
}

ProductRepositoryImpl.java

public class ProductRepositoryImpl implements ProductRepositoryCustom {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<WarehouseSummary> aggregate(float minPrice, float maxPrice) {
        // Match ==> filter
        Criteria priceCriteria = where("price").gt(minPrice).andOperator(where("price").lt(maxPrice));
        MatchOperation matchOperation = match(priceCriteria);

        // Group
        GroupOperation groupOperation = group("warehouse").last("warehouse").as("warehouse")
                .addToSet("id").as("productIds")
                .avg("price").as("averagePrice")
                .sum("price").as("totalRevenue");

        // Project
        ProjectionOperation projectionOperation = project("productIds", "averagePrice", "totalRevenue").and("warehouse")
                .previousOperation();

        Aggregation aggregation = Aggregation.newAggregation(matchOperation, groupOperation, projectionOperation);

        AggregationResults<WarehouseSummary> aggregationResults = mongoTemplate.aggregate(aggregation, Product.class, WarehouseSummary.class);

        List<WarehouseSummary> warehouseSummaries = aggregationResults.getMappedResults();
        return warehouseSummaries;
    }
}

AggregationBasicApplication.java

@SpringBootApplication
public class AggregationBasicApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(AggregationBasicApplication.class, args);
    }

    @Autowired
    private ProductRepository productRepository;

    private void saveProducts() {
        productRepository.save(new Product("NW1", "Norwich", 3.0f));
        productRepository.save(new Product("LN1", "London", 25.0f));
        productRepository.save(new Product("LN2", "London", 35.0f));
        productRepository.save(new Product("LV1", "Liverpool", 15.2f));
        productRepository.save(new Product("MN1", "Manchester", 45.5f));
        productRepository.save(new Product("LV2", "Liverpool", 23.9f));
        productRepository.save(new Product("LN3", "London", 55.5f));
        productRepository.save(new Product("LD1", "Leeds", 87.0f));
    }

    @Override
    public void run(String... args) throws Exception {
        saveProducts();
    }
}


问:
how many words end in certain character in function calling to different file?
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

```<code>def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
</code>```

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

```<code>def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
</code>```

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

答:
The line...

```<code>if ch in '?!.':
</code>```

...is not going to work as expected. You need to check each punctuation mark individually:

```<code>if any(ch.endswith(punc) for punc in '?!.'):
# or
if any(punc in ch for punc in '?!.'):
</code>```

Body:
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

Body:
The line...

if ch in '?!.':

...is not going to work as expected. You need to check each punctuation mark individually:

if any(ch.endswith(punc) for punc in '?!.'):
# or
if any(punc in ch for punc in '?!.'):


问:
Angular Hybrid App Test "Cannot read property 'nativeElement' of null"
I have a simple test:

```<code>it ('should be able to navigate to add program', fakeAsync(() => {
  let href = fixture.debugElement.query(By.css('.add-program-btn'));
  let link = href.nativeElement.getAttribute('href');
  expect(link).toEqual('/program/new');
}));
</code>```

And keep getting an error:

```<code>TypeError: Cannot read property 'nativeElement' of null
</code>```

I've tried using tick() with like 20000, and adding fixture.detectChanges() but nothing works. Another test that checks if a button was clicked and a function called has the same error. Is it that it can't find the element?

Everything this test is using is in Angular so I don't think it's because it's a hybrid app.

Thanks in advance.

答:
This happens when *ngIf is being used in the template and it's expression evaluates to a falsy value. You should set appropriate inputs to the component so that *ngIf can evaluate to true;

Here is some sample code:

it ('should be able to navigate to add program', async(() => {
  const component = fixture.componentInstance;

  // Set particular input so that ngIf makes your href visible to true
  component.inputName = true;

  // run change detection, updated input value should get used
  fixture.detectChanges();

  // in some cases you may want for things to stabilize
  await fixture.whenStable();

  // For debugging prupose, you may want to log innerHTML
  console.log(fixture.debugElement.nativeElement.innerHTML)

  // Rest of the test
  let href = fixture.debugElement.query(By.css('.add-program-btn'));
  let link = href.nativeElement.getAttribute('href');

  expect(link).toEqual('/program/new');
}));
```

Body:
I have a simple test:

it ('should be able to navigate to add program', fakeAsync(() => {
  let href = fixture.debugElement.query(By.css('.add-program-btn'));
  let link = href.nativeElement.getAttribute('href');
  expect(link).toEqual('/program/new');
}));

And keep getting an error:

TypeError: Cannot read property 'nativeElement' of null

I've tried using tick() with like 20000, and adding fixture.detectChanges() but nothing works. Another test that checks if a button was clicked and a function called has the same error. Is it that it can't find the element?

Everything this test is using is in Angular so I don't think it's because it's a hybrid app.

Thanks in advance.


问:
How to filter a List using Java 8 stream and startwith array of values
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

```<code>List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());
</code>```

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

答:
```<code>List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

</code>```

Following is the correct code:

Your code uses the following:

Body:
I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

Body:
List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

Following is the correct code:

Your code uses the following:


问:
unable to use custom cell
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

```<code>static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}
</code>```

Please shed some light on this.

Thanks in advance

答:
Be sure to give it the correct identifier in xcode:

```<code>if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:@"AlertCell"];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:@"AlertCellLandScape"];
}
</code>```

and to set it correctly (fil the Identifier field) in IB for the respective cells

Title: unable to use custom cell

Body:
I am not able to make out whatrs wrong with this piece of code all I am trying to do is use custom table cell 'AlertCell' when device is in portrait mode and 'AlertCellLandScape' if device is in 'landscape' mode.

its saying cell is undeclared and inside the condition check its saying unused cell

static NSString *CellIdentifier1 = @"Cell1";
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell;

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
}

if (cell == nil) {
   // cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    if (isPortraitMode) {
        cell = [[[AlertsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] autorelease];
    }
    else {
        cell = [[[AlertsTableCellLandScape alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
    }
}

Please shed some light on this.

Thanks in advance

Body:
Be sure to give it the correct identifier in xcode:

if (isPortraitMode)
{
    AlertsTableCell *cell = (AlertsTableCell *)[tableView dequeueReusableCellWithIdentifier:@"AlertCell"];
}

else {
    AlertsTableCellLandScape *cell = (AlertsTableCellLandScape *)[tableView dequeueReusableCellWithIdentifier:@"AlertCellLandScape"];
}

and to set it correctly (fil the Identifier field) in IB for the respective cells


问:
Asp.Net Core API disable startup complete message
As part of my application I have a .Net Core API project. Unlike most cases where this project would run as its own process, I have the API run in a thread, among others, in a single process. Also for my project, I have implemented a custom logging system to suit my needs. However, I have come across a slight problem. Every time I run my program, once the API starts, this message is printed to the console:

```<code>Hosting environment: Production
Content root path: C:\Users\Path\To\Code
Now listening on: http://*:8000
Application started. Press Ctrl+C to shut down.
</code>```

I would like to disable this message as there is no need for it, and it clutters up the otherwise well organized console log. I have a screenshot below so you know exactly what I'm talking about:

I have already disabled all other logging for the mvc (removed ILoggerFactory from ConfigureServices and set all logging to "None" in appsettings.json).

How do I go about disabling/suppressing this message?

答:
.NET Core 3.x

Good news!
These annoying messages are not being written by ASP.NET Core using plain Console anymore. Now abstract Logger is used, so startup messages will be written by your logger in configured format, just like any other logs.

But if you want to get rid of these logs all along, you can use one of two following approaches

The first way is to use .ConfigureLogging(...) method on host builder to remove all default providers from logger:

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggingBuilder =>
        {
            loggingBuilder.ClearProviders(); // <-- here
        })
        .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
</code>```

The other way is to configure .NET Core 3 logger with ConsoleLifetimeOptions in your Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);

    // ...
}
</code>```

NOTE: second approach won't disable Kestrel logs about an app being listened on port (but first will)

```<code>info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
</code>```

.NET Core 2.x

These messages can be disabled in 2 ways (besides already mentioned console settings):

1) You can disable them with Environment variable:
"ASPNETCORE_SUPPRESSSTATUSMESSAGES": "true"

2) Or through code (in Program.cs):

```<code>WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")
</code>```

or

```<code>WebHost.CreateDefaultBuilder(args)
    .SuppressStatusMessages(true);
</code>```

Body:
As part of my application I have a .Net Core API project. Unlike most cases where this project would run as its own process, I have the API run in a thread, among others, in a single process. Also for my project, I have implemented a custom logging system to suit my needs. However, I have come across a slight problem. Every time I run my program, once the API starts, this message is printed to the console:

Hosting environment: Production
Content root path: C:\Users\Path\To\Code
Now listening on: http://*:8000
Application started. Press Ctrl+C to shut down.

I would like to disable this message as there is no need for it, and it clutters up the otherwise well organized console log. I have a screenshot below so you know exactly what I'm talking about:

I have already disabled all other logging for the mvc (removed ILoggerFactory from ConfigureServices and set all logging to "None" in appsettings.json).

How do I go about disabling/suppressing this message?

Body:
.NET Core 3.x

Good news!
These annoying messages are not being written by ASP.NET Core using plain Console anymore. Now abstract Logger is used, so startup messages will be written by your logger in configured format, just like any other logs.

But if you want to get rid of these logs all along, you can use one of two following approaches

The first way is to use .ConfigureLogging(...) method on host builder to remove all default providers from logger:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggingBuilder =>
        {
            loggingBuilder.ClearProviders(); // <-- here
        })
        .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

The other way is to configure .NET Core 3 logger with ConsoleLifetimeOptions in your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);

    // ...
}

NOTE: second approach won't disable Kestrel logs about an app being listened on port (but first will)

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000

.NET Core 2.x

These messages can be disabled in 2 ways (besides already mentioned console settings):

1) You can disable them with Environment variable:
"ASPNETCORE_SUPPRESSSTATUSMESSAGES": "true"

2) Or through code (in Program.cs):

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")

or

WebHost.CreateDefaultBuilder(args)
    .SuppressStatusMessages(true);


问:
How to write a result of a variable type list in logfile?
I'm setting a code in python 2.7 where I have to write the result of a list variable in logfile

I tried logFile.write(.format(var))

also logFile.write.print(var)

```<code>var = []
logFile.write(var)
</code>```

答:
This is a very broad question; I'd recommend checking the basic python tutorial first to see what you'd actually need.

There are different options, depending on the format you'd like the resulting output file to be in.

Simple line-by-line

Just write the output of each of the variables in the list to a file, line-by-line:

```<code>import os

filename = "output.txt"

with open(filename, "w") as file_handle:
    for value in var:
        file_handle.write(value + os.linesep)
</code>```

What this does:

open a file handle in write mode, using a context manager. This assures the file will be closed afterwards and all values will be written

iterate through all values in the array

write each of the value to the file handle, followed by a line separator (\n on nix-like systems)

Body:
I'm setting a code in python 2.7 where I have to write the result of a list variable in logfile

I tried logFile.write(.format(var))

also logFile.write.print(var)

var = []
logFile.write(var)

Body:
This is a very broad question; I'd recommend checking the basic python tutorial first to see what you'd actually need.

There are different options, depending on the format you'd like the resulting output file to be in.

Simple line-by-line

Just write the output of each of the variables in the list to a file, line-by-line:

import os

filename = "output.txt"

with open(filename, "w") as file_handle:
    for value in var:
        file_handle.write(value + os.linesep)

What this does:

open a file handle in write mode, using a context manager. This assures the file will be closed afterwards and all values will be written

iterate through all values in the array

write each of the value to the file handle, followed by a line separator (\n on nix-like systems)