问:
Multi-tenant schema with Liquibase
I am currently fighting with the following problem: I have a Java EE application and want to use Liquibase as a DB migration tool. The problem is that I have multi-tenant model and each tenant has its own schema. Currently I am using a producer to start an update but not sure how to configure it to work with different schema.

I've found that there is some solution for Spring (see MultiTenantSpringLiquibase for more details). However, there is no solution for Java EE. Maybe the only solution is to write custom Liquibase servlet listener.

Thanks for any help and best regards, Erno

答:
If you have a different schema name for each tenant, than you may want to use Maven liquibase plugin.

You may want to declare different execution for each schema as below:

```<code>        <build>
            <plugins>
                <plugin>
                    <!--NOTE: clearCheckSums=true attribute will make the changesets run only once.
                        The runOnChange attribute added to changesets will not work as originally intended.-->
                    <groupId>org.liquibase</groupId>
                    <artifactId>liquibase-maven-plugin</artifactId>
                    <version>${database.liquibase.version}</version>
                    <executions>
                        <execution>
                            <id>admin-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>admin-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.adminschema.username}</username>
                                <password>${database.adminschema.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>user-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>user-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.username}</username>
                                <password>${database.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-mssql</artifactId>
                            <version>1.3.0</version>
                        </dependency>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-oracle</artifactId>
                            <version>3.1</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>

            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.csv</include>
                        <include>**/*.sql</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>false</filtering>
                    <excludes>
                        <exclude>**/*.xml</exclude>
                        <exclude>**/*.csv</exclude>
                        <exclude>**/*.sql</exclude>
                    </excludes>
                </resource>
            </resources>
        </build>
</code>```

You can always use the parameterized build with Maven, adding default values as:

```<code><properties>
    <liquibase.clearCheckSums>true</liquibase.clearCheckSums>
    <database.username>userSchema</database.username>
    <database.password>myUserPassword</database.password>
    <database.adminschema.username>adminSchema</database.adminschema.username>
    <database.adminschema.password>myAdminPassword</database.adminschema.password>
    <database.liquibasecontext>!IntegrationTesting</database.liquibasecontext>
</properties>
</code>```

Hope that this may help you.

Title: Multi-tenant schema with Liquibase

Body:
If you have a different schema name for each tenant, than you may want to use Maven liquibase plugin.

You may want to declare different execution for each schema as below:

        <build>
            <plugins>
                <plugin>
                    <!--NOTE: clearCheckSums=true attribute will make the changesets run only once.
                        The runOnChange attribute added to changesets will not work as originally intended.-->
                    <groupId>org.liquibase</groupId>
                    <artifactId>liquibase-maven-plugin</artifactId>
                    <version>${database.liquibase.version}</version>
                    <executions>
                        <execution>
                            <id>admin-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>admin-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.adminschema.username}</username>
                                <password>${database.adminschema.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>user-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>user-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.username}</username>
                                <password>${database.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-mssql</artifactId>
                            <version>1.3.0</version>
                        </dependency>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-oracle</artifactId>
                            <version>3.1</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>

            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.csv</include>
                        <include>**/*.sql</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>false</filtering>
                    <excludes>
                        <exclude>**/*.xml</exclude>
                        <exclude>**/*.csv</exclude>
                        <exclude>**/*.sql</exclude>
                    </excludes>
                </resource>
            </resources>
        </build>

You can always use the parameterized build with Maven, adding default values as:

<properties>
    <liquibase.clearCheckSums>true</liquibase.clearCheckSums>
    <database.username>userSchema</database.username>
    <database.password>myUserPassword</database.password>
    <database.adminschema.username>adminSchema</database.adminschema.username>
    <database.adminschema.password>myAdminPassword</database.adminschema.password>
    <database.liquibasecontext>!IntegrationTesting</database.liquibasecontext>
</properties>

Hope that this may help you.


来源: stackexchange

问:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.how to solve?
i have mysql database on aws when i try to access to through java progarm it give exception some time and some times its working

here is my java code

```<code>package com.iseva.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Connectionfactory.ConnectionFactory;

/**
 * Servlet implementation class ValidateUser
 */
@WebServlet("/ValidateUser")
public class ValidateUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Connection cn=null;
    public void init()
    {

         cn=ConnectionFactory.getConnection();
         System.out.println("connection");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        String logintype=request.getParameter("t1");
        String username=    request.getParameter("t2");
        String  password=   request.getParameter("t3");
        PreparedStatement ps=null;
        ResultSet rs=null;
           String result="";
        try {
            ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
            ps.setString(1,logintype);
            ps.setString(2,password);
            ps.setString(3,username);
             rs=ps.executeQuery();
             boolean b=rs.next();

            // RequestDispatcher dispatcher=null;

             if(b==true)
             {
                /* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
                 result="form1";
                 /*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");

                 dispatcher.forward(request,response);*/

                 System.out.println("entered");
             }
             else{
                 result="notfound";
                 System.out.println("not found");
             }
                response.getWriter().write(result);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        finally{
            if(cn!=null)
            {
                try {
                    cn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(ps!=null)
            {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(rs!=null)
            {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}
</code>```

when i try to access data base it gives following exception

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
    at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1187)
    at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1182)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4071)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4040)
    at com.iseva.Servlet.ValidateUser.doGet(ValidateUser.java:44)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
</code>```

how to solve this issue ?
is it the problem of  database or my code, please help me out.
i closed all connection in finally block as suggested by sites, even it gives same .
this exception may occur when our mysql data base idle for some time. is it?
if yes, what should i do. or how to solve it.

this Exception also coming when i refresh server

```<code>java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(Unknown Source)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:64)
 java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 java.lang.Thread.run(Unknown Source)
Dec 04, 2017 3:34:01 PM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
INFO: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1353)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1029)
    at com.mysql.jdbc.AbandonedConnectionCleanupThread.checkContextClassLoaders(AbandonedConnectionCleanupThread.java:90)
    at com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:63)
</code>```

答:
After one doGet() invocation your connection object are being closed so invoking it any next time after first usage will cause error because you won't have an opened connection. </p>

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //opening a connection before accessing db
    cn=ConnectionFactory.getConnection();

    String logintype=request.getParameter("t1");
    String username=    request.getParameter("t2");
    String  password=   request.getParameter("t3");
    PreparedStatement ps=null;
    ResultSet rs=null;
       String result="";
    try {
        ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
        ps.setString(1,logintype);
        ps.setString(2,password);
        ps.setString(3,username);
         rs=ps.executeQuery();
         boolean b=rs.next();

        // RequestDispatcher dispatcher=null;

         if(b==true)
         {
            /* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
             result="form1";
             /*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");

             dispatcher.forward(request,response);*/

             System.out.println("entered");
         }
         else{
             result="notfound";
             System.out.println("not found");
         }
            response.getWriter().write(result);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    finally{
        if(cn!=null)
        {
            try {
                cn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null)
        {
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(rs!=null)
        {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have mysql database on aws when i try to access to through java progarm it give exception some time and some times its working

here is my java code

package com.iseva.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Connectionfactory.ConnectionFactory;

/**
 * Servlet implementation class ValidateUser
 */
@WebServlet("/ValidateUser")
public class ValidateUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Connection cn=null;
    public void init()
    {

         cn=ConnectionFactory.getConnection();
         System.out.println("connection");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

        String logintype=request.getParameter("t1");
        String username=    request.getParameter("t2");
        String  password=   request.getParameter("t3");
        PreparedStatement ps=null;
        ResultSet rs=null;
           String result="";
        try {
            ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
            ps.setString(1,logintype);
            ps.setString(2,password);
            ps.setString(3,username);
             rs=ps.executeQuery();
             boolean b=rs.next();

            // RequestDispatcher dispatcher=null;

             if(b==true)
             {
                /* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
                 result="form1";
                 /*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");

                 dispatcher.forward(request,response);*/

                 System.out.println("entered");
             }
             else{
                 result="notfound";
                 System.out.println("not found");
             }
                response.getWriter().write(result);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        finally{
            if(cn!=null)
            {
                try {
                    cn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(ps!=null)
            {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(rs!=null)
            {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

when i try to access data base it gives following exception

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
    at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1187)
    at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1182)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4071)
    at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4040)
    at com.iseva.Servlet.ValidateUser.doGet(ValidateUser.java:44)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

how to solve this issue ?
is it the problem of  database or my code, please help me out.
i closed all connection in finally block as suggested by sites, even it gives same .
this exception may occur when our mysql data base idle for some time. is it?
if yes, what should i do. or how to solve it.

this Exception also coming when i refresh server

java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(Unknown Source)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:64)
 java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 java.lang.Thread.run(Unknown Source)
Dec 04, 2017 3:34:01 PM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
INFO: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1353)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1029)
    at com.mysql.jdbc.AbandonedConnectionCleanupThread.checkContextClassLoaders(AbandonedConnectionCleanupThread.java:90)
    at com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:63)

Body:
After one doGet() invocation your connection object are being closed so invoking it any next time after first usage will cause error because you won't have an opened connection.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //opening a connection before accessing db
    cn=ConnectionFactory.getConnection();

    String logintype=request.getParameter("t1");
    String username=    request.getParameter("t2");
    String  password=   request.getParameter("t3");
    PreparedStatement ps=null;
    ResultSet rs=null;
       String result="";
    try {
        ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
        ps.setString(1,logintype);
        ps.setString(2,password);
        ps.setString(3,username);
         rs=ps.executeQuery();
         boolean b=rs.next();

        // RequestDispatcher dispatcher=null;

         if(b==true)
         {
            /* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
             result="form1";
             /*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");

             dispatcher.forward(request,response);*/

             System.out.println("entered");
         }
         else{
             result="notfound";
             System.out.println("not found");
         }
            response.getWriter().write(result);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    finally{
        if(cn!=null)
        {
            try {
                cn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(ps!=null)
        {
            try {
                ps.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(rs!=null)
        {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}


问:
How can i get the child values from firebase database?
I am trying to get values from Firebase Database and set them to text view. My database has multiple child like in image. I want to get the Phone and Address values from it. How can I get them? I am new to Android and I have tried multiple answers here, but failed. Can anyone help me with this?

答:
To get that data, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String address = ds.child("Address").getValue(String.class);
            String phone = ds.child("Phone").getValue(String.class);
            Log.d("TAG", address + " / " + phone);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
</code>```

And this is the code to get the address from a single user:

```<code>String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String address = dataSnapshot.child("Address").getValue(String.class);
        Log.d("TAG", address);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
</code>```

Body:
To get that data, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String address = ds.child("Address").getValue(String.class);
            String phone = ds.child("Phone").getValue(String.class);
            Log.d("TAG", address + " / " + phone);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);

And this is the code to get the address from a single user:

String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String address = dataSnapshot.child("Address").getValue(String.class);
        Log.d("TAG", address);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);


问:
In Java, can the this/super keywords represent anything other than classes/enums?
I've noticed that:

```<code>class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}
</code>```

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

答:
Use A.this from the inner class.

And it cannot represent an interface, because you cannot define anynomous non-static classes within interfaces, because there wil never be an instance of the interface.

EDIT: Clarified by adding info from the comment.

ContentLicense: CC BY-SA 2.5

Body:
I've noticed that:

class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?


问:
Image elements are skipping while converting XSL
I'm having the image element, its skipping while I convert the XSL Tranformation, Please make it possible to change in my provided code. because the this code is working well with lot of input files,

My Input XML:

```<code><Body>
<h1>Local</h1>
<p>Early</p>
<h2>Home</h2>
<h3>Medicines</h3>
<p>Home</p>
<h3>General</h3>
<p>
<img alt="Man" height="187" width="300" class="right" src="https://tneb.com" />
</p>
<ul>
<li>
<p>Itching</p>
</li>
<li>
<p>pack</p>
</li>
</ul>
</Body>
</code>```

XSLT 2.0 I have used and I converted by using the saxon - PE 9.6.0.7,

```<code> <xsl:template match="Body">
      <xsl:for-each-group select="*[normalize-space()]" group-starting-with="h1">
         <topic outputclass="">
            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5"/></xsl:attribute>
            <title outputclass="">
               <xsl:apply-templates select="node()"/>
            </title>

            <xsl:for-each-group select="current-group() except ." group-starting-with="h2 | div[@data-swiq-type='callout-box']">
               <xsl:choose>
                  <xsl:when test="self::h2">
                     <topic outputclass="TOPIC-Section">
                        <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                        <title outputclass="Section">
                           <xsl:apply-templates select="node()"/>
                        </title>

                        <xsl:for-each-group select="current-group() except ." group-starting-with="h3 | div[@data-swiq-type='callout-box']">
                           <xsl:choose>
                              <xsl:when test="self::h3">
                                 <topic outputclass="TOPIC-Sub-Section">
                                    <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                    <title outputclass="Sub-Section">
                                       <xsl:apply-templates select="node()"/>
                                    </title>

                                    <xsl:for-each-group select="current-group() except ." group-starting-with="h4 | div[@data-swiq-type='callout-box']">
                                       <xsl:choose>
                                          <xsl:when test="self::h4">
                                             <topic outputclass="TOPIC-Sub-Section">
                                                <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                <title outputclass="Sub-Section">
                                                   <xsl:apply-templates select="node()"/>
                                                </title>

                                                <xsl:for-each-group select="current-group() except ." group-starting-with="h5 | div[@data-swiq-type='callout-box']">
                                                   <xsl:choose>
                                                      <xsl:when test="self::h5">
                                                         <topic outputclass="TOPIC-Sub-Section">
                                                            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                            <title outputclass="Sub-Section">
                                                               <xsl:apply-templates select="node()"/>
                                                            </title>

                                                            <body><xsl:apply-templates select="current-group() except ."/></body>
                                                         </topic>
                                                      </xsl:when>
                                                      <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                                         <topic outputclass="TOPIC-Box">
                                                            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                            <title><xsl:value-of select="h5"/></title>
                                                            <body><xsl:apply-templates/></body>
                                                         </topic>
                                                      </xsl:when>
                                                      <xsl:otherwise>
                                                         <body><xsl:apply-templates select="current-group()"/></body>
                                                      </xsl:otherwise>
                                                   </xsl:choose>
                                                </xsl:for-each-group>

                                                </topic>
                                          </xsl:when>
                                          <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                             <topic outputclass="TOPIC-Box">
                                                <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                <title><xsl:value-of select="h4"/></title>
                                                <body><xsl:apply-templates/></body>
                                             </topic>
                                          </xsl:when>
                                          <xsl:otherwise>
                                             <body><xsl:apply-templates select="current-group()"/></body>
                                          </xsl:otherwise>
                                       </xsl:choose>

                                    </xsl:for-each-group>

                                 </topic>
                              </xsl:when>
                              <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                 <topic outputclass="TOPIC-Box">
                                    <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                    <title><xsl:value-of select="h3"/></title>
                                    <body><xsl:apply-templates/></body>
                                 </topic>
                              </xsl:when>
                              <xsl:otherwise>
                                 <body><xsl:apply-templates select="current-group()"/></body>
                              </xsl:otherwise>
                           </xsl:choose>

                        </xsl:for-each-group>
                     </topic>
                  </xsl:when>
                  <xsl:when test="self::div[@data-swiq-type='callout-box']">
                     <topic outputclass="TOPIC-Box">
                        <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                        <title outputclass=""><xsl:value-of select="h2 | h3 | h4 | h5"/></title>
                        <body><xsl:apply-templates/></body>
                     </topic>
                  </xsl:when>
                  <xsl:otherwise>
                     <body><xsl:apply-templates select="current-group()"/></body>
                  </xsl:otherwise>
               </xsl:choose>
            </xsl:for-each-group>
         </topic>
      </xsl:for-each-group>
   </xsl:template>

   <xsl:template match="p">
      <xsl:choose>
         <xsl:when test="not(text()[normalize-space(.)] | child::*)"/>
         <xsl:otherwise>
            <p outputclass="Body_text_no_indent">
               <xsl:apply-templates/>
            </p>
         </xsl:otherwise>
      </xsl:choose>
   </xsl:template>

      <xsl:template match="img">
      <xsl:element name="image">
            <xsl:if test="@imageid">
               <xsl:attribute name="id"><xsl:value-of select="@imageid"/></xsl:attribute>
            </xsl:if>
            <xsl:if test="@title">
               <xsl:attribute name="xtrf"><xsl:apply-templates select="@title"/></xsl:attribute>
             </xsl:if>
            <xsl:if test="@src">
               <xsl:attribute name="href">
                  <xsl:variable name="resolutionremove">
                  <xsl:value-of select="tokenize(@src, '/')[position() = last() - 2 or position() = last()]" separator="_"/>
                  </xsl:variable>
                  <xsl:value-of select="replace($resolutionremove, '.([0-9]+)x([0-9]+)', '')"/>
               </xsl:attribute>
          </xsl:if>
            <xsl:if test="@alt">
            <xsl:attribute name="alt"><xsl:apply-templates select="@alt"/></xsl:attribute>
            </xsl:if>
         <xsl:if test="@height">
            <xsl:attribute name="height"><xsl:value-of select="@height"/></xsl:attribute>
         </xsl:if>
         <xsl:if test="@width">
            <xsl:attribute name="width"><xsl:value-of select="@width"/></xsl:attribute>
         </xsl:if>
         <xsl:if test="@align">
            <xsl:attribute name="align"><xsl:value-of select="@align"/></xsl:attribute>
         </xsl:if>
            <xsl:if test="@data-image">
               <xsl:attribute name="base">data-image(<xsl:value-of select="@data-image"/>)</xsl:attribute>
            </xsl:if>
         <xsl:attribute name="outputclass">Image_Ref</xsl:attribute>
      </xsl:element>
   </xsl:template>

<xsl:template match="ul" priority="0">
      <ul outputclass="">
         <xsl:apply-templates/>
      </ul>
   </xsl:template>

   <xsl:template match="ul/li" priority="0">
      <li outputclass="List_Bullet">
         <xsl:apply-templates/>
         <xsl:apply-templates select="following-sibling::*[1][self::ul]" mode="wrap"/>
      </li>
   </xsl:template>
</code>```

While I converting, the image element is getting skip, if I used this img inside the list tag means its coming. Can anyone please provide me the suggestion for this. Please make the change in the provide code of Body template. Thanks in advance

答:
Change

```<code><xsl:for-each-group select="*[normalize-space()]" group-starting-with="h1">
</code>```

to

```<code><xsl:for-each-group select="*[node()]" group-starting-with="h1">
</code>```

Body:
I'm having the image element, its skipping while I convert the XSL Tranformation, Please make it possible to change in my provided code. because the this code is working well with lot of input files,

My Input XML:

Local

Early

Home

Medicines

Home

General

Itching

pack

XSLT 2.0 I have used and I converted by using the saxon - PE 9.6.0.7,

 <xsl:template match="Body">
      <xsl:for-each-group select="*[normalize-space()]" group-starting-with="h1">
         <topic outputclass="">
            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5"/></xsl:attribute>
            <title outputclass="">
               <xsl:apply-templates select="node()"/>
            </title>

            <xsl:for-each-group select="current-group() except ." group-starting-with="h2 | div[@data-swiq-type='callout-box']">
               <xsl:choose>
                  <xsl:when test="self::h2">
                     <topic outputclass="TOPIC-Section">
                        <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                        <title outputclass="Section">
                           <xsl:apply-templates select="node()"/>
                        </title>

                        <xsl:for-each-group select="current-group() except ." group-starting-with="h3 | div[@data-swiq-type='callout-box']">
                           <xsl:choose>
                              <xsl:when test="self::h3">
                                 <topic outputclass="TOPIC-Sub-Section">
                                    <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                    <title outputclass="Sub-Section">
                                       <xsl:apply-templates select="node()"/>
                                    </title>

                                    <xsl:for-each-group select="current-group() except ." group-starting-with="h4 | div[@data-swiq-type='callout-box']">
                                       <xsl:choose>
                                          <xsl:when test="self::h4">
                                             <topic outputclass="TOPIC-Sub-Section">
                                                <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                <title outputclass="Sub-Section">
                                                   <xsl:apply-templates select="node()"/>
                                                </title>

                                                <xsl:for-each-group select="current-group() except ." group-starting-with="h5 | div[@data-swiq-type='callout-box']">
                                                   <xsl:choose>
                                                      <xsl:when test="self::h5">
                                                         <topic outputclass="TOPIC-Sub-Section">
                                                            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                            <title outputclass="Sub-Section">
                                                               <xsl:apply-templates select="node()"/>
                                                            </title>

                                                            <xsl:apply-templates select="current-group() except ."/>
                                                         </topic>
                                                      </xsl:when>
                                                      <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                                         <topic outputclass="TOPIC-Box">
                                                            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                            <title><xsl:value-of select="h5"/></title>
                                                            <xsl:apply-templates/>
                                                         </topic>
                                                      </xsl:when>
                                                      <xsl:otherwise>
                                                         <xsl:apply-templates select="current-group()"/>
                                                      </xsl:otherwise>
                                                   </xsl:choose>
                                                </xsl:for-each-group>

                                                </topic>
                                          </xsl:when>
                                          <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                             <topic outputclass="TOPIC-Box">
                                                <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                                <title><xsl:value-of select="h4"/></title>
                                                <xsl:apply-templates/>
                                             </topic>
                                          </xsl:when>
                                          <xsl:otherwise>
                                             <xsl:apply-templates select="current-group()"/>
                                          </xsl:otherwise>
                                       </xsl:choose>

                                    </xsl:for-each-group>

                                 </topic>
                              </xsl:when>
                              <xsl:when test="self::div[@data-swiq-type='callout-box']">
                                 <topic outputclass="TOPIC-Box">
                                    <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                                    <title><xsl:value-of select="h3"/></title>
                                    <xsl:apply-templates/>
                                 </topic>
                              </xsl:when>
                              <xsl:otherwise>
                                 <xsl:apply-templates select="current-group()"/>
                              </xsl:otherwise>
                           </xsl:choose>

                        </xsl:for-each-group>
                     </topic>
                  </xsl:when>
                  <xsl:when test="self::div[@data-swiq-type='callout-box']">
                     <topic outputclass="TOPIC-Box">
                        <xsl:attribute name="id">topic_<xsl:number count="h1 | h2 | h3 | h4 | h5 | div"/></xsl:attribute>
                        <title outputclass=""><xsl:value-of select="h2 | h3 | h4 | h5"/></title>
                        <xsl:apply-templates/>
                     </topic>
                  </xsl:when>
                  <xsl:otherwise>
                     <xsl:apply-templates select="current-group()"/>
                  </xsl:otherwise>
               </xsl:choose>
            </xsl:for-each-group>
         </topic>
      </xsl:for-each-group>
   </xsl:template>

   <xsl:template match="p">
      <xsl:choose>
         <xsl:when test="not(text()[normalize-space(.)] | child::*)"/>
         <xsl:otherwise>

               <xsl:apply-templates/>

         </xsl:otherwise>
      </xsl:choose>
   </xsl:template>

      <xsl:template match="img">
      <xsl:element name="image">
            <xsl:if test="@imageid">
               <xsl:attribute name="id"><xsl:value-of select="@imageid"/></xsl:attribute>
            </xsl:if>
            <xsl:if test="@title">
               <xsl:attribute name="xtrf"><xsl:apply-templates select="@title"/></xsl:attribute>
             </xsl:if>
            <xsl:if test="@src">
               <xsl:attribute name="href">
                  <xsl:variable name="resolutionremove">
                  <xsl:value-of select="tokenize(@src, '/')[position() = last() - 2 or position() = last()]" separator="_"/>
                  </xsl:variable>
                  <xsl:value-of select="replace($resolutionremove, '.([0-9]+)x([0-9]+)', '')"/>
               </xsl:attribute>
          </xsl:if>
            <xsl:if test="@alt">
            <xsl:attribute name="alt"><xsl:apply-templates select="@alt"/></xsl:attribute>
            </xsl:if>
         <xsl:if test="@height">
            <xsl:attribute name="height"><xsl:value-of select="@height"/></xsl:attribute>
         </xsl:if>
         <xsl:if test="@width">
            <xsl:attribute name="width"><xsl:value-of select="@width"/></xsl:attribute>
         </xsl:if>
         <xsl:if test="@align">
            <xsl:attribute name="align"><xsl:value-of select="@align"/></xsl:attribute>
         </xsl:if>
            <xsl:if test="@data-image">
               <xsl:attribute name="base">data-image(<xsl:value-of select="@data-image"/>)</xsl:attribute>
            </xsl:if>
         <xsl:attribute name="outputclass">Image_Ref</xsl:attribute>
      </xsl:element>
   </xsl:template>

<xsl:template match="ul" priority="0">

         <xsl:apply-templates/>

   </xsl:template>

   <xsl:template match="ul/li" priority="0">

         <xsl:apply-templates/>
         <xsl:apply-templates select="following-sibling::*[1][self::ul]" mode="wrap"/>

   </xsl:template>

While I converting, the image element is getting skip, if I used this img inside the list tag means its coming. Can anyone please provide me the suggestion for this. Please make the change in the provide code of Body template. Thanks in advance

Body:
Change

<xsl:for-each-group select="*[normalize-space()]" group-starting-with="h1">

to

<xsl:for-each-group select="*[node()]" group-starting-with="h1">


问:
How to log all HTTP requests to site, using Yii Framework?
I want to log all HTTP requests to site, framework Yii.

Can i use standard capabilities of framework?

答:
In Yii2 the events are called beforeRequest and afterRequest (http://www.yiiframework.com/doc-2.0/guide-structure-applications.html)

For example:

```<code>Yii::$app->on('afterRequest', function($event) {
    //do something...
    //response object is in $event->sender->response
    //response data is in $event->sender->response->data
    //request object is in $event->sender->request
});
</code>```

But this is before response data has been prepared into response content (according to response format, eg. Response::FORMAT_JSON) so if you want the true final response body you need to do this (http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#sending-response):

```<code>Yii::$app->response->on(\yii\web\Response::EVENT_AFTER_SEND, function($event) {  //alternatively use EVENT_AFTER_PREPARE
    //now you can access $event->sender->content and eg. $event->sender->getHeaders()
    //Also, you have access to the request through Yii::$app->request
});
</code>```

Body:
In Yii2 the events are called beforeRequest and afterRequest (http://www.yiiframework.com/doc-2.0/guide-structure-applications.html)

For example:

Yii::$app->on('afterRequest', function($event) {
    //do something...
    //response object is in $event->sender->response
    //response data is in $event->sender->response->data
    //request object is in $event->sender->request
});

But this is before response data has been prepared into response content (according to response format, eg. Response::FORMAT_JSON) so if you want the true final response body you need to do this (http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#sending-response):

Yii::$app->response->on(\yii\web\Response::EVENT_AFTER_SEND, function($event) {  //alternatively use EVENT_AFTER_PREPARE
    //now you can access $event->sender->content and eg. $event->sender->getHeaders()
    //Also, you have access to the request through Yii::$app->request
});


问:
wxDEV+OpenCV error : Undefined reference to `cvLoadImage''
Hello everyone, I am trying to use OpenCV library in wxDev C++, and it couldn't compiler correctly. (OpenCV version: 2.4.13.4)

These are the errors:

```<code>[Linker Error] undefined reference to `cvLoadImage'
[Linker Error] undefined reference to `cvShowImage'
[Linker Error] undefined reference to `cvWaitKey'
[Linker Error] undefined reference to `cvReleaseImage'
ld returned 1 exit status
</code>```

These are the codes:

```<code>#include "opencv2/opencv.hpp"
int main()
    {
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
    return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
    }
</code>```

These are the setting of wxDev:
wxDev Compiler Options

It seems that wxDev can't recognize those methods which I included from the library. What should I do?

//------------------------------------------------------------------------------

[12/4 update] I forgot to say that I've tried to use a different version of OpenCV(3.3.1) as well, so the settings in the screenshot have a little bug. "D:\OpenCV\2.4\opencv\build" is for 2.4.13.4. "D:\OpenCV\opencv\build" is for 3.3.1. I have included both of them in the setting but still doesn't work out. I don't know what is the differences between 3.3.1 and 2.4.1.3, but they are the newest update then.

I've tried to change the way I named the libraries, but it didn't work. For instance, "-opencv_core", "-lopencv_core", "-opencv_core.lib", "-lopencv_core.lib", "-lopencv_core.a".

//------------------------------------------------------------------------------

[12/5 update#1] It seems that there is something wrong with the libraries. So, instead of using the newer version of OpenCV, I tried using the older one, the OpenCV2.2. Fortunately, it worked pretty well! I did exactly the same thing but came out a different result. I assumed that the methods of the software have been modified somehow in the latest version. Hopefully, someone could provide a later tutorial for the recent version of OpenCV.

[12/5 update#2] After successfully compiler this program, I started running another OpenCV example. The same issues occurred.

Example Code:

```<code>#include <cstdio>
#include <opencv2/opencv.hpp>
using namespace cv;

int main(){
    Mat img = imread("lena.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    imwrite("output.jpg",img);

    namedWindow("Display window", WINDOW_AUTOSIZE);
    imshow("Display window", img);
    waitKey(0);

    return 0;
}
</code>```

Some of those errors:

```<code>[Linker Error] undefined reference to `cv::imread(std::string const&, int)
[Linker Error] undefined reference to `cv::namedWindow(std::string const&, int)
[Linker Error] undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)
[Linker Error] undefined reference to `cv::fastFree(void*)'
</code>```

The same problem just keep happening, still looking for savior.

//------------------------------------------------------------------------------

[12/6 update] After several attempts, I downgraded OpenCV into version 2.0. The program successfully worked. The only difference compared to the other versions is the library's direction which was included.

The other version won't work if I write #include <opencv2/opencv.hpp>.
Version 2.0 will work if I write #include <cv.h>, #include <highgui.h>.
(Version 2.0 doesn't have the file, opencv2, so I have to include the direction.) I have no idea why it ends up like this.

The solution is to use the version 2.0 and also not using #include <opencv2/opencv.hpp>. It can run perfectly well in most of the examples so far. Although I could start working on my project now, I still try to figure out how to use the latest version of OpenCV.

//------------------------------------------------------------------------------

Respond to Mark Setchell-
These are the screenshots of the files and settings so far:

The lib files and its directions

OpenCV 2.2.0 settings and directions

OpenCV 2.4.11 settings and directions

I have tried different versions of OpenCV to run the program, the details of the process written in "12/5 update". By the way, I did change the compiler before running the program. Thanks for helping!

答:
The opencv-libs are missing. In your screenshow you have add the folders, but the names in your config are defined as -opencv_core... . Normally the option for linking them is -L, even in wxDev++. So just add the libs like:

```<code>-Lopencv_core2413.lib
</code>```

Body:
Hello everyone, I am trying to use OpenCV library in wxDev C++, and it couldn't compiler correctly. (OpenCV version: 2.4.13.4)

These are the errors:

[Linker Error] undefined reference to `cvLoadImage'
[Linker Error] undefined reference to `cvShowImage'
[Linker Error] undefined reference to `cvWaitKey'
[Linker Error] undefined reference to `cvReleaseImage'
ld returned 1 exit status

These are the codes:

#include "opencv2/opencv.hpp"
int main()
    {
    IplImage *srcImg = NULL;

    srcImg = cvLoadImage( "temp.jpg", 1);
    if( srcImg == NULL ){
    return -1;
    }

    cvShowImage( "Source", srcImg );
    cvWaitKey(0);
    cvReleaseImage( &srcImg );
    }

These are the setting of wxDev:
wxDev Compiler Options

It seems that wxDev can't recognize those methods which I included from the library. What should I do?

//------------------------------------------------------------------------------

[12/4 update] I forgot to say that I've tried to use a different version of OpenCV(3.3.1) as well, so the settings in the screenshot have a little bug. "D:\OpenCV\2.4\opencv\build" is for 2.4.13.4. "D:\OpenCV\opencv\build" is for 3.3.1. I have included both of them in the setting but still doesn't work out. I don't know what is the differences between 3.3.1 and 2.4.1.3, but they are the newest update then.

I've tried to change the way I named the libraries, but it didn't work. For instance, "-opencv_core", "-lopencv_core", "-opencv_core.lib", "-lopencv_core.lib", "-lopencv_core.a".

//------------------------------------------------------------------------------

[12/5 update#1] It seems that there is something wrong with the libraries. So, instead of using the newer version of OpenCV, I tried using the older one, the OpenCV2.2. Fortunately, it worked pretty well! I did exactly the same thing but came out a different result. I assumed that the methods of the software have been modified somehow in the latest version. Hopefully, someone could provide a later tutorial for the recent version of OpenCV.

[12/5 update#2] After successfully compiler this program, I started running another OpenCV example. The same issues occurred.

Example Code:

#include <cstdio>
#include <opencv2/opencv.hpp>
using namespace cv;

int main(){
    Mat img = imread("lena.jpg",CV_LOAD_IMAGE_GRAYSCALE);
    imwrite("output.jpg",img);

    namedWindow("Display window", WINDOW_AUTOSIZE);
    imshow("Display window", img);
    waitKey(0);

    return 0;
}

Some of those errors:

[Linker Error] undefined reference to `cv::imread(std::string const&, int)
[Linker Error] undefined reference to `cv::namedWindow(std::string const&, int)
[Linker Error] undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)
[Linker Error] undefined reference to `cv::fastFree(void*)'

The same problem just keep happening, still looking for savior.

//------------------------------------------------------------------------------

[12/6 update] After several attempts, I downgraded OpenCV into version 2.0. The program successfully worked. The only difference compared to the other versions is the library's direction which was included.

The other version won't work if I write #include <opencv2/opencv.hpp>.
Version 2.0 will work if I write #include <cv.h>, #include <highgui.h>.
(Version 2.0 doesn't have the file, opencv2, so I have to include the direction.) I have no idea why it ends up like this.

The solution is to use the version 2.0 and also not using #include <opencv2/opencv.hpp>. It can run perfectly well in most of the examples so far. Although I could start working on my project now, I still try to figure out how to use the latest version of OpenCV.

//------------------------------------------------------------------------------

Respond to Mark Setchell-
These are the screenshots of the files and settings so far:

The lib files and its directions

OpenCV 2.2.0 settings and directions

OpenCV 2.4.11 settings and directions

I have tried different versions of OpenCV to run the program, the details of the process written in "12/5 update". By the way, I did change the compiler before running the program. Thanks for helping!

Body:
The opencv-libs are missing. In your screenshow you have add the folders, but the names in your config are defined as -opencv_core... . Normally the option for linking them is -L, even in wxDev++. So just add the libs like:

-Lopencv_core2413.lib


问:
Size of a blob field in Firebird
Is there a way to retrieve (using a select statement) the size of a blob field in Firebird??

I've a field called "data" and I'd like to know the total size of all the records in the table.

Thanks.

答:
If the field contains Images or another kind of data or even Text, you can use F_BLOBSIZE(blobfield) from FreeAdHocUDF

Input   BLOB    TextBLOb
For TextBLOb: returns the size/length (similar F_STRINGLENGTH)
For BinarBLOb: returns the size of file in byte

Title: Size of a blob field in Firebird


问:
Dynamic widths for css class with ::after pseudoelement
I'm doing some mvc testing and I've hit a roadblock when I'm going through my model to display some elements. Each element will have to have an "EXP" amount that is displayed dynamically in the ::after element in the css.

Is there a way to dynamically change the width of the ::after element? I am passing through the width for each element through the model but I don't display it yet

That's the bar that needs to change dynamically, here's an example piece of code of how I've done it so far:

.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
    }

        .pkmn-summary:after {
            content: '';
            position: relative;
            left: -181px;
            bottom: -31px;
            height: 5px;
            background: green;
            width: 73%;
            display: inline-block;
            border-radius: 0 0 0 5px;
        }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pkmn-pc">
    <div class="pkmn-summary">
        <img class="pkmn-sprite" src="https://cdn.bulbagarden.net/upload/e/ea/113MS.png" />
        <code class="pkmn-name">15Characterssss</code>
    </div>
    <div class="pkmn-info">
        <img class="crown" src="https://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" />
        <div class="pkmn-outer">
            <img class="heart" src="https://image.ibb.co/kB8vi6/heart.png">
            <div class="pkmn-inner"></div>
            <img class="star" src="https://image.ibb.co/e7w4bR/Shiny_VIStar.png">
        </div>
        <code class="pkmn-lvl">lvl 100</code>
    </div>
</div></code>```

Any help would be greatly appreciated! Thanks!

答:
If you have the EXP value available in the data (along with the other user info), you could create an element (we'll call it .pkmn-exp) and set the experience level (or width) in an inline style.

For example, if the user has an experience level of 73/100:

```<code><div class="pkmn-exp" style="width:73%;"></div>
</code>```

where the 73 comes from the user's data.

.pkmn-pc {
  color: white;
  margin: 10px;
  display: inline-block;
}

.pkmn-summary,
.pkmn-info {
  display: table-cell;
  vertical-align: middle;
  height: 60px;
}

.pkmn-summary {
  position: relative;
  width: 193px;
  background: #745fb5;
  background: linear-gradient(15deg, #745fb5, #9a6dbb);
  border-radius: 5px 0 0 5px;
  box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
  white-space: nowrap;
  border-bottom: solid 5px grey;
  text-align: left;
  padding-left: 5px;
}

.pkmn-exp {
  position: absolute;
  left: 0px;
  bottom: -5px;
  height: 5px;
  background: green;
  display: inline-block;
  border-radius: 0 0 0 5px;
}

.pkmn-info {
  background: #333538;
  border-radius: 0 5px 5px 0;
  width: 70px;
  text-align: center;
  box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
}

.pkmn-outer {
  padding-bottom: 2px;
}

.pkmn-inner {
  display: inline-block;
  width: 3px;
}

.pkmn-sprite {
  vertical-align: middle;
}

.pkmn-name {
  font-size: 1.2em;
}

.pkmn-lvl {
  font-size: 0.8em;
  display: block;
}

.crown {
  padding-top: 5px;
}

code {
  padding: 0;
  font-size: 1em;
  color: white;
  background-color: transparent;
  border-radius: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pkmn-pc">
  <div class="pkmn-summary">
    <img class="pkmn-sprite" src="https://cdn.bulbagarden.net/upload/e/ea/113MS.png" />
    <code class="pkmn-name">15Characterssss</code>
    <div class="pkmn-exp" style="width:73%"></div>
  </div>
  <div class="pkmn-info">
    <img class="crown" src="https://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" />
    <div class="pkmn-outer">
      <img class="heart" src="https://image.ibb.co/kB8vi6/heart.png">
      <div class="pkmn-inner"></div>
      <img class="star" src="https://image.ibb.co/e7w4bR/Shiny_VIStar.png">
    </div>
    <code class="pkmn-lvl">lvl 100</code>
  </div>
</div></code>```

Body:
I'm doing some mvc testing and I've hit a roadblock when I'm going through my model to display some elements. Each element will have to have an "EXP" amount that is displayed dynamically in the ::after element in the css.

Is there a way to dynamically change the width of the ::after element? I am passing through the width for each element through the model but I don't display it yet

That's the bar that needs to change dynamically, here's an example piece of code of how I've done it so far:

.pkmn-pc {
        color: white;
        margin: 10px;
        display: inline-block;
    }

    .pkmn-summary, .pkmn-info {
        display: table-cell;
        vertical-align: middle;
        height: 60px;
    }

    .pkmn-summary {
        width: 193px;
        background: #745fb5;
        background: linear-gradient(15deg, #745fb5, #9a6dbb);
        border-radius: 5px 0 0 5px;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
        white-space: nowrap;
        border-bottom: solid 5px grey;
        text-align: left;
        padding-left: 5px;
    }

        .pkmn-summary:after {
            content: '';
            position: relative;
            left: -181px;
            bottom: -31px;
            height: 5px;
            background: green;
            width: 73%;
            display: inline-block;
            border-radius: 0 0 0 5px;
        }

    .pkmn-info {
        background: #333538;
        border-radius: 0 5px 5px 0;
        width: 70px;
        text-align: center;
        box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
    }

    .pkmn-outer {
        padding-bottom: 2px;
    }

    .pkmn-inner {
        display: inline-block;
        width: 3px;
    }

    .pkmn-sprite {
        vertical-align: middle;
    }

    .pkmn-name {
        font-size: 1.2em;
    }

    .pkmn-lvl {
        font-size: 0.8em;
        display: block;
    }

    .crown {
        padding-top: 5px;
    }

    code {
        padding: 0;
        font-size: 1em;
        color: white;
        background-color: transparent;
        border-radius: 0;
    }

        15Characterssss

        lvl 100

Any help would be greatly appreciated! Thanks!

Body:
If you have the EXP value available in the data (along with the other user info), you could create an element (we'll call it .pkmn-exp) and set the experience level (or width) in an inline style.

For example, if the user has an experience level of 73/100:

<div class="pkmn-exp" style="width:73%;"></div>

where the 73 comes from the user's data.

.pkmn-pc {
  color: white;
  margin: 10px;
  display: inline-block;
}

.pkmn-summary,
.pkmn-info {
  display: table-cell;
  vertical-align: middle;
  height: 60px;
}

.pkmn-summary {
  position: relative;
  width: 193px;
  background: #745fb5;
  background: linear-gradient(15deg, #745fb5, #9a6dbb);
  border-radius: 5px 0 0 5px;
  box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
  white-space: nowrap;
  border-bottom: solid 5px grey;
  text-align: left;
  padding-left: 5px;
}

.pkmn-exp {
  position: absolute;
  left: 0px;
  bottom: -5px;
  height: 5px;
  background: green;
  display: inline-block;
  border-radius: 0 0 0 5px;
}

.pkmn-info {
  background: #333538;
  border-radius: 0 5px 5px 0;
  width: 70px;
  text-align: center;
  box-shadow: 0 1px 1px rgba(102, 119, 136, 0.55);
}

.pkmn-outer {
  padding-bottom: 2px;
}

.pkmn-inner {
  display: inline-block;
  width: 3px;
}

.pkmn-sprite {
  vertical-align: middle;
}

.pkmn-name {
  font-size: 1.2em;
}

.pkmn-lvl {
  font-size: 0.8em;
  display: block;
}

.crown {
  padding-top: 5px;
}

code {
  padding: 0;
  font-size: 1em;
  color: white;
  background-color: transparent;
  border-radius: 0;
}

<div class="pkmn-pc">
  <div class="pkmn-summary">
    <img class="pkmn-sprite" src="https://cdn.bulbagarden.net/upload/e/ea/113MS.png" />
    <code class="pkmn-name">15Characterssss</code>
    <div class="pkmn-exp" style="width:73%"></div>
  </div>
  <div class="pkmn-info">
    <img class="crown" src="https://cdn.bulbagarden.net/upload/c/c5/Leaf_Crown_Sprite.png" />
    <div class="pkmn-outer">
      <img class="heart" src="https://image.ibb.co/kB8vi6/heart.png">
      <div class="pkmn-inner"></div>
      <img class="star" src="https://image.ibb.co/e7w4bR/Shiny_VIStar.png">
    </div>
    <code class="pkmn-lvl">lvl 100</code>
  </div>
</div>


问:
Removing One String CSV elements from another CSV String in java
I am trying to remove elements from one CSV string with other CSV string :

Example:

```<code>String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */
</code>```

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?

答:
try to use String::replaceAll with some regex like this :

```<code>String regexReplace = "[" + s2.replace(",", "") + "]";//result [e5v]
s1 = s1.replaceAll(regexReplace, "") // replace all character in class [e5v] with empty
        .replaceAll(",{2,}", ",")// replace all two or more comma with one comma
        .replaceAll("(^,|,$)", "");// in some cases replace comma in start or in the end
</code>```

General solution (to match words and not letters) you can use this instead :

```<code>String regexReplace = "(" + s2.replace(",", "|") + ")";// result (e|5|v)
</code>```

Body:
I am trying to remove elements from one CSV string with other CSV string :

Example:

String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?

Body:
try to use String::replaceAll with some regex like this :

String regexReplace = "[" + s2.replace(",", "") + "]";//result [e5v]
s1 = s1.replaceAll(regexReplace, "") // replace all character in class [e5v] with empty
        .replaceAll(",{2,}", ",")// replace all two or more comma with one comma
        .replaceAll("(^,|,$)", "");// in some cases replace comma in start or in the end

General solution (to match words and not letters) you can use this instead :

String regexReplace = "(" + s2.replace(",", "|") + ")";// result (e|5|v)


问:
Postgresql: How to group items based on their percentage to the grandtotal
```<code>    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115
</code>```

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

```<code>     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%
</code>```

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

答:
Assuming the following code to create the data:

```<code>create table product(
  store int,
  name text,
  qtd int
  );

insert into product values(1,' apple',10);
insert into product values(1,' orange',12);
insert into product values(1,' grapes',9);
insert into product values(1,' mango',17);
insert into product values(2,' chicken',112);
insert into product values(2,' beef',90 );
insert into product values(2,' pork',89 );
insert into product values(2,' lamb',115);
</code>```

You can get the the output you need with this query:

```<code>with total_query as (
  SELECT store, sum(qtd) AS totalamount
    FROM product
    GROUP BY store
  ),
count_query as (
  SELECT store, count(qtd) AS totalcnt
    FROM product
    GROUP BY store

  ),
percent_query as (

select p.store, p.name,
  round(p.qtd::float/(select totalamount from total_query
          where total_query.store = p.store)*100) as percent

  from product p

)

select store,
case when row_number() over (
  partition by store order by percent desc)/
(select totalcnt from count_query where store = p.store)::float <= 0.5
then 'Other' else name end, percent

from percent_query p order by store, percent

| store |    name | percent |
|-------|---------|---------|
|     1 |  grapes |      19 |
|     1 |   apple |      21 |
|     1 |   Other |      25 |
|     1 |   Other |      35 |
|     2 |    beef |      22 |
|     2 |    pork |      22 |
|     2 |   Other |      28 |
|     2 |   Other |      28 |
</code>```

Body:
    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

Body:
Assuming the following code to create the data:

create table product(
  store int,
  name text,
  qtd int
  );

insert into product values(1,' apple',10);
insert into product values(1,' orange',12);
insert into product values(1,' grapes',9);
insert into product values(1,' mango',17);
insert into product values(2,' chicken',112);
insert into product values(2,' beef',90 );
insert into product values(2,' pork',89 );
insert into product values(2,' lamb',115);

You can get the the output you need with this query:

with total_query as (
  SELECT store, sum(qtd) AS totalamount
    FROM product
    GROUP BY store
  ),
count_query as (
  SELECT store, count(qtd) AS totalcnt
    FROM product
    GROUP BY store

  ),
percent_query as (

select p.store, p.name,
  round(p.qtd::float/(select totalamount from total_query
          where total_query.store = p.store)*100) as percent

  from product p

)

select store,
case when row_number() over (
  partition by store order by percent desc)/
(select totalcnt from count_query where store = p.store)::float <= 0.5
then 'Other' else name end, percent

from percent_query p order by store, percent

| store |    name | percent |
|-------|---------|---------|
|     1 |  grapes |      19 |
|     1 |   apple |      21 |
|     1 |   Other |      25 |
|     1 |   Other |      35 |
|     2 |    beef |      22 |
|     2 |    pork |      22 |
|     2 |   Other |      28 |
|     2 |   Other |      28 |


问:
How to add random str in laravel input
I have clone methode where i can duplicate (clone) my products but my title column is unique and I can't clone my products what i need is to add some random text or numbers before or after my title in order to be allowed to save new entry.

How can I add that str in my title?

here is my method:

```<code>public function clonemaker($id)
    {
      $product = Product::findOrFail($id);
      $newProduct->title = str_before('clone', 'title');
      $newProduct = $product->replicate();
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
    }
</code>```

Thanks.

答:
SOLVED

here is the solution:

```<code>public function clonemaker($id)
    {
      $product = Product::findOrFail($id);
      $title = $product->title;
      $newProduct = $product->replicate();
      $newProduct->title = str_before('cloned' .'_'. $title, 'dijd');
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
    }
</code>```

This will add new product name such as clone_product.

To answer @devsourav , I have to say it does make sense when your slug comes from your title it has to be unique in order to avoid 2 product with same slug.

PS: I really wish to know the person who doesn't know the answer and gave - to this question :)) some people are just hatred! with no reason.

Hope this help others.

Title: How to add random str in laravel input

Body:
I have clone methode where i can duplicate (clone) my products but my title column is unique and I can't clone my products what i need is to add some random text or numbers before or after my title in order to be allowed to save new entry.

How can I add that str in my title?

here is my method:

public function clonemaker($id)
    {
      $product = Product::findOrFail($id);
      $newProduct->title = str_before('clone', 'title');
      $newProduct = $product->replicate();
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
    }

Thanks.

Body:
SOLVED

here is the solution:

public function clonemaker($id)
    {
      $product = Product::findOrFail($id);
      $title = $product->title;
      $newProduct = $product->replicate();
      $newProduct->title = str_before('cloned' .'_'. $title, 'dijd');
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
    }

This will add new product name such as clone_product.

To answer @devsourav , I have to say it does make sense when your slug comes from your title it has to be unique in order to avoid 2 product with same slug.

PS: I really wish to know the person who doesn't know the answer and gave - to this question :)) some people are just hatred! with no reason.

Hope this help others.


问:
How to dispatch Hangfire jobs on all Azure available instances?
I have a Web Api app running on Azure. I run each morning a scheduler job at 2:00AM that creates a lot of hangfire jobs.

At this time, the Web Api app has only one available instance that is configure to scale out based on CPU metrics. These running hangfire jobs increase the CPU percentage to the limit and create new available instances of the api app.

Unfortunately, it seems to me a given hangfire job runs on the instance that created it. How can I configure Hangfire to dispatch jobs on all the available instances ?

答:
Unfortunately, it seems to me a given hangfire job runs on the instance that created it. How can I configure Hangfire to dispatch jobs on all the available instances ?

AFAIK, the job would in the default queue by default. If you run multiple server instances, the job would be distributed to available instances. For testing, I just adding my tasks as follows:

```<code>Enumerable.Range(11, 30).ForEach(i =>
{
    BackgroundJob.Enqueue(() => Console.WriteLine($"[Task-{i}] Getting Started with HangFire!"));
});
</code>```

Then, processing the jobs in a console application as follows:

```<code>using (var server = new BackgroundJobServer())
{
    Console.WriteLine("Hangfire Server started. Press any key to exit...");
    Console.ReadKey();
}
</code>```

I started two server instances and I got the following result:

Moreover, for configuring Job Queues you could follow here. Also, here is an issue that is the opposite of your issue about running a job only on one server instance.

Body:
Unfortunately, it seems to me a given hangfire job runs on the instance that created it. How can I configure Hangfire to dispatch jobs on all the available instances ?

AFAIK, the job would in the default queue by default. If you run multiple server instances, the job would be distributed to available instances. For testing, I just adding my tasks as follows:

Enumerable.Range(11, 30).ForEach(i =>
{
    BackgroundJob.Enqueue(() => Console.WriteLine($"[Task-{i}] Getting Started with HangFire!"));
});

Then, processing the jobs in a console application as follows:

using (var server = new BackgroundJobServer())
{
    Console.WriteLine("Hangfire Server started. Press any key to exit...");
    Console.ReadKey();
}

I started two server instances and I got the following result:

Moreover, for configuring Job Queues you could follow here. Also, here is an issue that is the opposite of your issue about running a job only on one server instance.


问:
PHP Search Query Error: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean
I'm trying to use a textbox and button to search my database then have it be displayed in a table, still starting out so I'm very shaking on this. I keep getting this error:

Warning: sqlsrv_fetch_array(): 2 is not a valid ss_sqlsrv_stmt resource in C:\RDEUsers\NET\531545\LocationPOST.php on line 55

Very confused as to what exactly is wrong.

```<code>        <?php

if(isset($_POST['Search']))
{
    $SearchValue = $_POST['SearchValue'];
    // search in all table columns
    // using concat mysql function
    $LocationQuery = "SELECT * FROM Location WHERE (Username, First_Name, Surname, Current_Location) LIKE '%".$SearchValue."%'";
    $search_result = FilterTable($LocationQuery);

}
 else {
    $LocationQuery = "SELECT * FROM Location";
    $search_result = FilterTable($LocationQuery);
}

// function to connect and execute the query
function FilterTable($LocationQuery)
{
$server = 'SQL2008.net.dcs.hull.ac.uk';
$connectionInfo = array("Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);

$Filter_Result = sqlsrv_query($conn, $LocationQuery);
 return $Filter_Result;
}

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title> Location Tracker </title>
</head>

<center><h1> ACW Location Tracker </h1></center>

<body>

 <form action="LocationPOST.php" method="POST">
<input type="text" name="SearchValue" placeholder="Username"><br><br>
<input type="submit" name="Search" value="Search"><br><br>

<table>
<tr>
<th> Username </th>
<th> First_Name </th>
<th> Surname </th>
<th> Current_Location </th>

</tr>

<?php while($row = sqlsrv_fetch_array($search_result)):?>

       <tr>
                    <td><?php echo $row['Username'];?></td>
                    <td><?php echo $row['First_Name'];?></td>
                    <td><?phpecho $row['Surname'];?></td>
                    <td><?php echo $row['Current_Location'];?></td>
       </tr>

<?php endwhile;?>

<?php

//set timezone to current timezone GMT
date_default_timezone_set('Europe/London');

$server = 'SQL2008.net.dcs.hull.ac.uk';
//sets up connection to database
$connectionInfo = array("Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);
//creates a table called location in the database
$LocationQuery='create table Location ';
$LocationQuery .= '(Username int NOT NULL IDENTITY(500, 23), First_Name varchar(50) NOT NULL, Surname varchar(50) NOT NULL, Current_Location varchar(50) NOT NULL, Date date NOT NULL, PRIMARY KEY (Username))';
$result = sqlsrv_query($conn, $LocationQuery);

if (!$result)
{
 if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "<p>Error: ".$error[ 'message']."</p>";
}
}
}
else
{
echo "<p>DB successfully created</p>";
}
//close server connection
sqlsrv_close($conn);

$server = 'SQL2008.net.dcs.hull.ac.uk';
$connectionInfo = array( "Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);
date_default_timezone_set('Europe/London');
$date =  new DateTime('');
$dateStr = $date->format("Y-m-d H:i:s");
$d=strtotime("");
$insert_query = "INSERT INTO Location (First_Name, Surname, Current_Location) VALUES (?, ?, ?, ?)";
$params = array("John","Doe","Hull" );
$result = sqlsrv_query($conn,$insert_query,$params);
$params = array("Jane","Doe","London");
$result = sqlsrv_query($conn,$insert_query,$params);
$params = array("Jon","Doe","Sheffield");
$result = sqlsrv_query($conn,$insert_query,$params);

//select all data from table Location in the database
$LocationQuery='SELECT * FROM Location';
$results = sqlsrv_query($conn, $LocationQuery);
// while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
// {
// echo '<p>'.$row['Username'].' '.$row['First_Name'].' '.$row['Surname'].' '.$row['Current_Location']. '</p>';
// }
// sqlsrv_close($conn);

//display the associative array results in a table
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
    echo "<tr><td>".$row['Username']."</td><td>".$row['First_Name']."</td><td>".$row['Surname']."</td><td>".$row['Current_Location']."</td><td>".$dateStr = $date->format("Y-m-d H:i:s")."</td></tr>";
}

sqlsrv_close($conn);
?>

</table>

</form>

</body>
</html>
</code>```

答:
One of your queries is failing (I'd guess "SELECT * FROM Location WHERE (Username, First_Name, Surname, Current_Location) LIKE '%".$SearchValue."%'").

If sqlsrv_query fails, it returns false (which you don't check for) and passes it to sqlsrv_fetch_array.

Body:
I'm trying to use a textbox and button to search my database then have it be displayed in a table, still starting out so I'm very shaking on this. I keep getting this error:

Warning: sqlsrv_fetch_array(): 2 is not a valid ss_sqlsrv_stmt resource in C:\RDEUsers\NET\531545\LocationPOST.php on line 55

Very confused as to what exactly is wrong.

        <?php

if(isset($_POST['Search']))
{
    $SearchValue = $_POST['SearchValue'];
    // search in all table columns
    // using concat mysql function
    $LocationQuery = "SELECT * FROM Location WHERE (Username, First_Name, Surname, Current_Location) LIKE '%".$SearchValue."%'";
    $search_result = FilterTable($LocationQuery);

}
 else {
    $LocationQuery = "SELECT * FROM Location";
    $search_result = FilterTable($LocationQuery);
}

// function to connect and execute the query
function FilterTable($LocationQuery)
{
$server = 'SQL2008.net.dcs.hull.ac.uk';
$connectionInfo = array("Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);

$Filter_Result = sqlsrv_query($conn, $LocationQuery);
 return $Filter_Result;
}

?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title> Location Tracker </title>

 ACW Location Tracker

 <form action="LocationPOST.php" method="POST">
<input type="text" name="SearchValue" placeholder="Username">

<input type="submit" name="Search" value="Search">

 Username
 First_Name
 Surname
 Current_Location

<?php while($row = sqlsrv_fetch_array($search_result)):?>

                    <?php echo $row['Username'];?>
                    <?php echo $row['First_Name'];?>
                    <?phpecho $row['Surname'];?>
                    <?php echo $row['Current_Location'];?>

<?php endwhile;?>

<?php

//set timezone to current timezone GMT
date_default_timezone_set('Europe/London');

$server = 'SQL2008.net.dcs.hull.ac.uk';
//sets up connection to database
$connectionInfo = array("Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);
//creates a table called location in the database
$LocationQuery='create table Location ';
$LocationQuery .= '(Username int NOT NULL IDENTITY(500, 23), First_Name varchar(50) NOT NULL, Surname varchar(50) NOT NULL, Current_Location varchar(50) NOT NULL, Date date NOT NULL, PRIMARY KEY (Username))';
$result = sqlsrv_query($conn, $LocationQuery);

if (!$result)
{
 if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "
Error: ".$error[ 'message']."
";
}
}
}
else
{
echo "
DB successfully created
";
}
//close server connection
sqlsrv_close($conn);

$server = 'SQL2008.net.dcs.hull.ac.uk';
$connectionInfo = array( "Database"=>"rde_531545");
$conn = sqlsrv_connect($server,$connectionInfo);
date_default_timezone_set('Europe/London');
$date =  new DateTime('');
$dateStr = $date->format("Y-m-d H:i:s");
$d=strtotime("");
$insert_query = "INSERT INTO Location (First_Name, Surname, Current_Location) VALUES (?, ?, ?, ?)";
$params = array("John","Doe","Hull" );
$result = sqlsrv_query($conn,$insert_query,$params);
$params = array("Jane","Doe","London");
$result = sqlsrv_query($conn,$insert_query,$params);
$params = array("Jon","Doe","Sheffield");
$result = sqlsrv_query($conn,$insert_query,$params);

//select all data from table Location in the database
$LocationQuery='SELECT * FROM Location';
$results = sqlsrv_query($conn, $LocationQuery);
// while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
// {
// echo '
'.$row['Username'].' '.$row['First_Name'].' '.$row['Surname'].' '.$row['Current_Location']. '
';
// }
// sqlsrv_close($conn);

//display the associative array results in a table
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
    echo "
".$row['Username']."	".$row['First_Name']."	".$row['Surname']."	".$row['Current_Location']."	".$dateStr = $date->format("Y-m-d H:i:s")."
";
}

sqlsrv_close($conn);
?>

</form>