text:
Q: Error: java.lang.NoSuchMethodError: org.hibernate.integrator.internal.IntegratorServiceImpl. I am getting below error while I am upgrading hibernate from 4.1 to 5.3.1. The project build just fine but when I run it I am getting this error. On doing some digging around, I found that this is mostly related with old hibernate jars being present in classpath.
Below are the jars present in lib folder of my latest war file.
all-themes-1.0.9.jar
antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.1.jar
aspectjrt-1.7.2.jar
aspectjweaver-1.7.2.jar
byte-buddy-1.8.12.jar
cglib-2.2.2.jar
classmate-0.8.0.jar
codegen-0.6.1.jar
commons-beanutils-1.8.3.jar
commons-codec-1.5.jar
commons-collections-3.2.1.jar
commons-configuration-1.9.jar
commons-dbcp-1.4.jar
commons-digester-2.1.jar
commons-fileupload-1.3.jar
commons-io-1.4.jar
commons-lang-2.6.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-net-2.0.jar
commons-pool-1.5.4.jar
commons-vfs2-2.0.jar
dom4j-1.6.1.jar
dozer-5.4.0.jar
ecj-3.7.2.jar
el-impl-2.2.jar
fr.opensagres.xdocreport.converter-1.0.3.jar
fr.opensagres.xdocreport.converter.docx.xwpf-1.0.3.jar
fr.opensagres.xdocreport.core-1.0.3.jar
fr.opensagres.xdocreport.document-1.0.3.jar
fr.opensagres.xdocreport.document.docx-1.0.3.jar
fr.opensagres.xdocreport.itext.extension-1.0.3.jar
fr.opensagres.xdocreport.template-1.0.3.jar
fr.opensagres.xdocreport.template.velocity-1.0.3.jar
gson-2.2.4.jar
guava-13.0.1.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-entitymanager-5.3.1.Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-validator-5.0.1.Final.jar
itext-2.1.7.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.inject-1.jar
javax.persistence-api-2.2.jar
jboss-el-2.0.0.GA.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
joda-time-2.2.jar
jsr305-1.3.9.jar
jta-1.1.jar
liferay-faces-1513-patch-3.2.4-ga5.jar
liferay-faces-bridge-api-3.1.3-ga4.jar
liferay-faces-bridge-impl-3.1.3-ga4.jar
liferay-faces-portal-3.1.3-ga4.jar
liferay-faces-util-3.1.3-ga4.jar
log4j-1.2.17.jar
maven-scm-api-1.4.jar
maven-scm-provider-perforce-1.8.jar
maven-scm-provider-svn-commons-1.4.jar
maven-scm-provider-svnexe-1.4.jar
mysema-commons-lang-0.2.4.jar
ojdbc14-10.2.0.4.0.jar
ooxml-schemas-1.1.jar
opencsv-2.3.jar
org.apache.poi.xwpf.converter.core-1.0.3.jar
org.apache.poi.xwpf.converter.pdf-1.0.3.jar
org.apache.poi.xwpf.converter.xhtml-1.0.3.jar
oro-2.0.8.jar
plexus-utils-3.0.3.jar
poi-3.9.jar
poi-ooxml-3.9.jar
primefaces-4.0.jar
primefaces-extensions-1.0.0.jar
querydsl-apt-3.3.0.jar
querydsl-codegen-3.3.0.jar
querydsl-core-3.3.0.jar
querydsl-jpa-3.3.0.jar
regexp-1.3.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-3.2.3.RELEASE.jar
spring-aspects-3.2.3.RELEASE.jar
spring-beans-3.2.3.RELEASE.jar
spring-context-3.2.3.RELEASE.jar
spring-context-support-3.2.3.RELEASE.jar
spring-core-3.2.3.RELEASE.jar
spring-data-commons-1.6.3.RELEASE.jar
spring-data-jdbc-core-1.0.0.RELEASE.jar
spring-data-jpa-1.4.3.RELEASE.jar
spring-data-oracle-1.0.0.RELEASE.jar
spring-expression-3.2.3.RELEASE.jar
spring-instrument-3.2.3.RELEASE.jar
spring-jdbc-3.2.3.RELEASE.jar
spring-orm-3.2.3.RELEASE.jar
spring-retry-1.0.0.RELEASE.jar
spring-tx-3.2.3.RELEASE.jar
spring-web-3.2.3.RELEASE.jar
stax-api-1.0.1.jar
validation-api-1.1.0.Final.jar
velocity-1.7.jar
vtd-xml-2.11.jar
xmlbeans-2.3.0.jar

The error I get
2019-03-30 14:46:04,315 ERROR org.springframework.web.context.ContextLoader:Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in file [C:\liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\temp\0-Kir\WEB-INF\classes\context\spring-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\temp\0-Kir\WEB-INF\classes\context\spring-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.integrator.internal.IntegratorServiceImpl.<init>(Ljava/util/LinkedHashSet;Lorg/hibernate/boot/registry/classloading/spi/ClassLoaderService;)V
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
        at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:741)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1099)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1621)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\liferay-portal-6.1.1-ce-ga2\tomcat-7.0.27\temp\0-Kir\WEB-INF\classes\context\spring-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.integrator.internal.IntegratorServiceImpl.<init>(Ljava/util/LinkedHashSet;Lorg/hibernate/boot/registry/classloading/spi/ClassLoaderService;)V
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:439)
        at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:277)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
        at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:71)
        at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:85)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1502)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1470)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
        ... 23 more
Caused by: java.lang.NoSuchMethodError: org.hibernate.integrator.internal.IntegratorServiceImpl.<init>(Ljava/util/LinkedHashSet;Lorg/hibernate/boot/registry/classloading/spi/ClassLoaderService;)V
        at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:224)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildBootstrapServiceRegistry(EntityManagerFactoryBuilderImpl.java:455)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:199)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:167)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:32)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:89)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:174)
        at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:149)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
        ... 38 more

How should I debug which jar is causing this issue ?

A: With 5.3.1 you definitely need to use hibernate-jpa-2.1.
Try to run the mvn dependency:tree to find which dependency is having the hibernate-jpa-2.0-api-1.0.0.Final.jar. Exclude this transitive dependency.


text: Q: Is CSS Grid Using Regular CSS Under the Hood? I have been wondering if CSS Grid is completely new functionality to the CSS language, or if it is essentially syntactic sugar - aka is grid just using the CSS that predated it under the hood. Can everything in CSS grid essentially be done using plain CSS?

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Place" or "Site"? I'm looking for the most appropriate term to refer to places/sites where you can do something specific. In my case it's going out for taking photos. Which of these two words would best suit that use? From a dictionary I've found that a site is more of a real estate or premises whereas a place is more neutrally a locality of anything. Or is there another word to use?
I'd like to avoid the term "location", too, because it's already part of the title. A subtitle would probably use another word for that to avoid repetition.

A: My choice would be "site". "Place" is a neutral word; it would mostly be a spatial reference in this case. A site is rather a place that you think of in a physical sense; it includes an impression of the surrounding landscape or something like that. A construction site is the physical plot of land where the building is being constructed, including piles of sand and such; the place of a building makes me think of its place in the sense of coordinates or on a map.
For photography, the landscape and the surroundings are said to be important, so that "site" would seem a good choice.
Note that the distinction is by no means clear cut or strict, and that both words have some related but different connotations as well.

A: Be careful about using "site" if there's any chance that people could become confused about whether or not you mean "website." If context will make it clear that it's not an online place, then I prefer site for the same reasons as @cerberus.

A: You might also consider spot, which I've often seen in this context.
Spot, or point, might work well if you are using a map.


text:
Q: How to calculate correctly in php? $total = 30 - $nr1 / 13 - $nr2 - 6 * $nr3 - 3

I know we learned that in school but what is first (+ or - or * or /), where are the brackets or do I even need them ?

A: You put brackets to priortizes what should be calculated first. In math though it starts from division, multiplication, subtraction and finally addition. So, here is the order of precedence for these:

*

*division

*multiplication

*subtraction

*addition

You can however override that rule by specifying brackets, for example you might want to have addition calculated first before anything else.
More Info:

*

*http://php.net/manual/en/language.operators.precedence.php

A: $total = 30 - ($nr1 / 13) - $nr2 - (6 * $nr3) - 3

I don't think extra brackets would harm. I always use them to improve readability

A: See the chapter about Operator Precedence in the PHP manual.

A: First partentheses are calculated. Then multiplication and division. Then plus and minus. If you write say ab/c, because multiplication doesn't precede division, nor does division precede multiplication, the computer will calculate it in the order it stands. So it will first calculate ab and then divide that by c.

A: division, multiplication, addition, subtraction (/, *, +, -)

A: the +- and */ pairs are of equal precedence. they are evaluated left to right.


text:
Q: java sql query error I have this code:
import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.Statement;

public class DBConntest {

    public static void main(String[] args) {
    try {

        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/?user=root&useSSL=false", "root", "root");
        System.out.println("Connection succes!");
        Statement stmt = conn.createStatement();
        String query1 = "USE test; insert into dbtester(name,age,email) values ('Aram',18,'aram@gmail.com');";
        stmt.executeUpdate(query1);

    }
    catch (Exception e){
        System.err.println(e);;
    }

    }

}

I use Eclipse, and after run it return this error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into dbtester(name,age,email) values ('Aram',18,'aram@gmail.com')' at line 1
Same SQL Query work in MySQL workbench. How I can solve this problem?

A: Change the line to String query1 = "insert into dbtester(name,age,email) values ('Aram',18,'aram@gmail.com');";
For no database selected exception :
Your URL for your database should include your database name. This is normally your URL followed by a "/databasename".
String url = "jdbc:mysql://localhost/databasename";
String username = "test";
String password = "test";
Connection connection = DriverManager.getConnection(url, username, password);


text:
Q: @Autowired BeanCreationException with JUnit I know this question has been asked many times but I've been stuck on this for a few days and cannot figure out why this is happening.
Here is my JUnit test suite, and the issue happens when I try to @Autowire RequestService:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/*.xml"})
public class RequestServiceTest {
    @Autowired
    private RequestService requestService;

    @Test
    public void add() throws Exception {
        requestService.add(new Request(1, "hello"));
        requestService.add(new Request(2, "hi"));
        Request requestResponseFromDatabase = (Request) requestService.findById(1);
        assertEquals("hello", requestResponseFromDatabase.getRestRequestParameters());
    }
}

Below is my code for my model, DAO, and service classes.
Model (leaving out the constructor and other fields for brevity)
@Entity
public class Request implements Serializable {

    @Id
    private Integer restRequestId;

    private Timestamp restRequestTimestamp;

    private String restRequestParameters;
}

DAO
@Component
public class RequestDAO {

    @Autowired
    private RequestService requestService;

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Request request) {
        entityManager.persist(request);
    }

    public void update(Request request) {
        entityManager.getTransaction().begin();
        entityManager.merge(request);
        entityManager.getTransaction().commit();
    }

    public Object findById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        }
        return request;
    }

    public void delete(Request request) {
        entityManager.getTransaction().begin();
        entityManager.remove(request);
        entityManager.getTransaction().commit();
    }

    public void deleteById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        } else if (request != null) {
            entityManager.getTransaction().begin();
            entityManager.remove(request);
            entityManager.getTransaction().commit();
        }
    }

    public List<Request> findAll() {
        Query query = entityManager.createQuery("SELECT e from Request e");
        List<Request> requests = query.getResultList();
        return requests;
    }

    public void deleteAll() {
        List<Request> requests = findAll();
        for (Request request : requests) {
            delete(request);
        }
    }

}

Service
@Component
public class RequestService {

    @Autowired
    private RequestDAO requestDAO;

    @Transactional
    public void add(Request request) {
        requestDAO.persist(request);
    }

    @Transactional
    public void update(Request request) {
        requestDAO.update(request);
    }

    @Transactional
    public Object findById(Serializable id) {
        return requestDAO.findById(id);
    }

    @Transactional
    public void delete(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteById(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteAll() {
        requestDAO.deleteAll();
    }

    @Transactional
    public void addAll(Collection<Request> requestCollection) {
        for (Request request : requestCollection) {
            requestDAO.persist(request);
        }
    }

    @Transactional(readOnly = true)
    public List<Request> findAll() {
        return requestDAO.findAll();
    }
}

spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        ">

<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans -->
    <context:component-scan base-package="com.company.mypackage"/>

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem://requestDb"/>
        <property name="username" value="user"/>
        <property name="password" value="pass"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="com.company.mypackage"
          p:dataSource-ref="dataSource">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManger"/>

</beans>

Full stacktrace:
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3498ed, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1a407d53, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3d8c7aca, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5ebec15, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@21bcffb5]
May 23, 2016 1:57:38 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@548b7f67: startup date [Mon May 23 13:57:38 EDT 2016]; root of context hierarchy
May 23, 2016 1:57:38 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1a407d53] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest@57175e74]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 32 more

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 32 more

Process finished with exit code -1

Additional Details

*

*Spring version: 4.2.5.RELEASE

*Hibernate version: 5.1.0.Final

*My spring.xml is located within src/main/resources (yes I am aware that it is not the best practice but wanted to make sure my tests work first. I did try to keep it in my src/test/resources folder but kept getting issues with my ApplicationContext not being able to load)

Resources followed:

*

*@Autowired with JUnit tests

*@AUTOWIRED : BeanCreationException

*@Autowired fails with JUnit & Spring

*Spring not autowiring in unit tests with JUnit

*Spring ORM example with JPA, Hibernate, Transactions
Any ideas on how to resolve this? I have asked similar questions to this in the past and do apologize - having a hard time understanding Spring along with all of it's documentation. I want to make sure I fully understand this to avoid making the same mistake in the future.

EDIT: Here is my folder structure:

Stack trace when using @ContextConfiguration(locations = {"classpath:spring.xml"}):
May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@60f82f98, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@35f983a6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@7f690630, org.springframework.test.context.transaction.TransactionalTestExecutionListener@edf4efb, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@2f7a2457]
May 23, 2016 3:20:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
May 23, 2016 3:20:39 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@174d20a: startup date [Mon May 23 15:20:39 EDT 2016]; root of context hierarchy
May 23, 2016 3:20:39 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.hsqldb.jdbcDriver
May 23, 2016 3:20:39 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
May 23, 2016 3:20:39 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
May 23, 2016 3:20:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 23, 2016 3:20:39 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 23, 2016 3:20:40 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : User not found: USER
May 23, 2016 3:20:40 PM org.springframework.context.support.GenericApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
May 23, 2016 3:20:40 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@35f983a6] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest@481ba2cf]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

java.lang.IllegalStateException: Failed to load ApplicationContext

    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Process finished with exit code -1

A: The problem happening over here is it is not able to load your spring bean xml file. can you put your spring xml file directly at the root level in the classpath.

A: The error msg is very clear, you need to config your hibernate properly.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

The possible reason could be:

*

*You haven't setup your hibernate properly.

*or there is no DB running during the test


text:
Q: How can I exclude grandchildren from my recursive querying process? I am trying to limit my db output -- which currently gives me from some categories every child and grandchild -- to only the child. So that no grandchildren are displayed.
I tried to limit the recursion to only happen once, but it doesn't work. I think the answer lies in the db query, but I am not familiar with dbs.
public function getChildCategories(&$result, &$categories, $level = 1)
{
    $db = EB::db();

    $ordering = $this->params->get('order', 'popular');
    $sort = 'desc';
    $total = (int) $this->params->get('count', 0);
    $hideEmptyPost = $this->params->get('hideemptypost', false);
    $language = EB::getCurrentLanguage();

    foreach ($result as $row) {
        // Initialize default structure
        $category = EB::table('Category');
        $category->bind($row);
        $category->cnt = $row->cnt;

        $categories[$row->id] = $category;
        $categories[$row->id]->childs = array();

        // Find child categories
        $query = array();
        $query[] = 'SELECT a.*, COUNT(' . $db->qn('b.id') . ') AS ' . $db->qn('cnt') . ',' . $db->Quote($level) . ' AS ' . $db->qn('level');
        $query[] = 'FROM ' . $db->qn('#__easyblog_category') . ' AS a';
        $query[] = 'LEFT JOIN ' . $db->qn('#__easyblog_post_category') . ' AS pc';
        $query[] = 'ON ' . $db->qn('a.id') . '=' . $db->qn('pc.category_id');
        $query[] = 'LEFT JOIN ' . $db->qn('#__easyblog_post') . ' AS b';
        $query[] = 'ON ' . $db->qn('b.id') . '=' . $db->qn('pc.post_id');
        $query[] = 'AND ' . $db->qn('b.published') . '=' . $db->Quote(EASYBLOG_POST_PUBLISHED);
        $query[] = 'AND ' . $db->qn('b.state') . '=' . $db->Quote(EASYBLOG_POST_NORMAL);
        $query[] = 'WHERE ' . $db->qn('a.published') . '=' . $db->Quote(1);
        $query[] = 'AND ' . $db->qn('parent_id') . '=' . $db->Quote($row->id);

        if ($language) {
            $query[] = 'AND(';
            $query[] = $db->qn('a.language') . '=' . $db->Quote($language);
            $query[] = 'OR';
            $query[] = $db->qn('a.language') . '=' . $db->Quote('');
            $query[] = 'OR';
            $query[] = $db->qn('a.language') . '=' . $db->Quote('*');
            $query[] = ')';
        }

        if (!$hideEmptyPost) {
            $query[] = 'GROUP BY ' . $db->qn('a.id');
        } else {
            $query[] = 'GROUP BY ' . $db->qn('a.id') . ' HAVING (COUNT(' . $db->qn('b.id') . ') > 0)';
        }

        if ($ordering == 'ordering') {
            $query[] = ' ORDER BY `lft` desc';
        }

        if ($ordering == 'popular') {
            $query[] = ' ORDER BY `cnt` desc';
        }

        if ($ordering == 'alphabet') {
            $query[] = ' ORDER BY a.`title` asc';
        }

        if ($ordering == 'latest') {
            $query[] = ' ORDER BY a.`created` desc';
        }

        $query = implode(' ', $query);
        $db->setQuery($query);
        $children = $db->loadObjectList();
        $ccounter = 0;

        // Recursion happens here
        if ($children) {
            $this->getChildCategories($children, $categories[$row->id]->childs, ++$level);
        }
    }
}

Can someone explain to me how to modify the db query? The output now is:
Category
-Child Cat
--Grandchild Cat
-Child Cat

I want:
Category
-Child Cat
-Child Cat

A: The comment from the user mickmackusa solves the problem. His solution works perfectly!
if ($children && $level < 2) {
    $this->getChildCategories($children, $categories[$row->id]->childs, $level + 1);
}


text:
Q: Why do I get invalid JSON payload when calling google cloud vision API from appcelerator? I was trying to use Google vision API v1 by Alloy Appcelerator
I create a request HTTPClient and call API https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY
But i have get response text from google :
  {
 error = {
     code = 400;
     details = (
                  {
                     "@type" = "type.googleapis.com/google.rpc.BadRequest";
                      fieldViolations = ({
                                        description = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
                                        });
                  }
                );
     message = "Invalid JSON payload received. Unknown name \"request\": Cannot bind query parameter. Field 'request' could not be found in request message.";
     status = "INVALID_ARGUMENT";
  };

}
And there is my code use HTTP request by Alloy
var requests =
{
  "requests":[
    {
      "image":{
        "content": "image_have_encodebase64",
      },
      "features":[
        {
          "type":"TEXT_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
};
var xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", 'https://vision.googleapis.com/v1/images:annotate?key=MY_APP_KEY');
xhr.send(JSON.stringify(requests));

Thanks for your help

A: By setting the Content-Length and Content-Type headers it should work:
xhr.setRequestHeader("Content-Length", size);
xhr.setRequestHeader("Content-Type", "application/json");

Also it should be noted that Google recommends resizing your image to 1024 x 768 -- you can resize your image with:
img = img.imageAsResized(1024,768);

After making these changes to my code I had everything working.


text:
Q: Drupal - get user id in non-drupal script im making an applicaiton (PHP), which will run on same server and same website as a Drupal installation. The think im trying to do is to get user id of user, who is currently logged in at Drupal (i never worked with Drupal before). I want just that id.
Does anyone know, where can i find that id (is it somewhere in the $_SESSION variable?)
Im using Drupal 6, PHP 5.3.

A: Update :
Sorry, I thought I understood what you wanted, but after re-reading your subject line, I'm thinking you want something a little different. Are you wanting to make a php script like test.php in the Drupal folder and access the Drupal user ID (based on cookie/session/etc)? In order to do that, you'll need to "bootstrap" Drupal first. Here is a function I've created to bootstrap Drupal (7) for maintenance scripts I create.
There may be a "better" way to do it, but it's what works for me.
function bootstrapDrupal($cDomain)
{
    $cDir = getcwd();

    //SETS DRUPAL BASE DIR
    define('DRUPAL_ROOT', '/www/dev');
    //DRUPAL FAILS TO LOAD SOME FILES IF NOT AT BASE
    chdir(DRUPAL_ROOT);

    //ATTEMPT TO DECIDE IF PHP IS RUNNING VIA CMDLINE
    if (isset($GLOBALS['PHP_SELF']))
    {
        //WHATEVER SITE YOUR SCRIPT IS FOR. HELPS SET DB.
        $_SERVER['HTTP_HOST'] = $cDomain;
        //SCRIPT ADDITIONALLY NEEDS TO BE SET FOR THE REDIRECT
        $_SERVER['SCRIPT_NAME'] = $GLOBALS['PHP_SELF'];
        //FORWARD SLASH IS IMPORTANT
        if (substr($_SERVER['SCRIPT_NAME'], 0, 1) != '/')
        {
            $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
        }

        //NEEDED TO SUPRESS BOOTSTAP ACCESS ERRORS - ANY IP WILL WORK
        $_SERVER['REMOTE_ADDR'] = '192.168.0.1';

    }

    //LOADS DRUPAL BOOTSTRAP CODE
    require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    //EXECUTES BOOTSTRAP
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    //LOADS DRUPAL COMMON FUNCTIONS
    require_once DRUPAL_ROOT . '/includes/common.inc';

    //BACK TO STARTING DIRECTORY
    chdir($cDir);
}

Original Answer :
In Drupal you can access the User ID via :
$GLOBALS['user']->uid

or
global $user;
$user->uid


text:
Q: Highchart autoscalling http://jsfiddle.net/Fr4CR/
In the above chart, if the values falls within x-axis 14 to -14 and y-axis 1 to -1 , it's plotting perfectly.
When the values falls outside  x-axis 14 to -14 and y-axis 1 to -1 , it's not plotting.
Here I have created chart,all points are not plotting
http://jsfiddle.net/Fr4CR/3/
$(function () {
new Highcharts.Chart({
    chart: {
        type: 'scatter',
        renderTo: 'container',
        showAxes: true
    },
    xAxis: {
        tickInterval: 2,
        min: -14,
        max: 14,
        tickLength: 0,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]
    },
    yAxis: {
        tickInterval: 0.2,
        min: -1,
        max: 1,
        gridLineWidth: 0,
        lineWidth: 1,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]
    },
    series: [{
        data: []
    }]
}, function (chart) {

    var xData = [1, 2, 3, 4, 5, 10],
        yData = [0.5356899, -20.5356899, 0.6356899,
                 0.2356899, 0.3356899, 40.1356899],
        series = chart.series[0],
        i = 0;

    setInterval(function () {
        var shift = series.data.length > 20,
            x = xData[i],
            y = yData[i];

        if (!x || !y)
            return;

        series.addPoint([x, y], true, shift);
        i++;
    }, 1000);

    var renderer = chart.renderer,
        xAxis = chart.xAxis[0],
        yAxis = chart.yAxis[0],
        step = 2 * Math.PI / 72,
        theta = 0,
        d = ['M'],
        h = 0,
        k = 0,
        r = 1,
        x,
        y;

    for (;  theta < 2*Math.PI; theta += step) {
        x = h + 10 * r * Math.cos(theta);
        y = k - 0.5 * r * Math.sin(theta);

        d.push(xAxis.toPixels(x), yAxis.toPixels(y), 'L');
    }

    d[d.length - 1] = 'Z';

    renderer.path({
        d: d,
        stroke: 'red',
        strokeWidth: 2
    }).add();
});

});

A: It is because you have bound the minimum and maximum values on both X-axis and Y-axis.
Replace this portion of code
xAxis: {
        tickInterval: 2,
        min: -14,
        max: 14,
        tickLength: 0,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]
    },
    yAxis: {
        tickInterval: 0.2,
        min: -1,
        max: 1,
        gridLineWidth: 0,
        lineWidth: 1,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]

With this one
xAxis: {
        tickInterval: 2,
        tickLength: 0,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]
    },
    yAxis: {
        tickInterval: 0.2,
        gridLineWidth: 0,
        lineWidth: 1,
        plotLines: [{
            value: 0,
            width: 1,
            color: '#999'
        }]

A: It's caused by setting min and max values for both, xAxis and yAxis. You need to use chart.x/yAxis.setExtremes() function to set new extremes and draw new (or update old one) ellipse.


text:
Q: Use of fission products for electricity generation Why can't we use fissions products for electricity production ?
As far has I know fissions products from current nuclear power plants create enough 'waste' heat to boil water; and temperature decreases too slowly for an human life. So why can't we design a reactor to use this energy.

A: Here are some "order-of-magnitude" arguments:
Quoting https://en.wikipedia.org/wiki/Decay_heat#Spent_fuel :

After one year, typical spent nuclear fuel generates about 10 kW of decay heat per tonne, decreasing to about 1 kW/t after ten years

Now since this is heat, you can't convert it to electricity with 100% efficiency, the maximum possible efficiency is given by the Carnot efficiency $\eta$:
$$
  \eta \le 1 - \dfrac{T_\mathrm{cold}}{T_\mathrm{hot}}
$$
where $T_\mathrm{hot}$ would be the temperature of the spent fuel rods (in Kelvin) and $T_\mathrm{cold}$ would be the temperature of a cold reservoir against which a generator would work. One would have to do another calculation what a reasonable temperature of the fuel rods would be (in practice they currently seem to be kept at 50 degrees C).
With 'primary' fuel typically 55 Gigawatt days per tonne can be produced, i.e. a 1 Gigawatt powerplant would use 365.25 / 55 = 6.6 tonnes per year.
Even assuming you would be able to convert this to electricity with 100% efficiency and assuming an average 5 kilowatts per tonne over 10 years, this would yield about 18'000 Kilowatt days or 0.018 Gigawatt days, about 0.03% of the primary energy production.
You'll also see from the Carnot efficiency above that higher temperatures imply a higher possible efficiency, i.e. if one can spend some energy to extract the still fissionable material to be used in a reactor again, that is likely to be more efficient in terms of electricity generation.
It's true on the other hand that radioisotope thermoelectric generators (radioactive sources combined with thermocouples) have been used on satellite missions.


text:
Q: CSS3 Reset Animation Requires Timeout (if set animation from external style sheet) I have a CSS animation. I apply it to a span within my div element with class span. I apply it from an external style sheet:
.skill > span { width:100%; -moz-animation:anim-skill 2s ease-out; -webkit-animation:anim-skill 2s ease-out; }

.anim-skill {width:100%; animation:anim-skill 2s ease-out; -moz-animation:anim-skill 2s ease-out; -webkit-animation:anim-skill 2s ease-out; -o-animation:anim-skill 2s ease-out;}

@keyframes anim-skill { from {width:0px;} to  {width:100%} }

When I want to reset the animation during run time I do this:
var mySkill = document.querySelector('.skill');
var bar = mySkill.childNodes[0];
//make it "from" state
bar.style.animation = 'none';
mySkill.style.width = 0;

//make it run
setTimeout(function () {
    mySkill.style.width = '';
    bar.style.animation = '';
}, 20);

This is very hacky. Is there a way to reset the animation this without using setTimeout? Note: If my timeout is 10ms or less it doesnt work also.

A: The problem is that you can not remove the class and set it again, without leaving the browser to render itself.
The non hacky way to do this is a little bit more sophisticated: make the animation remove itself
a quick and dirty implementation of this can be:
$(document).ready(function() {
    var ele = document.getElementById("test");

    ele.addEventListener( 'webkitAnimationEnd',
    function( event ) { ele.className = ""; }, false );
})

This will remove the animation class from the element, when the animation finishes. Afterwards, you can set the class again, without problems
fiddle


text:
Q: Python virtual environment doesn't use venv packages in Cloud9 I am currently using Cloud9 in AWS to develop and deploy Lambdas. I prefer to create a virtual environment to contain the specific packages that I will need for my Lambda, and I have been able to activate my venv and install the relevant packages in the environment.
My problem comes when I go to run my script and the runner/interpreter seems to use packages from the pre-built python instance when I create the cloud9 environment.
My only guess to the solution is to some how create a new runner that uses the virtual environment I created. But I am not sure how to do this.
Any assistance would be much appreciated.


text:
Q: PyQt4 ImportError for QtWebKit on Mac OS Leopard I've been requested to create an application with a webview in it.
I've tried to import QtWebKit module but I have this error:

Traceback (most recent call last):   File "", line 1, in
   ImportError:
  dlopen(/Library/Python/2.6/site-packages/PyQt4/QtWebKit.so, 2): Symbol
  not found: _kCFWebServicesProviderDefaultDisplayNameKey   Referenced
  from: /Library/Frameworks/QtWebKit.framework/Versions/4/QtWebKit
  Expected in:
  /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation

It's the only one module that returns this error. All other installed modules are ok. The file /Library/Python/2.6/site-packages/PyQt4/QtWebKit.so exists.
What could the problem be?
Thank you all.

A: I was able to fix the problem by upgrading to MacOSX Lion, but if that is not an option I would just ensure that PyQt4 is not using qt4.8, which is where this issue was introduced. If I remember correctly, everything works well with qt4.7.4


text:
Q: Highstock data points pixel spacing Is there a way to set point spacing in pixels on x/y axis for highstock? For example data points should be 5px apart.
Also is there way to shift chart left or right? For example shift all data points 5px right or left?

A: The spacing between points can be control by

*

*pointPadding

*groupPadding

*pointWidth

A: If you want the points of a line to be a certain distance apart, you need to make sure that the width of the plot area, divided by the number of points , equals that pixel value.
(or divided by the number of axis units, if you are artificially setting a min and max beyond the range of the data)
There can't possibly be a property to account for this - it's all about the space available and the number of points.
As for shifting left or right, it depends exactly what you mean. If you're looking to add spacing to the left or right end of the x axis, you can use midPadding or maxPadding.

*

*http://api.highcharts.com/highcharts#xAxis.minPadding

*http://api.highcharts.com/highcharts#xAxis.maxPadding


text:
Q: How do I stop old data from being updated by my macro? I've been working on what is basically a register for sales. My spreadsheet records sales, profits etc and from that prints a receipt however, I'd like to keep my own record of this data to use for graphs etc. At the moment my macro moves up from a specified column, beginning from row 100000, then when it reaches a row with data, moves down one to the empty cell. In it it places the cell reference for the new data it has found. I'm new to VBA so I'm not sure if I'm taking the right approach, this is my code:
Sub DataLog()
'
' DataLog Macro
' Record sales in the data log.
'

'
Sheets("Data").Select

Dim rngd As Range
Set rngd = Range("A100000").End(xlUp).Offset(1, 0)

Dim coke As Range
Set coke = Range("C100000").End(xlUp).Offset(1, 0)

Dim creamsoda As Range
Set creamsoda = Range("D100000").End(xlUp).Offset(1, 0)

Dim lemonade As Range
Set lemonade = Range("E100000").End(xlUp).Offset(1, 0)

Dim pasito As Range
Set pasito = Range("F100000").End(xlUp).Offset(1, 0)

Dim pepsi As Range
Set pepsi = Range("G100000").End(xlUp).Offset(1, 0)

Dim pepsim As Range
Set pepsim = Range("H100000").End(xlUp).Offset(1, 0)

Dim solo As Range
Set solo = Range("I100000").End(xlUp).Offset(1, 0)

Dim sprite As Range
Set sprite = Range("J100000").End(xlUp).Offset(1, 0)

Dim sunkist As Range
Set sunkist = Range("K100000").End(xlUp).Offset(1, 0)

Dim water As Range
Set water = Range("L100000").End(xlUp).Offset(1, 0)

rngd.Value = "=Form!D1"

coke.Value = "=Form!E7"

creamsoda.Value = "=Form!E8"

lemonade.Value = "=Form!E9"

pasito.Value = "=Form!E10"

pepsi.Value = "=Form!E11"

pepsim.Value = "=Form!E12"

solo.Value = "=Form!E13"

sprite.Value = "=Form!E14"

sunkist.Value = "=Form!E15"

water.Value = "=Form!E16"

When I clock the macro button, the first time it works, as does it the second time. Although, when it does record the second set of data in the row below, it updates all the previous data in each cell. How can I stop any previously entered data from being updated so I can keep a weekly record of information? Any help or insight is greatly appreciated, thank you :)
EDIT:
I should add, I have tried locking the cells once data has been added but this only protected them from manual alteration, the macro still updated the data.

A: To overwrite the all formulas in your Data sheet with values, add these two lines to the bottom of your script:
Sheets("Data").Cells.Copy
Sheets("Data").Cells.PasteSpecial (xlPasteValues)

If there are formulas you want to keep, you'll simply need to define the Range of soda values you do want to overwrite and follow the same pattern:
Dim SodaData As Range
'ex below sets SodaData range from A3 to C3
Set SodaData = Sheets("Data").Range(Sheets("Data").Cells(3, 1), Sheets("Data").Cells(3, 3))
SodaData.Copy
SodaData.PasteSpecial (xlPasteValues)


text: Q: Can't find a bash script anywhere in filesystem I have a bash script that uses ssh and requires 1 positional argument. If I type the name partially, the bash-completion completes it and the script works. The issue is that I can't find it anywhere to look into it. I checked for it in all the directories of $PATH, tried locate and find (without sudo so permission denied on /proc) and I can't find it. I am wondering how bash completion is completing it. It's not in the home directory for sure. I am using Debian 11


text:
Q: how to get corresponding 'Name' against 'Id' for two dictionary keys I have a dictionary in C# like below,
        var data = new Dictionary<string, List<string>>();
        data.Add("Id", new List<string> { "3", "5", "3" });
        data.Add("Name", new List<string> { "A", "B", "C" });

Against each "Id" key, there is a corresponding value in "Name" key.
note - Name will be unique against each Id
Now, I need all the values from "Name" for (A & C) for which corresponding "Id" key value is 3.
var a = data["Id"].Where(b => b == "3");

Or is there any better collection to resolve this issue?

A: The Zip method should help you out:
var names = data["Id"].Zip(data["Name"], (a,b) => new { Id = a, Name = b})
                      .Where(x => x.Id == 3)
                      .Select(x => x.Name);

(Note this will only work if there is guaranteed to be a 1-1 correspondence between the two lists.)

A: Within the confines you've defined, a more suitable structure would be:
var data = new Dictionary<string, List<string>>;
data.Add("3", new List<string> { "A", "C" });
data.Add("5", new List<string> { "B" });

Where the key of the dictionary is the ID, and the value is a list of names matching that ID.

A: According to your example data, Index of Id and Name are same in the Dictionary. So you have to find all index according to your condition then get all Name by using those Index.
Please check this:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var data = new Dictionary<string, List<string>>();
        data.Add("Id", new List<string> { "3", "5", "3" });
        data.Add("Name", new List<string> { "A", "B", "C" });

        //var a = data["Id"].FindIndex(b => b == "3");

        int[] indexs = data["Id"].Select((b,i) => b == "3" ? i : -1).Where(i => i != -1).ToArray();

        foreach(var index in indexs)
        {
            Console.WriteLine(data["Name"][Convert.ToInt16(index)]);
        }
    }
}

You can check output in DotNetFiddle.

A: I think you can change the way you are currently storing these values.
One alternative can be to to use Dictionary and store Names in Key and Id in Value.
var data = new Dictionary<string, int>();
data.Add("A", 3);
data.Add("B", 5);
data.Add("C", 3);

This would be if You also want to sometimes use Name to access the Id, but if you are only going to use Ids to find names, go with the solution in the other answer.

A: Why don't you just work with a regular Dictionary?
        var dict = new Dictionary<string, string[]> {{"3", new[] {"A", "C"}}, {"5", new[] {"B"}}};
        var a = dict.Where(x => x.Key == "3");


text:
Q: how to send app to AppStore for approval, if it depends on others interaction I have an app similar to ordering a taxi. It depends on somebody else answering to users request. How should I submit it to apple, given the fact that the response functionality can not be seen unless there is somebody in front of a computer to answer the request. What would you suggest?

A: You can put information such as this in the App's "Reviewer Notes" section when you upload your App binary in iTunes Connect to explain to Apple what they will need to do and/or what they will or will not be able to test themselves.


text:
Q: Getting a percentage of one PHP variable from another I am trying to get a percentage of a php variable from another, for example i have two databases of information, the first database is full of unidentified information.  The second database is full of the information we have identified. and so i want to work out dynamically the percentage of the total information identified.
Below is a php function to work out a percentage,
//TOTAL ENTRIES INTO Table 1 FOR total data
$result   = mysql_query( "SELECT * FROM table1" );
$num_total = mysql_num_rows( $result );

 //TOTAL ENTRIES IN Table 2  FOR THE PERCENTAGE
$result   = mysql_query( "SELECT * FROM table2" );
$num_amount = mysql_num_rows( $result );

 function percent($num_amount, $num_total) {
 $count1 = $num_amount / $num_total;
 $count2 = $count1 * 100;
 $count3 = 100 - $count2;
 $count = number_format($count3, 0);
 echo $count;
 }

Both queries return the correct information of the total number of rows counted in the database, however  the count variable does not return any information.
Any ideas or suggestions would be appreciated.
Thanks
Stan

A: You echo the result, but you do not return it from the function. That is probably the problem.
However, you can do the percentage calculation all in SQL:
SELECT 100*( SELECT COUNT(*) FROM table1 ) / ( SELECT COUNT(*) FROM table2 )
    AS percent;

Otherwise,
function percent($num, $total)
{
    return number_format((100.0*$num)/$total, 2);
}

A: My guess is that something like this should probably work (mind you, I have not tested this, so it probably needs tweaking):
<?php

//TOTAL ENTRIES INTO Table 1 FOR total data
$result   = mysql_query("SELECT COUNT(*) AS total FROM table1");
$table1_total = mysql_result($result, 0);

 //TOTAL ENTRIES IN Table 2  FOR THE PERCENTAGE
$result2 = mysql_query("SELECT COUNT(*) AS total FROM table2");
$table2_total = mysql_result($result2, 0);

function percent($num_amount, $num_total) {
    $count1 = $num_amount / $num_total;
    $count2 = $count1 * 100;
    $count3 = 100 - $count2;
    $count = number_format($count3, 0);
    echo $count;
}

percent($table1_total, $table2_total);

A: Try this:
    <?php

    function percent($num_amount, $num_total) {
     $count1 = $num_amount / $num_total;
     $count2 = $count1 * 100;
     $count = number_format($count2, 0);
     echo $count2."<br>";
     }

     percent(50,100);
     percent(13,100);
     percent(13,200);

    ?>


text: Q: Create action script to filter table data using drop down list in html from pandas I have a python script that converts a given dataframe to html. Now that if I want to add drop down list in html file to filter data based on a column. How would I achieve it from python pandas script ?


text:
Q: Optimization - Optimal velocity for fuel consumption I am working through a series of questions for my 1st year uni maths course and I am really stuck here so any help would be appreciated. I know how to optimize 3D objects and areas but just can't work out how to get the starting formula(e) here in which I will use to find the minimum stationary point of the graph. Thanks.
The cost per hour of running a train is proportional to:
$$100 + \frac {v^2}{36}$$
where $v$ (in mph) is the average speed of the journey.
Find the speed $v$ that makes the trip cheapest when the distance is $400$ miles.

A: Average speed (t = total time): $$v= \frac{400}{t}\tag{1}$$
Cost per hour: $$C_h = k(100+\frac{v^2}{36})\tag{2}$$
Total cost: $$C=C_h\cdot t \tag{3}$$
Insert $(1)$ in $(2)$, then $(2)$ in $(3)$ and differentiate $(3)$.


text:
Q: Armijo's rule line search I have read a paper (http://www.seas.upenn.edu/~taskar/pubs/aistats09.pdf) which describes a way to solve an optimization problem involving Armijo's rule, cf. p363 eq 13.
The variable is $\beta$ which is a square matrix. If $f$ is the objective function, the paper states that Armijo's rule is the following:
$f(\beta^{new})-f(\beta^{old}) \leq \eta(\beta^{new}-\beta^{old})^T \nabla_{\beta} f$
where $\nabla_{\beta} f$ is the vectorization of the gradient of $f$.
I am having problems with this as the expression on the right of the inequality above does not make sense due to dimension mismatch. I am unable to find an analogue of the above rule elsewhere. Can anyone help me as to figure out what the right expression means? The left expression is a scalar while the right expression suffers from a dimension mismatch...

A: In general (i.e. for scalar-valued $x$), Armijo's rule states
$$f(x^{new}) - f(x^{old}) \le \eta \, (x^{new}-x^{old})^\top \nabla f(x^{old}).$$
Hence, you need the vectorization of $\beta^{new}-\beta^{old}$ on the right hand side.
(Alternatively, you could replace $\nabla_\beta f$ by the gradient w.r.t. the frobenius inner product and write $(\beta^{new}-\beta^{old}) : \nabla_\beta f$, where $:$ denotes the frobenius inner product).


text:
Q: hyperref links to first subcaptionref with memoir This is more of a bug report than a question.
When using memoir's subcaptions (not the subcaption package) and links with the hyperref package, references to subfigures always point to the first instance of that label. Here's a minimal example:
\documentclass{memoir}
\newsubfloat{figure}

\usepackage[demo]{graphicx}
\usepackage{hyperref}

\begin{document}
\begin{figure}
  \subbottom[foo\label{foo}]{\includegraphics{figure1}}
  \subbottom[bar\label{bar}]{\includegraphics{figure2}}
  \caption{\subcaptionref{foo} foo and \subcaptionref{bar} bar.}
\end{figure}

\begin{figure}
  \subbottom[qux\label{qux}]{\includegraphics{figure3}}
  \subbottom[baz\label{baz}]{\includegraphics{figure4}}
  \caption{\subcaptionref{qux} qux and \subcaptionref{baz} baz.}
\end{figure}
\end{document}

The subcaptionref on the second figure ((a) qux and (b) baz) will link to the sub figures with the same labels on the first figure ((a) foo and (b) bar). Here's someone else on the internet with the same problem.
I've found that I can work around this by declaring the sub figures after loading the hyperref package, i.e.:
\usepackage{hyperref}
\newsubfloat{figure} % this line was moved to after \usepackage{hyperref}

But I would guess that this is something that should be fixed on hyperref or memoir (or documented in one of them).


text:
Q: Hazelcast load from data store or recovery from replica When starting a Hazelcast cluster instance, how can i decide whether i should pre-populate from data store or to rely on cluster auto recover from replica?
if every instance always loads at startup, that will cause to much dup workload?

A: Ben,
Hazelcast is in-memory data grid. With the default configuration, it doesn't touch a disk or RBMS.
However, you can implement MapLoader to prepopulate Hazelcast from a database of your choice.
You can find more examples here
p.s. you shouldn't worry about duplicate workload. Hazelcast will spread the keys of a map across member nodes, and the corresponding member will load data by this key.


text:
Q: libcompression.dylib not loaded I work on OS X Yosemite and recently experience multiple problems. All of them concern the error:
Dyld Error Message:
  Library not loaded: /usr/lib/libcompression.dylib

For example, XCode never opens even though it was deleted and reinstalled several times:
  Referenced from: /Applications/Xcode.app/Contents/SharedFrameworks/DTXConnectionServices.framework/Versions/A/DTXConnectionServices
  Reason: image not found

I can neither update my Zsh, nor load boost libraries. All those give me an error with libcompression.dylib but I have no idea how to fix this point.
Thank you in advance for your help!


text:
Q: Unable to install a dependencies package using my package.json I have a package.json but when I try to run it in my command console I got this error:
$ npm install
npm ERR! install Couldn't read dependencies
npm ERR! Windows_NT 5.1.2600
npm ERR! argv "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v0.12.2
npm ERR! npm  v2.7.4

npm ERR! Invalid version: "0.1"
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     F:\UwAmp\www\nodejs\express\npm-debug.log

Here's my package.json
{
    "name": "Express101",
    "version": "0.1",
    "description": "This is a practice demo for express node",
    "main": "app.js",
    "author": {
        "name": "Juan Dela Cruz",
        "email": "jdcruz01@gmail.com"
    },
    "dependencies": {
        "express": "^4.13.3",
        "jade": "^1.11.0"
    }
}

Can you help me with this? It says that I have an error in the version part.

A: The answer is in the error message:

npm ERR! Invalid version: "0.1"

In your package.json, you have this:

"version": "0.1",`

You need to format this to meet the semver requirements (see the npm package.json docs and the node-semver repo).  Add a 0 in front (0.0.1) and your error should vanish.


text:
Q: Insert a line before/after a row during drag&drop in listview I would like to show a blue line during drag&drop in a single listview. This should help to recognize if the dragged row will be dropped before or after the actual row. (The other needed events like .DragEnter, .DragDrop are working as expected).
How can I draw such a blue line in VB.NET without 3rd party listview controls?
So far, I found the event "GiveFeedback":
Sub listView1_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles listView1.GiveFeedback
    e.UseDefaultCursors = False
    Windows.Forms.Cursor.Current = Cursors.Cross

    '<--- Show the blue insertion line until row is dropped

End Sub

Could somebody please show me the missing code for a blue insertion line?

A: Thanks, for pointing me in the right direction! I found the desired solution in a .DragOver Event:
Sub ListView1_DragOver(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles ListView1.DragOver
    Dim MousePointerCoordinates As Point = ListView1.PointToClient(Cursor.Position)
    Dim RowIndex As Integer = ListView1.InsertionMark.NearestIndex(MousePointerCoordinates)
    ListView1.InsertionMark.Index = RowIndex
End Sub

The Color for the line itself is defined in the form.load with
ListView1.InsertionMark.Color = Color.Blue

A: This should hopefully point you in the right direction:
First, set ListView1.OwnerDraw = True
then add the following:
Private Sub ListView1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawListViewItemEventArgs) Handles ListView1.DrawItem
    e.DrawDefault = True

    'Do checks here if drag
    Dim Pos As Point = Me.ListView1.PointToClient(Cursor.Position)

    If Me.ListView1.GetItemAt(Pos.X, Pos.Y) Is e.Item Then
        e.Graphics.DrawLine(Pens.Blue, e.Bounds.Left, e.Bounds.Top, e.Bounds.Right, e.Bounds.Top)
    End If

End Sub

Please note this is rough, and you will need to add in code to check if drag is taking place. You would also need to Invalidate the listview (or at least the listviewitem's region) when moving the mouse.
I recommend you look at creating a new class that inherits from listview, as this will make it a lot easier to manage your code
Hope this helps point you in the right direction...

A: I needed something like this, but a bit different. What I wanted to achieve was to draw a line but depending on the position of the index, the line should be drawn before or after a specific item.
Example: I got a list view with 5 items.

*

*Scenarion 1: Move item 4 to position 2. The line is drawn before item 2.

*Scenarion 2: Move item 1 to position 5. The line is drawn after item 5.

And this is the code I have used to achieve this:
Private Sub lvDisplayed_DragOver(sender As Object, e As DragEventArgs) Handles lvDisplayed.DragOver
    Dim MousePointerCoordinates As Point = Me.lvDisplayed.PointToClient(Cursor.Position)
    Dim RowIndex As Integer = lvDisplayed.InsertionMark.NearestIndex(MousePointerCoordinates)
    Me.lvDisplayed.InsertionMark.AppearsAfterItem = Me.lvDisplayed.SelectedIndices(0) <= RowIndex
    Me.lvDisplayed.InsertionMark.Index = RowIndex
End Sub

And you will also need to set the InsertionMark.Color , I've set it in NEW.
Me.lvDisplayed.InsertionMark.Color = Color.DarkRed

Hope this helps as I looked for something like this a lot.


text:
Q: How to download a single directory from a Git repository What is the shortest, simplest way (preferably one line command) to download a single subdirectory from a Git repository? The goal is for an end-user (i.e. not a programmer) to get a copy of a subdirectory as easily as possible.

This is related to, but not a clone of "How do I clone a subdirectory only of a Git repository?", as that question concerns itself with cloning the directory and still being able to use the directory within Git. Whereas I just want the user to get a local copy, git history, and other information need not be downloaded in my case. Its ok if it is, its just not required.

A: Note that git, intrinsically, has nothing to do with downloads. A git repo just sits there on your disk, except for git daemon, which does will not help you make downloads available to ordinary users.
As far as I know, there is no easy way to do what you want. github in particular supports various ways to download flat files, but I do not believe that it provides a URL that packages up a directory; all it can do is 'release' tarballs. Subdirectories are especially problematic: you need a web service that responds with a ZIP or tar file, and the user will have to interact with the browser to get it unpacked.
I did find a PHP solution that you could layer atop a file system that happened to be populated from a git repo.

A: If the subdirectory was a submodule, it would be relatively easy; just git clone that. But you'd still get the whole repo, not the working tree. If you want just the working tree there is nothing git can do for you.
So you'd have to do things differently.If it is on a machine that you have control over you could make the directory in question accessible via e.g;

*

*rcp

*rsync

*ftp (as a zip or tar file)


text:
Q: Having trouble with getElementsByTagName(blockquote) I am trying to get it to return "ha, awesome" followed by the index of the word "awesome"
HTML:

ha, awesome

JS:
var x = document.getElementsByTagName(blockquote).innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName(blockquote).innerHTML = x + "
" + n;

If I change the JS to this, it works
var x = document.getElementById("blocky").innerHTML ;
var n = x.indexOf("awesome");
document.getElementById("blocky").innerHTML = x + "
" + n;

https://jsfiddle.net/mzrt/zaf98g8y/1/

A: Basically getElementsByTagName will return a node list, an array like object, you cannot access the property of a node from it directly, you have to use bracket notation to fetch the first node from it and then you can treat it as a node object,
var x = document.getElementsByTagName('blockquote')[0].innerHTML;

Since the element that you are targeting is an element with id, It is better to go with getElementById.

A: First off, you need to pass it a string, not a variable (unless that variable contains a string).
var x = document.getElementsByTagName('blockquote');

Next, document.getElementsByTagName returns a element collection, not a single element. You can get the first result using [0].
var x = document.getElementsByTagName('blockquote')[0];

Or you can iterate through all of the elements using a for loop.
for (var i = 0; i < x.length; i++) {
  var element = x[i];
  element.innerHTML = '...';
}

A: var x = document.getElementsByTagName('blockquote')[0].innerHTML ;
var n = x.indexOf("awesome");
document.getElementsByTagName('blockquote')[0].innerHTML = x + "
" + n;

Get element by tag name returns a node list, so you have to tell whitch node you do want.
Also you should pass tagname between single quotes.


text:
Q: Interchanging almost surely equal random variables in a conditional expectation Suppose we have random variables $U, V, Y$, where $Y$ is real-valued, and some event $A$ such that, almost surely,
$$
U \, \mathbb{1}_A = V \, \mathbb{1}_A
$$
where $\mathbb{1}_A$ is an indicator function.
Does it follow that
$$
\mathbb{E}[Y \mid \mathbb{1}_A = 1, U] \, \mathbb{P}(A \mid U)
= \mathbb{E}[Y \mid \mathbb{1}_A = 1, V] \, \mathbb{P}(A \mid U)
$$
almost surely?
If everything is discrete, then, provided $\mathbb{P}(U = u) > 0$, we have
$$
\mathbb{E}[Y \mid \mathbb{1}_A = 1, U = u] \, \mathbb{P}(\mathbb{1}_A = 1 \mid U = u) %= \left(\sum_{y} y \, \mathbb{P}(Y = y \mid \mathbb{1}_A=1, U=u)\right)\mathbb{P}(\mathbb{1}_A = 1 \mid U = u) \\
= \frac{\sum_y y \, \mathbb{P}(Y = y, \mathbb{1}_A=1, U=u)}{\mathbb{P}(\mathbb{1}_A=1, U=u)} \, \mathbb{P}(\mathbb{1}_A = 1 \mid U = u)\\
= \frac{\sum_y y \, \mathbb{P}(Y = y, \mathbb{1}_A=1, V=u)}{\mathbb{P}(\mathbb{1}_A=1, V=u)} \, \mathbb{P}(\mathbb{1}_A = 1 \mid U = u) \\
= \mathbb{E}[Y \mid A = a, V = u] \, \mathbb{P}(\mathbb{1}_A = 1 \mid U = u).
$$
I am wondering if the same holds true in general, i.e. under the general definition of conditional expectation, with $Y$ an arbitrary (integrable) random variable, and $U$ and $V$ arbitrary measurable functions (subject to the condition above).

A: You can say that
$$
\mathsf{E}[Y\mid 1_A,U]=\mathsf{E}[Y\mid 1_A,V] \quad\text{a.s. on }A
$$
because for any bounded, measurable function $g$,
\begin{align}
&\mathsf{E}[1_A \mathsf{E}[Y\mid 1_A,U]g(1_A,V)] \\
&\qquad=\mathsf{E}[\mathsf{E}[1_A Y\mid 1_A,U]g(1_A,U)] \\
&\qquad=\mathsf{E}[1_AY g(1_A,U)] \\
&\qquad=\mathsf{E}[1_AY g(1_A,V)] \\
&\qquad=\mathsf{E}[\mathsf{E}[1_A Y\mid 1_A,V]g(1_A,V)] \\
&\qquad=\mathsf{E}[1_A \mathsf{E}[Y\mid 1_A,V]g(1_A,U)].
\end{align}


text:
Q: OnNavigatedFrom is not called when the app is suspended Today I've encountered strange problem - seems that on my device (v. 8.10.14203.306) OnNavigatedFrom event is not getting called when the app is being suspended. As far as I remember some time ago it was working ok, and exacly as documentation stays:

Note  On Windows Phone, OnNavigatedFrom() is called when the app is suspended. OnNavigatedTo() is not called when the app is resumed.

I've tried a simple example (available at GitHub):
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    this.navigationHelper.OnNavigatedFrom(e);
    Debug.WriteLine("Navigation");
    this.Background = new SolidColorBrush(Colors.Red);
}

when there is normal navigation (e.g. by back button) the event is fired, but no more when the app is suspended - both in debug and release mode. I've also checked if the Suspending event is fired and it turnes out that it is:
// uncomment this to check if app is being suspended
App.Current.Suspending += (sender, e) => this.Background = new SolidColorBrush(Colors.Blue);

Am I missing something?

A: The only thing I can suggest is to make sure that you're calling Frame.GetNavigationState from within your Application.Suspending handler (this is usually done by SuspensionManager.SaveAsync). According to the docs:

Calling this method will call Page.OnNavigatedFrom for the current page using NavigationMode.Forward. GetNavigationState is usually called when the application is being suspended, so the current page is navigated away from.


text:
Q: data.table - group size relative to total number of rows I'm looking for a concise data.table solution for the following:
I want to add a new column "ratio" that is the size of each group in relation to the total number of rows of the dataframe.
We can do it as follows: Add a column "N" that is constant and contains the total number of rows. Then group by the variable "group" and divide the group size by the total size:
df = data.table(group=c(rep("a", 2), rep("b", 3)))
df[, N:=.N][, ratio := .N/N, group][,N:=NULL]

with the desired outcome:
   group ratio
1:   a   0.4
2:   a   0.4
3:   b   0.6
4:   b   0.6
5:   b   0.6

But is there a better way without adding/removing the dummy column?


text:
Q: Get information out of a JSON like file in c# (.NET 4.8) I'm currently still learning c# and im trying to find the best method to get the information out.
Tried Regex and even thought of using JSON but im pretty sure there is a simpler method.
I have data like this:
Main_name = {
    # Comment
    # Comment
    # Comment
    type1 = uselessname_importantNumber                                (e.g. ryu_3)
    type2 = "path" # Comment
    type3 = name
    type4 = true

    type5 = {
        name2
        name3...
        # Comment
    }
}

My objective is to store the values: Main_name, importantNumber, path, name, true, list of names in type5 in a List.
Currently im doing
TechData = new List<ClassTech>();

            string[] paths = Directory.GetFiles(path, "*.txt");

            foreach (string pathsl in paths)
            {

                using (StreamReader sr = File.OpenText(pathsl))
                {
                    string line;
                    int i = 0;
                    string[] words;

                    while ((line = sr.ReadLine()) != null)
                    {

                        if (line.Contains("{") == true && !line.Contains("#"))
                        {

                            // Get's the name
                            words = line.Split('=');
                            TechData.Add(new ClassTech(words[0].Trim(' '), "None", -1, null, "None", null, true));

                            // In {}
                            while ((line = sr.ReadLine()) != null)
                            {
                                if ((Regex.Match(line, @"\bera\b")).Success && (TechData[i].era == -1) && !line.Contains("#"))
                                {
                                    words = line.Split('=');
                                    TechData[i].era = words[1][words[1].Length - 1] - 48;

                                }
                                else if ((Regex.Match(line, @"\btexture\b")).Success && (TechData[i].texture == null) && !line.Contains("#"))
                                {
                                    words = line.Split('=');
                                    TechData[i].texture = words[1].Trim(' ', '"');

                                }
                                else if ((Regex.Match(line, @"\bcategory\b")).Success && (TechData[i].category == null) && !line.Contains("#"))
                                {
                                    words = line.Split('=');
                                    TechData[i].category = words[1].Trim(' ');

                                }
                                else if ((Regex.Match(line, @"\bcan_research\b")).Success && (Regex.Match(line, @"\bno\b")).Success && !line.Contains("#"))
                                {
                                    TechData[i].canResearch = false;

                                }
                                else if ((Regex.Match(line, @"\bmodifier\b")).Success && !line.Contains("#"))
                                {
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        if (line.Contains("}")) { break; }
                                        else if (line.Contains("="))
                                        {
                                            TechData[i].modifiers.Add(line.Trim(' '));
                                        }
                                        else { }

                                    }

                                }
                                else if ((Regex.Match(line, @"\bunlocking_technologies\b")).Success && !line.Contains("#"))
                                {
                                    while ((line = sr.ReadLine()) != null)
                                    {
                                        if (line.Contains("}")) { break; }
                                        else if (!string.IsNullOrEmpty(line) && !string.IsNullOrWhiteSpace(line))
                                        {
                                            TechData[i].restrictions.Add(line.Trim('\t'));
                                        }
                                        else { }
                                    }
                                }
                                else if (line.Contains("}") == true)
                                {
                                    break;
                                }
                                else
                                {
                                }

                            }
                            i++;
                        }

                    }

                }
            }

The problem is if the data becomes bigger, it will start to become harder and harder so my question is: is there a simpler way to do it and if possible faster?
Data example
sericulture = {
    # Unlocks Mulberry Groves PM on Rice Farms
    era = era_1
    texture = "gfx/interface/icons/invention_icons/sericulture.dds"
    category = production
    can_research = no

    modifier = {
        building_silk_plantation_throughput_mult = 0.25

    }
}

enclosure = {
    # Unlocks construction of Farms and Plantations
    era = era_1
    texture = "gfx/interface/icons/invention_icons/enclosure.dds"
    category = production
}

manufacturies = {
    # Unlocks Mercantilism Law
    # Unlocks Food Industry, Textile Mills, Furniture Manufacturies, Glassworks, Tooling Workshops, Paper Mills
    era = era_1
    texture = "gfx/interface/icons/invention_icons/manufacturies.dds"
    category = production
}

shaft_mining = {
    # Unlocks Coal Mine, Iron Mine, Lead Mine, Sulfur Mine
    era = era_1
    texture = "gfx/interface/icons/invention_icons/shaft_mining.dds"
    category = production

    unlocking_technologies = {
        enclosure
        manufacturies
    }
}

atmospheric_engine = {
    # Unlocks Motor Industry
    # Unlocks Atmospheric Engine Pump PM in Coal Mine, Iron Mine, Lead Mine, Sulfur Mine
    era = era_1
    texture = "gfx/interface/icons/invention_icons/atmospheric_engine.dds"
    category = production

    unlocking_technologies = {
        shaft_mining
    }
}

A: I broadly agree with @Jon Skeet's suggestion to convert these files to JSON. If you can do that at the source, do it.
If not, you'll either have to convert it yourself, or parse the data some other way.
Regardless, if you want this to be expandable, your goal should be to be able to get this data into C# without relying on beforehand knowledge of any property names.
I've put together a parser based on the example files you've left above. It's not perfect, but it should be a strong starting point:
The full project, and the primary parsing logic
It works by parsing the input file to a string-keyed dictionary containing values of Dictionary<string,object?>, List<string>, or object?.
Note: if you want to convert this JSON data to C# objects afterwards, go for it. It'll be much simpler once it's in JSON form, since there are many tools for that.
Example usage
SourceFile.txt
Main_name = {
    # Comment
    # Comment
    # Comment
    type1 = ryu_3
    type2 = "path" # Comment
    type3 = name
    type4 = true

    type5 = {
        name2
        name3...
        # Comment
    }
}

Program.cs
var outVal = new ObjectParserThing.ObjectParserThing().ParseFile("sourceFile.txt");

Console.WriteLine(JsonSerializer.Serialize(outVal, new JsonSerializerOptions {
    WriteIndented = true,
}));

Output
{
  "Main_name": {
    "type1": "ryu_3",
    "type2": "\u0022path\u0022",
    "type3": "name",
    "type4": "true",
    "type5": [
      "name2",
      "name3..."
    ]
  }
}