问:
Access to DialectResolutionInfo
I tried to make a simple Web application with Spring following this is Tutorial:  A simple Web application with Spring

Im trying to do the same project with Wampserver database

The error I am getting is this:

```<code>    oct. 20, 2016 12:33:57 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
Infos: validateJarFile(D:\FormationJEE\WORKSPACE\WORKSPACE-HIBERNATE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\tutoriel-web-spring\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: No Spring WebApplicationInitializer types detected on classpath
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext listenerStart
Grave: Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:150)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 22 more

oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext startInternal
Grave: Error listenerStart
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext startInternal
Grave: Erreur de démarrage du contexte [/tutoriel-web-spring] suite aux erreurs précédentes
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: Closing Spring root WebApplicationContext
oct. 20, 2016 12:33:58 AM org.apache.coyote.AbstractProtocol start
Infos: Starting ProtocolHandler ["http-bio-8085"]
oct. 20, 2016 12:33:58 AM org.apache.coyote.AbstractProtocol start
Infos: Starting ProtocolHandler ["ajp-bio-8009"]
oct. 20, 2016 12:33:58 AM org.apache.catalina.startup.Catalina start
Infos: Server startup in 10010 ms
</code>```

I modified the files:

server.xml

```<code><GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
                <Resource name="jdbc/app_gestion_cours"
                auth="Container"
                type="javax.sql.DataSource"
                username="user"
                password="user"
                driverClassName="com.mysql.jdbc.Driver"
                description="Global Address Database"
                url="jdbc:mysql://localhost:8080/app_gestion_cours"
                maxActive="15"
                maxIdle="3"/>

    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>
</code>```

context.xml

```<code>    ...
<ResourceLink name="jdbc/app_gestion_cours" global="jdbc/app_gestion_cours"
        type="javax.sql.DataSource" />
</code>```

dispatcher-servlet.xml

```<code>...
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
            <property name="jndiName" value="java:comp/env/jdbc/app_gestion_cours" />
        </bean>
...
</code>```

答:
Make sure you have this in you spring application properties:

Make sure you have an application.properties in your classpath and add the following properties, if you have something else that is not postgres need to put the correct class there

```<code>spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
</code>```

Title: Access to DialectResolutionInfo

Body:
I tried to make a simple Web application with Spring following this is Tutorial:  A simple Web application with Spring

Im trying to do the same project with Wampserver database

The error I am getting is this:

    oct. 20, 2016 12:33:57 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
Infos: validateJarFile(D:\FormationJEE\WORKSPACE\WORKSPACE-HIBERNATE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\tutoriel-web-spring\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: No Spring WebApplicationInitializer types detected on classpath
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext listenerStart
Grave: Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:150)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 22 more

oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext startInternal
Grave: Error listenerStart
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.StandardContext startInternal
Grave: Erreur de démarrage du contexte [/tutoriel-web-spring] suite aux erreurs précédentes
oct. 20, 2016 12:33:58 AM org.apache.catalina.core.ApplicationContext log
Infos: Closing Spring root WebApplicationContext
oct. 20, 2016 12:33:58 AM org.apache.coyote.AbstractProtocol start
Infos: Starting ProtocolHandler ["http-bio-8085"]
oct. 20, 2016 12:33:58 AM org.apache.coyote.AbstractProtocol start
Infos: Starting ProtocolHandler ["ajp-bio-8009"]
oct. 20, 2016 12:33:58 AM org.apache.catalina.startup.Catalina start
Infos: Server startup in 10010 ms

I modified the files:

server.xml

<GlobalNamingResources>

                <Resource name="jdbc/app_gestion_cours"
                auth="Container"
                type="javax.sql.DataSource"
                username="user"
                password="user"
                driverClassName="com.mysql.jdbc.Driver"
                description="Global Address Database"
                url="jdbc:mysql://localhost:8080/app_gestion_cours"
                maxActive="15"
                maxIdle="3"/>

    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

context.xml

    ...
<ResourceLink name="jdbc/app_gestion_cours" global="jdbc/app_gestion_cours"
        type="javax.sql.DataSource" />

dispatcher-servlet.xml

...
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
            <property name="jndiName" value="java:comp/env/jdbc/app_gestion_cours" />
        </bean>
...

Body:
Make sure you have this in you spring application properties:

Make sure you have an application.properties in your classpath and add the following properties, if you have something else that is not postgres need to put the correct class there

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect


来源: stackexchange

问:
What is the gold standard for creating a main() loop that waits for a Thread in Java
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

```<code>public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}
</code>```

ServerModule looks like this:

```<code>public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}
</code>```

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

```<code>while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
</code>```

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

答:
Also you can use CountDownLatch for your purpose, see example:

```<code>public class ServerModule extends Thread {
    private final CountDownLatch latch;

    ServerModule(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000L);
            //decrease counter of the latch when job is done
            latch.countDown();
        } catch (InterruptedException e) {
             e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // as ctor arg use threads count for countdown
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Start server");
        ServerModule serverModule = new ServerModule(latch);
        serverModule.start();

        try {
            //waiting until latch count will be 0
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Server is done");
    }
}
</code>```

Also with CountDownLatch you can create multiple server instances and waiting them in main thread until they are all done.

ContentLicense: CC BY-SA 3.0

Body:
I was tasked to write a small server application. It is supposed to be started via the console and then run in the background, processing some network traffic and calculating stuff locally until it receives a shutdown signal. I am pretty sure i can handle all of that - except the very basic application architecture. I am super unsure how to bring my main loop to wait for the application to finish. So here is my current code, cleaned up and omitting unnecessary parts.

public class TestServer {

public static Logger logger;
private static Boolean abortStartup = false;
private static ServerModule server;

public static void main(String[] args) {
    System.out.println("Starting Server...");
        initializeServer(); //this function reads config file, and initializes all variables and stuff. If anything goes wrong, abortStartup is set to true

        if (!abortStartup) {
            runMainLoop();
        }

        if (!abortStartup) {
            cleanup(); //clean up all initialized variables and objects
        }

    System.out.println("Goodbye.");
}

private static void runMainLoop() {
    //This is the main loop. Run this until application terminates.
    logger.log(null, "Starting main loop...", Logger.LOGLEVEL_NOTE);
        server.run();
        while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }
        }
    logger.log(null, "Done.", Logger.LOGLEVEL_NOTE);
}

ServerModule looks like this:

public class ServerModule{

public Boolean shutdown = false;
private Boolean stayAlive = true;

public ServerModule(){
    //setup everything
}

public void run() {
    //initalize timers, instantiate objects etc.. add listeners and everything. At some point, a network message will set stayAlive to false;
}

public Boolean isAlive() {
    return stayAlive;
}

Now for the actual question: is there a more elegant or more efficient way to go about this? i am talking about this part specifically:

while (server.isAlive()) {
            //wait until server dies.
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                logger.log(null, "Interrupted during wait for main thread.", Logger.LOGLEVEL_ERROR);
            }

Is thread.sleep okay here? Could or should i even omit it? I want to wait here at this very point of my code, so i can clean up after execution stops.

Body:
Also you can use CountDownLatch for your purpose, see example:

public class ServerModule extends Thread {
    private final CountDownLatch latch;

    ServerModule(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000L);
            //decrease counter of the latch when job is done
            latch.countDown();
        } catch (InterruptedException e) {
             e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // as ctor arg use threads count for countdown
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Start server");
        ServerModule serverModule = new ServerModule(latch);
        serverModule.start();

        try {
            //waiting until latch count will be 0
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Server is done");
    }
}

Also with CountDownLatch you can create multiple server instances and waiting them in main thread until they are all done.


问:
Ways to protect code repository from breaking or buggy commits?
How do you or have tried to protect your source code repositories from commits that introduce bugs or break builds? It seems that forced regression testing upon commit can go a long way towards preventing bugs from creeping into projects worked on by multiple developers. However, most common code versioning tools don't offer any features in this area.

Here is one method I have experimented with. I created subversion pre-commit hooks to generate a copy of the project with pending commit's changes merged in, then it ran syntax check and unit tests on this copy. If any of the tests failed, commit would get rejected with results of the syntax checker or unit testing to provide feedback to developer making that commit. If syntax checker and unit tests passed, commit would get accepted. It worked but the trade off was that it made commits really slow. If code versioning software provided better integration to facilitate this other than running external programs on pre-commit, I think speed could be improved.

I'm looking for methods you've used to achieve this, thoughts on why this is a good or a bad idea, or experiences with code versioning tools that provide support for regression testing / build testing on code check in. Also how important is speed of commits to you?

答: You should be making use of some form of Continuous Integration where the environment is making use of Hudson, CruiseControl, or other tool to facilitate this behavior.</p>

ContentLicense: CC BY-SA 2.5


问:
Invalid Length Parameter Passed to the Right Function After Converting MySQL to SQL Server
I am getting an error

Invalid length parameter passed to the RIGHT function

when I run this sql script

```<code>SELECT count(*) as count
FROM damage_reports AS a
JOIN comments AS b ON b.v_id = a.v_id AND b.comment_txt LIKE ('Damage Report #%')
JOIN VIN AS c ON a.v_id = c.v_id
JOIN damage_report_entries AS d ON a.dr_id = d.dr_id

WHERE LEFT(RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)),
CHARINDEX(':',RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt) -1)))=
convert(nvarchar(10), d.dr_id)
AND a.dateIncident BETWEEN '2017-04-26' AND '2017-06-05'
</code>```

The RIGHT function that is causing the issue is the 2nd RIGHT. If I remove the -1 it runs but gives wrong result. Any help is greatly appreciated!

答:
You most likely have some data which doesn't conform to the RIGHT clause. When you omit the -1 at the end you will get results, though some of the strings will be blank or NULL - this is what you're referring to when you are saying that you are getting incorrect data without the -1.

In order for you to catch those values, please try running the following query against your database. Whatever results you get here are the ones responsible for messing up your query.

```<code>SELECT
    count(*) as [count ]
FROM damage_reports AS a
JOIN comments AS b ON b.v_id = a.v_id AND b.comment_txt LIKE ('Damage Report #%')
JOIN VIN AS c ON a.v_id = c.v_id
JOIN damage_report_entries AS d ON a.dr_id = d.dr_id
WHERE LEN(LEFT(
    RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)),
    CHARINDEX(':',RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)))))<= 0
AND a.dateIncident BETWEEN '2017-04-26' AND '2017-06-05'
</code>```

Once you get these results, you'll have the requisite records which you'll need to tweak your join.

Best of luck.

Body:
I am getting an error

Invalid length parameter passed to the RIGHT function

when I run this sql script

SELECT count(*) as count
FROM damage_reports AS a
JOIN comments AS b ON b.v_id = a.v_id AND b.comment_txt LIKE ('Damage Report #%')
JOIN VIN AS c ON a.v_id = c.v_id
JOIN damage_report_entries AS d ON a.dr_id = d.dr_id

WHERE LEFT(RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)),
CHARINDEX(':',RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt) -1)))=
convert(nvarchar(10), d.dr_id)
AND a.dateIncident BETWEEN '2017-04-26' AND '2017-06-05'

The RIGHT function that is causing the issue is the 2nd RIGHT. If I remove the -1 it runs but gives wrong result. Any help is greatly appreciated!

Body:
You most likely have some data which doesn't conform to the RIGHT clause. When you omit the -1 at the end you will get results, though some of the strings will be blank or NULL - this is what you're referring to when you are saying that you are getting incorrect data without the -1.

In order for you to catch those values, please try running the following query against your database. Whatever results you get here are the ones responsible for messing up your query.

SELECT
    count(*) as [count ]
FROM damage_reports AS a
JOIN comments AS b ON b.v_id = a.v_id AND b.comment_txt LIKE ('Damage Report #%')
JOIN VIN AS c ON a.v_id = c.v_id
JOIN damage_report_entries AS d ON a.dr_id = d.dr_id
WHERE LEN(LEFT(
    RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)),
    CHARINDEX(':',RIGHT(b.comment_txt, LEN(b.comment_txt) - CHARINDEX('#',b.comment_txt)))))<= 0
AND a.dateIncident BETWEEN '2017-04-26' AND '2017-06-05'

Once you get these results, you'll have the requisite records which you'll need to tweak your join.

Best of luck.


问:
Highcharts. Series highlighting not showing up in download
I've been working on the following example: http://jsfiddle.net/d69otfmb/1/

```<code>function showSeries(e) {
    this.graph.attr("stroke", (e.checked ? this.color : '#ccc'));
    this.graph.attr("stroke-width", (e.checked ? 4 : 2));
    if(e.checked ==  true){
        this.group.toFront();
        this.options.enableMouseTracking=true;
    } else {
        this.options.enableMouseTracking=false;
    }
}
function highlightSer(chart){
    var series = chart.series, i;
    for(i=0; i<series.length; i++) {
        series[i].options.enableMouseTracking=false;
        if( series[i].selected==true) {
             series[i].options.enableMouseTracking=true;
             showSeries.call(series[i], {checked: true});
        }
    }
}

var optionsChart1 = {
    chart: {
        renderTo:'container'
    },
.
.
.
    plotOptions: {
        series: {
            showCheckbox:true,
            events: {
                checkboxClick:showSeries
            }
        }
    },
.
.
.
}

chart = new Highcharts.Chart(optionsChart1,highlightSer);
</code>```

I've set this up so I can use the checkboxes to highlight a series, and also so that only the highlighted series show up in the tooltip (through options.enableMouseTracking).

It works out pretty neat, but when it comes to exporting or downloading, any adjustments that have been made to the chart don't make it to the export server.

After checking many examples and reading the API a dozen times, I still can't make it work. Any ideas?

答:
You are changing graphical attributes of the series without using Highcharts API. You would need to the same in the exporting callback to have colored lines. Anyway, you can use series update to correctly update the series which will be exported as you would want to.

Except of updating colors, you should update selected option as well.

```<code>function showSeries(e) {
  e.preventDefault && e.preventDefault()

  if (e.checked == true) {
    this.group.toFront();
  }

  this.update({
    selected: e.checked,
    lineColor: e.checked ? this.color : '#ccc',
    lineWidth: e.checked ? 4 : 2,
    enableMouseTracking: e.checked
  }, true, false)
}

function highlightSer(chart) {
  var series = chart.series,
    i;
  for (i = 0; i < series.length; i++) {
    if (series[i].selected == true) {
      showSeries.call(series[i], {
        checked: true
      });
    }
  }
}
</code>```

example: http://jsfiddle.net/0uxehybb/

Body:
I've been working on the following example: http://jsfiddle.net/d69otfmb/1/

function showSeries(e) {
    this.graph.attr("stroke", (e.checked ? this.color : '#ccc'));
    this.graph.attr("stroke-width", (e.checked ? 4 : 2));
    if(e.checked ==  true){
        this.group.toFront();
        this.options.enableMouseTracking=true;
    } else {
        this.options.enableMouseTracking=false;
    }
}
function highlightSer(chart){
    var series = chart.series, i;
    for(i=0; i<series.length; i++) {
        series[i].options.enableMouseTracking=false;
        if( series[i].selected==true) {
             series[i].options.enableMouseTracking=true;
             showSeries.call(series[i], {checked: true});
        }
    }
}

var optionsChart1 = {
    chart: {
        renderTo:'container'
    },
.
.
.
    plotOptions: {
        series: {
            showCheckbox:true,
            events: {
                checkboxClick:showSeries
            }
        }
    },
.
.
.
}

chart = new Highcharts.Chart(optionsChart1,highlightSer);

I've set this up so I can use the checkboxes to highlight a series, and also so that only the highlighted series show up in the tooltip (through options.enableMouseTracking).

It works out pretty neat, but when it comes to exporting or downloading, any adjustments that have been made to the chart don't make it to the export server.

After checking many examples and reading the API a dozen times, I still can't make it work. Any ideas?

Body:
You are changing graphical attributes of the series without using Highcharts API. You would need to the same in the exporting callback to have colored lines. Anyway, you can use series update to correctly update the series which will be exported as you would want to.

Except of updating colors, you should update selected option as well.

function showSeries(e) {
  e.preventDefault && e.preventDefault()

  if (e.checked == true) {
    this.group.toFront();
  }

  this.update({
    selected: e.checked,
    lineColor: e.checked ? this.color : '#ccc',
    lineWidth: e.checked ? 4 : 2,
    enableMouseTracking: e.checked
  }, true, false)
}

function highlightSer(chart) {
  var series = chart.series,
    i;
  for (i = 0; i < series.length; i++) {
    if (series[i].selected == true) {
      showSeries.call(series[i], {
        checked: true
      });
    }
  }
}

example: http://jsfiddle.net/0uxehybb/


问:
Angular4: router, children (optional) parameters
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

```<code>matches/results/4/2017 or
matches/results/4 or
matches/results
</code>```

all should be valid and come through in this.route.snapshot.params

I tried this:

```<code>  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},
</code>```

with no luck, only :page comes through as param

答:
Consider the following structure:

```<code>const paths: Routes = [
  {
    path: 'matches',
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'fixtures' },
      { path: 'fixtures', component: FixturesComponent },
      { path: 'competitions', component: CompetitionsPageComponent },
      {
        path: ':page',
        component: PageComponent,
        children: [
          {
            path: ':team',
            component: TeamComponent
            children: [
              {
                path: ':season',
                component: SeasonComponent,
                children: [

                ]
              }
            ]
          }
        ]
      }
    ]
  }
];
</code>```

Depending on in which component you inject ActivatedRoute, you will be able to access different route parameters. For example

If you inject ActivatedRoute in SeasonComponent and do the following:

```<code>this._route.params.subscribe(p => console.log(JSON.stringify(p)));
</code>```

You will see an object made of page,team and season properties.

If you do the same for PageComponent, you will get an object made of only one property, page. If u get the point, if you inject ActivatedRoute in the TeamComponent, parameters would have only 2 properties.

The fact that you listen to the Router events and then read the properties in the ActivatedRoute instance dont make a difference, because the injected instance of the ActivatedRoute class contains only the parameters that where present in the route at the moment that the component, in which the instance is being injected, was generated.

So basically, at least with this approach, is not possible to access from a component at a certain level in the component hierarchy to route parameters further down in it.

Hope it helps!

Body:
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

matches/results/4/2017 or
matches/results/4 or
matches/results

all should be valid and come through in this.route.snapshot.params

I tried this:

  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},

with no luck, only :page comes through as param

Body:
Consider the following structure:

const paths: Routes = [
  {
    path: 'matches',
    children: [
      { path: '', pathMatch: 'full', redirectTo: 'fixtures' },
      { path: 'fixtures', component: FixturesComponent },
      { path: 'competitions', component: CompetitionsPageComponent },
      {
        path: ':page',
        component: PageComponent,
        children: [
          {
            path: ':team',
            component: TeamComponent
            children: [
              {
                path: ':season',
                component: SeasonComponent,
                children: [

                ]
              }
            ]
          }
        ]
      }
    ]
  }
];

Depending on in which component you inject ActivatedRoute, you will be able to access different route parameters. For example

If you inject ActivatedRoute in SeasonComponent and do the following:

this._route.params.subscribe(p => console.log(JSON.stringify(p)));

You will see an object made of page,team and season properties.

If you do the same for PageComponent, you will get an object made of only one property, page. If u get the point, if you inject ActivatedRoute in the TeamComponent, parameters would have only 2 properties.

The fact that you listen to the Router events and then read the properties in the ActivatedRoute instance dont make a difference, because the injected instance of the ActivatedRoute class contains only the parameters that where present in the route at the moment that the component, in which the instance is being injected, was generated.

So basically, at least with this approach, is not possible to access from a component at a certain level in the component hierarchy to route parameters further down in it.

Hope it helps!


问:
Unknown mappedBy in hibernate OneToOne relationship
This is yet another question on the unknown mappedBy exception thrown by Hibernate while create a OneToOne relationship between two objects.

From my understanding a mappedBy is required in one of the two objects to state that the tables are joined by a primary key by the second table.

This mapping declaration needs to exist on the table containing the foriegn key.

based on this , here are the two classes

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "second")
public class Second implements Serializable{

    @OneToOne(cascade= CascadeType.ALL)
    @JoinColumn(name="first_id")
    First first;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
</code>```

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "first")
public class First implements Serializable{

    @OneToOne(mappedBy="first")
    Second second;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

}
</code>```

This throws an exception

```<code>Unknown mappedBy in: First.second, referenced property unknown: Second.first
</code>```

What am I missing?

答: I hadnt registered the classes with the Hibernate Bundle instance in teh application class</p>

Body:
This is yet another question on the unknown mappedBy exception thrown by Hibernate while create a OneToOne relationship between two objects.

From my understanding a mappedBy is required in one of the two objects to state that the tables are joined by a primary key by the second table.

This mapping declaration needs to exist on the table containing the foriegn key.

based on this , here are the two classes

@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "second")
public class Second implements Serializable{

    @OneToOne(cascade= CascadeType.ALL)
    @JoinColumn(name="first_id")
    First first;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "first")
public class First implements Serializable{

    @OneToOne(mappedBy="first")
    Second second;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

}

This throws an exception

Unknown mappedBy in: First.second, referenced property unknown: Second.first

What am I missing?


问:
Custom class for UITabBarItem in ios
I have a tabbar with 5 tabs(0,1,2,3,4) at the bottom of the screen and they have different icons. What I am trying to achieve is for the 2nd tab I want a UIView on it and an image inside this UIView.

For this, I tried creating custom UITabBarItem class but I don't see any way I can add UIView in this custom class. Is there any way I can achieve this?

Hope you understand the problem.

Thanks in advance

答:
If you don't want to show one tab in specific condition then you should set viewcontrollers of tabbabcontroller something like,

```<code>  NSMutableArray *tabBarVcArr =  [self.tabBarController.viewControllers mutableCopy];

[tabBarVcArr removeObjectAtIndex:1];  // this will remove second tab

self.tabBarController.viewControllers = tabBarVcArr;
</code>```

if you want to add tab again then you can instantiate your tabbarcontroller from your storyboard !

That's it!! no need to subclass UITabBarButtonItem etc!

Title: Custom class for UITabBarItem in ios

Body:
If you don't want to show one tab in specific condition then you should set viewcontrollers of tabbabcontroller something like,

  NSMutableArray *tabBarVcArr =  [self.tabBarController.viewControllers mutableCopy];

[tabBarVcArr removeObjectAtIndex:1];  // this will remove second tab

self.tabBarController.viewControllers = tabBarVcArr;

if you want to add tab again then you can instantiate your tabbarcontroller from your storyboard !

That's it!! no need to subclass UITabBarButtonItem etc!


问:
on clicking the particular number in the table, how do i make it redirect to different popups/table
```<code>//http request from json data
$http({
     method: 'GET',
     url: '/Home/GetJson'
}).then(function successCallback(response) {
     console.log(response);
     $scope.jsonData = response;

     var data = response.data;
     $scope.ngData = response.data;
})
</code>```

table created from json data is as below:

```<code>    var table = $('<table id="Table"></table>');
    var someRow = "<tr class='someClass' ><th id='header1' >Product</th><th>P1</th><th>P2</th><th>P3</th><th>P4</th><th>Total</th></tr>";
    $("#Table").append(someRow);
    for (var i = 0; i <data.length; i++) {
        var tr = $('<tr></tr>');
        for (var key in data[i]) {
            var td = $('<td></td>');
            td.attr('class', key);
            td.append("<a href='#'>" + data[i][key] + "</a>");
            tr.append(td);
        }
        table.append(tr);
    }
    $('#div1').html(table.prepend(someRow));
</code>```

答:
This code is not related to AngularJS.
it s a pure JS/JQuery code.

Therefore; I'll provide a reply on JQuery.

You need to create dynamicly; AFTER the cell is created; for every button an event to load the popup such as :

```<code>for(var i=0;i< data.length;i++)
{
  for(var key=0;j< data[i].length;j++)
  {
    data[i][j].addEventListener('click',function(){
      // Your On Click code to load your modal

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

This code shall be added AFTER the element are on your DOM; therefore after : $('#div1').html(table.prepend(someRow));

------ EDIT

After more analysis; I see that you mixed AngularJS and JQUERY !
This is a very huge mistake as JS and Angular does not work the same.

Therefore; OR you change the loading part of your Json; and add a plan $ajax loading system; OR you remove your dynamic creating of DOM with Jquery and add a standard Angular JS behaviour

Body:
//http request from json data
$http({
     method: 'GET',
     url: '/Home/GetJson'
}).then(function successCallback(response) {
     console.log(response);
     $scope.jsonData = response;

     var data = response.data;
     $scope.ngData = response.data;
})

table created from json data is as below:

    var table = $('

');
    var someRow = "
Product	P1	P2	P3	P4	Total
";
    $("#Table").append(someRow);
    for (var i = 0; i <data.length; i++) {
        var tr = $('

');
        for (var key in data[i]) {
            var td = $('	');
            td.attr('class', key);
            td.append("" + data[i][key] + "");
            tr.append(td);
        }
        table.append(tr);
    }
    $('#div1').html(table.prepend(someRow));

Body:
This code is not related to AngularJS.
it s a pure JS/JQuery code.

Therefore; I'll provide a reply on JQuery.

You need to create dynamicly; AFTER the cell is created; for every button an event to load the popup such as :

for(var i=0;i< data.length;i++)
{
  for(var key=0;j< data[i].length;j++)
  {
    data[i][j].addEventListener('click',function(){
      // Your On Click code to load your modal

    },false);
  }
}

This code shall be added AFTER the element are on your DOM; therefore after : $('#div1').html(table.prepend(someRow));

------ EDIT

After more analysis; I see that you mixed AngularJS and JQUERY !
This is a very huge mistake as JS and Angular does not work the same.

Therefore; OR you change the loading part of your Json; and add a plan $ajax loading system; OR you remove your dynamic creating of DOM with Jquery and add a standard Angular JS behaviour


问:
how to make a single Main Menu active(has the colour ) in Accordian menu - jquery , javascript
here is the fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/13/

As you can see the Menu 2  does not have any child item , how to make the 'Menu 2 ' to have color when clicked (same color which appears while hovering submenu )

JS

```<code> $(document).ready(function () {

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });
</code>```

HTML

```<code><ul id="accordion" class="accordion">
<li>
                            <div class="link">Menu 1</div>
                            <ul class="submenu">
                                <li ><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                         <li>
                            <ul class="link">Menu 2</ul>
                        </li>
                        <li>
                            <div class="link">Menu 3</div>
                            <ul class="submenu">
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                        </ul>
</code>```

CSS

```<code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}
</code>```

答:
Check this https://jsfiddle.net/ucgff65k/17/ It should help you

 $(document).ready(function () {

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
  text-decoration: none;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.has-dropdown .submenu a:hover,
.accordion > li:not(.has-dropdown) > .link:active {
  background: #b63b4d;
  color: #FFF;
}</code>```

Menu 1

submenu1

submenu1

submenu1

   Menu 2

Menu 3

submenu1

submenu1

submenu1

```

Body:
here is the fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/13/

As you can see the Menu 2  does not have any child item , how to make the 'Menu 2 ' to have color when clicked (same color which appears while hovering submenu )

JS

 $(document).ready(function () {

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });

HTML

Menu 1

submenu1

submenu1

submenu1

Menu 2

Menu 3

submenu1

submenu1

submenu1

CSS

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.submenu a:hover {
  background: #b63b4d;
  color: #FFF;
}

Body:
Check this https://jsfiddle.net/ucgff65k/17/ It should help you

 $(document).ready(function () {

    $("#accordion > li > div").click(function () {
        $("#submenu li").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
    });
    });

.accordion {
  width: 100%;
  max-width: 260px;
  background: #FFF;
  margin: 0;
  padding: 0;
  box-sizing:border-box;

}

.accordion .link {
  cursor: pointer;
  display: block;
  padding: 15px 15px 15px 42px;
  font-size: 14px;
  font-weight: 700;
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
  border-right: 1px solid #CCC;
  position: relative;
  -webkit-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
  text-decoration: none;
}

/*-------------Submenu-----------------------------*/

.submenu {
   padding:0px;
  display: none;
  font-size: 14px;
}

.submenu li { border-bottom: 1px solid #4b4a5e; }

.submenu a {
  display: block;
  text-decoration: none;
  color: #23222d;
  background-color:#CCC;
  padding: 12px;
  padding-left: 42px;
  -webkit-transition: all 0.25s ease;
  -o-transition: all 0.25s ease;
  transition: all 0.25s ease;
}

#submenu li.active {
     display: block;
}

.has-dropdown .submenu a:hover,
.accordion > li:not(.has-dropdown) > .link:active {
  background: #b63b4d;
  color: #FFF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="accordion" class="accordion">
<li class='has-dropdown'>
    <div class="link">Menu 1</div>
    <ul class="submenu">
        <li ><a href="#">submenu1</a></li>
        <li><a href="#">submenu1</a></li>
        <li><a href="#">submenu1</a></li>
    </ul>
</li>
 <li>
   <a class="link" href="">Menu 2</a>
</li>
<li>
    <div class="link">Menu 3</div>
    <ul class="submenu">
        <li><a href="#">submenu1</a></li>
        <li><a href="#">submenu1</a></li>
        <li><a href="#">submenu1</a></li>
    </ul>
</li>
</ul>


问:
MATCH in mysql takes only a single column.
```<code>$tex = $_GET['searchMe'];
$query = $Config::$con->query("SELECT * FROM `news` WHERE MATCH(title,description) AGAINST('".$tex."')");
</code>```

MATCH only takes a single column , either title or description.
If i add both of the column names in it, i'll get null results when i fetch it.

*NOTE: I've already made both of my columns as FULLTEXT.

答:
You write a query Look Like this </p>

```<code>$tex = $_GET['searchMe'];
$query = $Config::$con->query("SELECT * FROM `news` WHERE title = '$tex' && description ='$tex'");
</code>```

Body:
$tex = $_GET['searchMe'];
$query = $Config::$con->query("SELECT * FROM `news` WHERE MATCH(title,description) AGAINST('".$tex."')");

MATCH only takes a single column , either title or description.
If i add both of the column names in it, i'll get null results when i fetch it.

*NOTE: I've already made both of my columns as FULLTEXT.

Body:
You write a query Look Like this

$tex = $_GET['searchMe'];
$query = $Config::$con->query("SELECT * FROM `news` WHERE title = '$tex' && description ='$tex'");


问:
Oracle- show all name columns (more then 30 characters) is possible?
Hy, can you help me whith this? I want to show the entire name of the columns(from the pivot). Ca this be possible? I know that tha maximum lenght is 30...</p>

答:
If I understand well, you want to build a query with a column alias longer than 30 characters; if so, you only can in Oracle 12.2 and on.

With previous versions, this is what you get:

```<code>SQL> select 1 as "Alias with 30 characters -----"
  2  from dual;

Alias with 30 characters -----
------------------------------
                             1

SQL> select 1 as "Alias with 31 characters -----X"
  2  from dual;
select 1 as "Alias with 31 characters -----X"
            *
ERROR at line 1:
ORA-00972: identifier is too long
</code>```

Body:
If I understand well, you want to build a query with a column alias longer than 30 characters; if so, you only can in Oracle 12.2 and on.

With previous versions, this is what you get:

SQL> select 1 as "Alias with 30 characters -----"
  2  from dual;

Alias with 30 characters -----
------------------------------
                             1

SQL> select 1 as "Alias with 31 characters -----X"
  2  from dual;
select 1 as "Alias with 31 characters -----X"
            *
ERROR at line 1:
ORA-00972: identifier is too long


问:
C#, Using Main variables in methods without passing parameters?
How can I use a variable/const, declared in Main, inside another method?
Without passing it like: static string my_method(string my_variable_to_pass)
Just using static void my_method()

What I want is to call any other method into Main and it has to use the variable declared in Main.

I do not want to use public static class either because it does not seem the proper way.
Is there another way?

Here is an example of what I want. This code does not work because "cats does not exist in the current contend" inside test_method().
But how could I make it work without adding too complicated code?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        string cats;

        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}
</code>```

答:
I do not want to use public static class either because it does not seem the proper way. Is there another way?

You don't need a class, but at least a static field or property or move an instance along. It is either of those.

The scope of the variable is now only on the method level, you can't access it from anywhere else.

This will do:

```<code>class Program
{
    public static string Cats {get;private set;}

    static void Main(string[] args)
    {
</code>```

Then call it:

```<code>var c = Program.Cats;
</code>```

You could also encapsulate the property into a class and move that instance along.

Body:
How can I use a variable/const, declared in Main, inside another method?
Without passing it like: static string my_method(string my_variable_to_pass)
Just using static void my_method()

What I want is to call any other method into Main and it has to use the variable declared in Main.

I do not want to use public static class either because it does not seem the proper way.
Is there another way?

Here is an example of what I want. This code does not work because "cats does not exist in the current contend" inside test_method().
But how could I make it work without adding too complicated code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        string cats;

        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}

Body:
I do not want to use public static class either because it does not seem the proper way. Is there another way?

You don't need a class, but at least a static field or property or move an instance along. It is either of those.

The scope of the variable is now only on the method level, you can't access it from anywhere else.

This will do:

class Program
{
    public static string Cats {get;private set;}

    static void Main(string[] args)
    {

Then call it:

var c = Program.Cats;

You could also encapsulate the property into a class and move that instance along.


问:
execute tasks on multipe hosts in one playbook
I have a playbook that automatically adds hosts to our monitoring system. The first part runs on the monitoring server while the second part runs on a client. Currently I'm running it with hosts: all and executing it with ansible-playbook -l new_client.

```<code>- hosts: monitoring_server
   tasks:
   - name: generate pki
...
 - hosts: all
   tasks:
   - name: downloading icinga2 repository
</code>```

When executing the playbook, the first task returns skipping: no hosts matched

How can I solve this problem?

答:
You can use host patterns, such as:

```<code>- hosts: all:!monitoring_server
</code>```

to execute play an all hosts except those in monitoring_server group (or host if it is an individual host).

Body:
I have a playbook that automatically adds hosts to our monitoring system. The first part runs on the monitoring server while the second part runs on a client. Currently I'm running it with hosts: all and executing it with ansible-playbook -l new_client.

- hosts: monitoring_server
   tasks:
   - name: generate pki
...
 - hosts: all
   tasks:
   - name: downloading icinga2 repository

When executing the playbook, the first task returns skipping: no hosts matched

How can I solve this problem?

Body:
You can use host patterns, such as:

- hosts: all:!monitoring_server

to execute play an all hosts except those in monitoring_server group (or host if it is an individual host).


问:
Show message if there is an error in the form in angular 2
I have the following form and I need that after the user clicks Save, an error message shows next to the radio group that is required (but no radio selected). I tried the following but it doesn't show the message at all.</p>

```<code><form #formList="ngForm" (ngSubmit)="Save(formList)">
    <div *ngFor="let item of data">
      <p>{{item.name}}</p>
      <input type="radio" name="{{item.id}}" [value]="1" [(ngModel)]="item.isSelected" required>Foo
      <input type="radio" name="{{item.id}}" [value]="2" [(ngModel)]="item.isSelected">Bar
      <div *ngIf="formList.controls.item?.id.required">
        The radio is required!
      </div>
    </div>
  <button type="submit">Save</button>
</form>
</code>```

答:
Try this code</p>

```<code><form #formList="ngForm" (ngSubmit)="Save(formList)">
    <div *ngFor="let item of data">
      <p>{{item.name}}</p>
      <input type="radio" name="{{item.id}}" [value]="1" [(ngModel)]="item.isSelected" required>Foo
      <input type="radio" name="{{item.id}}" [value]="2" [(ngModel)]="item.isSelected">Bar
      <div *ngIf="!formList.form.valid">
        The radio is required!
      </div>
    </div>
  <button type="submit">Save</button>
</form>
</code>```

Body:
I have the following form and I need that after the user clicks Save, an error message shows next to the radio group that is required (but no radio selected). I tried the following but it doesn't show the message at all.

<form #formList="ngForm" (ngSubmit)="Save(formList)">

{{item.name}}

      <input type="radio" name="{{item.id}}" [value]="1" [(ngModel)]="item.isSelected" required>Foo
      <input type="radio" name="{{item.id}}" [value]="2" [(ngModel)]="item.isSelected">Bar

        The radio is required!

  <button type="submit">Save</button>
</form>

Body:
Try this code

<form #formList="ngForm" (ngSubmit)="Save(formList)">
    <div *ngFor="let item of data">
      <p>{{item.name}}</p>
      <input type="radio" name="{{item.id}}" [value]="1" [(ngModel)]="item.isSelected" required>Foo
      <input type="radio" name="{{item.id}}" [value]="2" [(ngModel)]="item.isSelected">Bar
      <div *ngIf="!formList.form.valid">
        The radio is required!
      </div>
    </div>
  <button type="submit">Save</button>
</form>


答:
you can define variables at the class level, so they are scoped to the entire class:

```<code>class Program
{
    private static string cats;

    static void Main(string[] args)
    {
        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}
</code>```

because you are using this in static methods, make sure your field is also static, as your static methods would not be allowed to access and instance field.

Title: C#, Using Main variables in methods without passing parameters?

Body:
you can define variables at the class level, so they are scoped to the entire class:

class Program
{
    private static string cats;

    static void Main(string[] args)
    {
        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}

because you are using this in static methods, make sure your field is also static, as your static methods would not be allowed to access and instance field.


答:
What I want is to call any other method into Main and it has to use the variable declared in Main.

This is not possible without using a closure. However in your case it is much better to use a class-level field, like this:

```<code>class Program
{
    private static string cats;

    static void Main(string[] args)
    {
        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}
</code>```

Body:
What I want is to call any other method into Main and it has to use the variable declared in Main.

This is not possible without using a closure. However in your case it is much better to use a class-level field, like this:

class Program
{
    private static string cats;

    static void Main(string[] args)
    {
        cats = "1000 Cats";
        test_method();
        cats = "6 Cats";
        test_method();
    }

    static void test_method()
    {
        Console.Write(cats);
    }
}


问:
Give div a style when redirecting with header
I am redirecting to a page with a header link header('Location: ../index.php?resp=resp2#contact'); and when I press that link I want my div to start with the style left: 12vw. I don't want this to happen when you refresh the page. How can I do this?

I tried stuff with a resp in the link, but I already make use of resp's and I don't think it's possible to send 2 resp's at once? I also tried doing it with javascript so when a page is reloaded it will give the style, but then it also triggers on refresh.

It doesn't matter if it is javascript, JQuery , php or just normal html/css, I just hope I'll get it to work.

答:
You could set a session variable before the redirection, if the variable is set, echo that style and clear the given variable. That way, on refresh, it will not echo the style.

Page with redirection:

```<code>// session_start(); // if not yet started
$_SESSION['style_div'] = true;
header('Location: ../index.php?resp=resp2#contact');
exit; // just in case;
</code>```

Page with given DIV:

```<code>// ... [probably some code]
// session_start(); // if not yet started
if(isset($_SESSION['style_div'])){
    unset($_SESSION['style_div']);
    echo '<div style="left: 12vw ...">';
}else{
    echo '<div style="...">';
};
// ... [rest of code]
</code>```

Body:
You could set a session variable before the redirection, if the variable is set, echo that style and clear the given variable. That way, on refresh, it will not echo the style.

Page with redirection:

// session_start(); // if not yet started
$_SESSION['style_div'] = true;
header('Location: ../index.php?resp=resp2#contact');
exit; // just in case;

Page with given DIV:

// ... [probably some code]
// session_start(); // if not yet started
if(isset($_SESSION['style_div'])){
    unset($_SESSION['style_div']);
    echo '<div style="left: 12vw ...">';
}else{
    echo '<div style="...">';
};
// ... [rest of code]


问:
Implicit conversions and rounding
Just come across an interesting one:

```<code>declare @test as int
set @test = 47

select @test * 4.333
</code>```

returns 203.651

```<code>declare @test as int
set @test = 47

declare @out as int
set @out = (select @test * 4.333)

select @out
</code>```

returns 203

```<code>declare @test as int
set @test = 47

declare @out as int
set @out = round((select @test * 4.333),0)

select @out
</code>```

returns 204

Now I know why it does this.  Its because there is an implicit conversion from decimal to int, therefore the decimal places need chopped off (hence 203), whereas if I round prior to the implicit conversion I get 204.

My question is why when SQL Server does an implicit conversion is it not also rounding?  I know if I had a big number, and it needed stored in a small place, the first thing I'd do would be to round it so as to be as close to the original number as possible.

It just doesn't seem intuitive to me.

答:
This got me reading and the answer seems to be distinctly unsatisfying, The earliest SQL reference I've been able to find (ANSI 92 available here) in section 4.4.1  Characteristics of numbers states that

Whenever an exact or approximate numeric value is assigned to a
  data item or parameter representing an exact numeric value,
  an approximation of its value that preserves leading significant
  digits after rounding or truncating is represented in the data
  type of the target. The value is converted to have the precision and
  scale of the target. The choice of whether to truncate or round
  is implementation-defined.

Which leaves it up to Microsoft which of the two they chose to implement for T-SQL and I assume for the sake of simplicity they chose truncation. From the wikipedia article on rounding it seems that this wasn't an uncommon decision back in the day.

It's interesting to note that, according to the documentation I found, only conversions to integers cause truncation, the others cause rounding. Although for some bizarre reason the conversion from money to integer appears to buck the trend as it's allowed to round.

From     To       Behaviour

numeric  numeric  Round

numeric  int      Truncate

numeric  money    Round

money    int      Round

money    numeric  Round

float    int      Truncate

float    numeric  Round

float    datetime Round

datetime int      Round
```

Table from here.

Title: Implicit conversions and rounding

Body:
Just come across an interesting one:

declare @test as int
set @test = 47

select @test * 4.333

returns 203.651

declare @test as int
set @test = 47

declare @out as int
set @out = (select @test * 4.333)

select @out

returns 203

declare @test as int
set @test = 47

declare @out as int
set @out = round((select @test * 4.333),0)

select @out

returns 204

Now I know why it does this.  Its because there is an implicit conversion from decimal to int, therefore the decimal places need chopped off (hence 203), whereas if I round prior to the implicit conversion I get 204.

My question is why when SQL Server does an implicit conversion is it not also rounding?  I know if I had a big number, and it needed stored in a small place, the first thing I'd do would be to round it so as to be as close to the original number as possible.

It just doesn't seem intuitive to me.

Body:
This got me reading and the answer seems to be distinctly unsatisfying, The earliest SQL reference I've been able to find (ANSI 92 available here) in section 4.4.1  Characteristics of numbers states that

Whenever an exact or approximate numeric value is assigned to a
  data item or parameter representing an exact numeric value,
  an approximation of its value that preserves leading significant
  digits after rounding or truncating is represented in the data
  type of the target. The value is converted to have the precision and
  scale of the target. The choice of whether to truncate or round
  is implementation-defined.

Which leaves it up to Microsoft which of the two they chose to implement for T-SQL and I assume for the sake of simplicity they chose truncation. From the wikipedia article on rounding it seems that this wasn't an uncommon decision back in the day.

It's interesting to note that, according to the documentation I found, only conversions to integers cause truncation, the others cause rounding. Although for some bizarre reason the conversion from money to integer appears to buck the trend as it's allowed to round.

From     To       Behaviour

numeric  numeric  Round

numeric  int      Truncate

numeric  money    Round

money    int      Round

money    numeric  Round

float    int      Truncate

float    numeric  Round

float    datetime Round

datetime int      Round

Table from here.

ContentLicense: CC BY-SA 4.0


问:
Python requests dict as form-data
I have a python dict

```<code>x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}
</code>```

I'm trying to get my form-data to be

```<code>id=123
data[param1]=hello
data[param2]=world
</code>```

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

```<code>requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})
</code>```

The request goes out with form data looking like this

```<code>id=123
data=param1
data=param2
</code>```

Is there a way to get around this?

答:
Instead of posting data = x you should be posting data=x['data']. This should solve your issue.

```<code>requests.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})
</code>```

Or better way would be to remove the data key from your dict and directly create dict as

```<code>x = {'param1': 'hello', 'param2': 'world'}
</code>```

And then you can post like:

```<code>requests.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})
</code>```

Choose what works best for you..

Hope this helps :)

Title: Python requests dict as form-data

Body:
I have a python dict

x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}

I'm trying to get my form-data to be

id=123
data[param1]=hello
data[param2]=world

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})

The request goes out with form data looking like this

id=123
data=param1
data=param2

Is there a way to get around this?

Body:
Instead of posting data = x you should be posting data=x['data']. This should solve your issue.

requests.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})

Or better way would be to remove the data key from your dict and directly create dict as

x = {'param1': 'hello', 'param2': 'world'}

And then you can post like:

requests.post(url, data=x['data'], headers={'content-type': 'application/x-www-form-urlencoded'})

Choose what works best for you..

Hope this helps :)


问:
Overriding zuul error filter results in Forwarding error
I'm trying to override the default senderorfilter for zuul proxy so that I can present a better response when a service behind my gateway has crashed/is down. Here is the code that I took from the answer in Customizing Zuul Exception

```<code>public class RabbrErrorFilter extends ZuulFilter {

private static final Logger log = LoggerFactory.getLogger(RabbrErrorFilter.class);
protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return Integer.MIN_VALUE; // Needs to run before SendErrorFilter which has filterOrder == 0
}

@Override
public boolean shouldFilter() {
    // only forward to errorPath if it hasn't been forwarded to already
    RequestContext ctx = RequestContext.getCurrentContext();
    return ctx.containsKey("error.status_code") && !ctx.getBoolean(SEND_ERROR_FILTER_RAN,false);
}
@Override
public Object run() {
    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        Object e = ctx.get("error.exception");

        if (e != null && e instanceof ZuulException) {
            ZuulException zuulException = (ZuulException)e;
            log.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);

            // Remove error code to prevent further error handling in follow up filters
            ctx.remove("error.status_code");

            // Populate context with new response values
            ctx.setResponseBody("Overriding Zuul Exception Body");
            ctx.getResponse().setContentType("application/json");
            ctx.setResponseStatusCode(500); //Can set any error code as excepted
            ctx.setSendZuulResponse(false);
        }
    }
    catch (Exception ex) {
        log.error("Exception filtering in custom error filter", ex);
        ReflectionUtils.rethrowRuntimeException(ex);
    }
    return null;
}
</code>```

I've checked with a debugger that the code in run() is executed when a zuul exception is thrown, but in the console log I get this:

```<code>com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:157) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:132) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:78) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:161) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:120) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81) ~[zuul-core-1.1.0.jar:1.1.0]
</code>```

and the response from the service behind the gateway is timed out with status 500.

-- Edit*
Updating the spring-cloud dependencies (contains zuul 1.3.0 core) did not fix this

答:
Please check this solution: Spring Cloud: Zuul error handling. It worked for me, specially for Forwarding error of Zuul.

The Zuul error handling is being handled through RibbonRoutingFilter and SendErrorFilter and will forward any errored request to ${error.path}, which defaults to ‘/error’. In case you relay on the defaults that will be handled by Spring Boot’s BasicErrorController. You can overide this behaviour and implement your own ErrorController.

You don't necessarily need to follow a Vnd error style, just follow the general logic of coding a custom implementation of Spring's ErrorController.

Body:
I'm trying to override the default senderorfilter for zuul proxy so that I can present a better response when a service behind my gateway has crashed/is down. Here is the code that I took from the answer in Customizing Zuul Exception

public class RabbrErrorFilter extends ZuulFilter {

private static final Logger log = LoggerFactory.getLogger(RabbrErrorFilter.class);
protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return Integer.MIN_VALUE; // Needs to run before SendErrorFilter which has filterOrder == 0
}

@Override
public boolean shouldFilter() {
    // only forward to errorPath if it hasn't been forwarded to already
    RequestContext ctx = RequestContext.getCurrentContext();
    return ctx.containsKey("error.status_code") && !ctx.getBoolean(SEND_ERROR_FILTER_RAN,false);
}
@Override
public Object run() {
    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        Object e = ctx.get("error.exception");

        if (e != null && e instanceof ZuulException) {
            ZuulException zuulException = (ZuulException)e;
            log.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);

            // Remove error code to prevent further error handling in follow up filters
            ctx.remove("error.status_code");

            // Populate context with new response values
            ctx.setResponseBody("Overriding Zuul Exception Body");
            ctx.getResponse().setContentType("application/json");
            ctx.setResponseStatusCode(500); //Can set any error code as excepted
            ctx.setSendZuulResponse(false);
        }
    }
    catch (Exception ex) {
        log.error("Exception filtering in custom error filter", ex);
        ReflectionUtils.rethrowRuntimeException(ex);
    }
    return null;
}

I've checked with a debugger that the code in run() is executed when a zuul exception is thrown, but in the console log I get this:

com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:157) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:132) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:78) ~[spring-cloud-netflix-core-1.1.0.RC2.jar:1.1.0.RC2]
    at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:161) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:120) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116) ~[zuul-core-1.1.0.jar:1.1.0]
    at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81) ~[zuul-core-1.1.0.jar:1.1.0]

and the response from the service behind the gateway is timed out with status 500.

-- Edit*
Updating the spring-cloud dependencies (contains zuul 1.3.0 core) did not fix this


问:
How to get price of Chart HLine objects and calculate Fibonacci levels
Three part question:

How to find 2 user created horizontal lines on a chart by name and return the price of each.

Then determine which HLine was crossed by the price most recently to determine trend direction.

Calculate Fibonacci levels based on prices and direction

答:
Difficult to understand exactly what you are after, not sure if you are trying to find the graphical objects or just calculate levels based on the prices. Assuming you have the price of the two horizontal lines, the following structure and function can be used to calculate Fibonacci levels. (price 1 is earlier in time than price 2).

Calculation based on formula found here

```<code>struct FibLevel {
    double retrace38;
    double retrace50;
    double retrace61;
    double extension61;
    double extension100;
    double extension138;
    double extension161;
};

void FibLevel(double price1, double price2,FibLevel &fiblevel)
{
    double range = MathAbs(price1-price2);
    fiblevel.retrace38   =(price1<price2)?price2-range*0.382:price1+range*0.382;
    fiblevel.retrace50   =(price1<price2)?price2-range*0.500:price1+range*0.500;
    fiblevel.retrace61   =(price1<price2)?price2-range*0.618:price1+range*0.618;
    fiblevel.extension61 =(price1<price2)?price2+range*0.618:price1-range*0.618;
    fiblevel.extension100=(price1<price2)?price2+range      :price1-range;
    fiblevel.extension138=(price1<price2)?price2+range*1.382:price1-range*1.382;
    fiblevel.extension161=(price1<price2)?price2+range*1.618:price1-range*1.618;
}
</code>```

Body:
Difficult to understand exactly what you are after, not sure if you are trying to find the graphical objects or just calculate levels based on the prices. Assuming you have the price of the two horizontal lines, the following structure and function can be used to calculate Fibonacci levels. (price 1 is earlier in time than price 2).

Calculation based on formula found here

struct FibLevel {
    double retrace38;
    double retrace50;
    double retrace61;
    double extension61;
    double extension100;
    double extension138;
    double extension161;
};

void FibLevel(double price1, double price2,FibLevel &fiblevel)
{
    double range = MathAbs(price1-price2);
    fiblevel.retrace38   =(price1<price2)?price2-range*0.382:price1+range*0.382;
    fiblevel.retrace50   =(price1<price2)?price2-range*0.500:price1+range*0.500;
    fiblevel.retrace61   =(price1<price2)?price2-range*0.618:price1+range*0.618;
    fiblevel.extension61 =(price1<price2)?price2+range*0.618:price1-range*0.618;
    fiblevel.extension100=(price1<price2)?price2+range      :price1-range;
    fiblevel.extension138=(price1<price2)?price2+range*1.382:price1-range*1.382;
    fiblevel.extension161=(price1<price2)?price2+range*1.618:price1-range*1.618;
}


答:
Declare static string cats; in Program class:

```<code>class Program
{
   static string cats;

  static void Main(string[] args)
  {
    cats = "1000 Cats";
    test_method();
    cats = "6 Cats";
    test_method();
  }

  static void test_method()
  {
    Console.Write(cats);
  }
}
</code>```

That way cats can be accessed and used by any static method definied within Program class

Body:
Declare static string cats; in Program class:

class Program
{
   static string cats;

  static void Main(string[] args)
  {
    cats = "1000 Cats";
    test_method();
    cats = "6 Cats";
    test_method();
  }

  static void test_method()
  {
    Console.Write(cats);
  }
}

That way cats can be accessed and used by any static method definied within Program class


问:
PHP check payment method in returned object
I'm not so good in PHP because of the way it prints arrays. I return a var called $order, and I get the following:

```<code>{
    "id":14770,
    "parent_id":0,
    "status":"on-hold",
    "currency":"EUR",
    "version":"3.0.7",
    "prices_include_tax":true,
    "date_created":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "date_modified":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "discount_total":"0",
    "discount_tax":"0",
    "shipping_total":"4.09",
    "shipping_tax":"0.8589",
    "cart_tax":"1.1107",
    "total":"11.35",
    "total_tax":"1.9696",
    "customer_id":8,
    "order_key":"wc_order_59393eec03f4a",
    "payment_method":"bacs",
    "payment_method_title":"Bankoverschrijving",
    "transaction_id":"",
    "customer_user_agent":"mozilla\/5.0 (windows nt 10.0; win64; x64) applewebkit\/537.36 (khtml, like gecko) chrome\/58.0.3029.110 safari\/537.36",
    "created_via":"checkout",
    "customer_note":"",
    "date_completed":null,
    "date_paid":null,
    "cart_hash":"c517e3080e56d6d341bc93d4ff219b31",
    "number":"14770",
    "meta_data":[
        {
            "id":257891,
            "key":"_wc_customer_order_xml_export_suite_is_exported",
            "value":"0"
        },
        {
            "id":257892,
            "key":"_wc_customer_order_xml_export_suite_customer_is_exported",
            "value":"0"
        },
        {
            "id":257938,
            "key":"_billing_email-2"
        },
        {
            "id":257939,
            "key":"vat_number",
            "value":"NL234077232B02"
        },
        {
            "id":257940,
            "key":"_vat_country",
            "value":"NL"
        },
        {
            "id":257941,
            "key":"_vat_number_validated",
            "value":"valid"
        },
        {
            "id":257942,
            "key":"_customer_location_self_certified",
            "value":"no"
        },
        {
            "id":257943,
            "key":"_eu_vat_data",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "exchange_rates_provider_label":"BitPay",
                "invoice_currency":"EUR",
                "taxes":{
                    "25":{
                        "label":"21% NL BTW",
                        "vat_rate":"21.0000",
                        "country":"NL",
                        "tax_rate_class":"",
                        "tax_payable_to_country":"NL",
                        "amounts":{
                            "items_total":1.1107,
                            "shipping_total":0.8589
                        }
                    }
                },
                "vat_currency":"EUR",
                "vat_currency_exchange_rate":1,
                "vat_currency_exchange_rate_timestamp":1493135026
            }
        },
        {
            "id":257944,
            "key":"_eu_vat_evidence",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "location":{
                    "is_eu_country":1,
                    "billing_country":"NL",
                    "shipping_country":"NL",
                    "self_certified":"no"
                },
                "exemption":{
                    "vat_country":"NL",
                    "vat_number_validated":"valid"
                }
            }
        },
        {
            "id":257947,
            "key":"_wcpdf_proforma_date",
            "value":"2017-06-08 14:11:25"
        },
        {
            "id":257948,
            "key":"_wcpdf_proforma_number",
            "value":"513"
        },
        {
            "id":257949,
            "key":"_wcpdf_formatted_proforma_number",
            "value":"89000513"
        },
        {
            "id":257951,
            "key":"_order_stock_reduced",
            "value":"yes"
        }
    ],
    "line_items":{
        "17631":{

        }
    },
    "tax_lines":{
        "17633":{

        }
    },
    "shipping_lines":{
        "17632":{

        }
    },
    "fee_lines":[

    ],
    "coupon_lines":[

    ]
}
</code>```

I would like to do a check on the payment method, so I can create arguments based on that. Right now, the payment method is bacs, but how can I check that?
Any idea what I need to return for that?

答:
You are dealing with a json object. You need to use json_decode () and access it like an normal php indexed array.

```<code>$arr = json_decode ($your_array, true);
</code>```

Then access it like $arr ['payment_method'].

OR

```<code>$arr = json_decode ($your_array);
</code>```

Then access it like $arr->payment_method.

Body:
I'm not so good in PHP because of the way it prints arrays. I return a var called $order, and I get the following:

{
    "id":14770,
    "parent_id":0,
    "status":"on-hold",
    "currency":"EUR",
    "version":"3.0.7",
    "prices_include_tax":true,
    "date_created":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "date_modified":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "discount_total":"0",
    "discount_tax":"0",
    "shipping_total":"4.09",
    "shipping_tax":"0.8589",
    "cart_tax":"1.1107",
    "total":"11.35",
    "total_tax":"1.9696",
    "customer_id":8,
    "order_key":"wc_order_59393eec03f4a",
    "payment_method":"bacs",
    "payment_method_title":"Bankoverschrijving",
    "transaction_id":"",
    "customer_user_agent":"mozilla\/5.0 (windows nt 10.0; win64; x64) applewebkit\/537.36 (khtml, like gecko) chrome\/58.0.3029.110 safari\/537.36",
    "created_via":"checkout",
    "customer_note":"",
    "date_completed":null,
    "date_paid":null,
    "cart_hash":"c517e3080e56d6d341bc93d4ff219b31",
    "number":"14770",
    "meta_data":[
        {
            "id":257891,
            "key":"_wc_customer_order_xml_export_suite_is_exported",
            "value":"0"
        },
        {
            "id":257892,
            "key":"_wc_customer_order_xml_export_suite_customer_is_exported",
            "value":"0"
        },
        {
            "id":257938,
            "key":"_billing_email-2"
        },
        {
            "id":257939,
            "key":"vat_number",
            "value":"NL234077232B02"
        },
        {
            "id":257940,
            "key":"_vat_country",
            "value":"NL"
        },
        {
            "id":257941,
            "key":"_vat_number_validated",
            "value":"valid"
        },
        {
            "id":257942,
            "key":"_customer_location_self_certified",
            "value":"no"
        },
        {
            "id":257943,
            "key":"_eu_vat_data",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "exchange_rates_provider_label":"BitPay",
                "invoice_currency":"EUR",
                "taxes":{
                    "25":{
                        "label":"21% NL BTW",
                        "vat_rate":"21.0000",
                        "country":"NL",
                        "tax_rate_class":"",
                        "tax_payable_to_country":"NL",
                        "amounts":{
                            "items_total":1.1107,
                            "shipping_total":0.8589
                        }
                    }
                },
                "vat_currency":"EUR",
                "vat_currency_exchange_rate":1,
                "vat_currency_exchange_rate_timestamp":1493135026
            }
        },
        {
            "id":257944,
            "key":"_eu_vat_evidence",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "location":{
                    "is_eu_country":1,
                    "billing_country":"NL",
                    "shipping_country":"NL",
                    "self_certified":"no"
                },
                "exemption":{
                    "vat_country":"NL",
                    "vat_number_validated":"valid"
                }
            }
        },
        {
            "id":257947,
            "key":"_wcpdf_proforma_date",
            "value":"2017-06-08 14:11:25"
        },
        {
            "id":257948,
            "key":"_wcpdf_proforma_number",
            "value":"513"
        },
        {
            "id":257949,
            "key":"_wcpdf_formatted_proforma_number",
            "value":"89000513"
        },
        {
            "id":257951,
            "key":"_order_stock_reduced",
            "value":"yes"
        }
    ],
    "line_items":{
        "17631":{

        }
    },
    "tax_lines":{
        "17633":{

        }
    },
    "shipping_lines":{
        "17632":{

        }
    },
    "fee_lines":[

    ],
    "coupon_lines":[

    ]
}

I would like to do a check on the payment method, so I can create arguments based on that. Right now, the payment method is bacs, but how can I check that?
Any idea what I need to return for that?

Body:
You are dealing with a json object. You need to use json_decode () and access it like an normal php indexed array.

$arr = json_decode ($your_array, true);

Then access it like $arr ['payment_method'].

OR

$arr = json_decode ($your_array);

Then access it like $arr->payment_method.


问:
Saving app data, or recovering the data once the app has been deleted
I have an Ipad air 1, which currently has an app that won't start. I have information on the app, that won't start, but if I delete the app I will lose the data. Is there any way I can back up the app's data, or save it before deleting the app and restoring the data?

Ipad specs:

```<code>Model: md792b/a
ios version is 10.3 ios
</code>```

I have looked at phonedisk, which seems to only be valid up to 10.10, any help would be greatly appreciated,

答:
Look a view May be it will be helpfull http://addpod.com/juicephone.
this one too https://apple.stackexchange.com/questions/15183/can-i-extract-application-data-from-an-ios-device</p>

Body:
I have an Ipad air 1, which currently has an app that won't start. I have information on the app, that won't start, but if I delete the app I will lose the data. Is there any way I can back up the app's data, or save it before deleting the app and restoring the data?

Ipad specs:

Model: md792b/a
ios version is 10.3 ios

I have looked at phonedisk, which seems to only be valid up to 10.10, any help would be greatly appreciated,