Q:

Scala: Convert a string to string array with and without split given that all special characters except "(" an ")" are allowed

I have an array
val a = "((x1,x2),(y1,y2),(z1,z2))"

I want to parse this into a scala array
val arr = Array(("x1","x2"),("y1","y2"),("z1","z2"))

Is there a way of directly doing this with an expr() equivalent ?
If not how would one do this using split
Note : x1 x2 x3 etc are strings and can contain special characters so key would be to use  () delimiters to parse data -
Code I munged from Dici and Bogdan Vakulenko
val x2 = a.getString(1).trim.split("[\()]").grouped(2).map(x=>x(0).trim).toArray

val x3 = x2.drop(1) // first grouping is always null dont know why

var jmap = new java.util.HashMap[String, String]()

for (i<-x3)
{
 val index = i.lastIndexOf(",")
 val fv = i.slice(0,index)
 val lv = i.substring(index+1).trim
 jmap.put(fv,lv)
}

This is still suceptible to "," in the second string -

A:

Actually, I think regex are the most convenient way to solve this.
val a = "((x1,x2),(y1,y2),(z1,z2))"
val regex = "(\\((\\w+),(\\w+)\\))".r
println(
  regex.findAllMatchIn(a)
       .map(matcher => (matcher.group(2), matcher.group(3)))
       .toList
)

Note that I made some assumptions about the format:

no whitespaces in the string (the regex could easily be updated to fix this if needed)
always tuples of two elements, never more
empty string not valid as a tuple element
only alphanumeric characters allowed (this also would be easy to fix)


Q:

Context initialization failed: Spring & Hibernate Project

Everything was working fine until I added the Hibernate SessionFactory configuration in the spring configuration file(SpringMVCProj-servlet.xml).
I'm new to this ... so can't really make out the issue. I'm guess some changes that I need to make in my web.xml file. I have added the error log, web.xml and my spring configurations.
Error
 4  INFO ContextLoader:272 - Root WebApplicationContext: initialization started
12:11:36,178  INFO XmlWebApplicationContext:510 - Refreshing Root WebApplicationContext: startup date [Thu Mar 28 12:11:36 EDT 2013]; root of context hierarchy
[2013-03-28 12:11:36] JRebel-Spring: Monitoring Spring bean definitions in '/Users/ronyjohn007/JAR's Downloads/Databases/apache-tomcat-6.0.36/webapps/SpringMVCProj/WEB-INF/SpringMVCProj-servlet.xml'.
12:11:36,693  INFO XmlBeanDefinitionReader:315 - Loading XML bean definitions from ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]
12:11:37,962  INFO DefaultListableBeanFactory:577 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3394214b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,homeController,userDAOImpl,userServiceImpl,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,viewResolver,dataSource,sessionFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
12:11:38,121  INFO DefaultListableBeanFactory:444 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3394214b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,homeController,userDAOImpl,userServiceImpl,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,viewResolver,dataSource,sessionFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
12:11:38,122 ERROR ContextLoader:307 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.HibernateTransactionManager] for bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.HibernateTransactionManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1332)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:337)

Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 38 more
Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)

Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 43 more
Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1332)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:337)

Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 43 more
Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.HibernateTransactionManager] for bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.HibernateTransactionManager
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)

Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.HibernateTransactionManager
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 43 more
Mar 28, 2013 12:11:38 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.HibernateTransactionManager] for bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.HibernateTransactionManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1332)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:337)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:316)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:303)
    at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:1174)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:101)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:87)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:150)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
    ... 27 more
Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 38 more
Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.jdbc.datasource.DriverManagerDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1332)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:337)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:308)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:416)
    at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1188)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:277)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.detectMappedInterceptors(AbstractHandlerMapping.java:220)
    at org.springframework.web.servlet.handler.AbstractHandlerMapping.initApplicationContext(AbstractHandlerMapping.java:195)

Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:415)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1255)
    ... 43 more
Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)

Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)

Related cause:
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.HibernateTransactionManager] for bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/SpringMVCProj-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.HibernateTransactionManager
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1263)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:581)

SpringMVCProj-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- Annotation Driven Autowiring capability -->
    <context:annotation-config></context:annotation-config>

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Scans the classpath of this application for @Components to deploy as
        beans -->
    <context:component-scan base-package="com.job" />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources/ directory -->
    <mvc:resources mapping="/**" location="/" />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views
        directory -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <context:property-placeholder location="classpath:config.properties"></context:property-placeholder>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close">
       <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
        <property name="username" value="root" />
        <property name="password" value="12345" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.job"></property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Spring MVC Application</display-name>

<!--   <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>

 <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list> -->

   <servlet>
      <servlet-name>SpringMVCProj</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>SpringMVCProj</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/SpringMVCProj-servlet.xml</param-value>
</context-param>

<listener>
   <listener-class>
      org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>

</web-app>

A:

This error means the class loader could not find the class on the classpath.
java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)

You are missing the aopalliance jar on your classpath.
If you're using maven, you can add
<dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
</dependency>

to your dependencies.
Otherwise, download it manually from here and add it to your classpath.
Now you are getting more ClassNotFoundExceptions:
java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.DriverManagerDataSource

This one comes from spring jdbc
<!-- use whichever version you have for your other spring packages -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>3.2.1.RELEASE</version>
</dependency>

If you keep getting errors like this, you should try to find which library the missing class in and look it up to find the maven dependency.


Q:

sed back-reference not working

I need to process every line of a curve CSV to remove the last column of only those lines which start with 10 commas. the sed command I used was:
$ cat curves.csv
(...)
,,,,,,,,,,2017/10/18,20630.000000
,,,,,,,,,,2017/11/15,20595.000000
,usdSN,:usdSN,,,,8005,$,,2017/08/07,Settlement Date
,,,,,,,,,,2017/12/20,20575.000000
,,,,,,,,,,2018/01/17,20555.000000
,,,,,,,,,,2018/02/21,20535.000000
(...)
,,,,,,,,,,2018/12/21,20290.000000
,usdZS,:usdZS,,,,8007,$,,2017/08/07,Settlement Date
,,,,,,,,,,2017/08/16,2848.500000
(...)

$ sed  s/\(,,,,,,,,,,[0-9/]*\),[0-9.]*/\1/g  curves.csv

however, it didn't work. it printed out all lines unchanged.
Please help.

A:

The problem is the way you are running sed.  You did:
sed  s/\(,,,,,,,,,,[0-9/]*\),[0-9.]*/\1/g  curves.csv

But because the parameters aren't quoted the shell resolves the escape characters and what is actually run is:
sed  s/(,,,,,,,,,,[0-9/]*),[0-9.]*/\1/g  curves.csv

Which doesn't match anything because there are no parenthesis in your file.  How you should run it is:
sed 's/\(,,,,,,,,,,[0-9/]*\),[0-9.]*/\1/g' curves.csv


Q:

NSWindowController shows new window

I am very new to mac programming. Just started before 3 days.
I am making a sample app in which i have one button in main window
I am using this code to open a new wndowcontroller
ThirdViewController *tvc = [[ThirdViewController alloc] initWithWindowNibName:@"SecondViewController"];

     [tvc showWindow:self];

This working fine but when i press button again it will open same window again so after every click i have +1 window on screen.
What i want is if my new window is already on my screen then button can't add same window.
Thanks in advance:)

A:

If that code is being executed whenever the button is clicked then you’re effectively creating a new window controller, loading its window from a nib file, and showing that window as many times as the button is clicked.
The standard approach to prevent this from happening is having an instance variable that is initially nil and assigning it a window controller only once. Subsequently, the instance variable is not nil any longer and you can test that to avoid creating another controller and loading the nib file again.
You could, for example, declare the following instance variable in your application delegate or whatever controller should be responsible for the third window controller:
ThirdViewController *tvc;

and, when the button is clicked:
if (nil == tvc) {
    // If tvc is nil then it's the first time this code is being executed
    tvc = [[ThirdViewController alloc] initWithWindowNibName:@"SecondViewController"];
}

[tvc showWindow:self];


Q:

Visitor vs Composition

As I see it visitor design pattern is very similar to the way composition work.
In composition I would hold an interface member in the class and pass a concrete implementation of the interface in the constructor, and then either delegate a method to it or use it inside the class.
In visitor design pattern I also have a concrete implementation of the interface, and I send it to the visit method which then delegates the visit method to it.
To show this similarity in code, a visitor would be:
VisitorInterface v = new ConcreteVisitor();
MyClass c = new MyClass();
c.visit(v);
VisitorInterface dv = new DifferentVisitor();
c.visit(dv);

And composition would be:
SomeInterface i = new ConcreteImplementation();
MyClass c = new MyClass(i);
c.visit();  // called visit just to show the symmetry to visitor pattern
SomeInterface di = new DifferentImplementation();
c.changeReference(di);
c.visit();

I would like to hear your thoughts as to in which cases you would prefer one over the other and why

A:

Composition is the means of expressing a has-a relationship between objects, in other words, to model attributes of an object. A cow has horns. Injection is not essential to this. The Visitor pattern is a way to perform an external action on a type. They serve different purposes and operate on different portions of the object model. To answer your question, I prefer composition when the logic of the situation calls for a type to have an attribute, and the Visitor pattern to organize code to perform an action on instances of a type without altering the structure of the target type, as documented for that pattern.


Q:

Android Google Play Games Services

Trying to integrate google play games leaderboard in an android application.
Google API client get connected successfully. I am getting result code as -1 which is nothing but RESULT_OK.
But when I call google leaderboard api using leaderboard intent in my on activity result I get 10001 which stands for inconsistent state which is RESULT_RECONNECT_REQUIRED. Even though before calling the intent i am checking is the google api client is connected or not. Which returns true each and every time.
Not able to understand what might be causing this issue.

A:

The reason you might get that code is because app is not linked. So on play games developer console linked my application and it started to work.


Q:

Need help understanding instance variables

I have these instance variables in my class:
private int x1 = 0;
private int y1 = 0;
private int x2 = 0;
private int y2 = 0;
private int height = y2 - y1;
private int width = x2 - x1;

In my program I use methods that change the xs and ys, so I expect height and width to change as well. However, they don't. Can someone explain why this is the case, and how I can make their values "update" after a method call that changes the xs and ys?

A:

Your expression private int height = y2 - y1; is evaluated when the instance variable is initialised: i.e. when the class is instantiated. From that point on it is does nothing - it is not "linked" in any way to the source parts of the expression and does not update when they update.
You probably want a method on the class (public if it is used outside the class, private otherwise) which would be something like the below. You can get rid of your height and width fields:
public int getHeight() { return this.y2 - this.y1; }

However if you decide you still need the width and height internally I would change this to a private method named calculateHeight. Methods called getXYZ are usually accessors for fields and not mutation methods. You can then call this (or the equivalent calculateWidth()) whenever you change the field values for y2, y1, x2, x1.
public int getHeight() { return this.height; }
private int calculateHeight() { return this.y2 - this.y1; }
...
this.y2 = this.y2 + 10;
this.height = calculateHeight();

As an aside I would argue that width and height are positive numbers regardless of y2 being more or less than y1. You can use Math.abs to remove the sign on the subtraction result:
public int getHeight() { return Math.abs(y2 - y1); }

My preference would be to use a single method to return the height and width as a dimension. The two values are really a single piece of data at a point in time. You could use java.awt.Dimension for this:
public Dimension getDimension() {
  new Dimension(Math.abs(x2 - x1), Math.abs(y2 - y1));
}


Q:

Spark Dataframe to Dataset of Java class

I want to transform a Dataframe that is read in as Json to a Dataset of a given class. So far, that worked pretty well, when I was able to write own case classes.
case class MyCaseClass(...)
val df = spark.read.json("path/to/json")
val ds = df.as[MyCaseClass]

def myFunction(input: MyCaseClass): MyCaseClass = {
    // Do some validation and things
    input
}

ds.map(myFunction)

However, now I am bound to external Java classes (specifically ones created by thrift). So here a more concrete example with a custom class:
Json:
{"a":1,"b":"1","wrapper":{"inside":"1.1", "map": {"k": "v"}}}
{"a":2,"b":"2","wrapper":{"inside":"2.1", "map": {"k": "v"}}}
{"a":3,"b":"3","wrapper":{"inside":"3.1", "map": {"k": "v"}}}

Class:
class MyInnerClass(var inside: String, var map: Map[String, String]) extends java.io.Serializable {
  def getInside(): String = {inside}
  def setInside(newInside: String) {inside = newInside}
  def getMap(): Map[String, String] = {map}
  def setMap(newMap: Map[String, String]) {map = newMap}
}

class MyClass(var a: Int, var b: String, var wrapper: MyInnerClass)  extends java.io.Serializable {
  def getA(): Int = {a}
  def setA(newA: Int) {a = newA}
  def getB(): String = {b}
  def setB(newB: String) {b = newB}
  def getWrapper(): MyInnerClass = {wrapper}
  def setWrapper(newWrapper: MyInnerClass) {wrapper = newWrapper}
}

So I want to do:
val json = spark.read.json("path/to/json")
json.as[MyClass]

However, that throws:
Unable to find encoder for type stored in a Dataset.  Primitive type (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.

So, I found out about Custom Encoders: (here and here)
import org.apache.spark.sql.Encoders
val kryoMyClassEncoder  = Encoders.kryo[MyClass]
json.as[MyClass](kryoMyClassEncoder)

Which throws:
Try to map struct<a:bigint,b:string,wrapper:struct<inside:string,map:struct<k:string>>> to Tuple1, but failed as the number of fields does not line up

So how can I convert a Dataframe to a custom object Dataset.

A:

Instead of using kryo encoder, try using the product encoder, ie:
val productMyClassEncoder  = Encoders.product[MyClass]


Q:

NSData(contentsOfFile: "someexistingfile") returns nil in Playground

Is there a good reason that above returns nil in Playground? When run in AppDelegate the statements returns the file contents, but in Playground it's nil. Is it just another silly bug from Apple? Or just me not finding the docu which states that this is not allowed?

A:

It turned out that Playground was simply unwilling. Booo, Apple. I used the command
rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"

to get it going once again. A receipt I learned somewhere else on SO. This also cures a lot of other unwillingnesses of XCode.


Q:

Egyptian Fraction equation in Python

Some sort of function that finds the standard fractional notation version of the given Egyptian fraction.
For example:
input: 3, 15
output: 2/5

explained for those not familiar with Egyptian fractions:
(1/3 + 1/15) = 18/45 = 2/5

What kind of equation could do this? if not an equation then what set of operations?

A:

from fractions import Fraction

def egyptian(a, b):
    frac = (Fraction(1.0/a) + Fraction(1.0/b)).limit_denominator()
    return frac.numerator, frac.denominator

egyptian(3, 15)
>>> (2L, 5L)


Q:

Passing a jquery method as a parameter into a function?

Is it possible to pass a jQuery method as a parameter into a function , for example:
function set_action(a,b)
{
  $(a).b;
}

$(function(){
    $('#div_id1').click(function(){
        set_action('#div_id2','hide()');
    });
});

?

A:

You can access any property of an object with a string using bracket notation:
var foo = {
   bar: 5
};

console.log(foo['bar']);

So you could do:
function set_action(a,b) {
  $(a)[b]();
}

set_action('#div_id2','hide');

Note that this will throw an error if the object does not have a callable property with that name.


Q:

When one uses "povu" instead of "devas", what is the nuance?

Povu probably means "should", according to the Esperanto Bible:
https://bit.ly/2FMTKVo
However, we already have devi. So I wonder, is there any nuance being expressed here?
I looked up PIV, Wikipedia, and ReVo, with no meaningful results.

A:

I cannot read the text when I follow the link; is it Job 9:32?

Ĉar Li ne estas homo simile al mi,
  Ke mi povu respondi al Li,
  Ke ni povu ambaŭ iri al juĝo.
For he is not a man, as I am,that I should answer him,and we should come together in judgment. (KJV)

Here are more modern translations:

If God were human, I could answer him; we could go to court to decide our quarrel. (GNT)
He is not a mere mortal like me that I might answer him, that we might confront each other in court. (NIV)

The KJV's use of should here, to mean merely would,  is not totally archaic, but it is old-fashioned. Here is a quotation from Alice in Wonderland:

"For it might end, you know, [...] in my going out altogether, like a candle. I wonder what I should be like then?"

She isn't talking about what she ought to be, but about what she would be. It was formerly laid down as a rule in English that would cannot be used after I or we; it had to be replaced by should, and that I will implies a desire. This idea originated in the distinctions made by scholars translating from Latin:

The rule is [...] to express a future event without emotional overtones, one should say I shall, we shall, but you/he/she/they will; conversely, for emphasis, willfulness, or insistence, one should say I/we will, but you/he/she/they shall.
—John Wallis, Grammatica Linguae Anglicanae (1653)

Thus in the quotation from the Book of Job, ke mi povu respondi means "so that I would be able to answer", and the use of povu instead of just povus implies that it is a desire: Job would like to make an answer.


Q:

how to fix rotten exterior wall

Due to moisture my outside wall is rotten in a small section of house. Picture attached. What is the best way to fix this.

A:

I see that you have posted two questions about this situation. I fear you have to address a couple of problems here.  First and foremost is to try to route water away from this area. We can address this in another segment with more info on the area in question.
As far as the immediate problem, I am pretty sure you will have to remove the damaged sections of the rotted siding. I also suspect there will be damage to the bottom plate and will have to be replaced as well. Also inspect any insulation in this wall for moisture damage and mold.  I would be looking at replacing the sill plate with pressure treated lumber and seal it with caulk under the plate to avoid any water creeping indoors under the plate.  If you do not want to replace the entire height of the siding, you may be able to scab a matching replacement patch in there, but that could be unattractive.  You could install a horizontal trim piece along the bottom, under cut or flashed to the siding if the rotted section is not too high up the wall. The important thing here is to remove the rot and create a side wall that will not rot again. You could use a PVC trim board (1X8 etc) or other rot resistant material. This is one of those jobs that require a look-see and adapt a solution as the amount of damage is determined. If you are looking for step by step directions for cutting, removing, and replacing, that is a whole other discussion, depending  on your level of expertise and tools you have available.


Q:

When should I use multiscatter GGX?

One of the new Cycles features in 2.78 is Multiscatter GGX.

When should I use it instead of the default? (Bonus question: and when sould I use the other possibilities in the Glossy, Glass and Anisotropic BSDFs?)
So far I found only the following

Essentially, the improvement is that unlike classical GGX, which only models single scattering and sets
  the contribution of multiple bounces to zero, this new model performs a random walk on the microsurface until
  the ray leaves it again, which ensures perfect energy conservation.
  In practice, this means that the "darkening problem" - GGX materials becoming darker with increasing
  roughness - is solved in a physically correct and efficient way.
The downside of this model is that it has no (known) analytic expression for evalation. However, it can be
  evaluated stochastically, and although the correct PDF isn't known either, the properties of MIS and the
  balance heuristic guarantee an unbiased result at the cost of slightly higher noise.

This sounds too technical to me. I understand the not-darkening part, but that's all...

A:

What is it?
This is based on this paper.

Modeling multiple scattering in microfacet theory is considered an
  important open problem because a non-negligible portion of the energy
  leaving rough surfaces is due to paths that bounce multiple times.

This effect can be clearly seen in high roughness glass, where a lot of light rays were killed because they happened to reflect on the glass itself rather than reflecting or refracting away, which you can see it the images provided by them:

Their model enable the sample (light) to bounce multiple times before being killed, Which result a more relastic and lighter result. It is also worth mentioning that this model enable more efficient energy conservation because the light will bounce till it loose all its energy.
This can be seen here, where the alpha represent the roughness of the diffuse and the glass shader:

However it doesn't really matter when the shader has low roughness since it is nearly imposible for the light to bounce on itself again, this can be seen in this shader with varity in roughness, you can see that the rough parts have a greater impact while smooth ones have almost no impact.

As for the speed of the rendering, using the multiscatter model will result only 2.5% slowdown which is pretty acceptable if you asked me.
When to use it?
Well it is pretty obvious that you should use it when you have shaders that have high roughness to avoid the dark areas. notice that the amount of darknening is directly proportional to the roughness of the shader, so if you have a semi low roughness you don't have to use multiscatter.

A:

If you use a roughness different from zero it won't make the material lock darker if you increase the roughness.
So it might solve problem with dark materials.
It will probebly be useful if you are changing the roughness during an animation.
The second part is saying that it might create a new problem because it might be inaccurate.
The thing they are considering physically correct is the part of conservation of energy, moving the light ray might be correct if it is quantum mechanics they are tying to simulate, but not as long as it is Einstein or Newtons laws we are talking about.
the plain is on 0, 0, 0, and the lamp also

GGX

GGX Multiscatter


Q:

What is meant by getIntent().getExtras()?

I am new to Android development and I have come across something new while using Intent as getIntent().getExtras().
Can anyone please explain me how can we write getIntent().getExtras(),cause till now what I know is we can call method by creating object of that particular class but here we are call method getExtras() by using getIntent()method.

A:

getIntent().getExtras() is used to get values from intent that are stored in bundle.
Intent class is used to switch between activities. But sometimes we need to send data from one activity to another. So, at this particular moment we need to set some values to intent that can be transferred to destination activity. We can achieve this by the following code -
Bundle bundle = new Bundle();
bundle.putString("key1","someValue");
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putStringExtra("key","value");
intent.putExtras(bundle);
startActivity(intent);

Now, in the second activity we can get the value of "key" so we can use that in second activity. To do so, we use the getIntent().getIntent can store a Bundle. Let's see an example -
Intent intent=getIntent();
Bundle valueFromFirstActivity = intent.getExtras();
String valueOfKey = intent.getStringExtra("key");
String valueOfKey = bundle.getString("key1");

So this way, one can get values from activities. Bundle is a class that can hold values within itself and that instance of bundle can be given to intent using putExtras(). It is quite helpful in transferring the custom array list.


Q:

queryBroadcastReceivers does not find receivers registered with registerReceiver

I need to find out which broadcast receivers can handle a given Intent.
It seems that queryBroadcastReceivers() does not return receivers registered in code using registerReceiver() but only receivers declared in AndroidManifest.xml.
Is this behavior by design?
Any other way to find all installed receivers for some Intent ?
Thanks.

A:

It looks like it's not possible to detect receivers registered in code, as per this recent message on the mailing list: http://groups.google.com/group/android-developers/msg/5fd1cdb24b2a6760
This is disappointing as I was looking for a way to do the same thing.


Q:

my push() in stack class mutates every element in the stack

I made a stack array that based on DataRecord.
Both classes compiled without an error but when I do push() to the stack, it mutates data in every index of the stackArray[].
I cannot find which line of code make this issue.
Please helps me to find the cause, thank you.
DataRecord class:
public class DataRecord
{
    private String id;
    private String data;

    //default constructior
    public DataRecord( )
    {
        this.id = " ";
        this.data = " ";
    }

    //overloded constructor
    public DataRecord( String id, String data )
    {
        this.id = id;
        this.data = data;
    }

    //set method
    public void setIDandData( String id, String data )
    {
        this.id = id;
        this.data = data;
    }

    //get method
    public String getID()
    {
        return id;
    }
    public String getData()
    {
        return data;
    }

    //toString
    public String toString()
    {
        return "\n Your ID is : " + id +
                "\n Your DataRecord is : " + data + "\n";
    }
}//End of DataRecord

MyStack1 class:
class MyStack1
{
    private int maxSize;
    private DataRecord[] stackArray;
    private int top;
    private String tempString = "";

    public MyStack1(int sizeOfStack)
    {
        maxSize = sizeOfStack;
        stackArray = new DataRecord[maxSize];
        top = -1;
    }

    public void push( DataRecord userInput )
    {
        stackArray[++top] = userInput;
    }

    public DataRecord pop()
    {
        return stackArray[top--];
    }

    public String toString()
    {
        tempString = "";

        for(int i = 0; i <= top; i++)
        {
            tempString += i+1 + stackArray[i].toString();
        }
        return "\nThe max size of the stack is : " + maxSize +
                "\nThe top index of the stack is : " + top +
                "\nThe top element of the stack is : " + stackArray[top] +
                "\nThe list of element in the stack is : " +
                "\n" + tempString;
    }

    public static void main(String[] args)
    {
        MyStack1 stackArray = new MyStack1( 5 );

        DataRecord newData = new DataRecord(" Hello "," world! ");
        stackArray.push(newData);

        System.out.println("Results : " + stackArray.toString());

        newData.setIDandData("why","omg");
        stackArray.push( newData );

        System.out.println("Results : " + stackArray.toString());

        System.out.println("pop :"+stackArray.pop().toString());
        System.out.println("pop :"+stackArray.pop().toString());
    }
}

output looks like
When I compile and run, the output looks like picture above.

A:

DataRecord newData = new DataRecord(" Hello "," world! ");
stackArray.push(newData);

System.out.println("Results : " + stackArray.toString());

newData.setIDandData("why","omg");
stackArray.push( newData );

The line newData.setIDandData is modifying the object you already put in.  You must explicitly create a new DataRecord; Java will not implicitly copy objects.  When you push newData into the stack, it pushes a reference to that object; modifying that object in one place will still modify the object that you've put into the stack.
There is no way around this; this is how Java works.


Q:

deep copy cloning via serialization

I came accross this:
http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
and would like to use it to deep copy a object graph. Is it sufficient to mark all the classes that potentially participate in the object graph with:
[Serializable()]

and then invoke the clone method as suggested in the article?
I have my doubts that it is that simple and I may have to implement more?! Thought I ask the experts first before I dig any deeper.
Thanks.
Christian

A:

Putting SerializableAttribute on a class means that all the fields of the object (except those you attribute with NonSerialized) will be serialized (and so they, themselves, need to be serializable). For simple cases that is enough, but for more complicated objects, you might want to look at implementing ISerializable, which will transparently work with the code in the article. It very much depends on your exact situation. For simple cases, SerializableAttribute by itself is enough.


Q:

Retrofit Dynamic URL still appends to the Base URL

Here is my Retrofit Interface and creation code:
interface SSApi {
companion object {
    private fun create(): SSApi {
        val httpClient = OkHttpClient().newBuilder()
        val networkInterceptor = Interceptor { chain ->
            val request = chain.request()?.newBuilder()?.addHeader("api-key", SSConstants.API_KEY)?.build()
            chain.proceed(request!!)
        }

        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        httpClient.addNetworkInterceptor(networkInterceptor).addInterceptor(loggingInterceptor)

        val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(SSConstants.BASE_URL)
                .client(httpClient.build())
                .build()

        return retrofit.create(SSApi::class.java)
    }

    val api by lazy {
        SSApi.create()
    }

    var disposable: Disposable? = null
}

@GET
fun getWeatherInfo(@Url url: String): Observable<OpenWeatherMapInfo>
}

And here is how I use the disposable:
    private fun getWeather() {
    disposable = api
            .getWeatherInfo(SSConstants.OPEN_WEATHER_MAP_API_ENDPOINT)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    { results -> Log.i("Dale", results.toString())},
                    { error -> Log.i("Dale", error.message)}
            )
    }

When I execute the request, I can see that it my OPEN_WEATHER_MAP_API_ENDPOINT still appends to my baseUrl.
Here is my Constants class for reference:
object SSConstants {
const val OPEN_WEATHER_MAP_API_ENDPOINT = "api.openweathermap.org/data/2.5/weather?q=Catbalogan,PH&units=metric"
const val BASE_URL = "https://api.xxx.xxx/"
}

A:

Your issue is that you didn't provide the full URL in the dynamic call, and that's why Retrofit is trying to make the call relative to the base url still. Just add https:// to the dynamic URL:
const val OPEN_WEATHER_MAP_API_ENDPOINT = "https://api.openweathermap.org/data/2.5/weather?q=Catbalogan,PH&units=metric"

Here is an article discussing how the dynamic URL is resolved in different scenarios, for further reference.


Q:

Generic Event Args In Interface

I'm trying to save an object in a generic EventArgs class but because the EventHandler has an interface, I'm having difficulty accomplishing this.  Any way to get something like this working?
My EventArgs class:
public class PositionChangedEventArgs<T>
{
   public PositionChangedEventArgs(byte position, T deviceArgs)
   {
       Position = position;
       DeviceArgs = deviceArgs;
   }

   public byte Position { get; private set; }
   public T DeviceArgs { get; private set; }
}

Interface being used:
public interface IMoveable
{
    event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}

Example class usage:
public class SomeDevice : IMoveable
{
   public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged; //Compiler doesn't like this
}

A:

You need to change your interface definition to the following:
public interface IMoveable<T>
{
    event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}

You can consume it by passing the type to the interface like so:
public class SomeDevice : IMoveable<DeviceSpecificEventMessageArgs>
{
   public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged;
}


Q:

Msg 4104, Level 16, State 1, Procedure AddItemToCurrentItems, Line 11 The multi-part identifier "INSERTED.IsActive" could not be bound

I have following trigger written for my application which gives me this error "Msg 4104, Level 16, State 1, Procedure AddItemToCurrentItems, Line 11 The multi-part identifier "INSERTED.IsActive" could not be bound."
My intension with this trigger is to copy the inserted data in table "Item" to table "CurrentItems" but only if the bit field in Items table is set to True i.e. 1. Both tables have the same table structure
CREATE TRIGGER AddItemToCurrentItems
   ON ITEMS FOR INSERT
--,UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF INSERTED.IsActive = 1
    BEGIN
       INSERT INTO CurrentItems
           SELECT * FROM INSERTED
    END
END

Any ideas, what I am doing wrong here.

A:

You are missing a reference to the INSERTED table in you if clause, would need to look something like this:
IF exists (select * from inserted i where i.IsActive = 1) BEGIN
...

NOTE however that the inserted/updated tables can always contain multiple records, just like any SQL table, so you'll need to be sure your logic handles multi-record possibilities, for example your insert within your IF block should likely contain an additional where clause, something like this:
IF exists (select * from inserted i where i.IsActive = 1)
BEGIN
    INSERT CurrentItems SELECT * FROM INSERTED where IsActive = 1
END

Or, you could just leave out the IF block alltogether and do something like this:
INSERT CurrentItems SELECT * FROM INSERTED where IsActive = 1

NOTE that you probably should also consider including a column list in both your insert and select statements...


Q:

Can general relativity be explained by equations describing a fabric of space embedded in a flat 5-dimensional Minkowski space?

Does such a set of equations exist or does our universe have an intrinsic curvature that can't be explained by an embedding in a flat Minkowski space of 1 higher dimension? Even if general relativity can be explained by such equations, it still doesn't prove our universe is embedded in a flat Minkowski space of higher dimension.

A:

For Riemannian manifolds, I believe the best result currently known is that a manifold of dimension $n$ can be isometrically embedded in a euclidean space of dimension $2(2n+1)(3n+7)$.  So, for example, a 3-dimensional spacelike slice of spacetime can be embedded in a flat euclidean space of at most 224 dimensions.  Maybe in low-dimensional cases like this one can do better, but if so I'm not aware of it.
So much for space.  If you want to embed all of spacetime, I think the best known result is that every Lorentzian manifold can indeed be embedded in a flat Lorentzian manifold, but I don't think any bound is known on the necessary number of dimensions.
Edited to add:  I see by the reference I posted in the comments that there is in fact a known bound for Lorentzian manifolds:  $2(2n+1)(2n+6)$.  So you can imbed all of (four dimensional) spacetime in a copy of $R^{252}$, with signature $(126,126)$

A:

This is an afternote to WillO's answer which cites:
Robert E. Greene, "Isometric Embeddings," Bull. AMS 1969
which addressed known bounds on the dimension required of flat Euclidean / Minkowsian space if it is to be an embedding for a solution of the Einstein field equations, which of course is a four-dimensional signatured manifold.
It's worth noting that important special cases one can be embedded in much lower dimensions than the insanely loose bounds defined by the Nash embedding theorem and its Lorentzian equivalents. Such simplifications happen in cases of high symmetry. For example, the large scale homogeneous/ isotropic universe defined by the Friedmann–Lemaître–Robertson–Walker (FLRW) metric can indeed be thought of as being embedded in five dimensional space, with signature $(1,\,4)$, because it can be partitioned into foliations of space, with the foliations indexed by a universal time co-ordinate, and the spatial foliations are isometric to three dimensional spheres / hyperboloids in $\mathbb{R}^4$ with only the scale factor and energy / pressure evolving over time.
Indeed, the lecture notes:
Balša Terzić, Lecture notes for PHYS 652, Old Dominion University
take the unusual approach of lifting well known  19th century geometry results on the hypersphere / hyperboloid and linking them to a homogeneous, isotropic stress energy tensor. The Ricci tensor is of course diagonal in this case, so the student is relieved of the full complexity of GR and gets to see the direct link between stress energy (in the diagonal case) and curved spaces.

Lawrence B. Crowell's answer cites two other examples very like FRLW which can be split into spatial foliations such that the whole spacetime is embedded in 5 dimensions with a $(1,\,4)$ signature - the de Sitter and anti-de Sitter spaces, which are like FLRW but with no matter and pressure (vacuum solution) and a special value for the cosmological constant.

A:

General relativity in four dimensions does not need to be embedded in a larger space of any sort. Curvature in general relativity is completely defined according to curvatures that are intrinsic induced by parallel translation of vectors. One does not need to have the spacetime in four dimensions embedded in some higher dimension spacetime.
There is general relativity in five dimensions with the flat metric
$$
ds^2~=~dt^2~\pm~du^2~-~dx^2~-~dy^2~-~dz^2.
$$
The constraint
$$
t^2~\pm~u^2~-~x^2~-~y^2~-~z^2~=~\alpha^2
$$
defines hyperboloids embedded in this flat spacetime. The condition $\pm u^2$ defines the anti-deSitter $(+du^2)$ and de Sitter spacetimes $(-du^2)$. The constant $\alpha$ defines the cosmological constant. So this is a special case of what you are talking about.


Q:

Not allowed to load local resource

A user will upload an index.html file and a few images, that will be sent out as an HTML email. I am working on preview functionality, so they can check before sending.
I am running into the "Not allowed to load local resource" error in Chrome, when trying to access the uploaded files.
I am running my application on JBoss 7.1. Currently my server is running locally on my laptop, could this be the problem?
I have tried using the JBoss temp folder, but I get the same error.
I thought of copying the files temporarily into a folder within the WAR archive, but I have not been able to find a way to do this.
Is there a workaround or solution to this? Or is there a way to display a MimeMultipart object in a window?

A:

Using Jboss 8.1 Wildfly, I have found an alternate solution to this problem.
Adding an additional file handler to standalone.xml does the trick.
<server name="default-server">
    <http-listener name="default" socket-binding="http"/>
    <host name="default-host" alias="localhost">
        <location name="/" handler="welcome-content"/>
        <location name="/img" handler="images"/>
    </host>
</server>
<handlers>
    <file name="welcome-content" path="${jboss.home.dir}/welcome-content" directory-listing="true"/>
    <file name="images" path="/var/images" directory-listing="true"/>
</handlers>

Thanks to hwellman's reply on the following question


Q:

схожесть действий стандартных алгоритмов is_partitioned и all_of

Никак не смог понять чем отличаются эти два алгоритма.
string s = "(double) k / 12";
auto pred = [](char c) { return c == '/'; };
bool b1 = is_partitioned(s.begin(), s.end(), pred);
bool b2 = all_of(s.begin(), s.end(), pred);
cout << boolalpha << b1 << endl /*false*/ << b2; /*false */

Читал как они реализованы, но не нашел разницу. И чем же отличаются эти два алгоритма, кто поможет разобраться?
Добавление к вопросу:
Для того, чтобы я лучше понял,  прошу на моем примере добавить символы  или поменять предикат так, чтоб  результат двух алгоритмов был разным.

A:

all_off вовращает true если все элементы диапазона при проверке pred выдают true. Т.е. ни один элемент при проверке не даст false.
is_partitioned возвращает true если все элементы диапазона, которые при проверке выдают true находятся перед элементами, которые при проверке выдают false. Т.е. некоторые элементы могут при проверке давать false, но должны находиться после элементов, которые дают true:
[true, true, true, true, false, false] будет true.
[true, true, false, true, false, false] будет false, потому что после первого false еще есть true (или, что то же самое, до последнего true встречается как минимум один false).


Q:

React native w/ redux: dispatch is not a function

I am trying to implement the following example in my project:
https://github.com/reactjs/redux/tree/master/examples/async
But I keep running into the error: dispatch is not function
when executing the dispatch function from my actions class.
It seems as if Dispatcher is not getting passed down to my actions but I followed the flow in the example:
actions/index.js file:
    export const REQUEST_LOCAL_POSTS = 'REQUEST_LOCAL_POSTS';
export const RECEIVE_LOCAL_POSTS = 'RECEIVE_LOCAL_POSTS';
export const REQUEST_CURRENT_LOCATION = 'REQUEST_CURRENT_LOCATION';
export const RECEIVE_CURRENT_LOCATION = 'RECEIVE_CURRENT_LOCATION';

export const requestCurrentLocation = () => ({
    type: REQUEST_CURRENT_LOCATION
})

export const receiveCurrentLocation = currentLocation => ({
    type: RECEIVE_CURRENT_LOCATION,
    currentLocation,
    receivedCurrentLocationAt: Date.now()
})

export const requestLocalPosts = () => ({
    type: REQUEST_LOCAL_POSTS
})

export const receiveLocalPosts = json => ({
    type: RECEIVE_LOCAL_POSTS,
    posts: json,
    receivedAt: Date.now()
})

export const fetchLocalPosts = dispatch => {
    dispatch(requestCurrentLocation())
    navigator.geolocation.getCurrentPosition(
      (position) => {
         dispatch(requestLocalPosts()) // getting dispatch is not a function here
        return fetch(`http://192.168.1.3:9000/posts?lng=${position.coords.longitude}&lat=${position.coords.latitude}&radius=1000`)
    .then(response => response.json())
    .then(json => dispatch(receiveLocalPosts(json)))

      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    )

home.js (component):
import React, { Component } from 'react';
import {Text, View, ActivityIndicator, FlatList, Image, TouchableHighlight} from 'react-native';
import styles from './styles';
import MapView from 'react-native-maps';
import images from '../../config/images';
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { fetchLocalPosts } from '../../actions'

 class Home extends Component {

    static navigationOptions = ({ navigation }) => {
//const {dispatch , state, setParams} = navigation;

  return {
    title:<Text style={styles.title}>Localized</Text>,
    headerStyle: {backgroundColor: '#2c6da4'},
    headerRight: (
      <TouchableHighlight onPress={() => navigation.dispatch({ type: 'MAP_EXPLORE' })}>
  <Image
        source={images.icons.map}
      />
    </TouchableHighlight>

    ),
  };
};

static propTypes = {
    posts: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    lastUpdated: PropTypes.number,
    dispatch: PropTypes.func.isRequired
  }

    componentDidMount() {
        console.log(this.props)
        const { dispatch } = this.props
        dispatch(fetchLocalPosts()) // calling action from here
    }

    render() {

        return (

            <View style={styles.container}>

                 // i know posts isnt accessed here yet, still trying
                 to get past error
                <FlatList
                    data={this.state.data}
                    refreshing={this.state.refreshing}
                    showsVerticalScrollIndicator={false}
                    ListHeaderComponent={this.renderHeader}
                    onRefresh={this._onRefresh.bind(this)}

                    renderItem={({item}) => <View><FlatList
                        data={item.posts}
                        horizontal={true}
                        snapToAlignment='center'
                        showsHorizontalScrollIndicator={false}
                        renderItem={({item}) => <Text style={styles.item}>{item.title}{"\n"}{item.snippet}</Text>}/>
                        <Text style={styles.subItem}>{item.Name}{"\n"}{item.Address}</Text>
                    </View>}

                />

            </View>

        );
    }

}

const mapStateToProps = state => {
  const { postsByBusiness } = state
  const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsByBusiness || {
    isFetching: true,
    items: []
  }

  return {
    posts,
    isFetching,
    lastUpdated
  }
}

export default connect(mapStateToProps)(Home)

reducer/index.js:
import { combineReducers } from 'redux';
import { NavigationActions } from 'react-navigation';

import { AppNavigator } from '../navigators/AppNavigator';

import { RECEIVE_LOCAL_POSTS, REQUEST_LOCAL_POSTS } from '../actions';

const initialNavState=AppNavigator.router.getStateForAction(NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({
        routeName: 'Home',
      }),
    ],
}));

const MAP_EXPLORE = 'MAP_EXPLORE';
const LIST_EXPLORE = 'LIST_EXPLORE';

function nav(state = initialNavState, action) {
    let nextState;
    switch(action.type) {
        case MAP_EXPLORE:
        nextState = AppNavigator.router.getStateForAction(
            NavigationActions.navigate({ routeName: 'Map'}),
            state
            );
        break;
        case LIST_EXPLORE:
        nextState = AppNavigator.router.getStateForAction(
            NavigationActions.navigate({ routeName: 'List'}),
            state
            );
        break;
        default:
            nextState = AppNavigator.router.getStateForAction(action, state);
            break;
    }
    return nextState || state;

}

function postsByBusiness(state = { }, action) {
    switch(action.type) {
        case RECEIVE_LOCAL_POSTS:
        return {
            ...state,
            isFetching: false,
        didInvalidate: false,
        items: action.posts,
        lastUpdated: action.receivedAts
        }
        default:
        return state
    }
}

const AppReducer = combineReducers({
  nav,
  postsByBusiness

});

export default AppReducer;

A:

fetchLocalPosts should be returning a function that takes dispatch as an argument. Changing it to the following should fix it.
export const fetchLocalPosts = () => dispatch => {
  ...

It's another way of doing this:
export const fetchLocalPosts = () => {
    return function (dispatch) {
      ...


Q:

Disabling column names in ps output

How to format output of ps -p command?
To not show me something like this:
PID TTY                TIME CMD

but just PIDs.
I'm using Linux.

A:

Use the -o option to select which columns are displayed. If you put = after the column name, the header line is suppressed.
ps -o pid= -p 1 23 456
ps -o pid= -o ppid= -o pgid= -o sid= -p 1 23 456

A:

Use the --no-headers to have the header line omitted.
Original output:
ps
  PID TTY          TIME CMD
27027 pts/0    00:00:00 bash
27071 pts/0    00:00:00 ps

With --no-headers:
ps --no-headers
27027 pts/0    00:00:00 bash
27072 pts/0    00:00:00 ps

Combining with -p:
ps -p 1 --no-headers
    1 ?        00:00:33 systemd

The man page for ps clearly documents this:
man ps

[snip]

 --no-headers
          Print no header line at all.  --no-heading is an alias for this option.


Q:

"PHP Fileinfo extension must be installed/enabled to use Intervention Image." error

I'm getting this error "PHP Fileinfo extension must be installed/enabled to use Intervention Image." when I try out the Laravel example:
Route::get('/', function()
{
    $img = Image::make('foo.jpg')->resize(300, 200);

    return $img->response('jpg');
});

I've uncommented extension=php_fileinfo.dll in the php.ini file located in C:\MAMP\bin\php\php7.1.5 but that doesn't work. I restarted my PC and my MAMP after doing this. I'm hosting my website myself.

A:

You have edited the wrong ini file.
Check the loaded ini files section of phpinfo().

UPDATE you edited an ini in the bin folder and not the conf. Editing the one in conf should fix your issue.


Q:

How can I stream a large .m4v video file to my iOS app over HTTP?

I have a large .m4v video file on an HTTP server. As an example, this is the URL I want to hit:
http://www.myurl.com/movies/video1.m4v

The video1.m4v file is 1GB in this example. When I load that URL in my Safari browser on my iPhone the file starts playing automatically and perfectly. I can skip ahead, go back, use Airplay, and everything works great and fast.
When I load it up on my iPhone with this code it just hangs on Loading forever.
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:url];
[moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];

What is the proper way to play an m4v file in my iOS app just like mobile Safari does? The main reason I want to do this is to hide the URL from the user and to not have the user experience of jumping in and out of my app.

A:

I'd try loading the video through a UIWebView.
UIWebView *webView = [[UIWebView alloc] init];
// Hide the webview from the user
webView.frame = CGRectZero;
[self addSubview:webView];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.myurl.com/movies/video1.m4v"]]];


Q:

How to print x number of items per line

I was going to ask this question on here. But I solved it just before I did. I wanted to be able to print this Python 2.7 list in a more orderly fashion.
not_shuffled_deck = ["%i of %s" % (i, s) for i in range(2,10) for s in ('spades', 'diamonds', 'clubs', 'hearts')]

for i in not_shuffled_deck:
    print i + "|",

This is how it was originally turning out.
Well, it's actually worse than how it shows on here. It depends on the console size, screen size, if there is a text wrap, or not, etc. So in the consoles I've used or even in a normal text editor it will show up on multiple lines in a hard to read fashion.
 2 of spades| 2 of diamonds| 2 of clubs| 2 of hearts| 3 of spades| 3 of diamonds| 3 of clubs| 3 of hearts| 4 of spades| 4 of diamonds| 4 of clubs| 4 of hearts| 5 of spades| 5 of diamonds| 5 of clubs| 5 of hearts| 6 of spades| 6 of diamonds| 6 of clubs| 6 of hearts| 7 of spades| 7 of diamonds| 7 of clubs| 7 of hearts| 8 of spades| 8 of diamonds| 8 of clubs| 8 of hearts| 9 of spades| 9 of diamonds| 9 of clubs| 9 of hearts|

So I wanted a way to just print the four 2's on one line, then the 3's, etc.. With a space in between each.

A:

Group on the first item in the string:
from itertools import groupby

for _, group in groupby(not_shuffled_deck, lambda c: c.split()[0]):
    print '| '.join(group)
    print

Demo:
>>> from itertools import groupby
>>> not_shuffled_deck = ["%i of %s" % (i, s) for i in range(2,10) for s in ('spades', 'diamonds', 'clubs', 'hearts')]
>>> for _, group in groupby(not_shuffled_deck, lambda c: c.split()[0]):
...     print '| '.join(group)
...     print
...
2 of spades| 2 of diamonds| 2 of clubs| 2 of hearts

3 of spades| 3 of diamonds| 3 of clubs| 3 of hearts

4 of spades| 4 of diamonds| 4 of clubs| 4 of hearts

5 of spades| 5 of diamonds| 5 of clubs| 5 of hearts

6 of spades| 6 of diamonds| 6 of clubs| 6 of hearts

7 of spades| 7 of diamonds| 7 of clubs| 7 of hearts

8 of spades| 8 of diamonds| 8 of clubs| 8 of hearts

9 of spades| 9 of diamonds| 9 of clubs| 9 of hearts

You asked:

Can you give me an explanation in laymens term of how the formula
  works?

This all pivots around the lambda function; groupby() takes each value from not_shuffled_deck and only looks at the output of that function. c.split() splits the card string on whitespace and only the first element is returned, so '2' or '3', etc.
So groupby then produces groups where the first character is equal; the first element, second element, third element and fourth element of your list all have '2' as the first thing in their strings. _ will be set to '2' (but I ignore it here), and group is an iterable producing those 4 elements; we pass that value to '| '.join() to make a new string to print.
I always picture iterables as bucket-brigades; rows of people passing along buckets of water from a river or well or pump. Doesn't matter where the buckets come from, you have no idea how many will still come, but all you can do is take the next bucket. groupby is like someone organizing new mini bucket brigades for you giving you just a few of the buckets it handles.
So you ask groupby to group buckets by how many fishes were caught with the water. He'll first give you a person that says: I only give you buckets with 2 fishes in them. You keep asking for buckets, and at some point that person says: nope, out of buckets, I have no more for you. And you go back to the groupby arbiter, who says, here, a new person, and he'll only pass on buckets with 4 fishes. And then you talk to just the 4-fishes-bucket guy for a while.
In my answer, not_shuffled_deck is the well (it'll run out of water at some point), groupby doesn't count fishes but only looks at the first part of the string, and group is the person giving you buckets that all have the same first part of the string.
Because this is a bucket brigade, groupby has no idea what'll come next, so if there is a bunch of buckets with 2 fishes, then followed by a bunch with 3 fishes, then another bunch with just 2 fishes again, you'll get 3 different people handing you 3 different groups of buckets. Groups are formed when the outcome of the key (the second argument to groupby) changes from bucket to bucket. Also, if you don't take all the buckets from the group person, then groupby will toss away buckets. Empty them right onto the ground.
If you were taking a 2-fishes group of buckets, but went back to the groupby arbiter to ask for a new group person, the arbiter would toss out all buckets with 2 fishes in them until it found a bucket with a different number of fishes before giving you a new person to talk to. You cannot then go back to the 2-fishes-group person and ask for more buckets, those buckets have all been emptied out on the street now.


Q:

Как получить данные по внешнему ключу и записать их в TreeView? C#

Есть три таблицы:
Таблица "Types"
CREATE TABLE [dbo].[Types] (
[TypeID]   INT  NOT NULL,
[NameType] TEXT NOT NULL,
CONSTRAINT [PK_Types] PRIMARY KEY CLUSTERED ([TypeID] ASC));

Таблица "Status"
CREATE TABLE [dbo].[Status] (
[StatusID]   INT  NOT NULL,
[NameStatus] TEXT NOT NULL,
CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED ([StatusID] ASC));

Таблица "Objects"
CREATE TABLE [dbo].[Objects] (
[ObjectID]   INT  NOT NULL,
[NameObject] TEXT NOT NULL,
[TypeID]     INT  NOT NULL,
[StatusID]   INT  NOT NULL,
CONSTRAINT [PK_Objects] PRIMARY KEY CLUSTERED ([ObjectID] ASC),
CONSTRAINT [FK_Objects_Types] FOREIGN KEY ([TypeID]) REFERENCES [dbo].[Types] ([TypeID]),
CONSTRAINT [FK_Objects_Status] FOREIGN KEY ([StatusID]) REFERENCES [dbo].[Status] ([StatusID]));

Ранее писал такой запрос, но он не работает:
SqlCommand command = new SqlCommand("
        SELECT TypeID, StatusID FROM [Objects]
          WHERE TypeID = TypeID
          FROM [Types] StatusID = StatusID
          FROM [Status]"
, connect);

Как получить NameType и NameStatus по внешнему ключу и записать их в TreeView? Помогите пожалуйста.
Результат примерно такой:
Redline >
1)Rifle
2)Field-Tested
Asiimov >
1)Rifle
2)Battle-Scared
и т.д.

A:

Это должно помочь получить нужные Вам данные
Select p.NameObject, s.NameStatus, t.NameType
from Objects o
join Types t on o.typeid=t.id
join Status s on o.statusid=s.id


Q:

Solve: line and rectangle intersections

I have been trying to find the intersections between a rectangle and a line, following the example given in the Solve function:
Solve[{x, y} ∈ Line[{{-1, 0}, {2, 1}}] && {x, y} ∈
   Circle[], {x, y}]
Graphics[{{Blue, Line[{{-1, 0}, {2, 1}}],
   Circle[]}, {PointSize[Large], Red, Point[{x, y}] /. %}}]

this code works well of course, finding both intersections between the circle and the line. However, if I try to substitute the circle with a rectangle the code stops working:
lin := Line[{{-2, -3}, {2, 1}}]
rec := Rectangle[{-1, -1}, {1, 1}]
Solve[{x, y} ∈ lin && {x, y} ∈ rec, {x, y}]
Graphics[{{Red, lin, Blue, rec}, {PointSize[Large], Yellow,
   Point[{x, y}] /. %}}]

Any idea of how to make it work?
Thanks in advance

A:

The problem is that Rectangle has dimension 2, so the intersection of lin and recis a line and not 2 points. You can fix this by taking the boundary of the Rectangle instead:
lin = Line[{{-2, -3}, {2, 1}}]
rec = RegionBoundary @ Rectangle[{-1, -1}, {1, 1}]
Solve[{x, y} ∈ lin && {x, y} ∈ rec, {x, y}]
Graphics[{
    {Red, lin, Blue, rec},
    {PointSize[Large], Yellow, Point[{x, y}] /. %}
}]

Line[{{-2, -3}, {2, 1}}]
Line[{{-1, -1}, {1, -1}, {1, 1}, {-1, 1}, {-1, -1}}]
{{x -> 0, y -> -1}, {x -> 1, y -> 0}}

You could also just use RegionIntersection instead:
Graphics[{Red, lin, Blue, rec, PointSize[Large], Yellow, RegionIntersection[lin, rec]}]


Q:

How to set up MutationObserver to detect added DOM?

Problem: I want to change some of the default text of Facebook to my own.
I used jQuery's text(), but the problem is Facebook will add more DOM when user scrolls down, so I tried to use MutationObserver to detect whether there is new DOM coming in.
I tried this in my chrome content_script:
// I need to detect new .UFILikeLink elements
var target = document.querySelector('.UFILikeLink');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
    alert('test');
  });
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe(target, config);

but this doesn't work, the alert() is not firing.. I wonder is this the right way of using MutationObserver.

A:

The "target" is not a selector for the elements you want to filter, but it should be a single element that represents the root of the subtree you're watching.
For instance, if you want to get notified of all new elements in the body, target should be document.body.
If you need to filter results (you presumably do), you should do so in the callback.
(removed code)
Since you are already using jQuery, here's a more terse and robust version:
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    $(mutation.addedNodes).find(".UFILikeLink").each(function() {
      /* do something */
      console.dir(this); // Note, it's a DOM element, use $(this) if needed
    });
  });
});

observer.observe(document.body, { childList: true,  subtree: true });

Note that you need the subtree: true to watch for mutations deep in the document.


Q:

How to get data from another table according to a retrieved data in Firebase

I am doing an appointment application, this interface is to show to the user that which doctor they have booked an appointment.
I have already done something like this, now I need to use the theraid that I get to retrieve their name which is in another table in Firebase. Can someone teach me how to do it? Thanks in advance :)

Here is my firebase structure.

Here is the code in Java.
  a=new ArrayList<AppointmentObject>();
  namelist=new ArrayList<String>();

        databaseReference= FirebaseDatabase.getInstance().getReference().child("appointment");
        databaseReference.orderByChild("userid").equalTo(userid1).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {

                for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {

                    AppointmentObject thera= dataSnapshot1.getValue(AppointmentObject.class);
                    a.add(thera);

                }
               adapter=new MyRecyclerviewPAppointment(MainActivityPAppointment.this, a,namelist);
                rv.setAdapter(adapter);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getApplicationContext(), "Oh no!", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

Here is the Recyclerview class.
@Override
    public void onBindViewHolder(@NonNull final MyRecyclerviewPAppointment.MyViewHolder holder,final int position) {

     holder.tdate.setText(alist.get(position).getDate());
      holder.ttime.setText(alist.get(position).getTiming());
      holder.tname.setText(alist.get(position).getTheraid());

    }

    @Override
    public int getItemCount() {
        return alist.size();
    }
}

A:

The most direct way is to add an additional listener for each appointment, that then look up the user name for that appointment:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
databaseReference= rootRef.child("appointment");
databaseReference.orderByChild("userid").equalTo(userid1).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
        for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
            String theraid = dataSnapshot1.child("theraid").getValue(String.class);
            DatabaseReference userRef = rootRef.child("alluser/thera").child(theraid);
            userRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot userSnapshot) {
                    String name = userSnapshot.child("name").getValue(String.class);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            }
        }
       adapter=new MyRecyclerviewPAppointment(MainActivityPAppointment.this, a,namelist);
        rv.setAdapter(adapter);

    }

A few things to consider:

This loads the user name for each appointment, even if there are multiple appointments with the same user. In a more realistic scenario you'll want to keep a list of users you've already loaded, either for each appointment query or for a longer time.
While this load will be pretty fast since Firebase pipelines the requests over its existing connecting, it's still additional complexity on reading data. An alternatively would be to store the user name for each appointment in additional to their UID. This type of data duplication is quite common in NoSQL databases.


Q:

Linq-to-sql Null value not displayed in combobox bound to FK

I've a combobox that is binded to a FK entity (the object, not the ID-field). The combobox is filled with a Linq-query-ToList(). DisplayMember is set, ValueMember is empty. Property SelectedItem is used for binding. This all works fine, except if the FK is empty/null, the first item in the combobox is selected, while if I check out the Linq-object I can see that the FK is null. In this case I want the selecteditem of the combobox to be null as well. Am I missing something?

A:

It seems that this works:
Taken from http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/a530f011-54d9-44d1-a585-145ea28ff370/
"I've tested this solution but this will not help if you bind to custom object and set property of object (which is bound to combobox) to null value. Note: I'm binding SelectedItem property
my solution to is derive combobox and force SelectedItem to act correctly"
class MyComboBox : ComboBox
{
    public new object SelectedItem
    {
        get
        {
            return base.SelectedItem;
        }
        set
        {
            base.SelectedItem = value;
            if (value == null || value == System.DBNull.Value)
            {
                this.SelectedIndex = -1;
            }
        }
    }
}


Q:

Specify delay loading dll with #pragma in the cpp file

I have a static-linked library which uses some functions from a dll which i need to delay-load. So in my executable's properties i've added this dll under Linker/Input/Delay Loaded DLLs. I can't add this option in the lib itself since it doesn't have the Linker property pages (because it's a static lib)
So now whenever i use this lib in another executable tool i need to add the delay-loading option over and over again, which i want to avoid. I know there used to be a pragma for this
#pragma comment(linker, "/DELAYLOAD:mydll.dll")

However it doesn't work for me because it says
warning LNK4229: invalid directive '/DELAYLOAD:mydll.dll' encountered; ignored

Is there a way out, other than LoadLibrary?

A:

Did some research on google (guess as you) as I am alway interested in such matters. The obviously link is:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/807606af-f7d7-4d9b-a9f3-062b23fddb2b/using-the-delayload-linker-switch-with-a-custom-dll
Unfortunately it is from 2004, that' nine years and some VS versions before.
But it get worser, I found also this:
http://bytes.com/topic/net/answers/280580-delayload-pragma-fixed-whidbey
which is a year late and sounds very plausible:

No, this never worked reliably. It was a bug to allow it in 6.0. One
  that we fixed later by adding the warning.
Ronald Laeremans
Visual C++ team

I knew, beside your three suggestions no additional, other way.


Q:

python syntax error with the version 2.5 any idea how to fix it?

first i tried to run it by pressing F5. it said the syntax error is in the first line. i tried running the program from the command line but it said the same thing. any idea what's wrong or how to fix it ?

A:

F5 runs the script in the current window, but the current window doesn't display a script: it displays an interactive interpreter (also known as a REPL: Read, Evaluate, Print Loop).
In this window, you simply type valid Python statements, and they execute immediately. There is not way, or need, to run the contents of the window.


Q:

SSIS writing Datetime to CSV fails

I am attempting to write a Sql Server DateTime field to a CSV in SSIS and it keeps failing with:  "[Flat File Destination [742]] Error: Cannot copy or convert flat file data for column "Quotation_Date__c".
I checked the SQL using to pull the data from SQL server and it pulls the data with no errors.  Column "Quotation_Date__c" pulls data with no errors.  It's just when it attempts to write the DateTime column to the CSV is where the problem happens.  Any ideas?

A:

Check the flat file connection manager, target column data type should make sense.


Q:

C++ invoke method from string

There is in Qt such functionality: QMetaObject::invokeMethod(QObject * obj, const char * member, ...), which invokes method from string (member). How can I do the same (or similar)? Thanks)

A:

You can't do this in pure c++, but you can read about reflection/introspect in c++ in this question

A:

A similar thing can be achieved with a map<std::string, std::function<void()>>:
std::map<std::string, std::function<void()>> funs;
funs["hello world"] = [] () { std::cout << "hello world"; };
funs["hello world"]();

The question is how similar do you want it? How "native" should the call look like?. You can do things like:
void foobar(int, float);

...

    invoke("foobar", 5, 5.f);

but the implementation looks hacky and is non-trivial.
There is a related problem:

You can get pretty far with variadic templates and some template/virtual techniques. With the following codes, you'll be able to do something like:

std::string select_string (bool cond, std::string a, std::string b) {
    return cond ? a : b;
}

int main () {
    Registry reg;
    reg.set ("select_it", select_string);
    reg.invoke ("select_it", "1 John Wayne"));
    reg.invoke ("select_it", "0 John Wayne"));
}

i.e. where the argument list is dissected into a real argument list for a native function call. With variadic templates you can do a lot of things; I am not sure if you should.


Q:

Joining fields from 2 tables

I have 2 tables :
table 'g'
+------+
| id   |
+------+
|    1 |
|   32 |
|    3 |
|    6 |
|    5 |
|   22 |
|   54 |
|   21 |
+------+

table 'h'
+------+------+
| id   | sl   |
+------+------+
|    1 |  323 |
|   11 |  423 |
|    1 |  333 |
|   33 |   32 |
|   44 |  443 |
+------+------+

How can I show records from 2 tables like (select distinct id from 'g' and 'h' table and joining maximum 'sl' from 'h' table for each id. the 'id's of 'g' table which does not match with 'id' of table 'h', those 'sl' fields will be null)
+------+------+
| id   | sl   |
+------+------+
|    1 |  333 |
|   32 | null |
|    3 | null |
|    6 | null |
|    5 | null |
|   22 | null |
|   54 | null |
|   21 | null |
|   11 |  423 |
|   33 |   32 |
|   44 |  443 |
+------+------+

-Thanks.

A:

This can be done with a UNION between the two, left joined as a derived table against the h to get the MAX() values:
SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Subquery gets UNION (distinct, not UNION ALL) of ids from both tables */
  (SELECT id FROM g UNION SELECT id FROM h) allids
  /* LEFT JOINed back against `h` for the MAX() aggregates */
  LEFT JOIN h ON allids.id = h.id
GROUP BY id

http://sqlfiddle.com/#!2/2c348/3
Update after comments:
To force them to sort in the arbitrary (un-ordered) order that they were inserted, it may sort of work to place a number literal into the subquery which gets used in the ORDER BY.
The order rows are inserted isn't really meaningful to the RDBMS though. You cannot reliably assume that they would always be given back to you in the same order, absent an ORDER BY clause.
SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Awful hack adds a number literal which is used in the ORDER BY */
  /* This still won't guarantee that the rows from each table will be in the original order though */
  (SELECT id, 1 AS sort FROM g UNION SELECT id, 2 AS sort FROM h) allids
  LEFT JOIN h ON allids.id = h.id
GROUP BY id
ORDER BY sort

http://sqlfiddle.com/#!2/2c348/6


Q:

Removing Title Bar in Android 2.3 (Gingerbread) causes problem with SurfaceView

Anyone experiencing a problem with their app in Gingerbread? -- if you use
requestWindowFeature(Window.FEATURE_NO_TITLE);

And you switch to another window, when you come back it changes the dimensions of the surfaceview.
For now, I've put the titlebar back in to work around this issue.
Thanks for any help
Mark

A:

Yes, we too have experienced this after updating to Android 2.3.4. To fix it in our apps we eliminated the requestWindowFeature(Window.FEATURE_NO_TITLE); in our apps and then utilized a styles.xml, saved in the project's values folder with the following:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Transparent" parent="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">"
    <item name="android:windowBackground">@color/background</item>
</style>

Here a colors.xml will be utilized to set the @color/background, which is also saved in the project's value folder with the following:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <color name ="background">#000000</color>
</resources>

Then in the manifest file we utilized:
<application android:label="@string/app_name"
    android:icon="@drawable/icon"
    android:theme="@style/Theme.Transparent"
>

to apply the theme to the application as a whole. Perhaps others will have better suggestions and also maybe a reason for why this occurs in Gingerbread as in Froyo the requestWindowFeature(Window.FEATURE_NO_TITLE); worked well with SurfaceViews.