text:
Q: Why does the addition of @EnableAutoConfiguration cause spring-boot to fail with "Unable to find JPA packages to scan" Why does the addition of @EnableAutoConfiguration to the following spring-boot app cause it to not create an entityManagerFactory?
If I remove @EnableAutoConfiguration everything works fine.
Can anyone shed light on this behaviour?
package test.builder;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import test.builder.jpa.entity.Builder;
import test.builder.jpa.repository.BuilderRepository;

@Configuration
// @EnableAutoConfiguration
@EnableJpaRepositories("test.builder")
@PropertySource("classpath:application.properties")
public class BootApp implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(BootApp.class);

    @Value("${spring.datasource.driverClassName}")
    private String databaseDriverClassName;

    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    @Value("${spring.datasource.username}")
    private String databaseUsername;

    @Value("${spring.datasource.password}")
    private String databasePassword;

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public DataSource dataSource() {

        org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
        ds.setDriverClassName(databaseDriverClassName);
        ds.setUrl(datasourceUrl);
        ds.setUsername(databaseUsername);
        ds.setPassword(databasePassword);

        return ds;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
            JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("test.builder");

        return lef;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(true);
        hibernateJpaVendorAdapter.setGenerateDdl(false);
        hibernateJpaVendorAdapter.setDatabase(Database.SQL_SERVER);
        return hibernateJpaVendorAdapter;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager();
    }

    @Override
    public void run(String... args) {

        AbstractApplicationContext context = new AnnotationConfigApplicationContext(BootApp.class);
        BuilderRepository repository = context.getBean(BuilderRepository.class);
        Builder builder = repository.findOne(10);

        logger.info("Retrieved ", builder.toString());

        context.close();
    }

    public static void main(String[] args) {

        SpringApplication.run(BootApp.class, args);

    }

}

The underlying error is
Unable to find JPA packages to scan, please define a @ComponentScan annotation or disable JpaAutoConfiguration

The full output (including the stacktrace) is -
14:53:50,842 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
14:53:50,843 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
14:53:50,991 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
14:53:50,997 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
14:53:51,017 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
14:53:51,114 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
14:53:51,114 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
14:53:51,115 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
14:53:51,117 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@5ece2187 - Registering current configuration as safe fallback point

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::             (v0.5.0.M6)

14:53:51,849 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
14:53:51,854 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
14:53:51,854 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
14:53:51,855 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
14:53:51,856 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
14:53:51,856 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
14:53:51,856 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@722b9406 - Registering current configuration as safe fallback point
14:53:51.945 INFO  o.s.c.a.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6490832e: startup date [Thu Dec 19 14:53:51 GMT 2013]; root of context hierarchy
14:53:52.829 INFO  o.s.b.f.s.DefaultListableBeanFactory - Overriding bean definition for bean 'transactionManager': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=bootApp; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in class test.builder.BootApp] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=transactionManager; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
14:53:52.830 INFO  o.s.b.f.s.DefaultListableBeanFactory - Overriding bean definition for bean 'entityManagerFactory': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=bootApp; factoryMethodName=entityManagerFactory; initMethodName=null; destroyMethodName=(inferred); defined in class test.builder.BootApp] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=entityManagerFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
14:53:52.830 INFO  o.s.b.f.s.DefaultListableBeanFactory - Overriding bean definition for bean 'jpaVendorAdapter': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=bootApp; factoryMethodName=jpaVendorAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class test.builder.BootApp] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; factoryMethodName=jpaVendorAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]]
Exception in thread "main" 14:53:53.382 INFO  o.s.b.a.AutoConfigurationReportLoggingInitializer$AutoConfigurationReportLogger -

=========================
AUTO-CONFIGURATION REPORT
=========================

Positive matches:
-----------------

   MessageSourceAutoConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)

   AopAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.context.annotation.EnableAspectJAutoProxy,org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration: #{true} (OnExpressionCondition)
      - @ConditionalOnClass classes found: org.springframework.context.annotation.EnableAspectJAutoProxy,org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration: #{true} (OnExpressionCondition)

   AopAutoConfiguration.JdkDynamicAutoProxyConfiguration
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration: #{!false} (OnExpressionCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration: #{!false} (OnExpressionCondition)

   DataSourceAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration
      - existing auto database detected (DataSourceAutoConfiguration.DatabaseCondition)
      - existing auto database detected (DataSourceAutoConfiguration.DatabaseCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#jdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceAutoConfiguration.JdbcTemplateConfiguration#namedParameterJdbcTemplate
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) found no beans (OnBeanCondition)

   DataSourceTransactionManagerAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

   HibernateJpaAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
      - @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found the following [dataSource] (OnBeanCondition)

   ServerPropertiesAutoConfiguration#serverProperties
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.properties.ServerProperties; SearchStrategy: all) found no beans (OnBeanCondition)

Negative matches:
-----------------

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found the following [placeHolderConfigurer] (OnBeanCondition)

   RabbitAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

   AopAutoConfiguration.CglibAutoProxyConfiguration
      - SpEL expression on org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$CglibAutoProxyConfiguration: #{false} (OnExpressionCondition)

   BatchAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)

   JpaRepositoriesAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; SearchStrategy: all) found the following [&builderRepository] (OnBeanCondition)

   JpaRepositoriesAutoConfiguration.JpaWebConfiguration
      - web application classes not found (OnWebApplicationCondition)

   MongoRepositoriesAutoConfiguration
      - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

   DataSourceAutoConfiguration.DbcpConfiguration
      - tomcat DataSource (DataSourceAutoConfiguration.BasicDatabaseCondition)

   DataSourceAutoConfiguration.EmbeddedConfiguration
      - existing non-embedded database detected (DataSourceAutoConfiguration.EmbeddedDatabaseCondition)

   DataSourceAutoConfiguration.TomcatConfiguration
      - found database driver com.microsoft.sqlserver.jdbc.SQLServerDriver (DataSourceAutoConfiguration.TomcatDatabaseCondition)
      - found database driver com.microsoft.sqlserver.jdbc.SQLServerDriver (DataSourceAutoConfiguration.TomcatDatabaseCondition)
      - @ConditionalOnMissingBean (types: javax.sql.DataSource; SearchStrategy: all) found the following [dataSource] (OnBeanCondition)

   DataSourceTransactionManagerAutoConfiguration#transactionManager
      - @ConditionalOnMissingBean (names: transactionManager; SearchStrategy: all) found the following [transactionManager] (OnBeanCondition)

   JmsTemplateAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)

   DeviceResolverAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

   JpaBaseConfiguration.JpaWebConfiguration
      - web application classes not found (OnWebApplicationCondition)

   ReactorAutoConfiguration
      - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)

   ThymeleafAutoConfiguration
      - required @ConditionalOnClass classes not found: org.thymeleaf.spring3.SpringTemplateEngine (OnClassCondition)

   DispatcherServletAutoConfiguration
      - web application classes not found (OnWebApplicationCondition)

   EmbeddedServletContainerAutoConfiguration
      - web application classes not found (OnWebApplicationCondition)

   MultipartAutoConfiguration
      - required @ConditionalOnClass classes not found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)

   WebMvcAutoConfiguration
      - web application classes not found (OnWebApplicationCondition)

   WebSocketAutoConfiguration
      - required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory()] threw exception; nested exception is java.lang.IllegalArgumentException: Unable to find JPA packages to scan, please define a @ComponentScan annotation or disable JpaAutoConfiguration
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:584)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1089)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:984)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
    at test.builder.BootApp.main(BootApp.java:104)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory()] threw exception; nested exception is java.lang.IllegalArgumentException: Unable to find JPA packages to scan, please define a @ComponentScan annotation or disable JpaAutoConfiguration
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:573)
    ... 16 more
Caused by: java.lang.IllegalArgumentException: Unable to find JPA packages to scan, please define a @ComponentScan annotation or disable JpaAutoConfiguration
    at org.springframework.util.Assert.notEmpty(Assert.java:268)
    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.getPackagesToScan(JpaBaseConfiguration.java:109)
    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory(JpaBaseConfiguration.java:76)
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerByCGLIB$$7973d544.CGLIB$entityManagerFactory$4(<generated>)
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerByCGLIB$$7973d544$$FastClassByCGLIB$$360fed5a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:334)
    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerByCGLIB$$7973d544.entityManagerFactory(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    ... 17 more

Pom extract -
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>0.5.0.M6</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>sqljdbc4</artifactId>
        <version>4.0</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.0.13</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>
</dependencies>

Any advice appreciated.

A: Where are your @Repository interfaces?

Spring Data can create implementations for you of @Repository interfaces of various flavours. Spring Boot will handle all of that for you as long as those @Repositories are included in the same package (or a sub-package) of your @EnableAutoConfiguration class.

http://projects.spring.io/spring-boot/docs/docs/howto.html

A: It's because Spring Boot wants to create repositories for you and you haven't told it where they are. You need a @ComponentScan to do that (I think the error message says so at least in recent versions).  Your application is doing a lot of stuff it doesn't need to. This should work:
@Configuration
@EnableAutoConfiguration
@ComponentScan("test.builder")
public class BootApp implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(BootApp.class);

    @Autowired
    private BuilderRepository repository;

    @Override
    public void run(String... args) {
        Builder builder = repository.findOne(10);
        logger.info("Retrieved ", builder.toString());
    }

    public static void main(String[] args) {

        SpringApplication.run(BootApp.class, args);

    }

}


text:
Q: Google Cloud Endpoints Object is never Null I have the following cloud endpoint:
@ApiMethod(name = "test.insert")
public Test insertTest(final Test test)
{
// test is Test here, but not null
}

I pass null as parameter on the Android client:
api.test().insert(null).execute();

On the backend, a Test object is created, where all fields are null. But the object itself is not null.

*

*How can I test the object for null or prevent null to be passed into the API?

I know I can make @Named parameters @Nullable, but for the object parameter it looks like GCE or REST does not reconstitute null objects as expected.

A: Use com.google.api.client.util.Data.isNull method to check the value is null.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GIT Stash Clarification I have installed GIT in my ubuntu server.
I have a habit of stashing too often in git for the files which needs more work.
So far I have not come acrosss any issues regarding stashing.
I wanted to clarify whether when I create a stash does it have a lifetime and does it get deleted or cleared after a few days.Just how secure are my changes in the stash.
And while doing any other changes is there a risk of the stash being deleted.

A: Since about git version 1.6.0 the stash is set not to expire. Changelog of that git version said:
By default, stash entries never expire.  Set reflogexpire in [gc
"refs/stash"] to a reasonable value to get traditional auto-expiration
behaviour back

So in case you want the stash to expire do as hinted above.

A: Commits in the git stash have references as a local ref, so they will stick around indefinitely (i.e. won't get garbage-collected).


text:
Q: VB Chat Interface - Displaying Users I am new to Visual Basic and trying to get around in developing a good gui for a chat interface. I can understand the language as i have been using php and java from quite sometime.
Requirement
Basically i am trying to develop a interface which will show a list of users and along with that display a status (online/offline). My users will reside in mysql database. On clicking the user i want some actions to happen.
Question
I see there is datagrid, listview,listbox but not sure which one to use. Also is it a good idea to display the users by directly quering the mysql database or by accessing a php script which runs few queries and gives the data?

A: The ListBox control would not be a great option since it doesn't easily support multiple columns. The ListView control in Details view is a great option. I think it looks and works nicer than a DataGrid, but it doesn't natively support multi-line items. If you need multi-line items, the DataGrid control may be your best choice. Another option, which would give you more flexibility, would be to use a LayoutPanel control to display a vertical list of your own UserControl. You could design the UserControl anyway you want meaning you could fully control the size, look, and layout of each item in the list without being constrained by the list control.
As far as getting the data, that depends. If the database is always on the LAN and performance is important, then each client should go directly to the database.  Otherwise, getting the data from a php script, web service, or WCF service would be a much better choice.
Rather than using the TableLayoutPanel, I would recommend using the FlowLayoutPanel with the FlowDirection property to TopDown and the AutoScroll property set to True. Then, to add a control dynamically, you could do something like this:
Dim item As New MyUserControl()
' Set properties of user control
FlowLayouPanel1.Controls.Add(item)


text:
Q: Error:Program type already present: android.arch.lifecycle.LiveData When I press the run button in Android Studio, my app compiles but shows this error (redacted):
Error:Program type already present: android.arch.lifecycle.LiveData

(Full log)
I've tried deleting the .gradle folder, then going to Build > Clean Project and Build > Rebuild Project. However, it doesn't work. I've also tried deleting the source code, then cloning again from git and importing the folder to Android Studio. However, it still produces that error.
Here's my app's app/build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'
    defaultConfig {
        applicationId "com.edricchan.studybuddy"
        minSdkVersion 24
        targetSdkVersion 27
        versionCode 8
        versionName "1.0.0-rc.503"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resConfigs "en"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'com.android.support:support-annotations:27.1.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    testImplementation 'junit:junit:4.12'
    // Firebase stuff
    implementation 'com.google.firebase:firebase-storage:11.8.0'
    implementation 'com.google.firebase:firebase-firestore:11.8.0'
    implementation 'com.google.firebase:firebase-auth:11.8.0'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    implementation 'com.google.android.gms:play-services-auth:11.8.0'
    implementation 'com.firebaseui:firebase-ui-auth:3.1.0'
    implementation 'com.firebaseui:firebase-ui-firestore:3.1.0'
    implementation 'com.firebaseui:firebase-ui-storage:3.1.0'
    // Provide a way to update the app
    implementation 'com.github.javiersantos:AppUpdater:2.6.4'
    // Chrome Custom Tabs
    implementation 'com.android.support:customtabs:27.1.0'
    // The app's intro screen
    implementation 'com.heinrichreimersoftware:material-intro:1.6.2'
    // Use for new Material Text field boxes recently introduced
    implementation 'com.github.HITGIF:TextFieldBoxes:1.3.7'
    // Report an issue to Github without having to open a new tab and so on...
    implementation 'com.heinrichreimersoftware:android-issue-reporter:1.3.1'
}
apply plugin: 'com.google.gms.google-services'

A: Firebase-UI 3.1.0 isn't compatible with Firebase / Google Services 11.8.0
You will need to upgrade or downgrade according to https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries

*

*Firebase-UI 3.1.0 with Firebase / Google Services 11.4.2

*Firebase / Google Services 11.8.0 with Firebase-UI 3.1.3

Hope this help ;)

A: Apparently, this is intended behavior:

com.firebaseui:firebase-ui-firestore:3.1.0 depends on android.arch.lifecycle:extensions:1.0.0-beta1. Switching to version 3.2.2 fixes the issue by using the Lifecycle 1.1 libraries that Support Library 27.1.0 are built upon. - Issue Tracker

For me, removing the firebase-ui dependencies solved the issue since I wasn't even using the library in the first place.

A: I had the very same problem today when I raised the support library version.
Try to replace all '27.1.0' with '27.0.2'

Later on I did manage to remove the error by upgrading other libraries as well.
THis is my current working state:
root gradle:
buildscript {
    ext.kotlin_version = '1.2.21'
    ext.support_version = '27.1.0'
    ext.anko_version = '0.10.4'
    ext.android_plugin_version = '3.0.1'
    ext.google_services_version = '11.8.0'

    repositories {
        google()
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

        classpath 'com.android.tools.build:gradle:3.1.0-beta4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

//////////////////
app gradle libraries:
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }

    // kotlin:
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation "org.jetbrains.anko:anko-common:$anko_version"
    implementation "org.jetbrains.anko:anko-commons:$anko_version"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.3'

    // support libraries:
    implementation "com.android.support:recyclerview-v7:$support_version"
    implementation "com.android.support:support-v4:$support_version"
    implementation "com.android.support:design:$support_version"
    implementation "com.android.support:appcompat-v7:$support_version"
    implementation "com.android.support:cardview-v7:$support_version"
    implementation "com.android.support:support-vector-drawable:$support_version"

    // misc:
    implementation 'com.github.d-max:spots-dialog:0.7@aar'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta5'
    implementation 'com.backendless:backendless:4.4.0'
    implementation 'io.nlopez.smartlocation:library:3.3.3'

    // Google services:
    implementation "com.google.firebase:firebase-core:$google_services_version"
    implementation "com.google.firebase:firebase-auth:$google_services_version"
    implementation 'com.firebaseui:firebase-ui-auth:3.2.2'

    implementation "com.google.android.gms:play-services-location:$google_services_version"
    implementation "com.google.android.gms:play-services-auth:$google_services_version"

    implementation('com.google.api-client:google-api-client:1.23.0') {
        exclude group: 'com.google.code.findbugs', module: 'jsr305'
    }
}

///////////////
I also upgraded graddle-wrapper.properties to:
#Wed Dec 20 15:08:34 CET 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

A: This post is the top search result for the very similar error: "Program type already present: android.arch.lifecycle.ViewModelProvider$Factory"
My project uses Room and LiveData, but not firebase. The following changes removed the error:
FROM:
implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
implementation 'android.arch.lifecycle:extensions:1.0.0'
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'

TO:
implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
implementation 'android.arch.lifecycle:extensions:1.1.1'
annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'

--- UPDATED ANSWER ---
My previous answer was aimed at solving this error. However, I thought it would be worth presenting it again using best practises:
App level build.gradle file:
// Room components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"
androidTestImplementation "android.arch.persistence.room:testing:$rootProject.roomVersion"

// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"

Project level build.gradle file:
ext {
   roomVersion = '1.1.1'
   archLifecycleVersion = '1.1.1'
}

Reference:
https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#2

A: I also had the error posted in the original question, namely:
Error:Program type already present: android.arch.lifecycle.LiveData

It wasn't clear which libraries were causing the problem. With a hint from @lienmt above I realized that it may be related Firebase.
In my case, I am using Firebase and was also using firebase-ui library 3.2.2:
implementation 'com.firebaseui:firebase-ui-database:3.2.2'

I had upgraded all my other Firebase libraries to 15.0.0 but realized my firebase-ui library was incompatible and confirmed it here:
https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries
Be sure to match your firebase-ui version to the exact Firebase versions that for which they are fixed for pairing.
Bumping my firebase-ui version to 3.3.1 was what resolved the error:
implementation 'com.firebaseui:firebase-ui-database:3.3.1'

For reference here are the versions I'm using now and my app is running with no errors:
implementation 'com.google.android.gms:play-services-wearable:15.0.0'
implementation 'com.google.android.gms:play-services-auth:15.0.0'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.google.firebase:firebase-database:15.0.0'
implementation 'com.google.firebase:firebase-core:15.0.0'
implementation 'com.google.firebase:firebase-auth:15.0.0'
implementation 'com.google.firebase:firebase-messaging:15.0.0'
implementation 'com.firebaseui:firebase-ui-database:3.3.1'

A: Please add following dependencies in your app build.gradel file
implementation "android.arch.core:runtime:1.1.1"
implementation "android.arch.core:common:1.1.1"

A: @Edric: since I couldn't replay with images in the thread I am answering your question here.
Changes that worked for me:

PS: I also upgraded distributionUrl in gradle-wrapper.properties to
http://services.gradle.org/distributions/gradle-4.6-all.zip

A: Like Edric mention, this happens because some library still use the old version of android.arch.lifecycle:extensions library, that is android.arch.lifecycle:extensions:1.0.0.
One way to handle this is by forcing the app to use the same version of that library (and if we can, use the newest one).
There are two ways to do that:

*

*Explicitly defined the library version that we want to use in our Gradle, under dependencies section.
implementation 'android.arch.lifecycle:extensions:1.1.1
or

*Force resolution of the library, also under dependencies section.
android {
    configurations.all {
        resolutionStrategy.force 'android.arch.lifecycle:extensions:1.1.1'
    }
}

A: In my case, bumping targetSdkVersion and compileSdkVersion to 28, as well as using version 28 of all support libraries fixed the issue.

I encountered this when I upgraded Glide. I got an error regarding a duplicate CoordinatorLayout. I solved that by using com.android.support:design:27.1.0, but then I got another error regarding LiveData$LifecycleBoundObserver.
After a few hours, I gave up and upgraded targetSdkVersion and compileSdkVersion to API 28, as well as using
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'

because YOLO. By dumb luck, it worked.

A: Just gotta upgrade.  For me I had to upgrade the following in App build.gradle file:
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-auth:16.2.0'
implementation 'com.firebaseui:firebase-ui-database:3.2.2'

Then you will sync your files.  When you run you will get a new issue of installation failed pop up boxes.  Just cancel those and do the following:
1) Build -> Clean Project
2) Build -> Build Bundle(s) / APK(s) -> Build APK(s)
3) Run your project! Should work!

Follow this link if you want any other details on how I solved it but this should do the trick!


text:
Q: Stack Exchange design problem: advanced questions get lost Take for example the JavaScript tag on Stack Overflow. There is such a flurry of beginner questions that those of us who know the language very well and are interested in answering subtle, advanced questions stop following that tag.  It would be nice to be able to subscribe to the "hard" questions only.
A friend and I were discussing this and came up with the following solution: have an "I don't know" button, for when you see an answer, you realize that it is a legitimate question but simply don't know the answer.  Then people could subscribe to the questions that have at least 50 "I don't know"s or something.  The solution has some issues (such as, there are different areas, not just levels of expertise, but maybe the existing tag system takes care of that?), but it's something.
I'm wondering if people have thought about this and have other ideas to solve this problem.  Maybe a solution is already in place and I simply don't know about it?

A: Doesn't the Unanswered tab serve this purpose?  The first few pages of unanswered questions on a given tab are going to be upvoted questions that don't have super easy answers, in my experience.

A: I don't think yet another tool in the UI is the answer. What you consider a boringly trivial question, someone else with less experience or a different background might consider a super-tough question.
You really want someone with similar interests to tell you that a question is interesting. That means you need a social interaction tool, and what you want to do with it is advertise questions.
Inside Stack Exchange, create a Javascript experts' chat room, and use it to share questions that you guys find interesting. Or use external tools such as Twitter if you prefer.


text:
Q: Exclude __builtin__ module The __builtin__ module in Python clutters a developers namespace with lots of functions and classes that have very generic names (e.g. max, sum, id, hash etc.) that often get in the way of naming variables and when outside of a context-aware IDE one can accidentally overwrite a name without noticing.
Is there a way to stop this module from being implicitly accessed from a certain file and require explicit imports instead?
Something along the lines of:
from __builtins__ import hash as builtin_hash

hash = builtin_hash(foo)

I am aware that this is bad practice.

A: You can simply delete __builtins__, the name Python uses to find the built-in namespace:
>>> del __builtins__
>>> max
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'max' is not defined

Warning: If you do this in someone else's namespace, they will hate you.

...and require explicit imports instead?

Note that import statements are resolved using builtins  ;)
>>> del __builtins__
>>> from builtins import max
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: __import__ not found

... very generic names (e.g. max, sum, id, hash etc.) that often get in the way of naming variables and when outside of a context-aware IDE one can accidentally overwrite a name without noticing

You will only create a local variable which shadows the name.  This is actually fairly inconsequential if you do it from within a limited scope, although it's still bad form (readability counts).
# this shadows built-in hash function in this namespace ... meh?
hash = '38762cf7f55934b34d179ae6a4c80cadccbb7f0a'

# this stomps built-in hash ... not a honking great idea!
import builtins
builtins.hash = lambda obj: -1

Best practice:

*

*Use a context-aware editor which will give you a squiggly underline for name collisions, or

*Use Python long enough that you know the built-in names by heart (seriously!)

*Avoid name shadowing by using a synonym (e.g. checksum) or appending a trailing underscore on the name (e.g. hash_)


text:
Q: Am working on a timer, Why is the breakCount() function not updating after using setTimeout()? I want the breakCount function to start counting when the previous session times out, it only updates the variable $breakData but doesn't countdown, why? how can I make it work? If this snippet doesn't help you understand what I mean please say so.

function holdCount() {
  var t,
    secs = 60,
    mins = countSession.innerHTML;
  mins--;

  function countdown() {
    secs--;
    if (secs < 0) {
      mins--;
      secs = 59;
    };
    if (secs < 10) {
      countSession.innerHTML = mins + ':' + '0' + secs;
    } else {
      countSession.innerHTML = mins + ':' + secs;
    };
    t = setTimeout(countdown, 1000);

    if (mins == 0 && secs == 0) {
      clearTimeout(t);
      breakCount();

      function breakCount() {
        var $breakData = $('#displayBreak').text();
        $breakData--;
        $('#sessionCount').text($breakData);
      }
      setTimeout(breakCount, 1000);
    }
  }
  countdown();
}

countSession.addEventListener('click', holdCount, false);


text:
Q: How do I make react router v6 load elements without having to manualy refresh the url? When I send the user to a URL (in this case /login and /signup and then back to /)
the elements on my page don't load automatically by entering the URL, I instead have to manually refresh in order for the content to load.
This is my index.js which handles the routes (with react router v6)
import Navbar from "./components/navbar/navbar";
import Footer from "./components/footer/footer";

import Home from "./pages/home/home";
import Login from "./pages/user/login/login";
import Signup from "./pages/user/signup/signup";

ReactDOM.render(

<Navbar />
<BrowserRouter>
 <Routes>
<Route index path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
 <Route path="/signup" element={<Signup />} />
 </Routes>
</BrowserRouter>

,
  document.getElementById("root")
);

This is an example of what happens when I send the user to /login with the use of the Link component that I am importing through React-router.
Before refreshing the URL  on /login
I then have to manually reload the page by pressing the reload button, only after doing so the content will load.
After refreshing the URL on /login
the same applies if I try to go back to the homepage using the Link component
Before refreshing on the URL /
I then have to reload in order to remove the login box
After refreshing on the URL /

A: I reproduced the same behavior. CodeSandbox (try it and look at home.js)
You don't seem to be using the page navigation correctly. The most react way is to use the useNavigation() hook.

A: If navigation is working but the routes aren't then I suspect you are rendering them into separate routers. I notice you render the Navbar outside your BrowserRouter, and since navigation is working and updating the URL in the address bar is fairly safe to assume those links are correctly wrapped in a router. You'd see an invariant warning/error otherwise.
ReactDOM.render(

    <Navbar /> // <-- must have another router if it is working
    <BrowserRouter>
      <Routes>
        <Route index path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/signup" element={<Signup />} />
      </Routes>
    </BrowserRouter>

,
  document.getElementById("root")
);

You should have only one router wrapping the app and providing the routing context to all Routes, Route, Navigate, Link, etc... components.
Remove any extraneous routers in other components, like NavBar, and move them all to be within the BrowserRouter you are rendering here.
ReactDOM.render(
  <BrowserRouter>
    <Navbar />
    <Routes>
      <Route index path="/" element={<Home />} />
      <Route path="/login" element={<Login />} />
      <Route path="/signup" element={<Signup />} />
    </Routes>

  </BrowserRouter>,
  document.getElementById("root")
);


text:
Q: Rank of generalized eigenvector for matrix power $A$ is a square matrix with real entries. Let $v$ be a generalized eigenvector of $A$ with rank $r$, i.e., $(A-\lambda I)^rv=0$   and $(A-\lambda I)^{r-1} v\neq0$, where $v$ is non-null and $\lambda$ is an eigenvalue of $A$. We know that $v$ is also a generalized eigenvector of $A^n$ with rank $s\leq r$, because $(A^n-\lambda^n I)^rv=Q(A, \lambda)(A-\lambda I)^rv=Q(A, \lambda)0=0$. If $\lambda=0$, I think $ s=\lfloor r/n \rfloor$. Question is: if $\lambda\neq0$, what can we say about $s$? Is $s=r$? Feel free to throw in additional hypotheses that may help to solve the problem.

A: First of all, you need to realise that $v$ will be a generalised eigenvector of$~A^n$ not for$~\lambda$, but for the eigenvalue$~\lambda^n$. Now you know that it takes $r$ applications of $A-\lambda I$ to reduce $v$ to $0$, and you want to know how many applications of $A^n-\lambda^nI$ it will take to also reduce $v$ to $0$. Now the polynomial $X^n-\lambda^n$ is divisible by $X-\lambda$ with quotient $Q=X^{n-1}+\lambda X^{n-2} +\cdots+ \lambda^{n-2}X+\lambda^{n-1}$. When $\lambda\neq0$, the polynomial $Q$ does not have$~\lambda$ as a root, and is therefore relatively prime to $X-\lambda$. Hence $Q[A]$ acts invertibly of the generalised eigenspace for$~\lambda$ of$~A$. It follows that
$$(A^n-\lambda^nI)^k(v) = ((A-\lambda I)Q[A])^k(v)=(Q[A])^k((X-\lambda I)^k(v))
$$
which is $0$ if and only if $k\geq r$. So indeed, if $\lambda\neq0$, the rank of $v$ with respect to $A^n$ equals$~r$.


text:
Q: Divisibility of $n^2+9$ by $n+3$ How would one find all integers $n$ such that $n+3 \vert n^2 +9$? I assume it is important that $(n+3)^2 - 6n = n+3$, but I am struggling to see how you can find all $n$, and confirm an upper bound such that there are no more such $n$.

A: Clearly, $n+3\mid n^2-9$ holds for every natural $n$. So,$$n+3\mid n^2+9\iff n+3\mid18.$$There aren't many choices for $n$ then.

A: Hint
$$n^2+9=(n+3)^2-6(n+3)+18$$
so
$$\frac{n^2+9}{n+3}=(n+3)-6+\frac{18}{n+3}$$
and then $n+3|18$.

A: Alternatively:
$n+3|n^2+9 \iff$
$n+3|n^2 + 9 - n(n+3)\iff$
$n+3|-3n + 9\iff$
$n+3|-3n + 9 + 3(n+3)\iff$
$n+3|18$
$n+3 = \pm 1; \pm 2;\pm 3;\pm 6;\pm 9;\pm 18$
$-21,-12,-9,-6,-5,-4,-2,-1,0,3,6,15$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
{n^{2} + 9 \over n + 3} & =
{\bracks{\pars{n + 3} - 3}^{\, 2} + 9 \over n + 3} =
{\bracks{\pars{n + 3}^{2} - 6\pars{n + 3} + 9} + 9 \over n + 3} =
\pars{n + 3} - 6 + {18 \over n + 3}
\\[5mm] & =
n - 3 + {18 \over n + 3}
\end{align}

Then, $\ds{\pars{n + 3} \mid \pars{n^{2} + 9}}$ whenever
   $\ds{\pars{n + 3} \mid 18 \implies \exists\ p \in \mathbb{Z}\setminus\braces{0}}$ such that
  $\ds{{18 \over n + 3} = p \implies n = 3\pars{{6 \over p} - 1} \implies p \in \braces{\pm 1,\pm 2,\pm 3,\pm 6} \implies}$

  $\ds{\bbx{n \in \color{#f00}{\braces{-21,-12,-9,-6,0,3,6,15}}}}$.


text:
Q: Move block in Excel to line N Trying to write code to move the block at the N line in Excel, but alas so far nothing. Suggests that this is how you can:
namespace MoveBlockExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            Application objExcel = new Application();
            objExcel.DisplayAlerts = false;

            objExcel.Range range = ObjWorkSheet.get_Range("B10:F15");
            range.Paste(ObjWorkSheet.get_Range("B1:F5"));

            Workbook objWorkBook = objExcel.Workbooks.Open("C:\\Template_Modified.xls");
            Worksheet objWorkSheet = objWorkBook.Sheets[3];
        }
    }
}

But the code is not compiled, based on what objExcel not found.

A: This should cut the range B10:F15 and paste it to B1:F5.
var app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
var workbook = app.Workbooks.Open("C:\\Template_Modified.xls");
Worksheet worksheet = app.ActiveSheet;
worksheet.Range["B10:F15"].Cut(worksheet.Range["B1:F5"]);

Make sure that your refences include Microsoft.Office.Interop.Excel:


text:
Q: Probability density function dependent variable probability So if $f(x,y) = 8xy$ with $0<x<y<1$.
Now how would I find $P(Y<0.5)$?  I have no idea how to do it since $x$ and $y$ are dependent on each other, how would you get a numerical value since all your bounds contain a variable in them? I see no way of getting a numerical value since the bound for $x$ is $0<x < y$ and the bound for $y$ is $x < y < 0.5$.

A: To find $P(Y<1/2)$ you need to integrate $f(x,y)$ over all $(x,y)$ where
$y<1/2$ (yellow region in picture below). Since $f(x,y)=0$ for $(x,y)$ outside
the green triangle, the correct way to set up the double integral is
$$P(Y<1/2)=\int_0^{1/2} \int_0^y 8xy\, dx\,dy.$$
Can you take it from here?


text:
Q: ERROR couldn't connect to zsys daemon: connection error: desc = "transport: Error while dialing dial unix /run/zsysd.sock: I am on Ubuntu 20.04 (not on ZFS). However, somehow I got this error:

ERROR couldn't connect to zsys daemon: connection error: desc = "transport: Error while dialing dial unix /run/zsysd.sock: connect: connection refused"

The error screenshot

A: Had the same issue.
Use apt to remove zsys

$ sudo apt remove zsys

Then comment out the zsys commands when using apt (put '#' in front of each command) in /etc/apt/apt.conf.d/90_zsys_system_autosnapshot

// Takes a snapshot of the system before package changes.
#DPkg::Pre-Invoke {"/usr/libexec/zsys-system-autosnapshot snapshot ||
true";};
// Update our bootloader to list the new snapshot after the update is
done to not block the critical path
#DPkg::Post-Invoke {"/usr/libexec/zsys-system-autosnapshot
update-menu || true";};

I've done this and rebooted and all seems fine adding modules via apt

A: Just restart zsysd.service, eveything will be Ok.
The command is sudo systemctl restart zsysd.service.

A: Because I have a dual-boot system I agree with the option of "comment out" zsys commands per above.  I say this because one could attempt to install the ZFS file system (so I've read) to existing installs of Ubuntu 19.10 (and later?) to make the error go away, but according to the following article attempting to do so will wipe the whole drive, including other functioning partitions!
https://itsfoss.com/zfs-ubuntu/
Currently, I have a second partition on my dual-boot machine running Max OS 11.1 (Big Sur), and wouldn't want that to get wiped.
Finally, I did install of program before and after "comment out" of zsys commands per above and yes, the fix works!  Before: same error as above.  After: no error.  fyi, this is the program I installed (a mail program):
sudo apt-get install sylpheed


text:
Q: How to show Category Name instead of Category ID in View from another table? Got a little problem with figuring it out, how can I achieve this...
There are 2 db tables - Category and Product.

In my Kategoria column I want to show exactly name of the category, not ID. Below my model classes.
Product.cs
public partial class Category
{
    public int ID { get; set; }
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int ClientID { get; set; }
}

Category.cs
public partial class Product
{
    public int ID { get; set; }
    public int ProductID { get; set; }
    public string Name { get; set; }
    public int CategoryID { get; set; }
    public decimal Price { get; set; }
    public int Promotion { get; set; }
    public string Image1 { get; set; }
    public string Image2 { get; set; }
    public string Image3 { get; set; }
    public string Image4 { get; set; }
    public string Description { get; set; }
    public int ClientID { get; set; }

    public virtual Category Category { get; set; }
}

And the ViewPart:
@Html.DisplayFor(modelItem => item.CategoryID)

When I type modelItem => item.Category.Name it doesn't work (column is empty). Any ideas how can i do this?
Controller:
public class ProductsController : Controller
    {
        private ProductContext db = new ProductContext();

        private void LoadCreateViewBagData()
        {
            string domain = Request.Url.Host;
            int clientid = (from a in db.Client where a.Domain == domain select a.ID).First();

            int maxID = db.Product.Where(c => c.ClientID == clientid).Max(c => (int?)c.ProductID) ?? 0;

            ViewBag.MaxID = maxID + 1;

            IEnumerable<SelectListItem> categories = db.Category.Where(d => d.ClientID == clientid).Select(b => new SelectListItem { Text = b.Name, Value = b.CategoryID.ToString() });

            ViewData["categories"] = categories;

            ViewBag.ClientID = clientid;
        }

        // GET: Admin/Products
        public ActionResult Index()
        {
            string domain = Request.Url.Host;
            int clientid = (from a in db.Client where a.Domain == domain select a.ID).First();

            LoadCreateViewBagData();

            return View(db.Product.ToList().OrderByDescending(a => a.ProductID).Where(c => c.ClientID == clientid));
        }

A: Just change the line
return View(db.Product.Include(p =>p.Category).ToList().OrderByDescending(a => a.ProductID).Where(c => c.ClientID == clientid));

then below line will work in view
@Html.DisplayFor(modelItem => item.Category.Name)

Change the product class as per blow
public partial class Category
 {
   public Category()
    {
      this.Products = new HashSet<Product>();
    }

    public int ID { get; set; }
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int ClientID { get; set; }

   public virtual ICollection<Product> Products { get; set; }
}
public partial class Product
{
 public int ID { get; set; }
 public int ProductID { get; set; }
 public string Name { get; set; }
 public int CategoryID { get; set; }
 public decimal Price { get; set; }
 public int Promotion { get; set; }
 public string Image1 { get; set; }
 public string Image2 { get; set; }
 public string Image3 { get; set; }
 public string Image4 { get; set; }
 public string Description { get; set; }
 public int ClientID { get; set; }

 public virtual Category Category { get; set; }
}

A: Try this:
@Html.DisplayFor(modelItem => item.Category.Name)

Controller:
public class ProductsController : Controller
{
    private ProductContext db = new ProductContext();

    private void LoadCreateViewBagData()
    {
        string domain = Request.Url.Host;
        int clientid = (from a in db.Client where a.Domain == domain select a.ID).First();

        int maxID = db.Product.Where(c => c.ClientID == clientid).Max(c => (int?)c.ProductID) ?? 0;

        ViewBag.MaxID = maxID + 1;

        IEnumerable<SelectListItem> categories = db.Category.Where(d => d.ClientID == clientid).Select(b => new SelectListItem { Text = b.Name, Value = b.CategoryID.ToString() });

        ViewData["categories"] = categories;

        ViewBag.ClientID = clientid;
    }

    // GET: Admin/Products
    public ActionResult Index()
    {
        string domain = Request.Url.Host;
        int clientid = (from a in db.Client where a.Domain == domain select a.ID).First();

        LoadCreateViewBagData();

        return View(db.Product.Include("Category").Where(c => c.ClientID == clientid).OrderByDescending(a => a.ProductID).ToList());
    }

Tip for better performance
You are using ToList before Where:
return View(db.Product.ToList().OrderByDescending(a => a.ProductID).Where(c => c.ClientID == clientid));

Use Where to filter and then use ToList to get data:
return View(db.Product.Include("Category").Where(c => c.ClientID == clientid).OrderByDescending(a => a.ProductID).ToList());


text:
Q: Throwing custom exceptions in multi-layered spring project I am trying to handle the use case where there's a violation for an unique field (for example, the username/mail), would it be correct to handle it like so? (I am using jdbcInsert on the dao layer)
@Transactional
@Override
public User register(String name, String surname, String username, String email, String password) {
    User user = null;
    try {
        user = userDao.register(name, surname, username,
                email, passwordEncoder.encode(password));
    } catch (DuplicateKeyException duplicateKeyException) {
        throw new DuplicateUserException(duplicateKeyException.getMessage());
    } catch (DataAccessException dataAccessException) {
        throw new SystemUnavailableException(dataAccessException.getMessage());
    }
    return user;
}

And catching my custom exceptions in the controller:
@ControllerAdvice
public class ErrorControllerAdvice {
    @ExceptionHandler(DuplicateUserException.class)
    public ModelAndView keyViolation(DuplicateUserException ex) {
        ModelAndView mav = new ModelAndView("admin/user/new");
        mav.addObject("duplicateMessage", ex.getErrorMessage());
        return mav;
    }

    @ExceptionHandler(SystemUnavailableException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView unexpectedDatabaseError(SystemUnavailableException ex) {
        LOGGER.error(ex.getErrorMessage());
        return new ModelAndView("500");
    }
}

A: Looks fine to me. Your custom exceptions live at a different level of abstraction, which gives them good reason for existing.
You might consider handling the exceptions in your controller, instead of using an Error translator class (ErrorControllerAdvice) though. This makes things more explicit and limit surprises about how exceptions are handled.


text:
Q: All Scripts Stop Working After Navigating on Mobile I'm currently working on a mobile version of a website, the desktop version is working perfectly. On mobile, after the first navigation (random internal page), all jQuery scripts stop working. Even when I navigate back to index, it doesn't execute previously working scripts.
I have included html parts, for example:
$(".header").load("header.html");

And lots of different in-page scripts or slideshows, toggle buttons.
I'm aware of the DOM loading issue, tried all solution, none of them fixed the bug.
So how can I fix this without creating a completely different mobile version of the website?

A: Try this instead of load().
$(document).ready(function(){
    $.ajax( {
    url: "header.html",
    type: "GET",
    cache: false,
    success: function(html) {
        $(".header").html(html);
      }
    });
});


text:
Q: How to display 2 tables side by side using css in dompdf I try to use display inline-block but dompdf doesn't support display inline.
I have here :
using these codes:

                    Account No
                    :
                    <?=$client->acc_number?>

                    Full Name
                    :
                    <?=$client->fullname?>

                    Contact No
                    :
                    <?=$client->contact_num?>

                    Address
                    :
                    <?=$client->address?>

                    Status
                    :
                    <?=$client->remarks?>

                    Date of Loan
                    :
                    <?=strftime("%b. %d, %Y",strtotime($loan->date_loan))?>

                    Term of Loan
                    :
                    <?= $loan->loan_term;?> <?=$loan->loan_term == 1 ? " Month" : " Months"; ?>

                    End of Loan
                    :
                    <?= strftime("%b. %d, %Y",strtotime($loan->loan_end))?>

                    Collection
                    :
                    <?=$loan->collection?>

                    Principal
                    :
                    <?=number_format($loan->principal)?>

                    Interest
                    :
                    <?=$loan->interest?>%

                    Total Interest
                    :
                    <?=number_format($loan->total_interest)?>

                    Total Payment
                    :
                    <?=number_format($loan->total)?>

                    Amount of Payment
                    :
                    <?=number_format($loan->payment)?>

                    Total Paid
                    :
                    <?=number_format($total_paid)?>

                    Balace
                    :
                    <?=number_format($balance)?>

The border of the table is not following the floated div to the right.
I have search a lot dompdf table problem but still don't have find any answer please help me.
The border of the table is not following the floated div to the right.
I have search a lot dompdf table problem but still don't have find any answer please help me.
The border of the table is not following the floated div to the right.
I have search a lot dompdf table problem but still don't have find any answer please help me.
The border of the table is not following the floated div to the right.
I have search a lot dompdf table problem but still don't have find any answer please help me.
The border of the table is not following the floated div to the right.
I have search a lot dompdf table problem but still don't have find any answer please help me.

A: Remove the div you use and add another table

   your left side table
   your right side table


text:
Q: How to check c++ pointer pointing to invalid memory address? Is there anyone show me how to check my pointer is pointing to an invalid memory address.
#include<iostream>

class Node{
 public:
  int data;
  Node * next , * prev;
};

// Driver Code

int main () {

   Node * node = new Node{ 3 , nullptr , nullptr };
   Node * ptr = node;

   delete node;
   // here node gets deleted from memory and ptr pointing to invalid memory address

   if(ptr == nullptr)
      std::cout << "ptr is null \n";
   else std::cout << "ptr is not null !\n";
   return 0;
 }

 // OUTPUT : ptr is not null !

Here I have very simple code In which ' node ' is allocating memory in heap and pointer ' ptr '
points to the node after this I delete ' node ' and ' ptr ' is still pointing to 'node'. so the question is how I can check ' ptr ' is pointing to an invalid memory address.

A: A debugger on Windows will use ReadProcessMemory and WriteProcessMemory functions to access memory of the debugged program in a safe way. Those functions do not crash if memory is not accessible, but instead return an error.
Using ReadProcessMemory outside of a debugger has a lot of drawbacks:

*

*Extremely bad programming design.

*Not sure it works for own process.

*Not portable, need to figure out for Linux and macOS.

*The function is orders of magnitude slower than a direct memory access. Your program may become slow as hell.

*The fact that memory is accessible does not mean pointer is valid. It can point to other completely random application data. You cannot trust what you read; displaying for debug is OK, using it for real not. And writing is very dangerous

Alternatively, what you might actually need is Address Sanitizer. Address Sanitizer is an extremely powerful debug tool for C++, made by Google and currently builtin in all major compilers: GCC, Clang and MSVC.
Address Sanitizer will automatically check the validity of every pointer value before dereferencing them. A valid pointer means pointing inside a previously allocated and not et deallocated block. If you have a bad pointer, the program stops with a nice diagnostics message.
Valgrind is a similar debugging tool, but I would recommend
Address Sanitizer as it is much faster, uses less memory, and is available on all platforms.

A: Yes, you can check if a pointer is pointing to an allocated memory of certain size.
But no, you can't check if it points to the "correct" object. But since this wasn't your question, I will assume you only care if dereferencing a pointer would cause a crash in your program.
bool wouldDereferencingCauseCrash(int* ptr); //checks if ptr points to sizeof(int)
                                             //allocated on heap bytes

int* a = new(int);
int* b = a;
wouldDereferencingCauseCrash(b); //returns false - b points to memory alocated for a
free(a);
wouldDereferencingCauseCrash(b); //returns true -  b points to freed memory chunk
int* c = new(int);
wouldDereferencingCauseCrash(b); //returns ???? -  b points to either freed memory
                                 //                or memory allocated for c

Now how would we implement this mysterious function "wouldDereferencingCauseCrash"?
First, the basics. Let's assume you're using GCC compiler, and new() is actually just a malloc() in disguise (which is usually the case).
Heap is one contiguous block of memory. Malloc() returns a chunk of memory which for our purposes looks like this:
//this is a simplification but you can deduce all these parameters from the original

//struct contained in malloc.c

struct memory_chunk{

void* ptrToPreviousChunk; //we can deduce pointer to prev. allocated memory_chunk
void* ptrToNextChunk;     //we can deduce pointer to next allocated memory_chunk
void* ptrToChunk;         //this is what malloc() returns - usable memory.
int sizeOfChunk;          //we can deduce if this holds sizeof(int) bytes

};

Now if we just iteratore through all the allocated chunks and find our pointer - we know it points to an allocated memory. If sizeOfChunk is also sizeof(int) - we know it holds an integer. Voila, dereferencing this pointer won't cause a crash. Great! But just to be safe, don't try to write to this memory, copy it first :).
Now the hard stuff:
1/ depending on your compiler, malloc() might work differently,
2/ malloc() sometimes doesn't allocate memory chunks on the heap, sometimes it maps them using mmap() (but usually only if they are very very big),
3/ new() might not be based on malloc() (not likely),
4/ I simplified this quite a bit, read sources if you're intrested in implementing any of this. I recommend using unique_ptr instead or tracking the allocations/deallocations in some kind of a map.
Good luck! :) I hope I don't see this nonsense anywhere near me though :)
Sources:
https://sourceware.org/glibc/wiki/MallocInternals
https://reversea.me/index.php/digging-into-malloc/

A: I don't how to check invalid memory address but I have a solution for you're problem you can create your own Pointer. here's code
#include<iostream>

// Add this class in you're code
template<class T>
class Pointer {
 public:
       Pointer (T* node){
          this->node = node;
       }

       // use obj.DeletePtr() instead of 'delete' keyword
     void DeletePtr () {
        delete node;
        node = nullptr;
     }

     // compare to nullptr
     bool operator == (nullptr_t ptr){
       return node == ptr;
     }

 private:
    T* node;
};

class Node{
  public:
   int data;
   Node * next , * prev;
};

 int main () {
    Pointer ptr (new Node{3 , nullptr , nullptr}); // initialize pointer like this

    ptr.DeletePtr();

    if(ptr == nullptr)
     std::cout << "ptr is null \n";
    else
     std::cout << "ptr is not null !\n";

    return 0;
 }

A: As mentioned in the comments there is no canonical way to check whether a raw pointer points to a valid allocated memory. Any code trying to do so relying on underlying compiler specific semantics will produce brittle code.
Fortunately since C++11, the C++ standard library present us with 3 smart pointer types we can use to write safe code that can check the validity of memory. Look at the documentation for smart pointers.
The three smart pointer types are std::unique_ptr, std::shared_ptr and std::weak_ptr.

*

*unique_ptr allows only a single ownership of the underlying allocated memory. This means that at any point during the program's execution, only one unique_ptr object can be used to access the memory. Once the ownership is transferred to another unique_ptr object the old object can no longer be used to access the underlying memory. This kind of smart pointer is perfect for holding private state or for implementing move semantics API.

*shared_ptr allows shared ownership of the memory. As long as there is at least one shared_ptr object holding access to the memory the memory will not be released. This is achieved using reference counting. Every time the shared_ptr is copied the reference count is incremented. Every time a shared_ptr object goes out of scope the reference count is decremented. Once the count reaches 0 the memory is released.

*weak_ptr is also used for shared ownership of memory together with shared_ptr . However holding a weak_ptr object will not prevent the memory from being released (assigning a weak_ptr will not increase the reference count`). You may wonder why this is a good thing? The most trivial example is a circular reference. It will be shown in the code below.

Actually a linked list like the one on the question should not use unique_ptr (unless each node holds some private state) but rather shared_ptr and weak_ptr. In the sample code below I will show the use of all three types (the unique_ptr will be used for the data - not the list).
#include <memory>
#include <iostream>

class List;
// A small sample ilustrating the use of smart pointer
class Node {
    friend class List;
public:
    typedef std::shared_ptr<Node> ptr;

    ~Node() = default; // No need to handle releasing memory ourselves - the smart pointer will take care of it

    static ptr create_with_data(int data) {
        return ptr(new Node(data));
    }

    ptr next() {
        return next_;
    }

    ptr prev() {
        return prev_.lock(); // We need to upgrade the weak_ptr to shared_ptr to actually be able to access the data
                             // If we don't have a previous element od if it was deleted we will return nullptr
    }

    int data() const {
        return *data_;
    }

private:
    // We make the constructors private so we can only create shared pointers to Node
    Node() = default;
    Node(int data) {
        data_.reset(new int);
        *data_ = data;
    }
    // The data will be automatically released when Node is released.
    // This is obviously not needed for int but if we were dealing with more complex data
    // Then it would have come handy
    std::unique_ptr<int> data_;
    ptr next_; // Pointer to the next node in the list
               // If we are released so will be the next node unless someone else is using it
    std::weak_ptr<Node> prev_; // Pointer to the previous node in the list (We will however not prevent it from being released)
                               // If we were to hold a shared_ptr here we would have prevented the list from being freed.
                               // because the reference count of prev would never get to be 0
};

class List {
public:
    typedef std::shared_ptr<List> ptr;
    ~List() = default; // Once List is deleted all the elements in the list will be dleted automatically
                       // If however someone is still holding an element of the list it will not be deleted until they are done

    static ptr create() {
        return ptr(new List());
    }

    void append(Node::ptr next) {
        if(nullptr == head_) {
            head_ = next;
        }
        else {
            auto tail = head_;
            while(tail->next_) {
                tail = tail->next_;
            }
            tail->next_ = next;
            next->prev_ = tail; // This will not increment the reference count of tail as prev_ is a weak_ptr
        }
    }

    Node::ptr head() {
        return head_;
    }

    long head_use_count() const {
        return head_.use_count();
    }
private:
    Node::ptr head_;
};

int main(int, char const*[]) {

    auto list = List::create(); // List will go out of scope when main returns and all the list will be released
    auto node = Node::create_with_data(100); // This node will also live until the end of main.
    std::cout << "node reference count: " << node.use_count() <<std::endl;
    list->append(node); // node is now the head of the list and has a reference count of 2
    std::cout << "node reference count: " << node.use_count() <<std::endl;
    node.reset(); // Hey what is this? node is no longer valid in the scope of main but continues to live happily inside the list
                  // the head of the list has a reference count of 1
    std::cout << "node reference count: " << node.use_count() <<std::endl;

    if (nullptr != node) {
        std::cout << node->data() << std::endl;
    }
    else {
        std::cout << "node is released in this scope we can access the data using head()" << std::endl;
        std::cout << "Head is: " << list->head()->data() << std::endl;
        // You may thin that the below line should print 1. However since we requested
        // a copy of the head using head() it is 2
        std::cout << "Head reference count: " << list->head().use_count() << std::endl;
        // To print the use count from the list we will use the function we created for this
        // It will print 1 as expected
        std::cout << "Head reference count: " << list->head_use_count() << std::endl;
    }
    // Lets add another node to the list and then release the but continue holding our node and see what happens
    node = Node::create_with_data(200);
    list->append(node);
    // Did the reference count of the head changed? No because prev_ is weak_ptr
    std::cout << "Head reference count: " << list->head_use_count() << std::endl;
    auto prev = node->prev();
    // Did the reference count of the head changed? Yes because the call to prev() locks the  previous element for us
    // And the previous of node is the head
    std::cout << "Head reference count: " << list->head_use_count() << std::endl;
    prev.reset(); // Let's release our holding of the head
    std::cout << "Head reference count: " << list->head_use_count() << std::endl;
    // Traverse the list
    {
        auto next = list->head();
        while(next) {
            std::cout << "List Item: " << next->data() << std::endl;
            next = next->next();
        }
    }
    // Here we still hold a reference to the second element of the list.
    // Let's release the list and see what happens
    list.reset();
    if (nullptr != list) {
        std::cout << "The head of the list is " << list->head()->data() << std::endl;
    }
    else {
        // We will get here
        std::cout << "The list is released" <<std::endl;
        // So the list is released but we still have a reference to the second item - let's check this
        if (nullptr != node) {
            std::cout << "The data is " << node->data() << std::endl;
            // What about the head - can we maybe access it using prev?
            auto head = node->prev();
            if (nullptr != head) { // We will not get here
                std::cout << "The value of head is " << head->data() << std::endl;
            }
            else {
                // We will get here
                std::cout << "We are detached from the list" << std::endl;
            }
        }
        else {
            std::cout << "This is unexpected" << std::endl;
        }
    }
    return 0;
}

Note The callse to reset() you see in the code are just to illustrate what happens when you release the reference a shared_ptr holds. In most cases you will not call reset() directly.

A: I usually never call directly delete, I use a template function to clean memory:
    template < typename T > void destroy ( T*& p ) {
        if (p)
            delete p;
        p = nullptr;
    }

    ....

    Anything* mypointer = new ..... ;
    ....
    destroy(mypointer) ;   // Implicit instanciation, mypointer is nullptr on exit.

This way, you never have a destroyed object with a invalid pointer remaining. Better, the call to destroy is safe, you can call it on an already nullptr pointer without any consequences.

A: I end up with this solution It may help someone who runs into the same problem
  #include<iostream>

  class Node{
   public:
    int data;
    Node * next , * prev;
  };

  template<class T>
  void DeletePtr (T*** ptr) {
      T** auxiliary = &(**ptr);
      delete *auxiliary;
      **ptr = nullptr;
      *ptr = nullptr;
  }

  // Driver Code
  int main () {

     Node * node = new Node{ 3 , nullptr , nullptr };
     Node ** ptr = &node;
     DeletePtr(&ptr);

     if(ptr == nullptr && node == nullptr)
        std::cout << "ptr is null \n";
     else std::cout << "ptr is not null !\n";
     return 0;
   }


text:
Q: Pop & push automatic configurations as a reaction on priority release builds Within our company we use TeamCity for both automatically triggered build configurations, that are triggered quite regularly, and also manual not-as-often build configurations.
Examples of automatic builds are: up-to-date light builds, tests, etc. These are usually triggered because new code/data is available.
Currently, there is big chained process for a release of our product on all platforms. This is done manually by running the last composing build config, and it will do all the build configurations it needs to. None of them are ever automatically triggered, and all are unique to the release build chain.
My questions are, as the amount of agents we have available is quite limited, is it possible that the release process has priority in a way that it would:

*

*Pop any automatic builds and add them again to the queue (just cancelling would be fine, but less desirable) as long as the release chain is ongoing?

*Delay any automatic trigger build until the release build chain is finished?

I would understand that there is no existing solution for this, as the only thing I'm using for now is the priority classes. And even though it does work nicely for deciding what stuff on the queue to execute first, it doesn't affect any ongoing build process.
Do you know a great solution for that, or have an idea on how I could tackle this myself by implementing something using, for example, the REST API?

A: TeamCity have custom build queue priorities feature. You can configure your release process build configurations to have higher priority, so they will run before any non-prioritized build, and there no need to remove/readd builds from/into queue.


text:
Q: Algebra question grade 9 I am a a student and I am having difficulty with answering this question. I keep getting the answer wrong. Please may I have a step by step solution to this question so that I won't have difficulties with answering these type of questions in the future.
Question: Rearrange the formula below to make n the subject.
$$x = \sqrt{\frac{1+n}{1-n}}.$$
I got rid of the square roots first:
$$x^2(1-n) = 1+n.$$
However I don't know what to do next.
Kind Regards. Help would be appreciated

A: after squaring we get
$$x^2=\frac{n+1}{1-n}$$ and then (multiplying by the denominator and expanding)
$$x^2-x^2n=n+1$$
$$x^2-1=n(1+x^2)$$ (isolating $n$)
thus we get
$$n=\frac{x^2-1}{x^2+1}$$

A: After squaring the original equation you get,
$$\frac{x^2}{1} = \frac{1+n}{1-n}$$
Then use componendo-dividendo(it is an useful algebra tool for ratio manipulations and is worth knowing) to get,
$$\frac{x^2-1}{x^2+1} = \frac{2n}{2} = n$$

A: Your first step is correct. So, we have
$$x^2 = \frac{1+n}{1-n}$$
Now, the question is: how do we get rid of this fraction and simplify two $n$'s to one? The natural step is to cross multiply like this:
\begin{align}
{x^2} \cdot \color{#f00}{1} &= \frac{1+n}{1-n} \cdot \color{#f00}1\\
{x^2} \cdot  \color{red}{\left(\frac{1-n}{1-n} \right)} &= \frac{1+n}{1-n} \cdot  \color{red}{\left(\frac{1-n}{1-n}\right)}
\end{align}
The above is how cross multiplication works. Both sides are always being multiplied by $1$. We can rewrite the 1 as anything as long as the 1 simplifies to 1.
Which gives us what you came up with:
$$x^2 \cdot (1-n) = (1+n)$$
Now, it's a matter of just expanding and bringing all of our $n$'s to one side.
\begin{align}
x^2 \cdot (1-n) &= (1+n) \\
x^2 - nx^2 &= 1 + n \\
x^2 - 1 &= n + nx^2 \\
...
\end{align}
There are two more steps left which I have left for your to complete.
Some times it pays to just expand even if it looks ugly to you and then try to factor things based on whatever you are trying to rearrange for.
Let me know if you have any further questions :)
EDIT:
So, you have $x^2 - 1$ on one side and $n + nx^2$ on another side. Since you have all of your $n$'s in one place you can try separate the $n$'s from everything else because remember, you want to isolate for $n$.  You can do this by factoring $n$ from $n + nx^2$.  So you will have $n (1 + x^2)$.
Since you want $n$ by itself, you can divide both sides by $(1 + x^2)$ and come to your answer.
What you did is:
\begin{align}
\require{cancel}
x^2 - 1 &= n + nx^2 \\
\frac{\cancel{x^2} - 1}{\cancel{x^2}} &= \frac{n + n\cancel{x^2}} {\cancel{x^2}} \color{red}{Wrong.} \\
\end{align}
Remember, when you have more than one term in the numerator like you do above and divide by $1$ thing i.e. $x^2$ then what you are really saying is:
\begin{align}
x^2 - 1 &= n + nx^2 \\
\frac{x^2 - 1}{x^2} &= \frac{n + nx^2}{x^2} \\
\frac{x^2}{x^2} - \frac{1}{x^2} &= \frac{n}{x^2} + \frac{n^2x^2}{x^2}
\end{align}
I hope that clarifies your problem.


text:
Q: add UIImageView that covers navigation bar I think I'm missing something simple here. I need to create a semi-transparent UIImageView that covers the entire screen including the navigation toolbar. How do I do this?
This is what I'm trying to do ...

A: This is a possible solution:
UIImage *image=[UIImage imageNamed:@"whatever.png"];
UIImageView *overlay=[[UIImageView alloc] initWithImage:image];
overlay.alpha=0.5;
[[[[UIApplication sharedApplication] delegate] window] addSubview:overlay];

EDIT:

*

*It is likely that you would not be setting the alpha value for the overlay, but rather use a transparent PNG with embedded transparence levels. Still, it's a possibility.

*When not using ARC, you should [overlay release].

A: To focus the above answer a little bit, you just need to be clear on how views clip to what parts of the device's screen that they "own".
The key point is that in a navigation view, the Navigation bar itself is not part of your [myController view] - your view controller's view is everything below the bar and anything you do in that view clips to the rectangle below that bar.
The bar is, however, part of your [myAppDelegate window].  The window is essentially the entire screen of your device, while the views are sub portions responsible for managing their specific bounds.  So calling [[myAppDelegate window] addSubView:] will display above the bar where [[myViewController view] addSubView:] will not.


text:
Q: ASP.NET C# Get second column in gridview if checkbox is checked with Jquery I am facing this situation and have no idea how to solve it.
I have Gridview with this columns and this sample values:
CHECKBOX   NAME   SURNAME
-------------------------
Checkbox1  John   Smith
Checkbox2  Jerry  Rose
Checkobx3  Will   Mathews

I have a problem to get value from second column from dynamically created gridview where checkbox is checked. So I check Checkbox2 and now I want to get value from Name column for this row. In this case that would be "Jerry".
Also, if I checked Checkbox1 and Checkbox2 I want to get "John" and "Jerry" split by comma.
My code so far:
    $('#<%=GridView1.ClientID %> tbody >tr >td >input:checked').each(function () {
           alert($(this).find("td").eq(2).html());
      var values+=$(this).find("td").eq(2).html()+","; //values splitted by comma
    });

Below is my gridview code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSelected" runat="server"  />
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkBxHeader"
                            onclick="javascript:SelectAllCheckboxes1(this);" runat="server" />
                    </HeaderTemplate>
                </asp:TemplateField>

When I run this code results are just "undefined". What is wrong?
Please help me out.

A: Here is corrected JavaScript code:
var result = $('#<%=GridView1.ClientID %> tr td input[id*="chkSelected"][type=checkbox]:checked').map(function () {

    return $(this).closest('tr').find('td').eq(2).text();

    }).get().join();

Regards,
Uros


text:
Q: URL encoding for multibyte character string in c++ I am trying to achieve URL encoding for some of my strings via c++. Strings can contaim multibyte characters like ™, ®, ©, etc.
Input text: Something ™
Output should be: Something%20%E2%84%A2
I can achieve URL encode or decode in JS with encodeURIComponent and decodeURIComponent,
but I have some native code in c++ and hence need to encode some text via c++.
Any help here would be great relief for me.

A: It's not to hard to do manually, if you can't find a library. First encode the string as UTF-8 (there are other posts on SO about using the standard library to do that if the string is in another encoding) and then replace every character with a value above 127, and every one that's restricted in URLs, with the percent encoding of that character (A percent sign followed by the two hexadecimal digits representing the character's value).


text:
Q: ContentControl and its children - Same size? I guess this is a quite simple (read: very simple) question, but I have been using quite some time to figure it out.
I have a class, PresentationItem, which is derived from ContentControl. I am working in Expression Blend, which gives a problem with the height and width of the PresentationItem.
When I insert a PresentationItem, it automatically sizes too full grid (800x600). Then, when I insert for instance a textblock, the textblock sizes to something small. I think this is the normal and expected behaviour.
What I want, is the presentationitem and Content child (for instance, a textblock) has the same size. It is annoying to work with 2 different sizes when I have several of these. So either the content inside the presentationitem should be stretched, or the presentationitem should resize to fit its children.
(Also, using something else than a ContentControl is not an option).
Right now I have the following style:
 <Style TargetType="local:JSLDPresentationItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:JSLDPresentationItem">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="PresentationStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0:0:0.3"/>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="FocusedPresenting">
                                <Storyboard>
                                    <DoubleAnimation  Duration="0" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="LocalLayoutPanel" />
                                    <DoubleAnimation Duration="0" To="1.2" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="LocalLayoutPanel" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="AfterPresenting">
                                <Storyboard>
                                    <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LocalLayoutPanel" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="BeforePresenting">
                                <Storyboard>
                                    <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LocalLayoutPanel" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="UnfocusedPresenting"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>

                    <Grid x:Name="LocalLayoutPanel" Margin="0,0,0,0" VerticalAlignment="Top"   >

                        <Grid.RenderTransform>
                            <CompositeTransform/>
                        </Grid.RenderTransform>
                        <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" />
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

What to change and where? I guess it is some "*" or "auto" at the right place!

A: Try setting the HorizontalContentAlignment and VerticalContentAlignment of your derived control to Stretch.


text:
Q: Override element.style in Wordpress (CSS) I try to edit the height of a logo in mobile version of the site.
What I figured out is that I need mobile height to be 50% and when I inspect it it shows 100%

    @media only screen and (min-width: 1000px)
    header.centered_logo .q_logo {
    height: 50% !important;

    .q_logo {
    height: 50% !important;

I have tried to edit css but without any success.

A: Your code shows a media query with styles which will be applied when the minimum width is 1000px.
You should change it to "max-width". Also, the CSS seems to be missing some curly brakets.
Try this:
@media only screen and (max-width: 1000px) {
   .q_logo a img {
       height: 50% !important;
   }
}

A: it is issue with your anchor tag, you won't be able to set the height of the image since the default display property of anchor tag is inline, you might need to change that to display:inline-block; for treating the image inside it like a block element.

A: You've to remove the inline css from html "style="height: 100%;"" after thar follow the given css.

@media only screen and (max-width: 1000px)
header .q_logo img.normal {
    display: block!important;
    opacity: 1!important;
    position: relative;
    max-width: 100%;
    margin: 0px;
}


text:
Q: What is an easy way to drain a laptop battery to 0? I need a way to kill my battery in my Ubuntu laptop. Is there any mind numbing tasks I can Ubuntu do that will eat up the battery? I have already shut off the power management options.
The battery is giving my issues and and someone said I should discharge it fully an recharge it from 0.

A: Run lots of Virtual Machines
Do a full ls -Rlath /
Try to find a string of text within every file on the disk
Fun full screen games

A: Simply run:
while :; do :; done

In a terminal.  That is an infinite do-nothing loop that will increase CPU usage to ~100% for one core.  You could repeat this 4 times in parallel if you have a quad-core processor, but on the few laptops I've tested this on, it hasn't increased battery drain.
In addition:  Increase screen brightness to full, blast music at max volume, ensure WiFi is on, and plug in as many power draining USB devices as you can:  Phones, hard drives, etc.
This should kill most laptops in under 2 hours.

A: apt-get install stress - a utility specifically designed for testing CPU and other functions.  You can use it to peg your CPU at 100% usage until the battery dies.
I'm not sure what options exist to peg GPU usage at 100%.
You should drop to runlevel 1 and dismount all volumes possible since your system will not shutdown smoothly.

A: To find out how long it actually ran, I tend do start this little bash script, then start a 10-hour Youtube video or the like (modern browsers like Firefox often disable power management when playing videos):
while true
do
  date >> test.log
  sync
  sleep 60
done

This will write a timestamp to "test.log" every minute and assure it gets written to disc, so I can check how long the system ran afterwards.

A: Try fork bomb in shell:
:(){ :|: & };:

however you've big changes to crash your laptop instead, so run at your own risk. I'm sure it'll keep your laptop busy until the battery is dead.


text:
Q: How to continuously monitor the directory using inotifyd on an android device I need to watch a directory on an android device(e.g /sdcard). I need to log any actions occurred at /sdcard. For example, if an app creates file or directory at /sdcard, I would like to log a name of application and event, that occurred, into a file.
I searched on google about the command to watch a directory. I found that I can use "inotifyd" command. I really do not know how I can use it. I don't find clear an example of how to use this command
Does anyone helps me to understand this command, how does work?

A: On my phone, inotifyd spits out this usage:

usage: inotifyd PROG FILE[:MASK] ...

When a filesystem event matching MASK occurs to a FILE, run PROG as:
  PROG EVENTS FILE [DIRFILE]

If PROG is "-" events are sent to stdout.

This file is:
  a  accessed    c  modified    e  metadata change  w  closed (writable)
  r  opened      D  deleted     M  moved            0  closed (unwritable)
  u  unmounted   o  overflow    x  unwatchable

A file in this directory is:
  m  moved in    y  moved out   n  created          d  deleted

When x event happens for all FILEs, inotifyd exits (after waiting for PROG).

With some testing, I found this to works for me:
inotifyd - /sdcard/myfile.txt

This will then, for example, spit out e  /sdcard/myfile.txt if I run touch /sdcard/myfile.txt.
If you want to log the changes to a file instead, you can use:
inotifyd - /sdcard/myfile.txt >/sdcard/changes.log 2>&1

To instead call a script when changes occur, you can use:
inotifyd myscript.sh /sdcard/myfile.txt