问:
Expected at least 1 element matching "div#error_explanation", found 0.. Expected 0 to be >= 1
I'm a rails noob & can't make the connection of this error and the code while following Hartl's Rails tutorial.

Similar questions here @ stackoverflow don't solve the problem of my particular test failure error message as my partial code is same as Hartl's code on github and all other aspects of my integration testing pass green.

sample_app_3rd_edition/app/views/shared/_error_messages.html.erb

Here is my code from the integration test

/test/integration/password_resets_test.rb

```<code>       #Invalid password & confirmation
       patch password_reset_path(user.reset_token),
         email: user.email,
         user: { password:               "foobazz",
                 password_confirmation:  "barquux" }
       assert_select 'div#error_explanation'
</code>```

which generates an error message referring to line 6:

```<code>test_password_resets#PasswordResetsTest (1442030711.19s)
    Expected at least 1 element matching "div#error_explanation", found 0..
    Expected 0 to be >= 1.
</code>```

Next is the partial

/app/views/shared/_error_messages.html.erb

from which assert_select 'div#error_explanation' is supposed to render the error message needed for the invalid password and confirmation.

/app/views/shared/_error_messages.html.erb

```<code><% if @user.errors.any? %>
     <div id="error_explanation">
       <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count,"error") %>
       </div>
       <ul>
         <% @user.errors.full_messages.each do |msg| %>
           <li><%= msg %></li>
         <% end %>
       </ul>
    </div>
 <% end %>
</code>```

I simply don't understand why assert_select is not working here since the _error_message partial works for all other tests referencing the same partial.  I think I understand that the integration test failure is telling me that "there is no message (element) where there should be one."

Help clearing up my confusion is greatly appreciated! I'll be happy to post UserController/ PasswordController or whatever @user variable code is needed.

updated 10/10/15 here is user.rb

```<code>class User < ActiveRecord::Base
   attr_accessor :remember_token, :activation_token, :reset_token
   before_save   :downcase_email
   before_create :create_activation_digest
   validates     :name, presence: true, length: {maximum:50}
   VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
   validates :email,presence: true, length: {maximum:255},
             format: { with: VALID_EMAIL_REGEX },
             uniqueness: { case_sensitive: false }
</code>```

```<code>   has_secure_password
   validates :password, length: { minimum: 6 }, allow_blank: true
</code>```

Here is the PasswordResetsController

```<code>class PasswordResetsController < ApplicationController
   before_action :get_user,         only:[:edit, :update]
   before_action :valid_user,       only:[:edit, :update]
   before_action :check_expiration, only:[:edit, :update]
</code>```

```<code>   def new
   end

   def create
     @user = User.find_by(email: params[:password_reset]     [:email].downcase)
     if @user
        @user.create_reset_digest
        @user.send_password_reset_email
        flash[:info] = "Email sent with password reset instructions"
        redirect_to root_url
     else
       flash.now[:danger] = "Email address not found"
       render 'new'
     end
   end

   def edit
   end

   def update
     if password_blank?
       flash.now[:danger] = "Password can't be blank"
       render 'edit'
     elsif @user.update_attributes(user_params)
       log_in @user
       flash[:success] = "Password has been reset"
       redirect_to @user
     else
       render 'edit'
     end
   end

   private

     def user_params
       params.require(:user).permit(:password,
                                    :password_confirmation)
     end

     #Returns true if password is blank.

     def password_blank?
       params[:user][:password].blank?
     end

     #Before filters

     def get_user
        @user = User.find_by(email: params[:email])
     end

     #Confirms a valid user.
     def valid_user
       unless (@user && @user.activated? &&
               @user.authenticated?(:reset, params[:id]))
       redirect_to root_url
       end
     end

     #Checks expiration of reset token
     def check_expiration
       if @user.password_reset_expired?
         flash[:danger] = "Password reset has expired."
         redirect_to new_password_reset_url
       end
     end
 end
</code>```

答:
1) Failure:</p>

```<code>HomeControllerTest#test_should_get_home [/home/ubuntu/workspace/test/controllers/home_controller_test.rb:11]:
Expected at least 1 element matching "title", found 0..
Expected 0 to be >= 1.
</code>```

Body:
I'm a rails noob & can't make the connection of this error and the code while following Hartl's Rails tutorial.

Similar questions here @ stackoverflow don't solve the problem of my particular test failure error message as my partial code is same as Hartl's code on github and all other aspects of my integration testing pass green.

sample_app_3rd_edition/app/views/shared/_error_messages.html.erb

Here is my code from the integration test

/test/integration/password_resets_test.rb

       #Invalid password & confirmation
       patch password_reset_path(user.reset_token),
         email: user.email,
         user: { password:               "foobazz",
                 password_confirmation:  "barquux" }
       assert_select 'div#error_explanation'

which generates an error message referring to line 6:

test_password_resets#PasswordResetsTest (1442030711.19s)
    Expected at least 1 element matching "div#error_explanation", found 0..
    Expected 0 to be >= 1.

Next is the partial

/app/views/shared/_error_messages.html.erb

from which assert_select 'div#error_explanation' is supposed to render the error message needed for the invalid password and confirmation.

/app/views/shared/_error_messages.html.erb

<% if @user.errors.any? %>

      The form contains <%= pluralize(@user.errors.count,"error") %>

         <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

         <% end %>

 <% end %>

I simply don't understand why assert_select is not working here since the _error_message partial works for all other tests referencing the same partial.  I think I understand that the integration test failure is telling me that "there is no message (element) where there should be one."

Help clearing up my confusion is greatly appreciated! I'll be happy to post UserController/ PasswordController or whatever @user variable code is needed.

updated 10/10/15 here is user.rb

class User < ActiveRecord::Base
   attr_accessor :remember_token, :activation_token, :reset_token
   before_save   :downcase_email
   before_create :create_activation_digest
   validates     :name, presence: true, length: {maximum:50}
   VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
   validates :email,presence: true, length: {maximum:255},
             format: { with: VALID_EMAIL_REGEX },
             uniqueness: { case_sensitive: false }

   has_secure_password
   validates :password, length: { minimum: 6 }, allow_blank: true

Here is the PasswordResetsController

class PasswordResetsController < ApplicationController
   before_action :get_user,         only:[:edit, :update]
   before_action :valid_user,       only:[:edit, :update]
   before_action :check_expiration, only:[:edit, :update]

   def new
   end

   def create
     @user = User.find_by(email: params[:password_reset]     [:email].downcase)
     if @user
        @user.create_reset_digest
        @user.send_password_reset_email
        flash[:info] = "Email sent with password reset instructions"
        redirect_to root_url
     else
       flash.now[:danger] = "Email address not found"
       render 'new'
     end
   end

   def edit
   end

   def update
     if password_blank?
       flash.now[:danger] = "Password can't be blank"
       render 'edit'
     elsif @user.update_attributes(user_params)
       log_in @user
       flash[:success] = "Password has been reset"
       redirect_to @user
     else
       render 'edit'
     end
   end

   private

     def user_params
       params.require(:user).permit(:password,
                                    :password_confirmation)
     end

     #Returns true if password is blank.

     def password_blank?
       params[:user][:password].blank?
     end

     #Before filters

     def get_user
        @user = User.find_by(email: params[:email])
     end

     #Confirms a valid user.
     def valid_user
       unless (@user && @user.activated? &&
               @user.authenticated?(:reset, params[:id]))
       redirect_to root_url
       end
     end

     #Checks expiration of reset token
     def check_expiration
       if @user.password_reset_expired?
         flash[:danger] = "Password reset has expired."
         redirect_to new_password_reset_url
       end
     end
 end

Body:
1) Failure:

HomeControllerTest#test_should_get_home [/home/ubuntu/workspace/test/controllers/home_controller_test.rb:11]:
Expected at least 1 element matching "title", found 0..
Expected 0 to be >= 1.


来源: stackexchange

问:
IntelliJ does not recognize generated sources
There are already many similar questions, but none of the proposed solutions (mainly "Clear caches and restart IntelliJ) solves my problem.

I have a maven project that I imported into IntelliJ Community Edition 2017.1 . My maven build automatically creates some java sources from Google protobuf specifications.

Excerpt from pom.xml

```<code>         <plugin>
            <groupId>com.github.os72</groupId>
            <artifactId>protoc-jar-maven-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <protocVersion>3.1.0</protocVersion> <!-- 2.4.1, 2.5.0, 2.6.1, 3.1.0 -->
                        <inputDirectories>
                            <include>src/main/protobuf</include>
                        </inputDirectories>
                        <outputDirectory>${project.build.directory}/generated-sources/protobuf</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

The folder /generated-sources/protobuf is correctly recognized as "generated-sources" with a blue icon and the wheel for generated sources under IntelliJ -> File -> Project Structure -> Modules -> Sources

The maven target "compile" also works fine.

But the IntelliJ "internal" java compiler complains "Cannot resolve symbol" for my generated class.

Solutions I tired so far

add an intermediate folder /target/generated-sources/protobuf/  => did not help

Invalidate caches, delete project file, reimport, restart IDE => did not help

Maven -> Reimport all projects => did not help

Any more suggestions?

答:
SOLUTION:  The generated files were to large. Had to increase

```<code>idea.max.intellisense.filesize=2500
</code>```

in IDE_HOME\bin\idea.properties as described here: File size exceeds configured limit (2560000), code insight features not available

ContentLicense: CC BY-SA 3.0

Body:
There are already many similar questions, but none of the proposed solutions (mainly "Clear caches and restart IntelliJ) solves my problem.

I have a maven project that I imported into IntelliJ Community Edition 2017.1 . My maven build automatically creates some java sources from Google protobuf specifications.

Excerpt from pom.xml

         <plugin>
            <groupId>com.github.os72</groupId>
            <artifactId>protoc-jar-maven-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <protocVersion>3.1.0</protocVersion>
                        <inputDirectories>
                            <include>src/main/protobuf</include>
                        </inputDirectories>
                        <outputDirectory>${project.build.directory}/generated-sources/protobuf</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

The folder /generated-sources/protobuf is correctly recognized as "generated-sources" with a blue icon and the wheel for generated sources under IntelliJ -> File -> Project Structure -> Modules -> Sources

The maven target "compile" also works fine.

But the IntelliJ "internal" java compiler complains "Cannot resolve symbol" for my generated class.

Solutions I tired so far

add an intermediate folder /target/generated-sources/protobuf/  => did not help

Invalidate caches, delete project file, reimport, restart IDE => did not help

Maven -> Reimport all projects => did not help

Any more suggestions?

Body:
SOLUTION:  The generated files were to large. Had to increase

idea.max.intellisense.filesize=2500

in IDE_HOME\bin\idea.properties as described here: File size exceeds configured limit (2560000), code insight features not available


问:
Python UDP client did not respond
A python UDP client:

```<code>root@kali-linux:~# python
Python 2.7.14 (default, Sep 17 2017, 18:50:44)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> target_host = "127.0.0.1"
>>> target_port = 80
>>> client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
>>> client.sendto("AAABBBCCC",(target_host,target_port))
9
>>> data, addr = client.recvfrom(4096)
        # to this line,no response
>>>print data   # waiting for imput
</code>```

when I input "data, addr = client.recvfrom(4096)" then ENTER,I wait for ten minutes that no response.

But when I program a TCP client,it work.This is code:

```<code>root@kali-linux:~# python
Python 2.7.14 (default, Sep 17 2017, 18:55:37)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>import socket
>>>target_host = "www.baidu.com"
>>>target_port = 80
>>>client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>>client.connect((target_host,target_port))
>>>client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n")
35
>>>response = client.recv(4096)
>>>print response
#output
HTTP/1.1 200 OK
Date: Thu, 16 Nov 2017 12:05:07 GMT
Content-Type: text/html
Content-Length: 14613
Last-Modified: Wed, 01 Nov 2017 03:00:00 GMT
Connection: Keep-Alive
Vary: Accept-Encoding

AND SO ON ..........
</code>```

TCP client can work and UDP client can't work,why?

what should I do?

答:
UDP ports and TCP ports are different entities. You can have a TCP server running on TCP port 80 and something entirely different on UDP port 80 (e.g. an NTP server, although this is normally running on UDP port 123).

In your first code snippet you are sending a UDP packet to the UDP port 80. Mostly likely nothing is listening on UDP port 80 so the packet is silently discarded.

You line data, addr = client.recvfrom(4096) is then waiting for someone (not necessarily the server you sent the request to) sending you another UDP packet. Since usually there is nothing listening on UDP port 80 nothign happens, and the revcfrom call waits forever. It works ok. This is expected.

What you could do to receive something:
1. bind() your socket of your UDP snippet to port 2222 (or any free port), and run it. It will again wait forever.
2. Run a second instance (in a different shell) with `target_port = 2222'. Now you should receive a UDP packet with the content "AAABBBCCC" on the first instance.

In your second code snippet you are using TCP and you are contacting a web server on TCP port 80 (not UDP port 80) which responds. This works as expected as you can see, but only since there is something running on TCP port 80.

Title: Python UDP client did not respond

Body:
A python UDP client:

root@kali-linux:~# python
Python 2.7.14 (default, Sep 17 2017, 18:50:44)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> target_host = "127.0.0.1"
>>> target_port = 80
>>> client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
>>> client.sendto("AAABBBCCC",(target_host,target_port))
9
>>> data, addr = client.recvfrom(4096)
        # to this line,no response
>>>print data   # waiting for imput

when I input "data, addr = client.recvfrom(4096)" then ENTER,I wait for ten minutes that no response.

But when I program a TCP client,it work.This is code:

root@kali-linux:~# python
Python 2.7.14 (default, Sep 17 2017, 18:55:37)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>import socket
>>>target_host = "www.baidu.com"
>>>target_port = 80
>>>client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>>client.connect((target_host,target_port))
>>>client.send("GET / HTTP/1.1\r\nHost: baidu.com\r\n\r\n")
35
>>>response = client.recv(4096)
>>>print response
#output
HTTP/1.1 200 OK
Date: Thu, 16 Nov 2017 12:05:07 GMT
Content-Type: text/html
Content-Length: 14613
Last-Modified: Wed, 01 Nov 2017 03:00:00 GMT
Connection: Keep-Alive
Vary: Accept-Encoding

AND SO ON ..........

TCP client can work and UDP client can't work,why?

what should I do?


问:
How to use layoutinflator to add views at runtime?
I have two layouts: main.xml and buttonpanel.xml.  In buttonpanel.xml, in main linearlayout I set gravity to bottom.  Now i am trying to add the buttonpanel layout using the following code.

```<code>setContentView(R.layout.main);
LinearLayout layout=(LinearLayout)findViewById(R.id.mainlinearlayout);
LayoutInflater inflater= (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.buttonpanel,null);
layout.addView(view);
</code>```

My problem is that the panel is added to the top though i have set gravity to bottom in buttonpanel.xml.  If I add buttonpanel.xml to main.xml using include it works fine.

Can anyone help me what is the wrong with my code?

答: you can use childview index for setting it. i think it will help you.try another method for addview which include childindex</p>

Body:
I have two layouts: main.xml and buttonpanel.xml.  In buttonpanel.xml, in main linearlayout I set gravity to bottom.  Now i am trying to add the buttonpanel layout using the following code.

setContentView(R.layout.main);
LinearLayout layout=(LinearLayout)findViewById(R.id.mainlinearlayout);
LayoutInflater inflater= (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.buttonpanel,null);
layout.addView(view);

My problem is that the panel is added to the top though i have set gravity to bottom in buttonpanel.xml.  If I add buttonpanel.xml to main.xml using include it works fine.

Can anyone help me what is the wrong with my code?

ContentLicense: CC BY-SA 2.5


问:
Calling state changing functions from mapStateToProps
I am new to react-redux and I was surprised to see an example where a function, in this case being getVisiblieTodos, is called inside mapStateToProps. This function should be called in a reducer since it changes state? Is the code breaking "good form" for the sake of brevity? Is it okay to do this in general?

I am looking at code from this link

```<code>import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList
</code>```

答:
In redux we want the store to hold the minimal data needed for the app. Everything that is derived from the base data, should be computed on the fly, to prevent cloning pieces of the store, and the need to recompute all derived data when something changes in the store.

Since the visible todos list is not part of the store, but computed using the list of todos, and the visibilityFilter, the getVisibleTodos() doesn't change the store's state. It produces the derived computed data from the those two properties.

A function that is used to get data from the store, and compute derived data is known as a selector. Using selectors, the derived data is not part of the store, and computed when needed. In addition, we can use memoized selectors, to save the computation overhead.

Body:
I am new to react-redux and I was surprised to see an example where a function, in this case being getVisiblieTodos, is called inside mapStateToProps. This function should be called in a reducer since it changes state? Is the code breaking "good form" for the sake of brevity? Is it okay to do this in general?

I am looking at code from this link

import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList


问:
SimpleMessageListenerContainer - recover from failure
What would be the easiest way to shut down SimpleMessageListenerContainer (created programatically, not as bean) on any possible error (missing queue, connection problem, etc.), and create new one (with re-declaring all the bindings in the run time.

I'm using helix for partition management, and have 1 listener per partition. One possibility would be also to use existing SimpleMessageListenerContainer (not to always create new one), but in this case, I would need to retry queue re-declaration and rebinding in case of any failure.

Also, there seems to be different kinds of exceptions - fatal (eg queue deleted in runtime) and non fatal (connection lost). How to handle both situations at once?

What would be easier option of these two?

UPDATED

```<code>private Map<SimpleMessageListenerContainer, AtomicBoolean> shuttingDown = new ConcurrentHashMap<>();

@Override
public void onApplicationEvent(ListenerContainerConsumerFailedEvent listenerContainerConsumerFailedEvent) {

    boolean fatal = listenerContainerConsumerFailedEvent.isFatal();
    SimpleMessageListenerContainer listenerContainer = (SimpleMessageListenerContainer)listenerContainerConsumerFailedEvent.getSource();

    if(fatal){
        AtomicBoolean sd = shuttingDown
                .computeIfAbsent(listenerContainer, v -> new AtomicBoolean(false));
        if(sd.compareAndSet(false, true)) {
            System.out.println("RECREATING");
            String[] qn = listenerContainer.getQueueNames();
            String q = qn[0];
            recreateQueue(q);
            listenerContainer.stop();
            listenerContainer.start();
            //delete from shuttingDown ?
        }
        else{
            System.out.println("RECREATING_NOT");
        }
    }
    else{
        System.out.println("NON_FATAL");
    }
}
</code>```

and the output

```<code>NON_FATAL
NON_FATAL
NON_FATAL
NON_FATAL
22:36:44.044 [SimpleAsyncTaskExecutor-7] ERROR org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer - Consumer received fatal=false...\
...

RECREATING
RECREATING_NOT
RECREATING_NOT
RECREATING_NOT
22:36:44.057 [SimpleAsyncTaskExecutor-6] ERROR org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer - Stopping container from aborted consumer
</code>```

答:
Add an ApplicationEventPublisher to the container; ListenerContainerConsumerFailedEvents have a fatal boolean property.

EDIT

```<code>@SpringBootApplication
public class So47357940Application {

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

    @Bean
    public ApplicationRunner runner(AmqpAdmin admin) {
        return args -> admin.deleteQueue("so47357940");
    }

    @RabbitListener(queues = "so47357940")
    public void listen(String in) {
        System.out.println(in);
    }

    private final Map<SimpleMessageListenerContainer, AtomicBoolean> shuttingDown = new ConcurrentHashMap<>();

    @Bean
    public ApplicationListener<ListenerContainerConsumerFailedEvent> failures(AmqpAdmin admin,
            RabbitTemplate template) {
        return event -> {
            if (event.isFatal()) {
                SimpleMessageListenerContainer container = (SimpleMessageListenerContainer) event.getSource();
                AtomicBoolean sd = this.shuttingDown.computeIfAbsent(container, v -> new AtomicBoolean());
                if (sd.compareAndSet(false, true)) {
                    System.out.println("RECREATING");
                    String[] qn = container.getQueueNames();
                    String q = qn[0];
                    admin.declareQueue(new Queue(q));
                    // better to use a shared exec
                    ExecutorService exec = Executors.newSingleThreadExecutor();
                    exec.execute(() -> {
                        while (container.isRunning()) {
                            // should probably give up at some point
                            try {
                                Thread.sleep(100);
                            }
                            catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                            }
                        }
                        container.start();
                        template.convertAndSend("so47357940", "foo");
                        this.shuttingDown.remove(container);
                    });
                }
                else {
                    System.out.println("RECREATING_NOT");
                }
            }
            else {
                System.out.println("NON_FATAL");
            }
        };
    }

}
</code>```

Here are the debug logs I get...

```<code>RECREATING
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.c.CachingConnectionFactory       : Creating cached Rabbit Channel from AMQChannel(amqp://guest@127.0.0.1:5672/,3)
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.amqp.rabbit.core.RabbitTemplate      : Executing callback RabbitAdmin$$Lambda$144/1094003461 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.amqp.rabbit.core.RabbitAdmin         : declaring Queue 'so47357940'
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Cancelling Consumer@3a813488: tags=[Cancelling Consumer@3a813488: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.listener.BlockingQueueConsumer   : Closing Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.c.CachingConnectionFactory       : Closing cached Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2)
2017-11-17 17:38:53.903 ERROR 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
2017-11-17 17:38:53.903 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutting down Rabbit listener container
2017-11-17 17:38:53.903  INFO 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2017-11-17 17:38:53.903  INFO 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2017-11-17 17:38:54.003 DEBUG 42372 --- [pool-4-thread-1] o.s.a.r.l.SimpleMessageListenerContainer : Starting Rabbit listener container.
2017-11-17 17:38:54.004 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Starting consumer Consumer@3a2547b8: tags=[Starting consumer Consumer@3a2547b8: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0], channel=null, acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.005 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Started on queue 'so47357940' with tag amq.ctag-3wMG_13-68ibLL05ir3ySA: Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.005 DEBUG 42372 --- [ool-1-thread-11] o.s.a.r.listener.BlockingQueueConsumer   : ConsumeOK : Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.a.r.c.CachingConnectionFactory       : Creating cached Rabbit Channel from AMQChannel(amqp://guest@127.0.0.1:5672/,4)
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.amqp.rabbit.core.RabbitTemplate      : Executing callback RabbitTemplate$$Lambda$146/1108520685 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,4), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.amqp.rabbit.core.RabbitTemplate      : Publishing message (Body:'foo' MessageProperties [headers=Publishing message (Body:'foo' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=3, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])on exchange [], routingKey = [so47357940], contentType=text/plain, contentEncoding=UTF-8, contentLength=3, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])on exchange [], routingKey = [so47357940]
2017-11-17 17:38:54.012 DEBUG 42372 --- [ool-1-thread-12] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.012 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'foo' MessageProperties [headers=Received message: (Body:'foo' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=so47357940, deliveryTag=1, consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, consumerQueue=so47357940]), contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=so47357940, deliveryTag=1, consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, consumerQueue=so47357940])
2017-11-17 17:38:54.015 DEBUG 42372 --- [cTaskExecutor-3] .a.r.l.a.MessagingMessageListenerAdapter : Processing [GenericMessage [payload=foo, headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedRoutingKey=so47357940, amqp_contentEncoding=UTF-8, amqp_deliveryTag=1, amqp_consumerQueue=so47357940, amqp_redelivered=false, id=b614d9e6-1744-b600-7d86-ca9c51ad5844, amqp_consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, contentType=text/plain, timestamp=1510958334014}]]
foo
</code>```

Body:
What would be the easiest way to shut down SimpleMessageListenerContainer (created programatically, not as bean) on any possible error (missing queue, connection problem, etc.), and create new one (with re-declaring all the bindings in the run time.

I'm using helix for partition management, and have 1 listener per partition. One possibility would be also to use existing SimpleMessageListenerContainer (not to always create new one), but in this case, I would need to retry queue re-declaration and rebinding in case of any failure.

Also, there seems to be different kinds of exceptions - fatal (eg queue deleted in runtime) and non fatal (connection lost). How to handle both situations at once?

What would be easier option of these two?

UPDATED

private Map<SimpleMessageListenerContainer, AtomicBoolean> shuttingDown = new ConcurrentHashMap<>();

@Override
public void onApplicationEvent(ListenerContainerConsumerFailedEvent listenerContainerConsumerFailedEvent) {

    boolean fatal = listenerContainerConsumerFailedEvent.isFatal();
    SimpleMessageListenerContainer listenerContainer = (SimpleMessageListenerContainer)listenerContainerConsumerFailedEvent.getSource();

    if(fatal){
        AtomicBoolean sd = shuttingDown
                .computeIfAbsent(listenerContainer, v -> new AtomicBoolean(false));
        if(sd.compareAndSet(false, true)) {
            System.out.println("RECREATING");
            String[] qn = listenerContainer.getQueueNames();
            String q = qn[0];
            recreateQueue(q);
            listenerContainer.stop();
            listenerContainer.start();
            //delete from shuttingDown ?
        }
        else{
            System.out.println("RECREATING_NOT");
        }
    }
    else{
        System.out.println("NON_FATAL");
    }
}

and the output

NON_FATAL
NON_FATAL
NON_FATAL
NON_FATAL
22:36:44.044 [SimpleAsyncTaskExecutor-7] ERROR org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer - Consumer received fatal=false...\
...

RECREATING
RECREATING_NOT
RECREATING_NOT
RECREATING_NOT
22:36:44.057 [SimpleAsyncTaskExecutor-6] ERROR org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer - Stopping container from aborted consumer

Body:
Add an ApplicationEventPublisher to the container; ListenerContainerConsumerFailedEvents have a fatal boolean property.

EDIT

@SpringBootApplication
public class So47357940Application {

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

    @Bean
    public ApplicationRunner runner(AmqpAdmin admin) {
        return args -> admin.deleteQueue("so47357940");
    }

    @RabbitListener(queues = "so47357940")
    public void listen(String in) {
        System.out.println(in);
    }

    private final Map<SimpleMessageListenerContainer, AtomicBoolean> shuttingDown = new ConcurrentHashMap<>();

    @Bean
    public ApplicationListener<ListenerContainerConsumerFailedEvent> failures(AmqpAdmin admin,
            RabbitTemplate template) {
        return event -> {
            if (event.isFatal()) {
                SimpleMessageListenerContainer container = (SimpleMessageListenerContainer) event.getSource();
                AtomicBoolean sd = this.shuttingDown.computeIfAbsent(container, v -> new AtomicBoolean());
                if (sd.compareAndSet(false, true)) {
                    System.out.println("RECREATING");
                    String[] qn = container.getQueueNames();
                    String q = qn[0];
                    admin.declareQueue(new Queue(q));
                    // better to use a shared exec
                    ExecutorService exec = Executors.newSingleThreadExecutor();
                    exec.execute(() -> {
                        while (container.isRunning()) {
                            // should probably give up at some point
                            try {
                                Thread.sleep(100);
                            }
                            catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                            }
                        }
                        container.start();
                        template.convertAndSend("so47357940", "foo");
                        this.shuttingDown.remove(container);
                    });
                }
                else {
                    System.out.println("RECREATING_NOT");
                }
            }
            else {
                System.out.println("NON_FATAL");
            }
        };
    }

}

Here are the debug logs I get...

RECREATING
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.c.CachingConnectionFactory       : Creating cached Rabbit Channel from AMQChannel(amqp://guest@127.0.0.1:5672/,3)
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.amqp.rabbit.core.RabbitTemplate      : Executing callback RabbitAdmin$$Lambda$144/1094003461 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:53.893 DEBUG 42372 --- [cTaskExecutor-2] o.s.amqp.rabbit.core.RabbitAdmin         : declaring Queue 'so47357940'
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Cancelling Consumer@3a813488: tags=[Cancelling Consumer@3a813488: tags=[{}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.listener.BlockingQueueConsumer   : Closing Rabbit Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:53.901 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.c.CachingConnectionFactory       : Closing cached Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,2)
2017-11-17 17:38:53.903 ERROR 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
2017-11-17 17:38:53.903 DEBUG 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutting down Rabbit listener container
2017-11-17 17:38:53.903  INFO 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2017-11-17 17:38:53.903  INFO 42372 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2017-11-17 17:38:54.003 DEBUG 42372 --- [pool-4-thread-1] o.s.a.r.l.SimpleMessageListenerContainer : Starting Rabbit listener container.
2017-11-17 17:38:54.004 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Starting consumer Consumer@3a2547b8: tags=[Starting consumer Consumer@3a2547b8: tags=[{}], channel=null, acknowledgeMode=AUTO local queue size=0], channel=null, acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.005 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Started on queue 'so47357940' with tag amq.ctag-3wMG_13-68ibLL05ir3ySA: Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.005 DEBUG 42372 --- [ool-1-thread-11] o.s.a.r.listener.BlockingQueueConsumer   : ConsumeOK : Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.a.r.c.CachingConnectionFactory       : Creating cached Rabbit Channel from AMQChannel(amqp://guest@127.0.0.1:5672/,4)
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.amqp.rabbit.core.RabbitTemplate      : Executing callback RabbitTemplate$$Lambda$146/1108520685 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,4), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473]
2017-11-17 17:38:54.008 DEBUG 42372 --- [pool-4-thread-1] o.s.amqp.rabbit.core.RabbitTemplate      : Publishing message (Body:'foo' MessageProperties [headers=Publishing message (Body:'foo' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=3, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])on exchange [], routingKey = [so47357940], contentType=text/plain, contentEncoding=UTF-8, contentLength=3, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])on exchange [], routingKey = [so47357940]
2017-11-17 17:38:54.012 DEBUG 42372 --- [ool-1-thread-12] o.s.a.r.listener.BlockingQueueConsumer   : Storing delivery for Consumer@3a2547b8: tags=[{amq.ctag-3wMG_13-68ibLL05ir3ySA=so47357940}], channel=Cached Rabbit Channel: AMQChannel(amqp://guest@127.0.0.1:5672/,3), conn: Proxy@48c9a496 Shared Rabbit Connection: SimpleConnection@3bdd3f4a [delegate=amqp://guest@127.0.0.1:5672/, localPort= 55473], acknowledgeMode=AUTO local queue size=0
2017-11-17 17:38:54.012 DEBUG 42372 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer   : Received message: (Body:'foo' MessageProperties [headers=Received message: (Body:'foo' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=so47357940, deliveryTag=1, consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, consumerQueue=so47357940]), contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=so47357940, deliveryTag=1, consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, consumerQueue=so47357940])
2017-11-17 17:38:54.015 DEBUG 42372 --- [cTaskExecutor-3] .a.r.l.a.MessagingMessageListenerAdapter : Processing [GenericMessage [payload=foo, headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedRoutingKey=so47357940, amqp_contentEncoding=UTF-8, amqp_deliveryTag=1, amqp_consumerQueue=so47357940, amqp_redelivered=false, id=b614d9e6-1744-b600-7d86-ca9c51ad5844, amqp_consumerTag=amq.ctag-3wMG_13-68ibLL05ir3ySA, contentType=text/plain, timestamp=1510958334014}]]
foo


问:
How to disable HTML transformation in TYPO3 8 LTS completely
In TYPO3 8.7.8 LTS and a clean installation with the setting to create one blank basis page during install and the CKEditor extension disabled when you write something in a text element (I think it is the tt_content.bodytext field) it gets transformed (
 tags added, line breaks removed etc...) even so there is no WYSIWYG-Editor enabled. So this transformation has to happen in the TYPO3 backend.

I'm trying to disable this now for a while but I failed so far. I tried the approaches from https://docs.typo3.org/typo3cms/CoreApiReference/Rte/Transformations/Tsconfig/Index.html
And here mainly

This configuration in "Page TSconfig" will disable the RTE altogether:

RTE.default.disabled = 1

To be precise my Page TSConfig looks like this and the transformation still happens:

```<code>RTE.default.proc.dontRemoveUnknownTags_db = 1
RTE.default.proc.entryHTMLparser_db = 0
RTE.default.proc.exitHTMLparser_db = 0
RTE.default.disabled = 1

RTE.config.tt_content.bodytext.proc.dontRemoveUnknownTags_db = 1
RTE.config.tt_content.bodytext.proc.entryHTMLparser_db = 0
RTE.config.tt_content.bodytext.proc.exitHTMLparser_db = 0
RTE.config.tt_content.bodytext.disabled = 1
</code>```

So the question is, how can I disable the HTML transformations completely? Do I need to add something in the TypoScript Setup (I tried a bit but no luck) or do I have to do something completely different/in a different stop than the Page TSConfig?

答:
Looking at (and debugging) \TYPO3\CMS\Core\Html\RteHtmlParser and here RTE_transform($value, $specConf = [], $direction = 'rte', $thisConfig = []) which seems to be the responsible function for the transformation of this field, I know that the transformations for my case happen in the mode foreach.

I also know that my RTE.default.disabled = 1 wasn't in the wrong place. It was part of the loaded config, however at least at this point it has no effect at all.

What has an effect is setting RTE.default.proc.overruleMode = none or RTE.default.proc.mode = none. One would do it and any string which is not a registered mode works to disable any transformation.

IMHO: The TYPO3 documentation seems as messy as its code base, maybe RTE.default.disabled = 1 has a use case somewhere and maybe you would find it if you would digg further into the documentation but I fear it may also just be an artefact from some old version which most of this pre- and postprocessing logic seems to be (and from what I've seen here in the last two hours I'm not confident other parts of this framework are 'modern', the mere amount of db queries for simplest backend tasks indicates I could be right). Anyways, my problem is solved and good luck to anyone who also needs to work with this reptile from the past for some reason.

tl;dr: set RTE.default.proc.overruleMode = none in your Page TSConfig

Body:
In TYPO3 8.7.8 LTS and a clean installation with the setting to create one blank basis page during install and the CKEditor extension disabled when you write something in a text element (I think it is the tt_content.bodytext field) it gets transformed (
 tags added, line breaks removed etc...) even so there is no WYSIWYG-Editor enabled. So this transformation has to happen in the TYPO3 backend.

I'm trying to disable this now for a while but I failed so far. I tried the approaches from https://docs.typo3.org/typo3cms/CoreApiReference/Rte/Transformations/Tsconfig/Index.html
And here mainly

This configuration in "Page TSconfig" will disable the RTE altogether:

RTE.default.disabled = 1

To be precise my Page TSConfig looks like this and the transformation still happens:

RTE.default.proc.dontRemoveUnknownTags_db = 1
RTE.default.proc.entryHTMLparser_db = 0
RTE.default.proc.exitHTMLparser_db = 0
RTE.default.disabled = 1

RTE.config.tt_content.bodytext.proc.dontRemoveUnknownTags_db = 1
RTE.config.tt_content.bodytext.proc.entryHTMLparser_db = 0
RTE.config.tt_content.bodytext.proc.exitHTMLparser_db = 0
RTE.config.tt_content.bodytext.disabled = 1

So the question is, how can I disable the HTML transformations completely? Do I need to add something in the TypoScript Setup (I tried a bit but no luck) or do I have to do something completely different/in a different stop than the Page TSConfig?


问:
thermometer class logic error
I'm trying to make a class that has a single constructor that accepts a temperature (in Celsius) as a double, and if the temperature is less than -273.15, it sets it to -273.15. It also calculates other temperatures for different units of measurement, but that's not important. For some reason, I'm getting a logic error that doesn't correct inputs less than -273.15 to -273.15.

```<code>public class TemperatureC
{

private double temperature;

public TemperatureC(double c)
{
    if (temperature < -273.15)
    {
        temperature = -273.15;
    }
    else
    {
        temperature = c;
    }
}

public TemperatureC()
{
    temperature = -273.15;
}

public double getC()
{
    return temperature;
}

public double getF()
{
    return ((temperature * 1.8) + 32);
}

public double getK()
{
    return (temperature + 273.15);
}

public void setC(double c)
{
    if (temperature >= -273.15)
    {
        temperature = c;
    }

}

}
</code>```

And this is what's using the class.

```<code>import java.util.Scanner;

public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();

System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);

System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());

System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);

System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());

}
}
</code>```

And here is my faulty output:

```<code>Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
</code>```

It should correct inputs less than -273.15 to -273.15.

答:
You're only checking for temperate < -273.15 in the constructor, so any time you call setC then you won't correct it.  Additionally, in the setC method you don't set the temperature at all unless it's at or above -273.15

You could remove the constructor altogether since you aren't calling it anyway and change the logic in setC to check for temperates < -273.15

Title: thermometer class logic error

Body:
I'm trying to make a class that has a single constructor that accepts a temperature (in Celsius) as a double, and if the temperature is less than -273.15, it sets it to -273.15. It also calculates other temperatures for different units of measurement, but that's not important. For some reason, I'm getting a logic error that doesn't correct inputs less than -273.15 to -273.15.

public class TemperatureC
{

private double temperature;

public TemperatureC(double c)
{
    if (temperature < -273.15)
    {
        temperature = -273.15;
    }
    else
    {
        temperature = c;
    }
}

public TemperatureC()
{
    temperature = -273.15;
}

public double getC()
{
    return temperature;
}

public double getF()
{
    return ((temperature * 1.8) + 32);
}

public double getK()
{
    return (temperature + 273.15);
}

public void setC(double c)
{
    if (temperature >= -273.15)
    {
        temperature = c;
    }

}

}

And this is what's using the class.

import java.util.Scanner;

public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();

System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);

System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());

System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);

System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());

}
}

And here is my faulty output:

Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85

It should correct inputs less than -273.15 to -273.15.


问:
why does git treat some cpp files as binary?
here's output of git log :

```<code>* 5a831fdb34f05edd62321d1193a96b8f96486d69      HEAD (HEAD, origin/work, work)
|  LIB/xxx.cpp                        |  Bin 592994 -> 593572 bytes
|  LIB/xxx.h                          |    5 +++++
|  LIB/bbb/xxx.h                      |    9 +++++++++
|  LIB/aaa/xxx.cpp                    |  Bin 321534 -> 321536 bytes
|  LIB/aaa/yyy.cpp                    |   31 +++++++------------------------
|  tests/aaa/xxx.cpp                  |   29 +++++++++++++++++++++++++++++
|  tests/test_xxx.vcproj              |    4 ++++
|  7 files changed, 54 insertions(+), 24 deletions(-)
</code>```

why is it treating some files as binary, and others not? This gives serious problems since git also doesn't want to automatically merge them.. Hence pretty much all merge/rebase/pull actions become a pain.

Here's the repo config:

```<code>[core]
  repositoryformatversion = 0
  filemode = false
  bare = false
  logallrefupdates = true
  symlinks = false
  ignorecase = true
  hideDotFiles = dotGitOnly
[remote "origin"]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = https://xxx/project.git
[branch "master"]
  remote = origin
  merge = refs/heads/master
[branch "work"]
  remote = origin
  merge = refs/heads/work
[svn-remote "svn"]
  url = xxxx
  fetch = :refs/remotes/git-svn
</code>```

also core.autocrlf = false in the main .gitconfig.

edit
I set core.autocrlf to true as suggested in the comments, but this doesn't seem to affect the next merge I'm after (maybe it's too late now to change autocrlf? or is it unrelated to the problem?):

```<code>> git merge work
warning: Cannot merge binary files: LIB/xxx.cpp (HEAD vs. work)

warning: Cannot merge binary files: LIB/aaa/xxx.cpp (HEAD vs. work)

Auto-merging LIB/xxx.cpp
CONFLICT (content): Merge conflict in LLIB/xxx.cpp
Auto-merging LIB/xxx.h
Auto-merging LIB/aaa/xxx.cpp
CONFLICT (content): Merge conflict in LIB/aaa/xxx.cpp
Automatic merge failed; fix conflicts and then commit the result.
</code>```

Also now gits insist on changing lineendings in a couple of files (which is what I do not want).

答:
Try adding the following line to your $repo/.git/info/attributes:

```<code>*.cpp crlf diff
</code>```

You can specify it in gitattributes per-repo, per-user and per-system.

Basic check-list

• Do you actually have CRLF or LF line endings in your file?

 Yes, CRLF — set core.autocrlf to true (at least for this repo).

• Does the file contain funny non-ASCII characters: umlauts, diacritics, emoji, kanji, copyright sigil ©, invisible esoteric spaces, etc?..

 If yes, better ensure that all the stuff is encoded in UTF-8. Fuzzing  with surrogate pairs isn't fun.

• Does the file content start with UTF-8 BOM?

 Wipe it now, it makes no sense.

• Does the file content start with UTF16 BOM?

 Too bad; I've got no good advice for you at this point; sorry. Contact your system vendor.

ContentLicense: CC BY-SA 4.0

Body:
here's output of git log :

* 5a831fdb34f05edd62321d1193a96b8f96486d69      HEAD (HEAD, origin/work, work)
|  LIB/xxx.cpp                        |  Bin 592994 -> 593572 bytes
|  LIB/xxx.h                          |    5 +++++
|  LIB/bbb/xxx.h                      |    9 +++++++++
|  LIB/aaa/xxx.cpp                    |  Bin 321534 -> 321536 bytes
|  LIB/aaa/yyy.cpp                    |   31 +++++++------------------------
|  tests/aaa/xxx.cpp                  |   29 +++++++++++++++++++++++++++++
|  tests/test_xxx.vcproj              |    4 ++++
|  7 files changed, 54 insertions(+), 24 deletions(-)

why is it treating some files as binary, and others not? This gives serious problems since git also doesn't want to automatically merge them.. Hence pretty much all merge/rebase/pull actions become a pain.

Here's the repo config:

[core]
  repositoryformatversion = 0
  filemode = false
  bare = false
  logallrefupdates = true
  symlinks = false
  ignorecase = true
  hideDotFiles = dotGitOnly
[remote "origin"]
  fetch = +refs/heads/*:refs/remotes/origin/*
  url = https://xxx/project.git
[branch "master"]
  remote = origin
  merge = refs/heads/master
[branch "work"]
  remote = origin
  merge = refs/heads/work
[svn-remote "svn"]
  url = xxxx
  fetch = :refs/remotes/git-svn

also core.autocrlf = false in the main .gitconfig.

edit
I set core.autocrlf to true as suggested in the comments, but this doesn't seem to affect the next merge I'm after (maybe it's too late now to change autocrlf? or is it unrelated to the problem?):

> git merge work
warning: Cannot merge binary files: LIB/xxx.cpp (HEAD vs. work)

warning: Cannot merge binary files: LIB/aaa/xxx.cpp (HEAD vs. work)

Auto-merging LIB/xxx.cpp
CONFLICT (content): Merge conflict in LLIB/xxx.cpp
Auto-merging LIB/xxx.h
Auto-merging LIB/aaa/xxx.cpp
CONFLICT (content): Merge conflict in LIB/aaa/xxx.cpp
Automatic merge failed; fix conflicts and then commit the result.

Also now gits insist on changing lineendings in a couple of files (which is what I do not want).

Body:
Try adding the following line to your $repo/.git/info/attributes:

*.cpp crlf diff

You can specify it in gitattributes per-repo, per-user and per-system.

Basic check-list

• Do you actually have CRLF or LF line endings in your file?

 Yes, CRLF — set core.autocrlf to true (at least for this repo).

• Does the file contain funny non-ASCII characters: umlauts, diacritics, emoji, kanji, copyright sigil ©, invisible esoteric spaces, etc?..

 If yes, better ensure that all the stuff is encoded in UTF-8. Fuzzing  with surrogate pairs isn't fun.

• Does the file content start with UTF-8 BOM?

 Wipe it now, it makes no sense.

• Does the file content start with UTF16 BOM?

 Too bad; I've got no good advice for you at this point; sorry. Contact your system vendor.


问:
How can I export issues from IBM Cloud's Git Repos and Issue Tracking
I have a project on IBM Cloud's Git Repos and Issue Tracking service (built on GitLab CE) at https://git.ng.bluemix.net.  I'd like to export the issues in my project for reporting purposes, but I don't see any option provided in the project UI.  Is there some way to export my project's issues into a spreadsheet?</p>

答:
I just wrote a blog post on this on IBM developer works, entitled Getting Data from your IBM Cloud GitHub Project.  The blog is short, its a quick read.

The the code I used (Python 2.7) is out on GitHub, in a project called IBMCloud_GitLab_CSV.  It probably doesn't do exactly what you want, but the code is pretty simple and it does dump the data into a CSV file which you can use.


问:
Getting std::bad_alloc in Release but not in Debug
I just don't know what to do with it...

The functions runs well in debug, but not in release.

I am trying to learn about artificial neural networks and C++ vectors.

Here is the code (in Python 2.7) that I'm writing in C++:

http://neuralnetworksanddeeplearning.com/chap1.html#exercise_852508

(just scroll a little to reach it)

I'm using MinGW 7.2.0 from MSYS2 (C++11).

There are some "teste" prints inside the backpropagation method, that is where the problem is comming from (I guess). I also overloaded operators +, - and * to make things easier.

I know that there are some libs like Armadillo that could make things easier, but I really wanna use this problem to learn better.

And here is the files:

neuralnetwork.h

(I made everything public to make things easier to look at)

```<code>#define MIN_NUMBER_TOLERANCE 1e-8

namespace nn
{
    class neuralnetwork
    {
    //private:
    public:
        //total number of weights. useful to reserve memory
        int numWeights;
        //total number of biases. useful to reserve memory
        int numBiases;
        //total number of layers: 1 for input, n hidden layers and 1 for output
        int numLayers;
        //a vector to store the number of neurons in each layer: 0 index is about the input layer, last index is about the output layer
        std::vector<int> sizes;
        //stores all biases: num of neurons of layer 1 + ... + num of neurons of layer (numLayers - 1) (input layer has no bias)
        std::vector<std::vector<double>> biases;
        //stores all weights: (num of neurons of layer 1) x (num of neurons of layer ) + ... + ( num of neurons of layer (numLayers - 1) ) x ( num of neurons of layer (numLayers - 2) ) (input layer has no bias)
        std::vector<std::vector<std::vector<double>>> weights;
        //stores the output of each neuron of each layer
        std::vector<std::vector<double>> layersOutput;

        std::vector<std::vector<std::vector<double>>> derivativeWeights;
        std::vector<std::vector<double>> derivativeBiases;

        std::default_random_engine generator;
        std::normal_distribution<double> distribution;

        double randomNormalNumber(void);

        double costDerivatives(const double&, const double&);

        std::vector<double> costDerivatives(const std::vector<double> &, const std::vector<double> &);

        void backPropagation(const std::vector<double>& neuralNetworkInputs, const std::vector<double>& expectedOutputs, // inputs
                      std::vector<std::vector<std::vector<double>>>& derivativeWeights, std::vector<std::vector<double>>& derivativeBiases); // outputs

        void update_mini_batch( const std::vector<std::pair<std::vector<double>,std::vector<double>>> & mini_batch, double eta);

    //public:

        neuralnetwork(const std::vector<int>& sizes);

        std::vector<double> feedforward(const std::vector<double>&);
    };

    std::vector<double> sigmoid(const std::vector<double> &);
    double sigmoid(double);
    std::vector<double> sigmoid_prime(const std::vector<double> &);
    //double sigmoid_prime(double);

}
</code>```

neuralnetwork.cpp

```<code>#include "neuralnetwork.h"
#include <iostream>
#include <assert.h>
#include <algorithm>

namespace nn
{
    int counter = 0;

    neuralnetwork::neuralnetwork(const std::vector<int> &sizes)
    {
        this->distribution = std::normal_distribution<double>( 0.0 , 1.0 );

        this->numLayers = sizes.size();
        this->sizes = sizes;

        this->numWeights = 0;
        this->numBiases = 0;

        for ( int i = 1 ; i < this->numLayers ; i++ )
        {
            numWeights += this->sizes[ i ] * this->sizes[ i - 1 ];
            numBiases += this->sizes[ i ];
        }

        this->weights.reserve( numWeights );
        this->biases.reserve( numBiases );

        this->derivativeWeights.reserve( numWeights );
        this->derivativeBiases.reserve( numBiases );

        this->layersOutput.reserve( this->sizes[ 0 ] + numBiases );

        std::vector<double> auxVectorWeights;
        std::vector<std::vector<double> > auxMatrixWeights;

        std::vector<double> auxVectorBiases;

#ifdef DEBUG_BUILD
        std::cout << "debugging!\n";
#endif

        //just to accommodate the input layer with null biases and inputs (makes things easier to iterate and reading :D).
        this->layersOutput.push_back( std::vector<double>( this->sizes[ 0 ] ) );
        std::vector<std::vector<double>> matrixNothing( 0 );
        this->weights.push_back( matrixNothing );
        this->biases.push_back( std::vector<double>( 0 ) );

        //since the second layer (index 1) because there is no weights (nor biases) for the neurons of the first layer
        for ( int layer = 1 ; layer < this->numLayers ; layer++ )
        {
            //preallocate memory for the output of each layer.
            layersOutput.push_back( std::vector<double>( this->sizes[ layer ] ) );

            //-----------weights begin--------------
            //auxMatrixWeights will store the weights connections between one layer (number of columns) and its subsequent layer (number of rows)
            //auxMatrixWeights = new std::vector(this->sizes[layer], std::vector<double>( this->sizes[layer - 1] )); // it is not working...

            //size[layer] stores the number of neurons on the layer
            for ( int i = 0 ; i < this->sizes[ layer ] ; i++ )
            {
                //auxVectorWeights will have the size of the amount of wights necessary to connect the neuron i (from this layer) to neuron j (from next layer)
                auxVectorWeights = std::vector<double>( this->sizes[ layer - 1 ] );

                for ( int j = 0 ; j < auxVectorWeights.size() ; j++ )
                {
                    auxVectorWeights[ j ] = this->randomNormalNumber();
                }

                auxMatrixWeights.push_back( auxVectorWeights );
            }

            this->weights.push_back( auxMatrixWeights );

            auxMatrixWeights.clear();

            //-----------weights end----------------

            //-----------biases begin---------------
            auxVectorBiases = std::vector<double>( this->sizes[ layer ] );

            for ( int i = 0 ; i < auxVectorBiases.size() ; i++ )
            {
                auxVectorBiases[ i ] = this->randomNormalNumber();
            }

            this->biases.push_back( auxVectorBiases );
            //-----------biases end-----------------
        }

#ifdef _DEBUG
        for ( int i = 0 ; i < this->weights.size() ; i++ )
        {
            std::cout << "layer " << i << "\n";
            for ( int j = 0 ; j < this->weights[ i ].size() ; j++ )
            {
                std::cout << "neuron" << j << std::endl;
                for ( const auto k : this->weights[ i ][ j ] )
                {
                    std::cout << '\t' << k << ' ';
                }
                std::cout << std::endl;
            }
        }
#endif
    }

    template <class T>
    inline int lastIndex(std::vector<T> vector , int tail)
    {
        return (vector.size() - tail);
    }

    double neuralnetwork::randomNormalNumber(void)
    {
        return this->distribution( this->generator );
    }

    double sigmoid(double z)
    {
        return 1.0 / ( 1.0 + exp( -z ) );
    }

    std::vector<double> sigmoid(const std::vector<double> & z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(0);
            output[i] = 1.0 / ( 1.0 + exp( -z[i] ) );
        }

        return output;
    }

    /*double sigmoid_prime(double z)
    {
        return sigmoid( z ) * ( 1 - sigmoid( z ) );
    }*/

    std::vector<double> sigmoid_prime(const std::vector<double>& z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(sigmoid( z[i] ) * ( 1 - sigmoid( z[i] ) ) );
        }

        return output;
    }

    //scalar times vector
    std::vector<double> operator* (double a , const std::vector<double> & b)
    {
        int size = b.size();

        std::vector<double> result(size);

        for ( int i = 0 ; i < size ; i++ )
        {
            result[i] = a * b[ i ];
        }

        return result;
    }

    // inner product
    std::vector<double> operator* (const std::vector<double> & a , const std::vector<double> & b)
    {

#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size(); // or b.size(). they should have the same size.

        std::vector<double> result;
        result.reserve(size); // or b.size(). they should have the same size.

        for ( int i = 0 ; i < size ; i++ )
        {
            result.push_back( a[ i ] * b[ i ] );
        }

        return result;
    }

    //matrix times columns vector
    std::vector<double> operator* (const std::vector<std::vector<double>> & a , const std::vector<double> & b)
    {
#ifdef _DEBUG
        assert(a[0].size() == b.size());

        for(int i = 0 ; i < ( lastIndex( a , 1 )) ; i++)
        {
            assert(a[i].size() == a[i+1].size());
        }
#endif

        int lines = a.size();
        int columns = a[0].size();

        std::vector<double> result;
        result.reserve(lines);

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(0);
            for(j = 0 ; j < columns ; j++)
            {
                result[i] += a[ i ][ j ] * b[ j ];
            }
        }

        return result;
    }

    //scalar times matrix (calls scalar times vector)
    std::vector<std::vector<double>> operator* (double a , const std::vector<std::vector<double>> & b)
    {
#ifdef _DEBUG
        for(int i = 0 ; i < b.size()-1 ; i++)
        {
            assert(b[i].size() == b[i+1].size());
        }
#endif

        int lines = b.size();
        int columns = b[0].size();

        std::vector<std::vector<double>> result;

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(a * b[ j ]);
        }

        return result;
    }

    std::vector<double> operator+(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(0);
            result[i] = a[i] + b[i];
        }

        return result;
    }

    //sum of matrices
    std::vector<std::vector<double>> operator+(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] + b[i]);
        }

        return result;
    }

    //subtraction of vectors
    std::vector<double> operator-(const std::vector<double>& a, const std::vector<double>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

        std::vector<double> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result[i] = a[i] - b[i];
        }

        return result;
    }

    //subtraction of matrices (calls subtraction of vectors)
    std::vector<std::vector<double>> operator-(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] - b[i]);
        }

        return result;
    }

    //elementwise division
    std::vector<double> operator/(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            if(b[i] < MIN_NUMBER_TOLERANCE)
            {
                throw std::runtime_error("Can't divide by zero!");
            }
            result[i] = a[i] / b[i];
        }

        return result;
    }

    double neuralnetwork::costDerivatives(const double &networkOutput , const double &expectedOutput)
    {
        return expectedOutput - networkOutput;
    }

    std::vector<double> neuralnetwork::costDerivatives(const std::vector<double> &networkOutput , const std::vector<double> &expectedOutput)
    {
        assert(expectedOutput.size() == networkOutput.size());
        int size = networkOutput.size();
        std::vector<double> output;
        output.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            output.push_back(networkOutput[i] - expectedOutput[i]);
        }

        return output;
    }

    void neuralnetwork::backPropagation(const std::vector<double> &neuralNetworkInputs , const std::vector<double> &expectedOutputs, // inputs
                                        std::vector<std::vector<std::vector<double>>>& derivativeWeights , std::vector<std::vector<double>>& derivativeBiases) // outputs
    {

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.reserve( sizes.size() - 1 );
        derivativeBiases.reserve( sizes.size() - 1 );

        //to store one activation layer
        std::vector<double> activation = neuralNetworkInputs;
        //to store each one of the activation layers
        std::vector<std::vector<double>> activations;

        activations.reserve(sizes.size()); // numBiases is the same as the number of neurons (except 1st layer)
        activations.push_back(activation);
        int maxLayerSize = 0;

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        for ( int i = 1 ; i < numBiases ; i++ )
        {
            maxLayerSize = std::max(sizes[i], maxLayerSize);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        // to store one weighted sum
        std::vector<double> z;
        z.reserve(maxLayerSize);
        // to store each one of the weighted sums
        std::vector<std::vector<double>> zs;
        zs.reserve(sizes.size());

        // layer and neuron counter
        int layer, neuron;

        for ( layer = 1 ; layer < numLayers ; layer++ )
        {
            z = (weights[layer] * activation) + biases[layer];
            zs.push_back(z);
            activation = sigmoid(z);
            activations.push_back(activation);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        std::vector<double> delta = costDerivatives(activations[ lastIndex( activations , 1 )] , expectedOutputs) * sigmoid_prime(z);
        delta.reserve(maxLayerSize);

        derivativeBiases.push_back(delta);

        int j;

        std::vector<std::vector<double>> dummyMatrix;
        dummyMatrix.reserve(maxLayerSize);

        for (neuron = 0; neuron < sizes[ lastIndex( sizes , 1 )]; neuron++)
        {
            dummyMatrix.push_back(std::vector<double>(activations[ lastIndex( activations , 2 )].size()));
            for (j = 0; j < activations[ lastIndex( activations , 2 )].size(); j++)
            {
                dummyMatrix[neuron][j] = delta[neuron] * activations[ lastIndex( activations , 2 )][j];
            }
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.push_back(dummyMatrix);
        dummyMatrix.clear();

        std::vector<double> sp;
        sp.reserve(maxLayerSize);

        std::vector<double> dummyVector;
        dummyVector.reserve(maxLayerSize);

        double dummyDouble = 0;

        for(layer = 2 ; layer < numLayers ; layer++)
        {
            z = zs[ lastIndex( zs , layer )];
            sp = sigmoid_prime(z);

            for(j = 0 ; j < sizes[ lastIndex( weights , layer )] ; j++)
            {
                for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer - 1 )]; neuron++)
                {
                    dummyDouble += weights[ lastIndex( weights , layer - 1 )][neuron][j] * delta[neuron];
                }
                dummyVector.push_back(dummyDouble * sp[j]);
                dummyDouble = 0;
            }
            delta = dummyVector;
            dummyVector.clear();

            derivativeBiases.push_back(delta);

            for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer )]; neuron++)
            {
                dummyMatrix.push_back(std::vector<double>(sizes[ lastIndex( sizes , layer + 1 )]));
                for (j = 0; j < sizes[ lastIndex( sizes , layer + 1 )]; j++)
                {
                    dummyMatrix[neuron][j] = activations[ lastIndex( activations , layer + 1 )][j] * delta[neuron];
                }
            }
            derivativeWeights.push_back(dummyMatrix);
            dummyMatrix.clear();
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        //both derivativeWeights and derivativeBiases are reversed. so let's reverse it.
        std::reverse(derivativeWeights.begin(),derivativeWeights.end());
        std::reverse(derivativeBiases.begin(),derivativeBiases.end());

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

    }
}
</code>```

main.cpp

```<code>#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "neuralnetwork.h"
#include <string>

void printAll(const std::vector<double> & v, const std::string & name)
{
    int size = v.size();

    std::cout << "\t" <<  name << ":\t";

    for(int i = 0 ; i < size ; i++)
    {
        std::cout << v[i] << "\t";
    }

    std::cout << std::endl;
}

template<class T>
void printAll(const std::vector<T> & v, const std::string & name)
{
    int size = v.size();

    std::cout << name << ":" << std::endl;

    for(int i = 0 ; i < size ; i++)
    {
        printAll(v[i], "\t" + ("[" + std::to_string(i)) + "]");
    }
}

int main(int argc, char** argv )
{

    nn::neuralnetwork n({2,4,3});

    n.weights = {{},{{1,2},{3,4},{5,6},{7,8}} , {{9,8,7,6},{5,4,3,2},{1,2,3,4}}};
    n.biases = {{},{1, 4, 6, 8} , {9, 2, 4}};

    printAll(n.weights,"weights");
    printAll(n.biases,"biases");

    std::vector<std::vector<std::vector<double>>> derivativeWeights;
    std::vector<std::vector<double>> derivativeBiases;
    n.backPropagation({1,2},{1,2,3},derivativeWeights,derivativeBiases);

    printAll(n.derivativeWeights,"derivativeWeights");
    printAll(n.derivativeBiases,"derivativeBiases");

    system("PAUSE");

    return 0;
}
</code>```

答:
I didn't found the problem, but I realised that, for this problem (artificial neural network), I can initialize each property of the class with each right sizes without loss of generality. So this is what I'm going to do.

I feel a little ashamed that I am not finding it... :/

Body:
I just don't know what to do with it...

The functions runs well in debug, but not in release.

I am trying to learn about artificial neural networks and C++ vectors.

Here is the code (in Python 2.7) that I'm writing in C++:

http://neuralnetworksanddeeplearning.com/chap1.html#exercise_852508

(just scroll a little to reach it)

I'm using MinGW 7.2.0 from MSYS2 (C++11).

There are some "teste" prints inside the backpropagation method, that is where the problem is comming from (I guess). I also overloaded operators +, - and * to make things easier.

I know that there are some libs like Armadillo that could make things easier, but I really wanna use this problem to learn better.

And here is the files:

neuralnetwork.h

(I made everything public to make things easier to look at)

#define MIN_NUMBER_TOLERANCE 1e-8

namespace nn
{
    class neuralnetwork
    {
    //private:
    public:
        //total number of weights. useful to reserve memory
        int numWeights;
        //total number of biases. useful to reserve memory
        int numBiases;
        //total number of layers: 1 for input, n hidden layers and 1 for output
        int numLayers;
        //a vector to store the number of neurons in each layer: 0 index is about the input layer, last index is about the output layer
        std::vector<int> sizes;
        //stores all biases: num of neurons of layer 1 + ... + num of neurons of layer (numLayers - 1) (input layer has no bias)
        std::vector<std::vector<double>> biases;
        //stores all weights: (num of neurons of layer 1) x (num of neurons of layer ) + ... + ( num of neurons of layer (numLayers - 1) ) x ( num of neurons of layer (numLayers - 2) ) (input layer has no bias)
        std::vector<std::vector<std::vector<double>>> weights;
        //stores the output of each neuron of each layer
        std::vector<std::vector<double>> layersOutput;

        std::vector<std::vector<std::vector<double>>> derivativeWeights;
        std::vector<std::vector<double>> derivativeBiases;

        std::default_random_engine generator;
        std::normal_distribution<double> distribution;

        double randomNormalNumber(void);

        double costDerivatives(const double&, const double&);

        std::vector<double> costDerivatives(const std::vector<double> &, const std::vector<double> &);

        void backPropagation(const std::vector<double>& neuralNetworkInputs, const std::vector<double>& expectedOutputs, // inputs
                      std::vector<std::vector<std::vector<double>>>& derivativeWeights, std::vector<std::vector<double>>& derivativeBiases); // outputs

        void update_mini_batch( const std::vector<std::pair<std::vector<double>,std::vector<double>>> & mini_batch, double eta);

    //public:

        neuralnetwork(const std::vector<int>& sizes);

        std::vector<double> feedforward(const std::vector<double>&);
    };

    std::vector<double> sigmoid(const std::vector<double> &);
    double sigmoid(double);
    std::vector<double> sigmoid_prime(const std::vector<double> &);
    //double sigmoid_prime(double);

}

neuralnetwork.cpp

#include "neuralnetwork.h"
#include <iostream>
#include <assert.h>
#include <algorithm>

namespace nn
{
    int counter = 0;

    neuralnetwork::neuralnetwork(const std::vector<int> &sizes)
    {
        this->distribution = std::normal_distribution<double>( 0.0 , 1.0 );

        this->numLayers = sizes.size();
        this->sizes = sizes;

        this->numWeights = 0;
        this->numBiases = 0;

        for ( int i = 1 ; i < this->numLayers ; i++ )
        {
            numWeights += this->sizes[ i ] * this->sizes[ i - 1 ];
            numBiases += this->sizes[ i ];
        }

        this->weights.reserve( numWeights );
        this->biases.reserve( numBiases );

        this->derivativeWeights.reserve( numWeights );
        this->derivativeBiases.reserve( numBiases );

        this->layersOutput.reserve( this->sizes[ 0 ] + numBiases );

        std::vector<double> auxVectorWeights;
        std::vector<std::vector<double> > auxMatrixWeights;

        std::vector<double> auxVectorBiases;

#ifdef DEBUG_BUILD
        std::cout << "debugging!\n";
#endif

        //just to accommodate the input layer with null biases and inputs (makes things easier to iterate and reading :D).
        this->layersOutput.push_back( std::vector<double>( this->sizes[ 0 ] ) );
        std::vector<std::vector<double>> matrixNothing( 0 );
        this->weights.push_back( matrixNothing );
        this->biases.push_back( std::vector<double>( 0 ) );

        //since the second layer (index 1) because there is no weights (nor biases) for the neurons of the first layer
        for ( int layer = 1 ; layer < this->numLayers ; layer++ )
        {
            //preallocate memory for the output of each layer.
            layersOutput.push_back( std::vector<double>( this->sizes[ layer ] ) );

            //-----------weights begin--------------
            //auxMatrixWeights will store the weights connections between one layer (number of columns) and its subsequent layer (number of rows)
            //auxMatrixWeights = new std::vector(this->sizes[layer], std::vector<double>( this->sizes[layer - 1] )); // it is not working...

            //size[layer] stores the number of neurons on the layer
            for ( int i = 0 ; i < this->sizes[ layer ] ; i++ )
            {
                //auxVectorWeights will have the size of the amount of wights necessary to connect the neuron i (from this layer) to neuron j (from next layer)
                auxVectorWeights = std::vector<double>( this->sizes[ layer - 1 ] );

                for ( int j = 0 ; j < auxVectorWeights.size() ; j++ )
                {
                    auxVectorWeights[ j ] = this->randomNormalNumber();
                }

                auxMatrixWeights.push_back( auxVectorWeights );
            }

            this->weights.push_back( auxMatrixWeights );

            auxMatrixWeights.clear();

            //-----------weights end----------------

            //-----------biases begin---------------
            auxVectorBiases = std::vector<double>( this->sizes[ layer ] );

            for ( int i = 0 ; i < auxVectorBiases.size() ; i++ )
            {
                auxVectorBiases[ i ] = this->randomNormalNumber();
            }

            this->biases.push_back( auxVectorBiases );
            //-----------biases end-----------------
        }

#ifdef _DEBUG
        for ( int i = 0 ; i < this->weights.size() ; i++ )
        {
            std::cout << "layer " << i << "\n";
            for ( int j = 0 ; j < this->weights[ i ].size() ; j++ )
            {
                std::cout << "neuron" << j << std::endl;
                for ( const auto k : this->weights[ i ][ j ] )
                {
                    std::cout << '\t' << k << ' ';
                }
                std::cout << std::endl;
            }
        }
#endif
    }

    template <class T>
    inline int lastIndex(std::vector<T> vector , int tail)
    {
        return (vector.size() - tail);
    }

    double neuralnetwork::randomNormalNumber(void)
    {
        return this->distribution( this->generator );
    }

    double sigmoid(double z)
    {
        return 1.0 / ( 1.0 + exp( -z ) );
    }

    std::vector<double> sigmoid(const std::vector<double> & z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(0);
            output[i] = 1.0 / ( 1.0 + exp( -z[i] ) );
        }

        return output;
    }

    /*double sigmoid_prime(double z)
    {
        return sigmoid( z ) * ( 1 - sigmoid( z ) );
    }*/

    std::vector<double> sigmoid_prime(const std::vector<double>& z)
    {
        int max = z.size();
        std::vector<double> output;
        output.reserve(max);

        for(int i=0;i<max;i++)
        {
            output.push_back(sigmoid( z[i] ) * ( 1 - sigmoid( z[i] ) ) );
        }

        return output;
    }

    //scalar times vector
    std::vector<double> operator* (double a , const std::vector<double> & b)
    {
        int size = b.size();

        std::vector<double> result(size);

        for ( int i = 0 ; i < size ; i++ )
        {
            result[i] = a * b[ i ];
        }

        return result;
    }

    // inner product
    std::vector<double> operator* (const std::vector<double> & a , const std::vector<double> & b)
    {

#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size(); // or b.size(). they should have the same size.

        std::vector<double> result;
        result.reserve(size); // or b.size(). they should have the same size.

        for ( int i = 0 ; i < size ; i++ )
        {
            result.push_back( a[ i ] * b[ i ] );
        }

        return result;
    }

    //matrix times columns vector
    std::vector<double> operator* (const std::vector<std::vector<double>> & a , const std::vector<double> & b)
    {
#ifdef _DEBUG
        assert(a[0].size() == b.size());

        for(int i = 0 ; i < ( lastIndex( a , 1 )) ; i++)
        {
            assert(a[i].size() == a[i+1].size());
        }
#endif

        int lines = a.size();
        int columns = a[0].size();

        std::vector<double> result;
        result.reserve(lines);

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(0);
            for(j = 0 ; j < columns ; j++)
            {
                result[i] += a[ i ][ j ] * b[ j ];
            }
        }

        return result;
    }

    //scalar times matrix (calls scalar times vector)
    std::vector<std::vector<double>> operator* (double a , const std::vector<std::vector<double>> & b)
    {
#ifdef _DEBUG
        for(int i = 0 ; i < b.size()-1 ; i++)
        {
            assert(b[i].size() == b[i+1].size());
        }
#endif

        int lines = b.size();
        int columns = b[0].size();

        std::vector<std::vector<double>> result;

        int j = 0;

        for ( int i = 0 ; i < lines ; i++ )
        {
            result.push_back(a * b[ j ]);
        }

        return result;
    }

    std::vector<double> operator+(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(0);
            result[i] = a[i] + b[i];
        }

        return result;
    }

    //sum of matrices
    std::vector<std::vector<double>> operator+(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] + b[i]);
        }

        return result;
    }

    //subtraction of vectors
    std::vector<double> operator-(const std::vector<double>& a, const std::vector<double>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

        std::vector<double> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result[i] = a[i] - b[i];
        }

        return result;
    }

    //subtraction of matrices (calls subtraction of vectors)
    std::vector<std::vector<double>> operator-(const std::vector<std::vector<double>>& a, const std::vector<std::vector<double>>& b)
    {
#ifdef _DEBUG
        assert(a.size() == b.size());
#endif

        int size = a.size();

#ifdef _DEBUG
        for(int i = 0 ; i < size ; i++)
        {
            assert(a[i].size() == b[i].size());
        }
#endif

        std::vector<std::vector<double>> result;
        result.resize(size);

        for(int i = 0 ; i < size ; i++)
        {
            result.push_back(a[i] - b[i]);
        }

        return result;
    }

    //elementwise division
    std::vector<double> operator/(const std::vector<double>& a, const std::vector<double>& b)
    {
        assert(a.size() == b.size());

        int size = a.size();

        std::vector<double> result;
        result.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            if(b[i] < MIN_NUMBER_TOLERANCE)
            {
                throw std::runtime_error("Can't divide by zero!");
            }
            result[i] = a[i] / b[i];
        }

        return result;
    }

    double neuralnetwork::costDerivatives(const double &networkOutput , const double &expectedOutput)
    {
        return expectedOutput - networkOutput;
    }

    std::vector<double> neuralnetwork::costDerivatives(const std::vector<double> &networkOutput , const std::vector<double> &expectedOutput)
    {
        assert(expectedOutput.size() == networkOutput.size());
        int size = networkOutput.size();
        std::vector<double> output;
        output.reserve(size);

        for(int i = 0 ; i < size ; i++)
        {
            output.push_back(networkOutput[i] - expectedOutput[i]);
        }

        return output;
    }

    void neuralnetwork::backPropagation(const std::vector<double> &neuralNetworkInputs , const std::vector<double> &expectedOutputs, // inputs
                                        std::vector<std::vector<std::vector<double>>>& derivativeWeights , std::vector<std::vector<double>>& derivativeBiases) // outputs
    {

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.reserve( sizes.size() - 1 );
        derivativeBiases.reserve( sizes.size() - 1 );

        //to store one activation layer
        std::vector<double> activation = neuralNetworkInputs;
        //to store each one of the activation layers
        std::vector<std::vector<double>> activations;

        activations.reserve(sizes.size()); // numBiases is the same as the number of neurons (except 1st layer)
        activations.push_back(activation);
        int maxLayerSize = 0;

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        for ( int i = 1 ; i < numBiases ; i++ )
        {
            maxLayerSize = std::max(sizes[i], maxLayerSize);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        // to store one weighted sum
        std::vector<double> z;
        z.reserve(maxLayerSize);
        // to store each one of the weighted sums
        std::vector<std::vector<double>> zs;
        zs.reserve(sizes.size());

        // layer and neuron counter
        int layer, neuron;

        for ( layer = 1 ; layer < numLayers ; layer++ )
        {
            z = (weights[layer] * activation) + biases[layer];
            zs.push_back(z);
            activation = sigmoid(z);
            activations.push_back(activation);
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        std::vector<double> delta = costDerivatives(activations[ lastIndex( activations , 1 )] , expectedOutputs) * sigmoid_prime(z);
        delta.reserve(maxLayerSize);

        derivativeBiases.push_back(delta);

        int j;

        std::vector<std::vector<double>> dummyMatrix;
        dummyMatrix.reserve(maxLayerSize);

        for (neuron = 0; neuron < sizes[ lastIndex( sizes , 1 )]; neuron++)
        {
            dummyMatrix.push_back(std::vector<double>(activations[ lastIndex( activations , 2 )].size()));
            for (j = 0; j < activations[ lastIndex( activations , 2 )].size(); j++)
            {
                dummyMatrix[neuron][j] = delta[neuron] * activations[ lastIndex( activations , 2 )][j];
            }
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        derivativeWeights.push_back(dummyMatrix);
        dummyMatrix.clear();

        std::vector<double> sp;
        sp.reserve(maxLayerSize);

        std::vector<double> dummyVector;
        dummyVector.reserve(maxLayerSize);

        double dummyDouble = 0;

        for(layer = 2 ; layer < numLayers ; layer++)
        {
            z = zs[ lastIndex( zs , layer )];
            sp = sigmoid_prime(z);

            for(j = 0 ; j < sizes[ lastIndex( weights , layer )] ; j++)
            {
                for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer - 1 )]; neuron++)
                {
                    dummyDouble += weights[ lastIndex( weights , layer - 1 )][neuron][j] * delta[neuron];
                }
                dummyVector.push_back(dummyDouble * sp[j]);
                dummyDouble = 0;
            }
            delta = dummyVector;
            dummyVector.clear();

            derivativeBiases.push_back(delta);

            for (neuron = 0; neuron < sizes[ lastIndex( sizes , layer )]; neuron++)
            {
                dummyMatrix.push_back(std::vector<double>(sizes[ lastIndex( sizes , layer + 1 )]));
                for (j = 0; j < sizes[ lastIndex( sizes , layer + 1 )]; j++)
                {
                    dummyMatrix[neuron][j] = activations[ lastIndex( activations , layer + 1 )][j] * delta[neuron];
                }
            }
            derivativeWeights.push_back(dummyMatrix);
            dummyMatrix.clear();
        }

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

        //both derivativeWeights and derivativeBiases are reversed. so let's reverse it.
        std::reverse(derivativeWeights.begin(),derivativeWeights.end());
        std::reverse(derivativeBiases.begin(),derivativeBiases.end());

        std::cout << "teste "<< counter++ << std::endl;
        system("PAUSE");

    }
}

main.cpp

#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "neuralnetwork.h"
#include <string>

void printAll(const std::vector<double> & v, const std::string & name)
{
    int size = v.size();

    std::cout << "\t" <<  name << ":\t";

    for(int i = 0 ; i < size ; i++)
    {
        std::cout << v[i] << "\t";
    }

    std::cout << std::endl;
}

template<class T>
void printAll(const std::vector<T> & v, const std::string & name)
{
    int size = v.size();

    std::cout << name << ":" << std::endl;

    for(int i = 0 ; i < size ; i++)
    {
        printAll(v[i], "\t" + ("[" + std::to_string(i)) + "]");
    }
}

int main(int argc, char** argv )
{

    nn::neuralnetwork n({2,4,3});

    n.weights = {{},{{1,2},{3,4},{5,6},{7,8}} , {{9,8,7,6},{5,4,3,2},{1,2,3,4}}};
    n.biases = {{},{1, 4, 6, 8} , {9, 2, 4}};

    printAll(n.weights,"weights");
    printAll(n.biases,"biases");

    std::vector<std::vector<std::vector<double>>> derivativeWeights;
    std::vector<std::vector<double>> derivativeBiases;
    n.backPropagation({1,2},{1,2,3},derivativeWeights,derivativeBiases);

    printAll(n.derivativeWeights,"derivativeWeights");
    printAll(n.derivativeBiases,"derivativeBiases");

    system("PAUSE");

    return 0;
}