Q:

Could not initialize proxy - hibernate - grails - multi tenants

I'v inherited code that uses Grails Multi tenant plugin along with Spring and Hibernate.
It has been asked of me to create a Rest API method that allows the saving of some data but without the user authenticating (which was the way the tenant was set).
I have been trying the following:
Tenant.withTenantId(plan.tenantId) {
              customerService.createCustomer([
                          params: cmd.properties)
          }

But I am getting the following Exception:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
    at org.codehaus.groovy.grails.orm.hibernate.proxy.HibernateProxyHandler.unwrapProxy(HibernateProxyHandler.java:83)
    at org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.unwrapProxy(GrailsHibernateUtil.java:445)
    at org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil$unwrapProxy$1.call(Unknown Source)
    at org.codehaus.groovy.grails.orm.hibernate.cfg.HibernateUtils$_handleLazyProxy_closure1.doCall(HibernateUtils.groovy:72)
    at sun.reflect.GeneratedMethodAccessor857.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1260)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke(ClosureMetaMethod.java:80)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1725)
    at groovy.lang.ExpandoMetaClass.getProperty(ExpandoMetaClass.java:1140)
    at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:3461)
    at groovy.lang.ExpandoMetaClass.getProperty(ExpandoMetaClass.java:1152)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassGetPropertySite.getProperty(PogoMetaClassGetPropertySite.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
    at com.saasplex.customer.CustomerService.createCustomer(CustomerService.groovy:39)
    at com.saasplex.customer.CustomerService$$FastClassBySpringCGLIB$$1a0ebff9.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:700)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:633)
    at com.saasplex.customer.CustomerService$$EnhancerBySpringCGLIB$$b8e870fa.createCustomer(<generated>)
    at com.saasplex.customer.CustomerService$createCustomer.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.menios.api.TestupApiTestupController$_Testup_closure3.doCall(TestupApiTestupController.groovy:124)
    at com.menios.api.TestupApiTestupController$_Testup_closure3.doCall(TestupApiTestupController.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:69)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at grails.plugin.multitenant.core.MultiTenantService$_doWithTenantId_closure1_closure2.doCall(MultiTenantService.groovy:32)
    at sun.reflect.GeneratedMethodAccessor683.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$_withTransaction_closure1.doCall(HibernateTemplates.groovy:39)
    at sun.reflect.GeneratedMethodAccessor682.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1086)
    at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:910)
    at groovy.lang.Closure.call(Closure.java:411)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$_withTransaction_closure1.call(HibernateTemplates.groovy)
    at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:51)
    at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:81)
    at com.sun.proxy.$Proxy55.doInTransaction(Unknown Source)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:131)
    at sun.reflect.GeneratedMethodAccessor681.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1260)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates.withTransaction(HibernateTemplates.groovy:37)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$withTransaction$0.call(Unknown Source)
    at grails.plugin.multitenant.core.MultiTenantService$_doWithTenantId_closure1.doCall(MultiTenantService.groovy:31)
    at sun.reflect.GeneratedMethodAccessor678.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.call(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$_withNewSession_closure2.doCall(HibernateTemplates.groovy:65)
    at sun.reflect.GeneratedMethodAccessor677.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1086)
    at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:910)
    at groovy.lang.Closure.call(Closure.java:411)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$_withNewSession_closure2.call(HibernateTemplates.groovy)
    at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:51)
    at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:81)
    at com.sun.proxy.$Proxy52.doInHibernate(Unknown Source)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:339)
    at sun.reflect.GeneratedMethodAccessor675.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1260)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates.withNewSession(HibernateTemplates.groovy:57)
    at grails.plugin.hibernatehijacker.template.HibernateTemplates$withNewSession.call(Unknown Source)
    at grails.plugin.multitenant.core.MultiTenantService.doWithTenantId(MultiTenantService.groovy:30)
    at grails.plugin.multitenant.core.MultiTenantService$doWithTenantId.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at grails.plugin.multitenant.core.MultiTenantService$doWithTenantId.call(Unknown Source)
    at grails.plugin.multitenant.singledb.MtSingleDbPluginSupport$_createWithTenantIdMethod_closure2.doCall(MtSingleDbPluginSupport.groovy:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.OriginalClassInvoker.invoke(OriginalClassInvoker.java:47)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1086)
    at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1110)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:910)
    at groovy.lang.Closure.call(Closure.java:411)
    at grails.plugin.multitenant.singledb.MtSingleDbPluginSupport$_createWithTenantIdMethod_closure2.call(MtSingleDbPluginSupport.groovy)
    at org.codehaus.groovy.runtime.metaclass.ClosureStaticMetaMethod.invoke(ClosureStaticMetaMethod.java:59)
    at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite$StaticMetaMethodSiteNoUnwrapNoCoerce.invoke(StaticMetaMethodSite.java:148)
    at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.call(StaticMetaMethodSite.java:88)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
    at com.menios.api.TestupApiTestupController$$EOss5vYt.Testup(TestupApiTestupController.groovy:123)
    at com.menios.api.TestupApiTestupController$$DOss5vYt.Testup(Unknown Source)
    at com.menios.api.TestupApiTestupController.Testup(TestupApiTestupController.groovy)
    at com.menios.api.TestupApiTestupController$$EOss5vYt.Testup(TestupApiTestupController.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springsource.loaded.ri.ReloadedTypeInvoker$2.invoke(ReloadedTypeInvoker.java:122)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1283)
    at org.codehaus.groovy.grails.web.servlet.mvc.MixedGrailsControllerHelper.invoke(MixedGrailsControllerHelper.java:154)
    at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.invoke(ProxyAwareMixedGrailsControllerHelper.java)
    at org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.handleAction(AbstractGrailsControllerHelper.java:354)
    at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.handleAction(ProxyAwareMixedGrailsControllerHelper.java)
    at org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.executeAction(AbstractGrailsControllerHelper.java:231)
    at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.executeAction(ProxyAwareMixedGrailsControllerHelper.java)
    at org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.handleURI(AbstractGrailsControllerHelper.java:197)
    at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.handleURI(ProxyAwareMixedGrailsControllerHelper.java)
    at org.codehaus.groovy.grails.web.servlet.mvc.AbstractGrailsControllerHelper.handleURI(AbstractGrailsControllerHelper.java:121)
    at grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.handleURI(ProxyAwareMixedGrailsControllerHelper.java)
    at org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController.handleRequest(SimpleGrailsController.java:72)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet.doDispatch(GrailsDispatcherServlet.java:355)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
    at grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter.doFilter(MemoryPageFragmentCachingFilter.java)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at org.codehaus.groovy.grails.web.util.WebUtils.forwardRequestForUrlMappingInfo(WebUtils.java:332)
    at org.codehaus.groovy.grails.web.util.WebUtils.forwardRequestForUrlMappingInfo(WebUtils.java:297)
    at org.codehaus.groovy.grails.web.util.WebUtils.forwardRequestForUrlMappingInfo(WebUtils.java:288)
    at org.codehaus.groovy.grails.web.mapping.filter.UrlMappingsFilter.doFilterInternal(UrlMappingsFilter.java:217)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.executeFilterChainWithWrappedResponse(GrailsPageFilter.java:233)
    at org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.obtainContent(GrailsPageFilter.java:208)
    at org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.doFilter(GrailsPageFilter.java:153)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at grails.plugin.multitenant.core.servlet.CurrentTenantServletFilter.doFilter(CurrentTenantServletFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at javax.servlet.FilterChain$doFilter.call(Unknown Source)
    at org.grails.plugin.resource.DevModeSanityFilter.doFilter(DevModeSanityFilter.groovy:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    at org.codehaus.groovy.grails.plugins.springsecurity.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:40)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.codehaus.groovy.grails.plugins.springsecurity.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:69)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.codehaus.groovy.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1686)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

Any help in the form of comments, suggestions, and requests for additional information will be truly helpful. I feel that I'm missing something about how the sessions and multi-tenancy are funcioning but I havn't found it yet in the online documentation I've been reading.
I have tried different variations of Tenant. methods, as well as excluding this. I think something is going on at a higher configuration level but as I said I havn't found it.

A:

In my specific case, I was missing a way to resolve the tenantin the TenantResolver.
I added the following to resolve and it worked:
...
 else if(request.getParameter("partnerID")!=null) {
            try{
                tenantId = Integer.parseInt(request.getParameter("partnerID"));
            }catch(Exception e)
            {}
        }
...
return tenantId

Reference:

http://multi-tenant.github.io/grails-multi-tenant-single-db/docs/v0.8.3/guide/2.%20Plugin%20concepts.html#2.3.%20Tenant%20resolver


Q:

How do I make Makefile to recompile only changed files?

I have been struggling a bit to get make to compile only the files that have been edited. However I didn't have much success and all the files get recompiled. Can someone explain me why?
My files are:
main.c
a_functions.c

where main.c includes main.h
and a_functions.c includes a.h
Here is my makefile:
CC=gcc
CFLAGS=-Wall -I. -c
EXEC_FILE=program1

all: program

a_functions.o: a_functions.c
a_functions.c: a.h
main.o: main.c
main.c: main.h

objects: a_functions.c main.c
    $(CC) a_functions.c main.c $(CFLAGS)

program: a_functions.o main.o
    $(CC) a_functions.o main.o -o $(EXEC_FILE)

Changing the makefile as per suggestions seems to have the same problem::
all: program

a_functions.o: a_functions.c a.h
    gcc a_functions.c -c

main.o: main.c main.h
    gcc main.c -c

program: a_functions.o main.o
    gcc a_functions.o main.o -o program1

A:

The specific problem you're talking about -- Make rebuilds program1 (by relinking the objects) even when nothing has changed -- is in this rule:
program: a_functions.o main.o
    gcc a_functions.o main.o -o program1

The target of this rule is program, and Make assumes that it is a file. But since there is no such file, every time you run Make, Make thinks that this file needs to be rebuilt, and executes the rule. I suggest this:
program1: a_functions.o main.o
    gcc a_functions.o main.o -o program1

Or better, this:
program1: a_functions.o main.o
    gcc $^ -o $@

Or better still this:
$(EXEC_FILE): a_functions.o main.o
    $(CC) $^ -o $@

(And don't forget to change the all rule to match.)
A few other points:

As @paxdiablo pointed out,
a_functions.o: a_functions.c a.h
main.o: main.c main.h

It doesn't make sense to link these objects together unless something in one (probably main.o) calls something in the other (probably a_functions.o), so I would expect to see a dependency like this:
main.o: a.h

So I suspect that you have some misplaced declarations.
You declare an objects rule, but never refer to it. So you never actually use it; Make uses the default rule for %.o: %.c. I suggest this:
OBJECTS = a_functions.o main.o
$(OBJECTS): %: %.c
    $(CC) $< $(CFLAGS) -o $@

(In which case you can change $(EXEC_FILE): a_functions.o main.o to $(EXEC_FILE): $(OBJECTS).) Or just this:
%.o: %.c
    $(CC) $< $(CFLAGS) -o $@

A:

Not sure if this is causing your specific problem but the two lines:
a_functions.c: a.h
main.c: main.h

are definitely wrong, because there's generally no command to re-create a C file based on a header it includes.
C files don't depend on their header files, the objects created by those C files do.
For example, a main.c of:
#include <hdr1.h>
#include <hdr2.h>
int main (void) { return 0; }

would be in the makefile as something like:
main.o: main.c hdr1.h hdr2.h
    gcc -c -o main.o main.c

Change:
a_functions.o: a_functions.c
a_functions.c: a.h
main.o: main.c
main.c: main.h

to:
a_functions.o: a_functions.c a.h
main.o: main.c main.h

(assuming that a_functions.c includes a.h and main.c includes main.h) and try again.
If that assumption above is wrong, you'll have to tell us what C files include what headers so we can tell you the correct rules.

If your contention is that the makefile is still building everything even after those changes, you need look at two things.
The first is the output from ls -l on all relevant files so that you can see what dates and times they have.
The second is the actual output from make. The output of make -d will be especially helpful since it shows what files and dates make is using to figure out what to do.

In terms of investigation, make seems to work fine as per the following transcript:
=====
pax$ cat qq.h
#define QQ 1
=====
pax$ cat qq.c
#include "qq.h"
int main(void) { return 0; }
=====
pax$ cat qq.mk
qq: qq.o
        gcc -o qq qq.o

qq.o: qq.c qq.h
        gcc -c -o qq.o qq.c
=====
pax$ touch qq.c qq.h
=====
pax$ make -f qq.mk
gcc -c -o qq.o qq.c
gcc -o qq qq.o
=====
pax$ make -f qq.mk
make: `qq' is up to date.


Q:

How to relate 2 tables to a third when the first 2 tables have a relationship?

For once, I find myself at an utter loss in terms of coming up with a good question title.
Consider the three following tables. Each has additional columns, but only the columns relevant to the relationships between the tables are mentioned:

Table a has a primary key a_id
Table b has a primary key b_id and a column a_id which is a foreign key to a (one-to-many relationship)
Table reference has a primary key ref_id

reference is a list of sources that are cited to substantiate information contained in the other 2 tables. As such, I need tables to relate them together. Both a and b have many-to-many relationships with reference, but there is an additional complication: a footnote number. This footnote number must be unique for each a and reference pair, but it is only required when a relationship between a b and the same reference exists. (Of course, that b must be related to the same a.) The best way I have come up with to represent this relationship so far is a pair of tables:
bridge_a_reference:

Columns: a_id, ref_id, footnote_num (nullable)
Primary key: a_id, ref_id
Foreign keys: a_id to table a; ref_id to table reference

bridge_b_reference:

Columns: b_id, a_id, ref_id
Primary key: b_id, ref_id
Foreign keys: b_id, a_id to table b; a_id, ref_id to table bridge_a_reference

This ensures data consistency. There can only be a relationship between b and reference if a corresponding relationship between a and reference exists and b is related to the correct a. It also ensures that the footnote number will be consistent for all a/reference pairs. However, it's redundant, storing the relationship between a and b a second time (though enforced to be consistent, at least), and it doesn't ensure the footnote number is required for the b/reference relationships.
I've tried rearranging the tables in my head a few times, but everything else I can come up allows some kind of inconsistency (b to reference relationships without the corresponding a to reference or b to a relationship or inconsistent footnote numbers for the a/reference pairs.) How can I better structure my bridge tables to eliminate redundancy and ensure the footnote requirements? Is it even possible?

A:

Here is a suggestion so you can enforce the constraints you want declaratively. (I've simplified the table names a bit, removed the bridge_ prefix.)
We remove footnote_num from:
Table:      a_ref         -- was named:  bridge_a_reference
     a_id,
     ref_id
Primary key:
     (a_id, ref_id)
Foreign keys:
     a_id  -> a
     ref_id -> reference

We add this table - which will basically store only those rows from a_ref with footnote, those you want to add children into the b_ref:
Table:      a_ref_with_footnote
    a_id,
    ref_id,
    footnote_num
Primary key:
    (a_id, ref_id)
Unique key:
    (a_id, footnote_num)
Foreign keys:
    (a_id, ref_id)  -> a_ref

And finally the 3rd table stays as in your design except the foreign keys which now reference the intermediate table (a_ref_with_footnote):
 Table:     b_ref         -- was named: bridge_b_reference:
     a_id,
     b_id,
     ref_id,
 Primary key:
     (b_id, ref_id)
 Foreign keys:
     (a_id, b_id) -> b
     (a_id, ref_id) -> a_ref_with_footnote


Q:

Supply 3.3V via GPIO header (Pi3)

I need to power a Raspberry Pi 3 via its GPIO header: I have a beefy regulated PSU capable of providing stable 4.98V, which I planned to route to the 5V pins of the Raspberry as stated in this answer:
How do I supply power through the GPIO?
The problem is I need to use a lot of 3.3V devices (3-4 ICs and various outputs) and I've read that I can only take ~80mA from the GPIO header reliably.
I am planning to add an LM317 biased to provide the necessary voltage, but I am not sure if I can connect it back to the board or if I should leave it separated from the Raspberry and use it only for my other devices.
What is the safety margin I have to respect to be able to connect an external 3.3V to the Raspberry header?

A:

Never connect a power source to a Pi 3V3 pin.  You'll likely damage the Pi.
Power via one of the 5V pins - preferably with a 5V supply (you can use lower voltages but that will stop things which need 5V from working).
The 5V pin feeds in to the power supply chain which will then supply the 3V3 rail.  You can draw say 750 mA from the Pi3's 3V3 rail.  The often quoted 50 mA figure is for what may be supplied by the GPIO.  The 3V3 rail is not a GPIO.


Q:

Entity Framework - DbContext SaveChanges()

Can someone tell me is it possible, and if it is how to avoid using two times  _context.SaveChanges() in this code?
        Message m = new Message
        {
            Title = message.Title,
            Body = message.Body,
            Date = DateTime.Now
        };

        _context.Messages.Add(m);
        _context.SaveChanges();

        UserMessage messageToUser = new UserMessage
        {
            MessageID = m.ID,
            ProductID = message.ProductID,
            SenderID = message.SenderID,
            RecieverID = reciever.Id
        };

        _context.UserMessages.Add(messageToUser);
        _context.SaveChanges();

This is how my Entities look like
public class UserMessage
{
    public int ID { get; set; }
    public string SenderID { get; set; }
    public string RecieverID { get; set; }
    public int? ProductID { get; set; }
    public int MessageID { get; set; }

    public User Sender { get; set; }
    public User Reciever { get; set; }
    public Product Product { get; set; }
    public Message Message { get; set; }
}

public class Message
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime Date { get; set; }
    }

A:

On your UserMessage class, you set the reference instead of the foreign key, as the foreign key is not known yet.
In your code, that would mean:
    Message m = new Message
    {
        Title = message.Title,
        Body = message.Body,
        Date = DateTime.Now
    };

    _context.Messages.Add(m);

    UserMessage messageToUser = new UserMessage
    {
        ProductID = message.ProductID,
        SenderID = message.SenderID,
        RecieverID = reciever.Id,
        Message = m
    };

    _context.UserMessages.Add(messageToUser);
    _context.SaveChanges();


Q:

Reserving multiple jobs from a beanstalkd queue

Is there a way I can reserve multiple jobs from a beanstalkd queue at once?
I'm making requests to an external API that can return up to 10 results per query. They limit the number of requests I can make each day, so the more results I get per request the better.
I couldn't find any mention of this functionality in the documentation so I'm using this workaround. Does anyone know of a better way to achieve this? Or a more appropriate tool for the job than beanstalkd perhaps?
loop do
  sleep(0.3)

  while @beanstalk.tubes[example].peek(:ready)
    jobs = []

    catch(:done) do
      10.times do |i|
        if @beanstalk.tubes[example].peek(:ready) then
          job = @beanstalk.tubes[example].reserve(0)
          jobs << job.body
          job.delete
        else
          throw(:done)
        end
      end
    end

    process(jobs)

  end
end

A:

You can reserve several jobs concurrently by calling reserve
several times in a row before deleting or releasing those jobs.
Based on the code sample you provided, it could look something
roughly like this:
loop do
  timeout = nil
  jobs = []

  begin
    10.times do |i|
      jobs << @beanstalk.tubes[example].reserve(timeout)
      timeout = 0
    end
  rescue Beaneater::TimedOutError
    # nothing to do
  end

  process(jobs.map{|j| j.body})

  jobs.map do |job|
    job.delete
  end
end


Q:

why when my car's engine is warm it need long start for turning on?

when my car's engine is cold, it turning on immediately. But when it is warm an turn it off, then after 20 or 30 minutes need long start for turning on. where is problem?
my car is peugeot 405 made in 2001 with magnet mailer ecu.
I replace the rpm sensor but nothing changed.

A:

It sounds like the car is unable to maintain sufficient pressure in the fuel rail.
Have a look at this answer for more details on potential causes for hot start problems.
The reason why this happens only for hot starts is because the fuel is more likely to vaporize as temperature increases. In order to avoid vaporization problems the fuel lines are expected to be pressurized during a hot start.


Q:

Scrolling table cell - but only if necessary

I'd like to display a table that just consists of 2 cells really - at the left, there is a (fixed size) image, at the right, a list of items that is filled dynamically, meaning that it will usually be longer than the height of the image - so it should have a scrolling feature.
That works fine so far - apart from the fact that there are scrollbars even if the "list" is empty. Is there a way to display the scrollbars only if they are necessary? I know I want much. 8-) ..
This is my current code:

A:

You can make the container scrollable only when it's necessary by using overflow: auto;.
Here is an example: http://jsfiddle.net/ZHEHT/


Q:

CSS - UL Background Not Working

For some reason when I try to set a UL background the background doesn't work. It works on my body background but it isn't working for the UL.
I know my image is named correctly. I have quadruple checked that. Here is my code:
HTML

        <title>Header</title>

        <link rel="stylesheet" type="text/css" href="css/Style.css" />

Link1

Main

CSS
body
{
    background-image: url('../Images/body-background.jpg');
}

#page-wrap
{
    width:1040px;
    margin: 0 auto;
}

ul#nav
{
    margin: 0 auto;
    width: 1040px; height: 185px;
    background-image: url('../Images/header-logo.jpg');
    background-repeat: no-repeat;
}

From what it seems the UL itself isn't working with the  tag.  Without it the "Link1" shows up. With it though nothing shows up. Either way the background isn't displaying.
Thanks!

A:

http://jsfiddle.net/Z7MzE/2/
Looks like it's working to me.
Quintuple check that image for me.


Q:

Set of all rational numbers less than given computable real number is decidable

Prove that set of rational numbers less than given computable real
  number is decidable

This problem was in my exam yesterday, but I was not able to solve it. However I still want to give it another try.

Same problem can be stated in this way:
Construct an algorithm, which answers the question: Is our given rational number less or greater than their(fixed) computable number?
Here's my poor try so far.
Since it's analysis related problem, I used the $\epsilon - \delta$ definition of computable number, which is:
$\exists f$ computable function, such that $\forall \epsilon > 0, \epsilon \in \mathbb{Q}, f$ gives us $\delta > 0, \delta \in \mathbb{Q}$ such that$|a - \delta| \leq \epsilon$ holds for given computable number $a$
Let $p \in \mathbb{Q}$ be our input, and let $f$ compute for us 2 rationals $q_1$ and $q_2$. It is well known that $|q_1 - q_2| < 2\epsilon$
Now let's choose $\epsilon = \frac{1}{2^{i}}, i = 0,1,2,...$
For each $i$-th step I compute $f$ twice and get $q_{i_{1}},q_{i_{2}}$. I think that our given rational $p$ should hold some condition with both $q_{i_1},q_{i_2}$ which will help me to finish the algorithm, but I couldn't figure this out. I believe there are finitely many checks for each step which will let me know that for example $p < a$ just like in picture below.

What do you think about this problem? Maybe there's more straightforward way to prove this. Thank you.

A:

I would approach this problem as follows. Let $a$ be the computable real, and $A = \{x\in\mathbb{Q}\ |\ x<a\}$.
If $a \in \mathbb{Q}$, then $A$ is decidable since $x<a$ is a comparison between rationals, which is decidable.
Otherwise, we can assume $a$ is irrational. Our algorithm performs the following.
First, we take the candidate $x\in\mathbb{Q}$ as input.
We then query $f$ (the function which approximates $a$ as requested) repeatedly with $q=2^{-n}$ for every $n>0$.
Eventually, for some $n$ we will obtain one of
$$
f(2^{-n}) + 2^{-n} < x
\qquad \lor\qquad
x < f(2^{-n}) - 2^{-n}
$$
Indeed, this will happen as soon as $2^{-n} < |x-a| / 2$, which is a possibility because we know $x \neq a$.
In the first case, we return $x > a$ ($x \notin A$), in the second we return $x<a$ ($x \in A$).
The correctness comes from
$$
a \leq f(2^{-n}) + 2^{-n}
\qquad \land\qquad
f(2^{-n}) - 2^{-n} \leq a
$$
being true for all $n$.

Note that this solution is not uniform in $a$. That is, we only prove that there is an algorithm for any computable $a$, taking a candidate rational $x$ as input. We do not show that there is a single algorithm that, given both $a$ and $x$ as input is able to decide $<$ (indeed, that would be undecidable).


Q:

prepareAsync of MediaPlayer in one Activity, play in another

I am developing an application that, among other things, plays some video files (streaming). I would like to prepare the MediaPlayer in one activity but play the video once it is ready in another activity, so that the user can navigate through the content of the first activity to kill some time. Is this possible?
There is an static MediaPlayer defined in the Application class, like this:
public class EGDF_App extends Application {

    private static MediaPlayer mediaPlayer = null;

    public static MediaPlayer getMediaPlayer() {
        if(mediaPlayer == null)
            return new MediaPlayer();
        else
            return mediaPlayer;
    }

}

I have a button with a text (Load video). This text is changed when the video is ready, and when the user clicks on it, it triggers the following activity.
The problem is that I get the following error in LogCat:
09-06 20:43:34.606: D/ChapterPlayer(31999): surfaceCreated called
09-06 20:43:34.684: V/ChapterPlayer(31999): startVideoPlayback
09-06 20:43:34.684: E/MediaPlayer(31999): start called in state 1
09-06 20:43:34.684: E/MediaPlayer(31999): error (-38, 0)
09-06 20:43:34.684: D/ChapterPlayer(31999): surfaceChanged called
09-06 20:43:34.700: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
09-06 20:43:34.715: E/MediaPlayer(31999): Error (-38,0)
09-06 20:43:34.715: D/ChapterPlayer(31999): onCompletion called
09-06 20:43:34.751: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer

This is the code contained in the first Activity:
public void watchChapter(View view){
    Log.i("Button", "Watch chapter button PRESSED");
    Button b = (Button) view;
    String loadChapter = getString(R.string.load_chapter_button_text);
    String watchChapter = getString(R.string.watch_chapter_button_text);

    if(((String) b.getText()).equals(loadChapter)){
        prepareVideo(view);

    }else if(((String) b.getText()).equals(watchChapter)){

        Intent intent = new Intent(this,ChapterAsyncMediaPlayerActivity.class);
        intent.putExtra(Constants.chapterVideoResParse, getIntent().getExtras().getString(Constants.chapterVideoResParse));
        intent.putExtra("duration", String.valueOf(duration));
        startActivity(intent);
    }

}

private void prepareVideo(View view){
    MediaPlayer mMediaPlayer;
    String path;
    final Button button = (Button) view;
    String resource = extras.getString(Constants.chapterVideoResParse);
    path = SecurityHandler.obtainURL(resource, this.getResources().openRawResource(R.raw.output), 10);

    try {
        // Gets the media player and set the listeners
        mMediaPlayer = EGDF_App.getMediaPlayer();
        mMediaPlayer.setDataSource(path);
        mMediaPlayer.prepareAsync();
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener(){

            @Override
            public void onPrepared(MediaPlayer mp) {
                button.setText(getString(R.string.watch_chapter_button_text));
                Log.i("MediaPlayer", "MediaPlayer ready");
                duration = mp.getDuration();
                Log.i("Video duration", String.valueOf(mp.getDuration()));
            }

        });
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And this is the code in the second Activity:
public class ChapterAsyncMediaPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl {

    private static final String TAG = "ChapterPlayer";
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;
    private MediaController mController;
    private SurfaceView mPreview;
    private SurfaceHolder holder;
//  private String path;
//  private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;

    private Handler handler = new Handler();

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapter_media_player);
        mPreview = (SurfaceView) findViewById(R.id.mediaPlayerSurface);
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setKeepScreenOn(true);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mController.show();
        return false;
    }

    private void playVideo() {
        doCleanUp();
        try {

            // Create a new media player and set the listeners
            mMediaPlayer = EGDF_App.getMediaPlayer();
//          mMediaPlayer.setDataSource(path);
            mMediaPlayer.setDisplay(holder);
//          mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);
            mMediaPlayer.setScreenOnWhilePlaying(true);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mController = new MediaController(this);

        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");
        mIsVideoReadyToBePlayed = true;
        mController.setMediaPlayer(this);
        mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
        handler.post(new Runnable(){

            @Override
            public void run() {

                mController.setEnabled(true);
                mController.show();

            }
        });
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {

            startVideoPlayback();
        }
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        Log.d(TAG, "surfaceChanged called");

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceDestroyed called");
    }

    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated called");
        playVideo();
        mIsVideoReadyToBePlayed = true;
        mController.setMediaPlayer(this);
        mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
        handler.post(new Runnable(){

            @Override
            public void run() {

                mController.setEnabled(true);
                mController.show();

            }
        });
        if (mIsVideoReadyToBePlayed) {
            startVideoPlayback();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMediaPlayer.pause();
    }

    @Override
    protected void onRestart() {
        super.onPause();
        mMediaPlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
    }

    private void startVideoPlayback() {
        Log.v(TAG, "startVideoPlayback");
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
        mMediaPlayer.setScreenOnWhilePlaying(true);
    }

    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return true;
    }

    @Override
    public boolean canSeekForward() {
        return true;
    }

    @Override
    public int getBufferPercentage() {
        return 0;
    }

    @Override
    public int getCurrentPosition() {
        if(mMediaPlayer != null)
            return mMediaPlayer.getCurrentPosition();
        else
            return 0;
    }

    @Override
    public int getDuration() {
        if(mMediaPlayer != null)
            return mMediaPlayer.getDuration();
        else
            return 0;
    }

    @Override
    public boolean isPlaying() {
        if(mMediaPlayer != null)
            return mMediaPlayer.isPlaying();
        else
            return false;
    }

    @Override
    public void pause() {
        if(mMediaPlayer != null)
            mMediaPlayer.pause();
    }

    @Override
    public void seekTo(int pos) {
        mMediaPlayer.seekTo(pos);
    }

    @Override
    public void start() {
        if(mMediaPlayer != null)
            mMediaPlayer.start();
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, "onBufferingUpdate percent:" + percent);

    }

    public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, "onCompletion called");
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        Log.v(TAG, "onVideoSizeChanged called");
        if (width == 0 || height == 0) {
            Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed) {
            startVideoPlayback();
        }
    }
}

I would appreciate some help or advice. Thanks!

A:

I don't think you're saving the MediaPlayer in your application, you're just returning a new instance of it. Try changing it as so:
public static MediaPlayer getMediaPlayer() {
    if(mediaPlayer == null) {
        mediaPlayer = new MediaPlayer();
    }
    return mediaPlayer;
}


Q:

Polynomially solvable problems with exponential extension complexity

The maximum matching problem is solvable in polynomial time using Edmonds' blossom algorithm. However, unlike for example the spanning tree polytope, it has been proven fairly recently that the matching polytope has exponential extension complexity, meaning that it cannot be represented by a polynomially sized linear program Rothvoss (2017). I think this is a very interesting result, as it illustrates the limitations of expressing problems as linear programs. My question: are there any other problems that are solvable in polynomial time but whose polytopes have exponential extension complexity?

A:

I think the spanning tree polytope also falls under this category. Computing the minimum spanning tree is easy. However, we would require all the sub-tour elimination constraints (which is exponential in number of vertices) to represent the spanning tree polytope in 0-1 variables as a LP.
EDIT:
From the comments below, one can find a reference for a polynomial characterization of the spanning tree polytope. So my answer that the spanning tree has ``exponential extension complexity" is incorrect. I will however let this answer remain because I think not many people are aware of polynomial formulations for the spanning tree polytope. The edit is meant to notify people who read this post, not to overlook that fact.


Q:

How to control order of startup items for users at login?

I have seen a few applications with mixed reviews that will allow a user to change the order of startup items.  I would simply prefer the "bare metal" method and stick to using the shell or the Open Directory / netinfo editor to do this.  I realize that this isn't controlled via launchd so what is the mechanism and where is the preference location for app startup definition?
I have found OS X's restore app/window process to be less than lackluster and I need to guarantee certain apps start first before others (such as ScreenRecycler as I need applications to open on the other display when they fire up).

A:

So since I've not seen any recommendations I'm going to go ahead and put forth the answer that I've gone forward with so far.
The solution so far for me has been Startupizer.  It's not optimal obviously since it is both a paid for solution and it is not a method that is directly available from the OS, but it works and has allowed me to create dependency conditions and various other delays to the order that has been helpful and met my needs.
Hope this helps someone and I certainly hope someone recommends a more OS integral solution soon.

A:

If you're using a shell script to open applications, try something like this:
osascript -e 'launch app "ScreenRecycler"'
pgrep -qx Alfred||open -jga Alfred
sleep 10
pgrep -qx Mail||open -jga Mail
pgrep -qx Transmission||open -jga Transmission

You can run the script at login by for example saving the plist below as ~/Library/LaunchAgents/some.label.plist.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>some.label</string>
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-c</string>
    <string>osascript -e 'launch app "ScreenRecycler"'
pgrep -qx Alfred||open -jga Alfred
sleep 10
pgrep -qx Mail||open -jga Mail
pgrep -qx Transmission||open -jga Transmission</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

osascript -e 'launch app "AppName" and osascript -e 'activate app "AppName" are blocked until the application finishes opening. launch doesn't make an application frontmost but activate does. If an application like TextEdit or Mail is not running, launch and activate open a new visible default window. osascript -e 'tell app "TextEdit"' -e reopen -e activate -e end also reopens a default window if TextEdit is running but has no open windows.
open -jg usually opens an application hidden (-j) and without making it frontmost (-g). For some applications like TextEdit and Mail, it opens a new visible window if the application is running but has no open windows. To avoid that, check if the application is already running with for example pgrep. The -j option for open was added in 10.8 and it is only shown in the help message and not on the man page.
lsappinfo launch launchandhide=true nofront=true /Applications/TextEdit.app also always opens TextEdit hidden and without making it frontmost. lsappinfo was added in 10.9. I don't know how to use lsappinfo to wait until an application finishes opening.
The settings for login items are stored in ~/Library/Preferences/com.apple.loginitems.plist. You can add a login item with AppleScript:
osascript -e 'tell application "System Events" to make new login item at end with properties {path:"/Applications/TextEdit.app", name:"TextEdit", hidden:true}'
Some applications and processes are started up via property lists in ~/Library/LaunchAgents/, /Library/LaunchAgents/, or /Library/LaunchDaemons/. _com.apple.SMLoginItemBookmarks in /var/db/launchd.db/com.apple.launchd.peruser.$UID/overrides.plist is used to configure login items for helper applications used by sandboxed applications like ScreenFlow, DayOne, and TuneUp.
Since 10.7 there has been a relatively long delay before some login items or launchd jobs are started. I don't know any way to reduce it, but KeyRemap4MacBook's FAQ says it is caused by Resume:

KeyRemap4MacBook does not work after boot on OS X 10.7. What should I do?
"Resume" feature introduced by Lion delays launching apps at login.
Until KeyRemap4MacBook.app is launched at login, the keyboard layout is not changed. Please wait a minute until menu of KeyRemap4MacBook is shown.


Q:

XmlDocumentFragment equivalent in LINQ to XML?

I am unable to find something like XDocumentFragment. Is there an equivalent of XmlDocumentFragment in LINQ to XML?
I know that I can keep nodes in a collection. But how to conveniently serialize a bunch of various nodes to string, like this:
new XDocumentFragment(myNodes).ToString()

A:

You can simply concatenate string representation of nodes:
var xml = String.Concat(myNodes);


Q:

What are the differences between egg whites and egg yolks?

Egg whites are obviously different from egg yolks in that the former are, well, white when cooked, while the latter are yellow. But, what other differences are there?
Some possibilities:

Nutrition
Texture (both uncooked and cooked)
Cooking time and temperature to solidify
Behavior when "overcooked"
Behavior when beaten
Food safety issues
Taste

(If it matters, assume we're talking about good old generic chicken eggs.)

A:

I will not particularly get into most of the points of your question, as things like nutrition is off topic an highly polarizing and things like taste or in my view almost entirely opinion based and personal preference or culturally based.  OK, in violation of that I will make statements about nutrition which is based on years of research while raising eggs, but primarily to give info, not to say do this or this is healthy, except I will start with one opinion:  An egg is naturally nutritionally almost a perfect food, containing everything needed for the healthy development from two-cell to a healthy, self-reliant bird through the first week out of the shell.  We do not however eat natural eggs, we eat eggs from selectively breed, unnatural birds that are fed a diet very different from what they evolved to eat and have altered the make-up of those eggs in doing so.   Our generic chicken eggs stopped being that perfect food long ago, but truthfully, good sourced ones really are not as far away from that ideal as some would claim.  Sorry about that, but that was my personal two cents on the off-topic part.
The difference between the yolk and white really boils down to the purpose of the two.  The yolk is the main natural nutritional element for a growing embryo.  It has most of the things needed to grow a bird and even provide it all the nutrients needed for the first few days of its life out of the shell.  It has the fats, yes, including the dreaded cholesterol.  In a hen raise with adequate sunlight, a well-balanced diet, and especially allowed to forage, it is actual a well-balanced “good-bad” cholesterol ratio and nothing of concern to those without other cholesterol issues, but that subject also becomes polarizing so I will stop there.  It also has saturated fats, but really, we are actually talking about roughly one and a half grams per egg, so probably not a lot as compared to what most of us get from other sources.  The yolk contains about 99% of all fat in the egg and the vast majority of some major nutrients like Iron, Zinc, and major vitamins and minerals.
The white of an egg is primarily a protective organ for the embryo and water reservoir.  It also contains more of the protein than the yolk, and some vitamins and minerals that are needed more in the later development such as for bones, like Niacin, Phosphorous and Magnesium.  Downside for some, it also contains far more sodium than the yolk.
Most of those generalities are from USDA nutritional charts that can be found quoted all over, here is one site that reproduces the chart:  https://www.ahealthiermichigan.org/2011/10/11/the-nurtional-value-of-egg-whites-versus-egg-yolks-what-do-you-use/  Always remember that those numbers can readily be altered by changing the diet of the birds though, those are averaged numbers.  Is it healthier to only eat egg whites, or only yolks?  Well, that is debatable according to your own goals.  If you do not want the fats, they exclude the yolk, but you will also be losing a lot of very valuable nutrients.  If you have those covered, then your call.  Exclude the whites and you are saving yourself sodium, some extra protein and losing some other vitamins and minerals.
The role of eggs in cooking is all over the board, for proving body and structure, an emulsifier, color, flavor, fat, moisture, and on and on and the yolk and white serve different roles in different applications.  For instance a classic sponge cake, the yolk and its fats are a binder and help provide the body of the cake, hold it together, while the foam made from the white becomes almost a leavening agent, creating the airiness as the water from them bake out.  The roles though can be all over the board and really is too broad to touch on without talking about individual applications in my opinion.
Sorry, too long non answer, meaning the entire question is likely too broad to be on topic.


Q:

MUD-based game books?

Is there much crossover between published RPGs and the MUDs of old?
I am looking for specific examples of MUDs that were later published as game books.

A:

Everquest was based off of Diku codebase (even if they deny it.) They made a tabletop rpg.  This is the only one I can think of that was released with any real distribution.  I Remember there were a few of the larger realms that made it from MUD to G(raphical)MUD but the tech wasnt really there to do what we wanted in a web page at the time.  I know of a few short stories and even amature novellas were written about some of the MUDS.  But most of them existed only on Newsgroups and BBS's.  Most of the effort that went into the mud was to make more content or tweak code/add new functionality.  Most of the logic and math used for it would be to complicated to replicate at the table top level.  Its much easier for a computer to manage thousands of HP and 20 hits per second than a GM.


Q:

Does the upgrading from Parallels Desktop (for Mac) 5 to 6 means reinstall Windows?

I have Parallels Desktop 5 for Mac. Does the upgrade to Parallels Desktop 6 means that I have to reinstall Windows 7 and all the other programs?

A:

No, your Windows VM and all the programs installed on it are stored on a virtual hard drive file. Upgrading Parallels won't affect the VM.


Q:

How do I parallellise a for loop, and save the results of each repetition in a matrix?

I'm running a simulation for several repetitions and I'm trying to see if it would be possible to parallellise these repetitions to improve computation time.
Currently I simply run the simulation several times in a for loop, but ideally these could all be run at the same time, and then the results from each repetition saved to an array for processing.
Currently my code is something like
public static void getAllTheData(){

   int nReps = 10;
   double[][] allResults = new double[nReps][]

   //this for loop is what I want to parallellise
   for(int r = 0; r < nReps; r++){

       //run the simulation to completion here
       simulation.doStuffToCompletion()

       allResults[r] = simulation.getValues()

   }
//average allResults here and do further analysis
}

My question is, how can I run all these repetitions at the same time in parallel, and save the results from each parallel run in an allResults type array?
Thanks very much.

A:

You can try something like parallel streams to do parallelism like one of the below lines.
Stream.of(allResults).parallel().forEach(i -> processData(i));

Arrays.stream(allResults).parallel().forEach(i -> processData(i));


Q:

Python - Removing specific frequencies between a range

I have a Spectrogram:

I want to clean the spectrogram up, so I only capture the frequencies within a specific range (i.e. in this example, between 2627 - 3939) and remove all of the blocks that are below this frequency. My overall aim is to only be left with the 4  segments that are within this frequency range, and, can be identified.
Here is my code so far:
import wave, struct, numpy as np, matplotlib.mlab as mlab, pylab as pl
def wavToArr(wavefile):
    w = wave.open(wavefile,"rb")
    p = w.getparams()
    s = w.readframes(p[3])
    w.close()
    sd = np.fromstring(s, np.int16)
    return sd,p

def wavToSpec(wavefile,log=False,norm=False):
    wavArr,wavParams = wavToArr(wavefile)
    print wavParams
    return  mlab.specgram(wavArr, NFFT=256,Fs=wavParams[2],window=mlab.window_hanning,noverlap=128,sides='onesided',scale_by_freq=True)

wavArr,wavParams = wavToArr("4bats.wav")
Pxx, freqs, bins = wavToSpec("4bats.wav")
Pxx += 0.0001

freqs += (len(wavArr) / wavParams[2]) / 2.
hf=pl.figure(figsize=(12,12));
ax = hf.add_subplot(2,1,1);
#plot spectrogram as decibals
hm = ax.imshow(10*np.log10(Pxx),interpolation='nearest',origin='lower',aspect='auto')
hf.colorbar(hm)
ylcnt = len(ax.get_yticklabels())
ycnt = len(freqs)
ylstep = int(ycnt / ylcnt)
ax.set_yticklabels([ int(freqs[f]) for f in xrange(0,ycnt,ylstep) ])
pl.show()

The problem is, I don't know how to do this using Python. I know the ranges (2627 - 3939) but, would I iterate through the entire 2D-array and sum up all the blocks, or, for each block within the Spectrogram, calculate the frequency and if it's higher than the threshold, keep it, otherwise the values become 0.0?
If I sum up each of the bins, I get the following:

I need to keep these blocks, but, want to remove every other block apart from these.
I hope someone can help me!

A:

Maybe you want something like:
Pxx[np.greater(np.sum(Pxx, axis=1), 2955), :] = 0.

or, I might have your axes switched, so also try:
Pxx[:, np.greater(np.sum(Pxx, axis=0), 2955)] = 0.

Or maybe you want something else... I find the question a bit unclear.


Q:

VBA - Rename worksheet after source file

I have a question as to how to rename a sheet after the source file name, but only a portion of it.  So if the file name is "010117Siemens Hot - Cold Report .xls", I want just the first numbers.  So in short, I would like "Sheet2" for example to be called "010117".
Sub ImportData()

    Application.ScreenUpdating = False

    Dim wkbCrntWorkBook As Workbook
    Dim wkbSourceBook   As Workbook
    Dim fNameAndPath As Variant

    Set wkbCrntWorkBook = ActiveWorkbook
    fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel 2007, *.xls; *.xlsx; *.xlsm; *.xlsa", Title:="Select File To Import")
    If fNameAndPath = False Then Exit Sub
    Call ReadDataFromSourceFile(fNameAndPath)

    Set wkbCrntWorkBook = Nothing
    Set wkbSourceBook = Nothing

    ActiveWorkbook.Worksheets("Set Up").Select

End Sub

Sub ReadDataFromSourceFile(filePath As Variant)

    Application.ScreenUpdating = False

    Dim n As Double
    Dim wksNew As Excel.Worksheet
    Dim src As Workbook
    Set src = Workbooks.Open(filePath, False, False)

    Dim srcRng As Range
    With src.Worksheets("Sheet1")
        Set srcRng = .Range(.Range("A1"), .Range("A1").End(xlDown).End(xlToRight))
    End With

    With ThisWorkbook
            Set wksNew = .Worksheets.Add(After:=.Worksheets(.Sheets.Count))
            n = .Sheets.Count
            .Worksheets(n).Range("A1").Resize(srcRng.Rows.Count, srcRng.Columns.Count).Value = srcRng.Value
    End With

    ' CLOSE THE SOURCE FILE.
    src.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src = Nothing

End Sub

Thanks in advance!

A:

Use the RegEx object to extract the numeric part (from 1 to 9 consecutive numeric) from the file name (src.Name).
Code
Sub ReadDataFromSourceFile(filePath As Variant)

    Application.ScreenUpdating = False

    Dim n As Double
    Dim wksNew As Excel.Worksheet
    Dim src As Workbook
    Set src = Workbooks.Open(filePath, False, False)

    Dim srcRng As Range
    With src.Worksheets("Sheet1")
        Set srcRng = .Range(.Range("A1"), .Range("A1").End(xlDown).End(xlToRight))
    End With

    With ThisWorkbook
            Set wksNew = .Worksheets.Add(After:=.Worksheets(.Sheets.Count))
            n = .Sheets.Count
            .Worksheets(n).Range("A1").Resize(srcRng.Rows.Count, srcRng.Columns.Count).Value = srcRng.Value
    End With

    ' ======= get the digits part from src.Name using a RegEx object =====
    ' RegEx variables
    Dim Reg As Object
    Dim RegMatches As Variant

    Set Reg = CreateObject("VBScript.RegExp")
    With Reg
        .Global = True
        .IgnoreCase = True
        .Pattern = "\d{0,9}" ' Match any set of 0 to 9 digits
    End With

    Set RegMatches = Reg.Execute(src.Name)
    If RegMatches.Count >= 1 Then ' make sure there is at least 1 match
        ThisWorkbook.Worksheets(n).Name = RegMatches(0) ' rename new sheets to the numeric part of the filename
    End If

    ' CLOSE THE SOURCE FILE.
    src.Close False             ' FALSE - DON'T SAVE THE SOURCE FILE.
    Set src = Nothing

End Sub


Q:

Bottom bracket creaking only when pedaling hard.

When pedaling with a decent amount of force a very loud creaking sound can be heard coming from the bottom bracket area (it is very loud when standing on the pedals). It makes a creaking noise on each foot's down stroke. So with both feet pedaling equals two creaks per full revolution. If I unclip either foot and pedal with only one foot, a creaking noise will be heard once per revolution (on the down stroke of the pedaling foot). If I pedal softly, no noise is heard.
Things that I have done so far, yet the problem remains:

Changing pedals, regreasing their threads and making sure they are tightened.
Tightening chaining bolts.
Replacing the actual crankset.
Taking the crankset out, cleaning all the old grease and regreasing.
Making sure the crank arm is tightened correctly.

Is there anything left besides it being the bottom bracket causing the problem? I haven't had a chance to inspect that yet because it's a pressfit and I don't have the proper tools to take it out and reinsert it.

A:

Turns out it was the rear skewer of all things causing the creaking! It seemed like it was from the bottom bracket area because it was in sync with my pedalling but I put a dab of grease near the contact points of the skewers and the noise is gone.
So if anyone else is having similar problems, check your skewers first because it's a lot easier than taking your cranks and bottom bracket apart.


Q:

make countdown when app is not active windows phone

I want to make a countdown timer (lets say 20 min.) for my windows phone application. But it should still be counting down, even if the application is not active.
For example: user clicks a button, then this button should not be available for 20 min. Even if the app is restarted, the phone is restartet or whatever.
How should i basically approach this? Is the background agent the way to go? Make some kind of periodicall shedule? Or read the phone clock?
Or are there other possibilities?
It should also not be easy to avoid (for example change the time on the phone, so that it is 20 min. later on the clock)
Has someone an idea? just searching for a point in the right direction here :).
Thanks

A:

If you don't trust the phone to provide the time of record, the obvious answer is to use a remote time server to mark application activation time according to the remote server. If you also mark the local phone time at activation and calculate the difference between the two, you can use that difference to store what the remote server would (ideally) believe to be the current time that the button is pressed without having to call the remote server again.
One example of such a service is http://www.timeapi.org/utc/now.


Q:

No module named difflib

I want to execute python code from C# with following code.
   static void Main(string[] args)
    {
        ScriptEngine engine = Python.CreateEngine();
        ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py");
        source.Execute();
    }

I have the problem at line source.Execute(), I got error "No module named difflib".
What is wrong in my code?
This is my python code (extracter.py).
import re
import itertools
import difflib
print "Hello"

A:

This looks like your engine does not have access to Python standard library - it does not see difflib.py. Either fix the sys.path or copy difflib.py from Python 2.6 to f:\script folder.
re and itertools modules are written in C# and are part of IronPython.modules.dll - that's why importing them work.


Q:

Rails Asset Pipeline - How to determine if an asset exists?

Is there any way to ask the Asset Pipeline if an asset exists? The suggestions I largely see involve manually checking the file path with File.exist?. The problem with that is that I have several gems that include assets, so I would have to look at the assets directories for each of those, right? This seems like something I would expect to be baked into the Asset Pipeline, but I can't find any reference to it.
My current solution is an ugly hack, so I hope you have something better. Calling asset_path(file) will either return a new URL (/asset/xyz) for an asset or the same path if it does not exists (or if it's an absolute path). So my ugly hack is:
def has_asset?(path)
  # Asset pipeline only does relative paths
  if path[0] == '/'
    return false
  end
  asset_path(path) != '/#{path}'
end

A:

I just found that I can use assets.find_asset:
def has_asset?(path)
  Rails.application.assets.find_asset(path) != nil
end

A:

The currently accepted answer does not work in production.
I use the following method to work in both development and production environments:
module AssetHelper
  def asset_exists?(path)
    if Rails.env.production?
      Rails.application.assets_manifest.find_sources(path) != nil
    else
      Rails.application.assets.find_asset(path) != nil
    end
  end
end


Q:

PHPUnit e Selenium - Como chamar funções específicas do script de teste?

Preciso criar vários scripts de teste para WEB utilizando PHPUnit e Selenium. Obtive sucesso com meus testes iniciais. Consegui inclusive testar o login e logout de minha página WEB efetivamente.
O problema é que eu só consigo executar todas as funções do script de uma vez, e isso me faz perder muito tempo em um único teste, além de me impedir de reutilizar o código já escrito para outros testes.
Gostaria saber como faço para, em um script de testes como o mostrado abaixo, executar somente algumas funções específicas.
<?php

class LoginTest extends PHPUnit_Extensions_Selenium2TestCase
{
 protected function setUp()
 {
    $url = EXAMPLE_URL;
    $this->setBrowser('firefox');
    $this->setBrowserUrl($url);
    $this->prepareSession();
    $this->url(EXAMPLE_URL/users/login);
    $this->currentWindow()->maximize();
    }

private function testTitle($title = null)
{
    if (!$title)
        $title = EXAMPLE_TITLE_LOGIN;
    $this->assertEquals($title,$this->title());
    }

private function testLoginFormExists()
{
    //Verifica se está na tela de login
    $this->testTitle();

    $name = $this->byName('data[User][username]');
    $passwd = $this->byName('data[User][password]');

    $this->assertEquals('',$name->value());
    $this->assertEquals('',$passwd->value());

    }

private function testLoginAction()
{
    //Verifica se o form de login existe
    $this->testLoginFormExists();

    $form = $this->byId('UserLoginForm');
    $action = $form->attribute('action');
    $this->assertEquals(EXAMPLE_URL/users/login, $action);

    $this->byName('data[User][username]')->value('admin');
    $this->byName('data[User][password]')->value('ventovento');

    $form->submit();

    //Verifica se logou corretamente
    $this->testTitle(EXAMPLE_TITLE_HOME);

    }

private function testLogoutAction()
{
    //Verifica se realiza login
    $this->testLoginAction();

    //Realiza logout
    $this->byId('img-logout')->click();

    //Verifica se realizou logout corretamente
    $this->testTitle();
    }

}

?>

Para exemplificar melhor o que eu estou querendo fazer: no script acima, eu pretendo chamar somente a função testLogoutAction(). Entretanto, quando executo o script, ele executa todas as funções declaradas em ordem.
Isso também acontece quando eu extendo a classe a outra. Por exemplo, no teste a seguir, ele executa todas as funções do código anterior, e depois continua a execução dos testes da respectiva classe.
<?php

require_once("LoginTest.php");

class ContasTest extends LoginTest
{ ...

A:

Use as opções de seleção na linha de comando:
$ phpunit -h

Test Selection Options:

  --filter <pattern>        Filter which tests to run.
  --testsuite <pattern>     Filter which testsuite to run.
  --group ...               Only runs tests from the specified group(s).
  --exclude-group ...       Exclude tests from the specified group(s).
  --list-groups             List available test groups.
  --test-suffix ...         Only search for test in files with specified
                            suffix(es). Default: Test.php,.phpt

ex:
class AssertionTest extends PHPUnit_Framework_TestCase{
    /**
     * @group grupo1
     * @author Paulo Henrique
     */
    public function testAssertTrue(){
        $this->assertTrue(2+3==5);
    }

    /**
     * @group grupo2
     */
    public function testAssertFalse(){
        $this->assertFalse(2+2 == 5);
    }
    /**
     * @group grupo2
     * @author Paulo Henrique
     */
    public function testAssertEquals(){
    $this->assertEquals( 2+5, 7, " It should be 7" );
    }
}

Executando na linha de comando:
filter executa somente os testes que atendam a regex que vc escrever. ex:
$ phpunit --filter 'AssertTrue' AssertionsTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.25Mb

OK (1 test, 1 assertion)

group executa somente os testes que tenham o annotation @group.
$ phpunit --color --group grupo2 AssertionsTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.

..

Time: 0 seconds, Memory: 3.25Mb

OK (2 tests, 2 assertions)

Além da annotation @group, você pode rodar todos os testes escritos por um só desenvolvedor, se passar ,como grupo, o nome da annotation @author.
$ phpunit --color --group "Paulo Henrique" AssertionsTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.

..

Time: 0 seconds, Memory: 3.25Mb

OK (2 tests, 2 assertions)

Você encontrará mais detalhes na documentação.


Q:

How is the community doing? [2019]

We, the elected moderators, wanted to take a minute to check in and see how the community feels like things are going on the site.
We did this in 2017 and 2018 and it was very helpful. So again we'd like to share our thoughts and also get yours on what is going well and what we could improve.
How this specific Q&A is run so that we get good value out of it
One clear premise per answer

We'll post some of the things we've done/observations we have/things we think still need improvement. Please share your thoughts as well! Make sure and note whether you think the thing is an improvement, a problem, or some mix of the two (one person might see the same change as bad that you see as good, or vice versa)...
Post one kind of thing per answer, so that when people upvote/downvote based on whether they agree or not it's more clearly actionable - if you write an essay about 4 different things, it's not going to be clear what part(s) people agree or disagree with and thus it becomes unactionable. You can of course contribute multiple answers.
Upvote or downvote the answers based on your agreement with whether you see that thing happening and concur with the answer's premise that it's good or it's a problem. (In other words, if someone says "We get too many new users and I hate them," you would upvote if you agree, and downvote if either you don't think we get too many new users or if you don't hate them.)

No long comment threads

If you disagree with an answer, post your own answer, don't argue in comments. If you post more than one comment on an answer, you should consider if that is useful at all. We're interested in overall community sentiment as shown by votes, not so much that one person is so irritated they post 10 comments.
This isn't the place to workshop solutions - if a problem gets a lot of votes, we should open a new meta question to do justice to that issue. Solutions hidden in a comment thread on one of these questions are unable to be clearly vetted and voted on so they will tend to go undone.

As usual, Be Nice applies to meta as well as the main site.
You may strongly disagree with other users or with the mods or whoever, but we trust you can find ways to express what you like or don't like without being hostile or insulting to others. Focus on actions rather than characterizing people.
So here we go - our thoughts on things that are going well or need improvement. Feel free and add on!

A:

Homebrew review questions still aren't great
It seems like there are more of them, and they are generally following the new guidance How can I ask a good homebrew review question?.
Unfortunately, IMO they are not a great part of the site.  We get multiple revisions of the same thing clearly with no playtesting (in between or initially, by the poster or the answerers, see also When do homebrew suggestions need to be playtested by an answerer?).  They're a tough fit for the site Q&A format in general.
We should probably have a new meta on how to improve these or what we want to do with them.

A:

The community is continuing to perform most of the site moderation activity
In a trend continuing from last year, the community is performing the majority of close/edits, is flagging plenty of comments, and in general is making the mods do less; I know my site workload continues to slowly shift downward, which is great.
See also 2018: a year in moderation

A:

Answers in comments may not be reduced, but are handled quickly by the community
I'm not sure if we are getting less comments in the answers1 (as I had hoped in my answer to last year's community check-in), but I think we are dealing with them much quicker and with much less squabbling then in the past.
In my experience, they are generally left by newer users and are generally swept up by community flags and/or mods before any issues could be caused.
We may even be over-flagging some types of comments as answers when they shouldn't be and this might have to be addressed at some point.
Overall though, I think we are much improved over last year.

1 - An informal survey of my personal flags might indicate a slight increase over last year at the same time, but that can be due to many factors (traffic, how actively I'm flagging, etc.). There's still no easy way to figure out a quantifiable way to measure the issue that I've heard or been able to come up with unfortunately.


Q:

C# Entity Framework6 Specify the property of the table in parameter

My application must update a lot of parameters in my database (in different tables, parameters come in disorder). I just read a label (name) and a value, and must store the value in the correct place in the database according to the name.
For now I use a switch(), but this solution doesn't seem to be good as the treatment for each parameters is different and may become quite heavy in the future ( I have over 500 parameters).
Here is the code (with the switch for now)
private void MyFunc(int id, int value, string name_param){

using (var db = new mydatabaseEntities())
{
    var result = db.mytable.Where(b => b.id == id).First();

    switch (name_param){
         case "M12":
              result.m12 = value;
              break;
         case "M14":
              result.m14 = value;
              break;
         case "M16":
              result.m16 = value;
              break;
         //etc... 500 cases
     }
   db.SaveChanges();
   }
}

Would you know how to specify in parameter which property of my table I want to update :m12,m14, m16... (So I don't need to use a switch) ?
Thanks !

A:

You should be able to do it through reflection:
private void MyFunc(int id, int value, string name_param)
{
    using (var db = new mydatabaseEntities())
    {
        var result = db.mytable.Where(b => b.id == id).First();
        var prop = result.GetType().GetProperty(name_param);

        if (prop == null)
            throw new InvalidOperationException();    //Or something appropriate

        prop.SetValue(result, value);

        db.SaveChanges();
    }
}

Just be aware that this uses reflection and can be slow for doing a lot of operations. You can speed it up a little bit by caching the type information and the property.
By the way, if your name_param casing is different than the property name, you can narrow it down using LINQ:
var prop = result.GetType()
                 .GetProperties()
                 .Where(p => string.Compare(p.Name, param_name, true) == 0)
                 .FirstOrDefault();

Or just use the correct binding flags:
var prop = result.GetType().GetProperty(name_param,
                              BindingFlags.IgnoreCase |
                              BindingFlags.Public |
                              BindingFlags.Instance);


Q:

Execute one feature at a time during application execution

I'm using Karate in this way; during application execution, I get the test files from another source and I create feature files based on what I get.
then I iterate over the list of the tests and execute them.
My problem is that by using
CucumberRunner.parallel(getClass(), 5, resultDirectory);

I execute all the tests at every iteration, which causes tests to be executed multiple times.
Is there a way to execute one test at a time during application execution (I'am fully aware of the empty test class with annotation to specify one class but that doesn't seem to serve me here)
I thought about creating every feature file in a new folder so that I can specify the path of the folder that contains only one feature at a time, but CucumberRunner.parallel() accepts Class and not path.
Do you have any suggestions please?

A:

You can explicitly set a single file (or even directory path) to run via the annotation:
@CucumberOptions(features = "classpath:animals/cats/cats-post.feature")

I think you already are aware of the Java API which can take one file at a time, but you won't get reports.
Well you can try this, set a System property cucumber.options with the value classpath:animals/cats/cats-post.feature and see if that works. If you add tags (search doc) each iteration can use a different tag and that would give you the behavior you need.
Just got an interesting idea, why don't you generate a single feature, and in that feature you make calls to all the generated feature files.
Also how about you programmatically delete (or move) the files after you are done with each iteration.
If all the above fails, I would try to replicate some of this code: https://github.com/intuit/karate/blob/master/karate-junit4/src/main/java/com/intuit/karate/junit4/Karate.java


Q:

Filter specifc dates in ASP.net Core mvc

I currently work on an agenda where I want to return the days from the upcomming week.
The code code in my controller for this view is as follows:
public ViewResult List()
{

    return View(repository.Days
        .OrderBy(d => d.date));
}

However, this function only orders and returns all the dates and not just next week's days.
I wonder if someone can help me with getting the dates/days of the upcomming week and thus the the sorting operator this requires.

A:

Found a suitable solution:
    public ViewResult List()
    {
        DateTime startOfCurrentWeek = DateTime.Today.AddDays(-1 * (int)(DateTime.Today.DayOfWeek));
        DateTime startOfNextWeek = startOfCurrentWeek.AddDays(8);
        DateTime endOfNextWeek = startOfCurrentWeek.AddDays(14);

        return View(repository.Days
            .Where(d => d.date >= startOfNextWeek && d.date <= endOfNextWeek));
    }

What this code does is:

Get this weeks start date (startOfCurrentWeek)
Adds 8 days to make it start at a monday, next week(startOfNextWeek)
Adds 14 days to the current week's start day, to get the last day of next week (endOfNextWeek)
returns all days that are equal or after the start of next week's monday (d => d.date >= startOfNextWeek)
return no values after sunday of next week, thus limits the output to the 7 days of next week (d.date <= endOfNextWeek)


Q:

Build Project > How to checkout different repositories in different folders

I am new to TeamCity. I have my projects in different repositories. I want to checkout my projects in Different subfolders. e.g.
Lets suppose that I have following 3 .net Projects in three different projects.

Framework
XYZ
MyProject

Each project is stored in its own repository. MyProject contains a solution file, which expects that Framwork and XYZ Projects Folders are in main Folder so that the Folder structure looks like that

+FrameWork
 -ProjectFile
 -.........

+XYZ
 -ProjectFile

+MyProject
 -SolutionFile(has references of both Projects.)

Now my problem is I want to checkout my projects from different repositories in own Folders. How to configure it in TeamCity.
Thanks

A:

You would need to configure each VCS Root in Version Control Settings. For each root, you can
specify what folders are of interest to you with the Checkout Rules. When creating the checkout rules, you have the option to leave the folder structure the same as it is in your VCS or you can remap the struture to suit your needs.
http://confluence.jetbrains.net/display/TCD5/2.Version+Control+Settings
http://confluence.jetbrains.net/display/TCD5/VCS+Checkout+Rules
In Order to solve the given problem. Following checkout Rules need to be applied on corresponding version control root.
+:.=>FrameWork
+:.=>XYZ
+:.=>MyProject


Q:

Unable to compile .proto files for Tensorflow object-detection API

I'm trying to install Tensorflow and im having trouble compiling the .proto files.
I try running this command in the research folder:
C:/protoc/bin/protoc object_detection/protos/*.proto --python_out=.
but it outputs:
object_detection/protos/*.proto: No such file or directory
Any idea why this is happening?

A:

I have found a solution, it is cumbersome.
It works if i compile them one by one.
e.g.
C:/protoc/bin/protoc object_detection/protos/anchor_generator.proto --python_out=.
Where C:/protoc/bin/protoc is the path to protoc.exe file


Q:

computing an integration with a floor function

I am trying to compute
$$\int_0^1 \left(\frac{1}{x} -  \biggl\lfloor \frac{1}{x}\biggr\rfloor\right) dx$$
with no success.
Any hints?

A:

$$\int_0^1 \left(\frac{1}{x} - \left\lfloor \frac{1}{x}\right\rfloor\right) dx=\lim_{k\to +\infty}\int_{\frac{1}{k}}^1 \left(\frac{1}{x} - \left\lfloor \frac{1}{x}\right\rfloor\right) dx$$
Now to compute the other integral use the decomposition:
$$\int_{\frac{1}{k}}^1 \left(\frac{1}{x} - \left\lfloor \frac{1}{x}\right\rfloor\right) dx=\sum_{i=1}^{k-1} \int_{\frac{1}{i+1}}^{\frac{1}{i}}\left(\frac{1}{x} -i\right)dx=\sum_{i=1}^{k-1}\left[\ln(x)-ix\right]_{\frac{1}{i+1}}^{\frac{1}{i}}$$
and you can compute this sum and determine the limit, After computation you obtain:

$$\sum_{i=1}^{k-1}\left[\ln(x)-ix\right]_{\frac{1}{i+1}}^{\frac{1}{i}}=\ln(k)-\sum_{i=2}^{k}\frac{1}{i}$$

and this gives you:

$$\int_0^1 \left(\frac{1}{x} - \left\lfloor \frac{1}{x}\right\rfloor\right) dx=1-\gamma$$

with $\gamma$ denotes Euler–Mascheroni constant


Q:

Java what is the benefit of Throwing RuntimeException

What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.
public void testRuntimeEx()throws RuntimeException{

if(1==1){throw new RuntimeException()}

}

//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();

}

A:

It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.
In your example code snippet, it is pretty meaningless, though.

A:

if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.


Q:

How to compare different similarity measurements in text clustering?

I have a dataset which contains vectors generated from subtitles (each column represents a genre, each row is a movie name), my purpose is to find the most similar movie titles, I want to use different distance/similarity measurements and compare them, what is the best method to use?
For now, I tried L1 distance, cosine similarity, Euclidean distance, Mahalanobis Distance, I got the results of top n most similar titles, but all the results seem very reasonable, how can I compare them to see which method perform best?
I also tried to do k-means, when I implement K-means clustering, it used Euclidean distance by default, how to use other distance to implement K-means?Also any suggestions about other similarity measurements? Many thanks

A:

I would try a different approach than clustering.

For now, I tried L1 distance, cosine similarity, Euclidean distance, Mahalanobis Distance

First, you could have a look at approximate string matching measures. These are likely to give you much better similarity results on a pair of movie titles. It's usually a good idea to use not only word-based measures but also character-based or char n-grams based measures.

how can I compare them to see which method perform best?

A proper evaluation framework would require annotating manually a large amount of pairs of titles as similar/not similar (or even a degree of similarity). Unless you have a lot of time, this is completely impractical because there is certainly a massive imbalance between positive and negative pairs. So instead you could use bootstrapping, which means running a few similarity measures on your data, extract the top N pairs for each measure, then manually annotate only these. It's likely that this would give you a high amount of (rare) positive cases, and you can build a labeled dataset by assuming that other instances are negative. It's obviously a simplification, otherwise you can take the time to annotate a lot of negative cases as well (it's still much faster than without bootstrapping, since you already have your positive cases).

my purpose is to find the most similar movie titles, I want to use different distance/similarity measurements and compare them, what is the best method to use?

Based on the dataset you have built, you can now train a supervised model, with a pair of titles as instance. You can use various similarity measures as features, and you should vary the type of similarity (char-based, ngram-based, word-based) across these features in order to provide the model with a diversity of characteristics.
Then you can predict the similarity between any two pairs. This gives you a graph of similarity relations between all the movies, from which you can extract groups which are similar together.
Note that this is just a general strategy, many parts of it can be refined/adapted to your data and of course it depends how much time you want to spend on this problem.