问:
How to install cvxopt for Python 3.5 on Windows 7
I recently updated to python 3.5.0 and want to install cvxopt, so far without luck. So I tried python 2.7 and following the instructions here i installed mingw (4.9.3) and built blas and lapack from source without issue.
When I run

```<code> python setup.py build --compiler=mingw32
</code>```

I get the following output:

```<code>running build
running build_py
running build_ext
building 'base' extension
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/base.c -o build\temp.win32-2.7\Release\src\c\base.o
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/dense.c -o build\temp.win32-2.7\Release\src\c\dense.o
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/sparse.c -o build\temp.win32-2.7\Release\src\c\sparse.o
src/C/sparse.c: In function 'sparse_concat':
src/C/sparse.c:368:30: warning: variable 'blk_ncols' set but not used [-
but-set-variable]
         int_t blk_nrows = 0, blk_ncols = 0;
                              ^
writing build\temp.win32-2.7\Release\src\c\base.def
C:\minGW\bin\dllwrap.exe -mdll -static --entry _DllMain@12 --output-lib
mp.win32-2.7\Release\src\c\libbase.a --def build\temp.win32-2.7\Release\
se.def -s build\temp.win32-2.7\Release\src\c\base.o build\temp.win32-2.7
\src\c\dense.o build\temp.win32-2.7\Release\src\c\sparse.o -Lsrc -LC:\Py
ibs -LC:\Python27\PCbuild -LC:\Python27\PC\VS9.0 -lm -llapack -lblas -lg
-lpython27 -lmsvcr90 -o build\lib.win32-2.7\cvxopt\base.pyd
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0xbb): undefined reference to `signbitq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0xe7): undefined reference to `finiteq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0x314): undefined reference to `finiteq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0x7f2): undefined reference to `isnanq'
collect2.exe: error: ld returned 1 exit status
dllwrap: gcc exited with status 1
error: command 'C:\\minGW\\bin\\dllwrap.exe' failed with exit status 1
</code>```

With 3.5 I use Anaconda. On this site they show how to install cvxopt via the conda command and when I try this, I get the Unknown MS Compiler version 1900 Error.
Using this "patch" the installation gets past that point, but ends in errors for all packages conda wants to install (output not included, because too long)

Is this a problem with version 3.5? Or mingw? Or the 64 bit anaconda? I'm trying to install VC15 to see if that changes things, but have really no clue where or what to look out for.

EDIT:
I still don't know what exactly causes the problem, but the binaries from this site, as suggested here work perfectly for Anaconda 64 bit and python 3.5 (though you have to uninstall numpy and scipy and use the version from the site)

As for as minGW is concerned, it might not work with python 3.5 yet, as suggested in a comment here and why 2.7 gave these fortran errors I can't say at all.

答:
it is a late reply and I see you already found a solution for your problem by installing the custom wheels. However I would like to point to another option for your specific problem. Since you are seemingly running python 3.5 with Anaconda there is a channel of rdonnelly who might help you out.

```<code>conda install -c rdonnelly cvxopt=1.1.9
</code>```

This solution is particularly handy for people not ready to install a custom numpy and scipy like myself, since they broke my python install twice. This was the only way I got cvxopt to run on my win64 py35 system. Note that this package is tailored for python 3.5 and the current Conda will install 3.6 by default. I chose to install an older release of Conda just for this purpose.

Body:
I recently updated to python 3.5.0 and want to install cvxopt, so far without luck. So I tried python 2.7 and following the instructions here i installed mingw (4.9.3) and built blas and lapack from source without issue.
When I run

 python setup.py build --compiler=mingw32

I get the following output:

running build
running build_py
running build_ext
building 'base' extension
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/base.c -o build\temp.win32-2.7\Release\src\c\base.o
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/dense.c -o build\temp.win32-2.7\Release\src\c\dense.o
C:\minGW\bin\gcc.exe -mdll -O -Wall -IC:\Python27\include -IC:\Python27\
c/C/sparse.c -o build\temp.win32-2.7\Release\src\c\sparse.o
src/C/sparse.c: In function 'sparse_concat':
src/C/sparse.c:368:30: warning: variable 'blk_ncols' set but not used [-
but-set-variable]
         int_t blk_nrows = 0, blk_ncols = 0;
                              ^
writing build\temp.win32-2.7\Release\src\c\base.def
C:\minGW\bin\dllwrap.exe -mdll -static --entry _DllMain@12 --output-lib
mp.win32-2.7\Release\src\c\libbase.a --def build\temp.win32-2.7\Release\
se.def -s build\temp.win32-2.7\Release\src\c\base.o build\temp.win32-2.7
\src\c\dense.o build\temp.win32-2.7\Release\src\c\sparse.o -Lsrc -LC:\Py
ibs -LC:\Python27\PCbuild -LC:\Python27\PC\VS9.0 -lm -llapack -lblas -lg
-lpython27 -lmsvcr90 -o build\lib.win32-2.7\cvxopt\base.pyd
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0xbb): undefined reference to `signbitq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0xe7): undefined reference to `finiteq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0x314): undefined reference to `finiteq'
c:/mingw/bin/../lib/gcc/mingw32/4.9.3\libgfortran.a(write.o):(.text$writ
0x7f2): undefined reference to `isnanq'
collect2.exe: error: ld returned 1 exit status
dllwrap: gcc exited with status 1
error: command 'C:\\minGW\\bin\\dllwrap.exe' failed with exit status 1

With 3.5 I use Anaconda. On this site they show how to install cvxopt via the conda command and when I try this, I get the Unknown MS Compiler version 1900 Error.
Using this "patch" the installation gets past that point, but ends in errors for all packages conda wants to install (output not included, because too long)

Is this a problem with version 3.5? Or mingw? Or the 64 bit anaconda? I'm trying to install VC15 to see if that changes things, but have really no clue where or what to look out for.

EDIT:
I still don't know what exactly causes the problem, but the binaries from this site, as suggested here work perfectly for Anaconda 64 bit and python 3.5 (though you have to uninstall numpy and scipy and use the version from the site)

As for as minGW is concerned, it might not work with python 3.5 yet, as suggested in a comment here and why 2.7 gave these fortran errors I can't say at all.

Body:
it is a late reply and I see you already found a solution for your problem by installing the custom wheels. However I would like to point to another option for your specific problem. Since you are seemingly running python 3.5 with Anaconda there is a channel of rdonnelly who might help you out.

conda install -c rdonnelly cvxopt=1.1.9

This solution is particularly handy for people not ready to install a custom numpy and scipy like myself, since they broke my python install twice. This was the only way I got cvxopt to run on my win64 py35 system. Note that this package is tailored for python 3.5 and the current Conda will install 3.6 by default. I chose to install an older release of Conda just for this purpose.


来源: stackexchange

问:
onclick function not executing to change image
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

```<code>function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}
</code>```

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.

答:
You had a typo. When defining an inline onclick you have written:

```<code><div onclick()="changeImage()"></div>
</code>```

It should be:

```<code><div onclick="changeImage()"></div>
</code>```

See snippet below:

function changeImage() {

        if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
        {
            document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
        }
        else
        {
            document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
   height: 25px;
      padding-right: 4px;
  }
  li {
   margin: 4px;
      clear: both;
  }
  li:nth-child(odd) {
   background: #f0f0f5;
  }</code>```

Username

```

ContentLicense: CC BY-SA 3.0

Body:
In the following codepen I'm trying to change the image of an image with id="chrome" using JavaScript but it does not appear to be doing anything. What am I doing wrong and how do I fix. Thank you in advanced.

The first image has an id of chrome and when clicked I'm trying to change the image.

https://codepen.io/centem/pen/NgKEmG

Here is the js I'm using.

function changeImage() {

    if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
    {
        document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
    }
    else
    {
        document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
    }
}

Basically, for the first row that has an chrome icon I would like to change it to an x image upon click.

Body:
You had a typo. When defining an inline onclick you have written:

<div onclick()="changeImage()"></div>

It should be:

<div onclick="changeImage()"></div>

See snippet below:

function changeImage() {

        if (document.getElementById("chrome").src == "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png")
        {
            document.getElementById("chrome").src = "https://www.centerpointe.com/v2/wp-content/uploads/2014/01/red-x.png";
        }
        else
        {
            document.getElementById("chrome").src = "https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png";
        }
    }

img {
   height: 25px;
      padding-right: 4px;
  }
  li {
   margin: 4px;
      clear: both;
  }
  li:nth-child(odd) {
   background: #f0f0f5;
  }

<ul class="list-unstyled">
    <li>Username<span class="pull-right">
          <img onclick="changeImage()" id ="chrome" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png"></span><span class="pull-right"><img id="firefox" src="http://pngimg.com/uploads/firefox/firefox_PNG16.png"></span><span class="pull-right">
          <img id="ie" src="https://ma.ttias.be/wp-content/uploads/2015/07/internet-explorer-logo.png"></span></li>

   </ul>


问:
hibernate annotation config in tomee : Missing required persistence.xml
I'm trying to run Spring mvc annotation config with Tomee.
I dont have any xml config in my project, but i have got

Missing required persistence.xml

this is my config file

```<code>@EnableTransactionManagement
@Configuration
@EnableWebMvc
@ComponentScan({"controller","service","model"})
public class AppConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver configureViewResolvers() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver ;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[]{"model"});
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/e");
        dataSource.setUsername("postgres");
        dataSource.setPassword("admin");
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private final Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto","create");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        return properties;
    }
}
</code>```

and stack trace

```<code>31-May-2017 16:52:39.386 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults FAIL ... EE-System-0.8.0:   Missing required persistence.xml for @PersistenceContext ref "java:comp/env/aa" to unit ""
31-May-2017 16:52:39.387 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults Invalid EjbModule(name=EE-System-0.8.0, path=D:\ee-system\ear\target\ear-1.0-SNAPSHOT\EE-System-0.8.0)
31-May-2017 16:52:39.388 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults FAIL ... ee:    Missing required persistence.xml for @PersistenceContext ref "java:comp/env/aa" to unit ""
31-May-2017 16:52:39.390 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults Invalid WebModule(name=EE-System-0.8.0, path=D:\ee-system\ear\target\ear-1.0-SNAPSHOT\EE-System-0.8.0)
31-May-2017 16:52:39.391 INFO [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.deploy Set the 'openejb.validation.output.level' system property to VERBOSE for increased validation details.
31-May-2017 16:52:39.881 SEVERE [http-nio-8080-exec-4] org.apache.openejb.assembler.DeployerEjb.deploy Can't deploy D:\ee-system\ear\target\ear-1.0-SNAPSHOT.ear
 org.apache.openejb.config.ValidationFailedException: Module failed validation. AppModule(name=ear-1.0-SNAPSHOT)
    at org.apache.openejb.config.ReportValidationResults.deploy(ReportValidationResults.java:88)
    at org.apache.openejb.config.AppInfoBuilder.build(AppInfoBuilder.java:321)
    at org.apache.openejb.config.ConfigurationFactory.configureApplication(ConfigurationFactory.java:1040)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:244)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.security.internal.InternalSecurityInterceptor.invoke(InternalSecurityInterceptor.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
    at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
    at org.apache.openejb.core.singleton.SingletonContainer._invoke(SingletonContainer.java:256)
    at org.apache.openejb.core.singleton.SingletonContainer.invoke(SingletonContainer.java:212)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbObject_BUSINESS_METHOD(EjbRequestHandler.java:371)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:182)
    at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:360)
    at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:247)
    at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:104)
    at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:60)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

any idea and help appreciated.

答: if your application doesn't use EE maybe just add in conf/exclusions.list the prefix of your jars (like myapp-) to exclude it and avoid the container to scan your spring code and analyzis it in a EE fashion.</p>

Body:
I'm trying to run Spring mvc annotation config with Tomee.
I dont have any xml config in my project, but i have got

Missing required persistence.xml

this is my config file

@EnableTransactionManagement
@Configuration
@EnableWebMvc
@ComponentScan({"controller","service","model"})
public class AppConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver configureViewResolvers() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver ;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[]{"model"});
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/e");
        dataSource.setUsername("postgres");
        dataSource.setPassword("admin");
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private final Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto","create");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        return properties;
    }
}

and stack trace

31-May-2017 16:52:39.386 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults FAIL ... EE-System-0.8.0:   Missing required persistence.xml for @PersistenceContext ref "java:comp/env/aa" to unit ""
31-May-2017 16:52:39.387 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults Invalid EjbModule(name=EE-System-0.8.0, path=D:\ee-system\ear\target\ear-1.0-SNAPSHOT\EE-System-0.8.0)
31-May-2017 16:52:39.388 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults FAIL ... ee:    Missing required persistence.xml for @PersistenceContext ref "java:comp/env/aa" to unit ""
31-May-2017 16:52:39.390 SEVERE [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.logResults Invalid WebModule(name=EE-System-0.8.0, path=D:\ee-system\ear\target\ear-1.0-SNAPSHOT\EE-System-0.8.0)
31-May-2017 16:52:39.391 INFO [http-nio-8080-exec-4] org.apache.openejb.config.ReportValidationResults.deploy Set the 'openejb.validation.output.level' system property to VERBOSE for increased validation details.
31-May-2017 16:52:39.881 SEVERE [http-nio-8080-exec-4] org.apache.openejb.assembler.DeployerEjb.deploy Can't deploy D:\ee-system\ear\target\ear-1.0-SNAPSHOT.ear
 org.apache.openejb.config.ValidationFailedException: Module failed validation. AppModule(name=ear-1.0-SNAPSHOT)
    at org.apache.openejb.config.ReportValidationResults.deploy(ReportValidationResults.java:88)
    at org.apache.openejb.config.AppInfoBuilder.build(AppInfoBuilder.java:321)
    at org.apache.openejb.config.ConfigurationFactory.configureApplication(ConfigurationFactory.java:1040)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:244)
    at org.apache.openejb.assembler.DeployerEjb.deploy(DeployerEjb.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.security.internal.InternalSecurityInterceptor.invoke(InternalSecurityInterceptor.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
    at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
    at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
    at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
    at org.apache.openejb.core.singleton.SingletonContainer._invoke(SingletonContainer.java:256)
    at org.apache.openejb.core.singleton.SingletonContainer.invoke(SingletonContainer.java:212)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.doEjbObject_BUSINESS_METHOD(EjbRequestHandler.java:371)
    at org.apache.openejb.server.ejbd.EjbRequestHandler.processRequest(EjbRequestHandler.java:182)
    at org.apache.openejb.server.ejbd.EjbDaemon.processEjbRequest(EjbDaemon.java:360)
    at org.apache.openejb.server.ejbd.EjbDaemon.service(EjbDaemon.java:247)
    at org.apache.openejb.server.ejbd.EjbServer.service(EjbServer.java:104)
    at org.apache.openejb.server.httpd.ServerServlet.service(ServerServlet.java:60)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

any idea and help appreciated.


问:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?
I have a string like:

```<code> SomeCamel WasEnteringText
</code>```

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

```<code>    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;
</code>```

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

```<code>$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Which gets it done but seems excessive. Works though.

答:
```<code>s/(?<!^)[A-Z][a-z]*+(?!\s+)\K/ /g;
</code>```

And the less "screw this horsecrap" version:

```<code>s/
 (?<!^)          #Something not following the start of line,
    [A-Z][a-z]*+ #That starts with a capital letter and is followed by
                 #Zero or more lowercased letters, not giving anything back,
 (?!\s+)          #Not followed by one or more spaces,
\K               #Better explained here [1]
/ /gx;            #"Replace" it with a space.
</code>```

EDIT: I noticed that this also adds extra whitespace when you add punctuation into the mix, which probably isn't what the OP wants; thankfully, the fix is simply changing the negative look ahead from \s+ to \W+. Although now I'm beginning to wonder why I actually added those pluses. Drats, me!

EDIT2: Erm, apologies, originally forgot the /g flag.

EDIT3: Okay, someone downvote me. I went retarded. No need for the negative lookbehind for ^ - I really dropped the ball on this one. Hopefully fixed:

```<code>s/[A-Z][a-z]*+(?!\W)\K/ /gx;
</code>```

1: http://perldoc.perl.org/perlre.html

Body:
I have a string like:

 SomeCamel WasEnteringText

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;

Which gets it done but seems excessive. Works though.

Body:
s/(?<!^)[A-Z][a-z]*+(?!\s+)\K/ /g;

And the less "screw this horsecrap" version:

s/
 (?<!^)          #Something not following the start of line,
    [A-Z][a-z]*+ #That starts with a capital letter and is followed by
                 #Zero or more lowercased letters, not giving anything back,
 (?!\s+)          #Not followed by one or more spaces,
\K               #Better explained here [1]
/ /gx;            #"Replace" it with a space.

EDIT: I noticed that this also adds extra whitespace when you add punctuation into the mix, which probably isn't what the OP wants; thankfully, the fix is simply changing the negative look ahead from \s+ to \W+. Although now I'm beginning to wonder why I actually added those pluses. Drats, me!

EDIT2: Erm, apologies, originally forgot the /g flag.

EDIT3: Okay, someone downvote me. I went retarded. No need for the negative lookbehind for ^ - I really dropped the ball on this one. Hopefully fixed:

s/[A-Z][a-z]*+(?!\W)\K/ /gx;

1: http://perldoc.perl.org/perlre.html

ContentLicense: CC BY-SA 2.5


问:
CopyOnWriteArraySet is too slow
When I ran the following program, it took around 7 to 8 minutes to execute. I am really not sure where I am mistaken as this program is taking so much time to execute.

```<code>public class Test {
            public static void main(String[] args) {
            final Integer[] a= new Integer[1000000];
            for (int i=0; i < a.length; i++) {
                a[i] = i;
            }
            final List<Integer> source = Arrays.asList(a);
            final Set<Integer> set = new CopyOnWriteArraySet<Integer>(source);
        }
    }
</code>```

Can some one help me understand, why this program is too slow.

My machine is Core I7  with 4GB RAM

答:
I have tested and indeed with a List of 1 000 000 elements provided to the constructor, it takes a good time (7 minutes).

It is a referenced issue on Open JDK the 2013-01-09 :

JDK-8005953 - CopyOnWriteArraySet copy constructor is unusable for large collections

The problem would cause by the CopyOnWriteArrayList#addAllAbsent() method invoked by the CopyOnWriteArraySet constructor.

Extract of the issue :

CopyOnWriteArraySet's copy constructor is too slow for large
  collections. It takes over 10 minutes on a developer laptop with just
  1 million entries in the collection to be copied...

As resolution status, you can read : Won't Fix.

And you can read as last message :

addAllAbsent can be made faster for larger input, but it would impact
  the performance for small sizes.  And it's documented that
  CopyOnWriteXXX classes are better suited for collections of small
  sizes.

The CopyOnWriteArraySet javadoc specifies indeed this point :

It is best suited for applications in which set sizes generally stay
  small, read-only operations vastly outnumber mutative operations, and
  you need to prevent interference among threads during traversal.

Title: CopyOnWriteArraySet is too slow

Body:
When I ran the following program, it took around 7 to 8 minutes to execute. I am really not sure where I am mistaken as this program is taking so much time to execute.

public class Test {
            public static void main(String[] args) {
            final Integer[] a= new Integer[1000000];
            for (int i=0; i < a.length; i++) {
                a[i] = i;
            }
            final List<Integer> source = Arrays.asList(a);
            final Set<Integer> set = new CopyOnWriteArraySet<Integer>(source);
        }
    }

Can some one help me understand, why this program is too slow.

My machine is Core I7  with 4GB RAM


问:
Getting a cx ID for custom search, Google API - Python
How can I get a generic cx ID for using the custom search API in Python?
http://code.google.com/p/google-api-python-client/source/browse/samples/customsearch/main.py

From what I have read I understand that this cx ID is for certain sites only(when creating a custom search engine it asks me for specific sites), but I want it to search on google, so I can get the first 3-5 results from a google-search.

So I want to search on GOOGLE using Custom Search API, I already got a Developer Key, I just need to find how can I get an cx ID for searching on google, not a personal site, or something like that.

答:
As of 2017 (this may be outdated in the future), here are the steps:

1) After getting the API key (under Custom Search API) here

2) Head to CSE home

3) Click on Add below Edit Search Engine

4) You'll get a search box, type in www.google.com and then click on Create at the bottom

5) You'll get your cx code (called Search Engine ID) to use with your API key

ContentLicense: CC BY-SA 4.0


问:
Tables: How to achieve “normal” td widths, but 100% table width?
On our site we have tables containing data. We like the column widths we get with a normal table, but we like the border-bottom of tds to stretch the entire width of the page like we get with CSS: table { width:100% }, as can be seen on a demo table widths page, which renders like this:

Is it possible to achieve the same column widths as with a normal (non-width-100%) table in a table where the border-bottom stretches the entire width?

And no, td { white-space: nowrap } in combination with an extra width: 100% td (see the link above) is not good, as sometimes the tds are long and so we want the tds to wrap exactly like in a normal table.

We need a solution that works in at least IE6-8 + FF.

Btw, is there a better way (tm) of showing HTML snippets than linking to an external page? I can show just source, but having HTML rendered too is very illustrative.

This was originally posted on Webmasters, but following a suggestion there, I now (re)post it here.

答:
You can use the new CSS properties min-width and max-width to bound the columns sizes without setting them explicitly.

To get a proportional version of what would be rendered when the table's width is not specified, I think you'd have to let it render normally (remove your table width setting) and then use javascript to read the column widths and resize.

Pulled this example of using jQuery to syncronize the column widths of two tables from another question:

```<code>$("#t1").width($("#t2").width());
$("#t1 tr td").each(function (i){
       $(this).width($($("#t2 tr:first td")[i]).width());
})
</code>```

Should be a pretty good starting point for scaling your column widths.

Body:
You can use the new CSS properties min-width and max-width to bound the columns sizes without setting them explicitly.

To get a proportional version of what would be rendered when the table's width is not specified, I think you'd have to let it render normally (remove your table width setting) and then use javascript to read the column widths and resize.

Pulled this example of using jQuery to syncronize the column widths of two tables from another question:

$("#t1").width($("#t2").width());
$("#t1 tr td").each(function (i){
       $(this).width($($("#t2 tr:first td")[i]).width());
})

Should be a pretty good starting point for scaling your column widths.


问:
iOS - Filter array of objects which contains today's date only
Basically my challenge is :

I got an array of objects . Each object has a date property .
I want to get the array of objects which matches today's date.

So, I want to group the array based on date.

I want to show in history list by grouping objects from today, yesterday, last 7 days ,.....

I can sort array using sort function:

```<code>historylist.sort(by: {$0.createdDate! as Date > $1.createdDate! as Date })
</code>```

But I need a filter function based on date.
I want all the data in historicist which are created today only.

Any quick pseudo code .

Thanks.

答:
Demo of how this works with filtering date objects:

```<code>let d1 = Date().addingTimeInterval(22000000)
let d2 = Date().addingTimeInterval(23000000)
let d3 = Date().addingTimeInterval(30000000)
let dates = [d1, d2, d3, Date(), Date()]

let calendar = Calendar.current
let todayDates = dates.filter({calendar.isDateInToday($0 as Date)})
print(todayDates) // [2017-06-03 15:50:11 +0000, 2017-06-03 15:50:11 +0000]
</code>```

So in your case you should do it like this:

```<code>let todayDates = historylist.filter({calendar.isDateInToday($0.createdDate as Date)})
</code>```

Update:

To convert a string to a Date use the following:

```<code>extension String {
    var toDate: Date {
        return Date.Formatter.customDate.date(from: self)!
    }
}

extension Date {
    struct Formatter {
        static let customDate: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "MM-dd-yyyy hh:mm:ss a"
            return formatter
        }()
    }
}

let strDate = "06-01-2017 09:32:48 PM"
let date = strDate.toDate
</code>```

Body:
Basically my challenge is :

I got an array of objects . Each object has a date property .
I want to get the array of objects which matches today's date.

So, I want to group the array based on date.

I want to show in history list by grouping objects from today, yesterday, last 7 days ,.....

I can sort array using sort function:

historylist.sort(by: {$0.createdDate! as Date > $1.createdDate! as Date })

But I need a filter function based on date.
I want all the data in historicist which are created today only.

Any quick pseudo code .

Thanks.

Body:
Demo of how this works with filtering date objects:

let d1 = Date().addingTimeInterval(22000000)
let d2 = Date().addingTimeInterval(23000000)
let d3 = Date().addingTimeInterval(30000000)
let dates = [d1, d2, d3, Date(), Date()]

let calendar = Calendar.current
let todayDates = dates.filter({calendar.isDateInToday($0 as Date)})
print(todayDates) // [2017-06-03 15:50:11 +0000, 2017-06-03 15:50:11 +0000]

So in your case you should do it like this:

let todayDates = historylist.filter({calendar.isDateInToday($0.createdDate as Date)})

Update:

To convert a string to a Date use the following:

extension String {
    var toDate: Date {
        return Date.Formatter.customDate.date(from: self)!
    }
}

extension Date {
    struct Formatter {
        static let customDate: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "MM-dd-yyyy hh:mm:ss a"
            return formatter
        }()
    }
}

let strDate = "06-01-2017 09:32:48 PM"
let date = strDate.toDate


答: Instead of onclick()="changeImage()";.... Use onclick="changeImage()".....Remove "()" bracket in onclick function

Title: onclick function not executing to change image


答:
```<code>let date1 = NSDate()
let date2 = NSDate()
let dates = [date1, date2]

let calendar = NSCalendar.currentCalendar()
let todayDates = dates.filter({calendar.isDateInToday($0)})
</code>```

Title: iOS - Filter array of objects which contains today's date only


问:
Running rake routes on Rails 5 giving instantiation error
I'm trying to setup a barebones Rails app. So far I have generated a sample Article model, added some records to the database, edited my routes config to the following:

```<code>Rails::Application.routes.draw do
  resources :articles
end
</code>```

But when I run bin/rake routes, bundle exec rake routes, and just rake routes I receive the following error:

```<code>$ bin/rake routes                                                                                (articles-controller✱)
rake aborted!
Rails::Application is abstract, you cannot instantiate it directly.
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:206:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/engine.rb:434:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:124:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:162:in `new'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:162:in `instance'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:95:in `instance'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:184:in `method_missing'
/Users/sam/turing/2module/personal_work/projects/blogger/config/routes.rb:1:in `<top (required)>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `block in load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:258:in `load_dependency'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `block in load_paths'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `each'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `load_paths'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:18:in `reload!'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:41:in `block in updater'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/file_update_checker.rb:81:in `call'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/file_update_checker.rb:81:in `execute'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:42:in `updater'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:31:in `execute_if_updated'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/finisher.rb:128:in `block in <module:Finisher>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:30:in `instance_exec'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:30:in `run'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:59:in `block in run_initializers'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:58:in `run_initializers'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:353:in `initialize!'
/Users/sam/turing/2module/personal_work/projects/blogger/config/environment.rb:5:in `<top (required)>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:329:in `require'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:329:in `require_environment!'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:445:in `block in run_tasks_blocks'
Tasks: TOP => routes => environment
(See full trace by running task with --trace)
</code>```

Any ideas? All of my gems are up to date using bundle update

答: Oops, looks like the syntax for the routes.rb file is a bit different in Rails 5. For anyone else with this issue, the syntax for the do block is Rails.application.routes.draw do, not Rails::Application.routes.draw do

Body:
I'm trying to setup a barebones Rails app. So far I have generated a sample Article model, added some records to the database, edited my routes config to the following:

Rails::Application.routes.draw do
  resources :articles
end

But when I run bin/rake routes, bundle exec rake routes, and just rake routes I receive the following error:

$ bin/rake routes                                                                                (articles-controller✱)
rake aborted!
Rails::Application is abstract, you cannot instantiate it directly.
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:206:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/engine.rb:434:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:124:in `initialize'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:162:in `new'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:162:in `instance'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:95:in `instance'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/railtie.rb:184:in `method_missing'
/Users/sam/turing/2module/personal_work/projects/blogger/config/routes.rb:1:in `<top (required)>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `block in load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:258:in `load_dependency'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/dependencies.rb:286:in `load'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `block in load_paths'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `each'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:55:in `load_paths'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:18:in `reload!'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:41:in `block in updater'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/file_update_checker.rb:81:in `call'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/activesupport-5.1.1/lib/active_support/file_update_checker.rb:81:in `execute'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:42:in `updater'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/routes_reloader.rb:31:in `execute_if_updated'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application/finisher.rb:128:in `block in <module:Finisher>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:30:in `instance_exec'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:30:in `run'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:59:in `block in run_initializers'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/initializable.rb:58:in `run_initializers'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:353:in `initialize!'
/Users/sam/turing/2module/personal_work/projects/blogger/config/environment.rb:5:in `<top (required)>'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:329:in `require'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:329:in `require_environment!'
/Users/sam/.rvm/gems/ruby-2.2.6/gems/railties-5.1.1/lib/rails/application.rb:445:in `block in run_tasks_blocks'
Tasks: TOP => routes => environment
(See full trace by running task with --trace)

Any ideas? All of my gems are up to date using bundle update


问:
Ignoring empty cells in a chart VBA
I created a macro that results in a set of two columns and 0 to x rows.(x=number of rows in raw data). I'm plotting a chart with the next line of code.

```<code>Set MyChart = Sheet3.Shapes.AddChart(xlColumnClustered).Chart
MyChart.SetSourceData Source:=Sheet2.Range("$A$1:$A$10,$b$1:$b$10")
</code>```

This will plot just the Top 10 data .The problem is that there are cases where I have less than 10 rows. So, is there a way to make VBA to ignore empty pair of cells under the last data cell?

Update1:
I need to use a colum chart and I'm deleting any past chart in the sheet and adding a new one
Thanks.

答:
```<code>Sub test()
        Dim MyChart As Chart
        Dim Ws As Worksheet

        Set Ws = Sheet3
        With Ws
            If .ChartObjects.Count > 0 Then
                .ChartObjects.Delete
            End If

            Set MyChart = .Shapes.AddChart(xlColumnClustered).Chart
            MyChart.SetSourceData Source:=Sheet2.Range("a1").CurrentRegion
        End With
    End Sub
</code>```

Title: Ignoring empty cells in a chart VBA

Body:
I created a macro that results in a set of two columns and 0 to x rows.(x=number of rows in raw data). I'm plotting a chart with the next line of code.

Set MyChart = Sheet3.Shapes.AddChart(xlColumnClustered).Chart
MyChart.SetSourceData Source:=Sheet2.Range("$A$1:$A$10,$b$1:$b$10")

This will plot just the Top 10 data .The problem is that there are cases where I have less than 10 rows. So, is there a way to make VBA to ignore empty pair of cells under the last data cell?

Update1:
I need to use a colum chart and I'm deleting any past chart in the sheet and adding a new one
Thanks.


问:
Python class calling function that belongs to same class
I am trying to call function that belongs to same function. Below is the code

```<code>class Asrconfig():
    def __init__(self, hostname, net_username, net_password):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def connect(self, cmd):
        print "connect"
        self.cmd = cmd
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username,
            password=self.net_password,look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        buff = ''
        remote_conn.send(cmd)
        while not buff.endswith('#'):
            resp = remote_conn.recv(9999)
            buff += resp
            print resp
    def inventory(self, cmd):
        cmd = "show inventory"
        self.connect(cmd)
asr = Asrconfig(hostname, net_username, net_password)
asr.inventory()
</code>```

I am getting below output when I run the output:

```<code>RP#
Traceback (most recent call last):
  File "onboard/testpara1.py", line 43, in <module>
    asr.inventory()
TypeError: inventory() takes exactly 2 arguments (1 given)
</code>```

I need below help

I am not able to call connect function in class Asrconfig under inventory function.

答:
Rewrite your inventory method like this:

```<code>def inventory(self, cmd="show inventory"):
    self.connect(cmd)
</code>```

Body:
I am trying to call function that belongs to same function. Below is the code

class Asrconfig():
    def __init__(self, hostname, net_username, net_password):

        ''' SSH connection Establish '''
        self.hostname = hostname
        self.net_username = net_username
        self.net_password = net_password
    def connect(self, cmd):
        print "connect"
        self.cmd = cmd
        self.remote_conn_pre = paramiko.SSHClient()
        self.remote_conn_pre.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        self.remote_conn_pre.connect(self.hostname, username=self.net_username,
            password=self.net_password,look_for_keys=False, allow_agent=False)
        self.remote_conn = self.remote_conn_pre.invoke_shell()
        buff = ''
        remote_conn.send(cmd)
        while not buff.endswith('#'):
            resp = remote_conn.recv(9999)
            buff += resp
            print resp
    def inventory(self, cmd):
        cmd = "show inventory"
        self.connect(cmd)
asr = Asrconfig(hostname, net_username, net_password)
asr.inventory()

I am getting below output when I run the output:

RP#
Traceback (most recent call last):
  File "onboard/testpara1.py", line 43, in <module>
    asr.inventory()
TypeError: inventory() takes exactly 2 arguments (1 given)

I need below help

I am not able to call connect function in class Asrconfig under inventory function.

Body:
Rewrite your inventory method like this:

def inventory(self, cmd="show inventory"):
    self.connect(cmd)


问:
How do I get the AD Kerberos ticket lifetime using .NET?
How do I get the ticket lifetime from the Active Directory Kerberos Policy? Basically, I need to access the values found here: Computer Configuration > Policy > Windows Settings > Security Settings > Account Policies > Kerberos Policy.

(in both Windows Serve 2003 and Windows Serve 2008)

答:
This can be done using WMI.  Specifically in .NET you'll want to use WMI.NET.  To find the specific value you're looking for I recommend that you use this tool:

http://thepowershellguy.com/blogs/posh/archive/2007/03/22/powershell-wmi-explorer-part-1.aspx

This allows you to browse the CIMV2 root and futz with the query until you're sure you've got it correct, then you can just paste the query into your WMI.NET code.

It'll look something like this:

```<code>WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery);

foreach (ManagementObject disk in searcher.Get())
{
  Console.WriteLine(disk.ToString());
}
</code>```

Body:
This can be done using WMI.  Specifically in .NET you'll want to use WMI.NET.  To find the specific value you're looking for I recommend that you use this tool:

http://thepowershellguy.com/blogs/posh/archive/2007/03/22/powershell-wmi-explorer-part-1.aspx

This allows you to browse the CIMV2 root and futz with the query until you're sure you've got it correct, then you can just paste the query into your WMI.NET code.

It'll look something like this:

WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery);

foreach (ManagementObject disk in searcher.Get())
{
  Console.WriteLine(disk.ToString());
}


问:
Converting a input (Password) into MD5
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

```<code>import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()
</code>```

The error is:

```<code>AttributeError: '_hashlib.HASH' object has no attribute 'encode'
</code>```

答:
Perhaps something like following:</p>

```<code>import hashlib

def PasswordCreate():
    password = raw_input(str("Please enter a password next to this text: "))
    return hashlib.md5(password).hexdigest()

PasswordCreate()
</code>```

Title: Converting a input (Password) into MD5

Body:
Hi I'm a bit new to this and can't exactly figure out how to get it working.

Here is my current code:

import hashlib

def PasswordCreate():
    password = input(str("Please enter a password next to this text"))
    password = hashlib.md5()
    password.update(password.encode('utf-8'))
    return password.hexdigest()

PasswordCreate()

The error is:

AttributeError: '_hashlib.HASH' object has no attribute 'encode'

Body:
Perhaps something like following:

import hashlib

def PasswordCreate():
    password = raw_input(str("Please enter a password next to this text: "))
    return hashlib.md5(password).hexdigest()

PasswordCreate()


问:
Update self variable within __init__ everytime it is called in python
I want a self variable within init to update every time it is called  e.g. every time I execute Data(10).plot, self.plot should reinitialise by parsing the self.n to the Plot class.

```<code>class Data(object):
    def __init__(self, n):
        self.n = n
        self.plot = Plot(self.n)

    def minus(self, x):
        self.n -= x
        return self.n

class Plot(object):
    def __init__(self, n):
        self.n = n

    def double(self):
        return self.n * 2
</code>```

Another example: When I execute the following code, I want the answer variable to equal 16. Instead it equals 20. How do I implement this behaviour within the above classes?

```<code>data = Data(10)
data.minus(2)
answer = vcf.plot.double())
</code>```

答:
You don't need n in the Data-object:

```<code>class Data(object):
    def __init__(self, n):
        self.plot = Plot(n)

    def minus(self, x):
        self.plot.n -= x

class Plot(object):
    def __init__(self, n):
        self.n = n

    def double(self):
        return self.n * 2
</code>```

Body:
I want a self variable within init to update every time it is called  e.g. every time I execute Data(10).plot, self.plot should reinitialise by parsing the self.n to the Plot class.

class Data(object):
    def __init__(self, n):
        self.n = n
        self.plot = Plot(self.n)

    def minus(self, x):
        self.n -= x
        return self.n

class Plot(object):
    def __init__(self, n):
        self.n = n

    def double(self):
        return self.n * 2

Another example: When I execute the following code, I want the answer variable to equal 16. Instead it equals 20. How do I implement this behaviour within the above classes?

data = Data(10)
data.minus(2)
answer = vcf.plot.double())

Body:
You don't need n in the Data-object:

class Data(object):
    def __init__(self, n):
        self.plot = Plot(n)

    def minus(self, x):
        self.plot.n -= x

class Plot(object):
    def __init__(self, n):
        self.n = n

    def double(self):
        return self.n * 2


问:
WSUS clients missing from WSUS server database
I have a set of workstations set to use WSUS rather than windows update. Most update fine, however, in few cases, whilst client machines appear to contact the WSUS server fine, and download/apply updates, the WSUS summary does not list these IPs as ever having contacted the server.

As an example, one affected client machine shows, in windowsUpdate.log:

2017-06-03  15:57:27:352    1084     a8     Report  Uploading 2 events using cached cookie, reporting URL = http:///ReportingWebService/ReportingWebService.asmx

2017-06-03  15:57:27:367    1084     a8     Report  Reporter successfully uploaded 2 events.

However, the wsus_server in question shows no record of this client IP having contacted it...

Any ideas?

答:
Ah - it looked like this was the solution:

https://blogs.technet.microsoft.com/sus/2009/05/05/resolving-the-duplicate-susclientid-issue-or-why-dont-all-my-clients-show-up-in-the-wsus-console/

It fitted the symptoms perfectly...but on trial, the solution proposed didn't do the job...

Next idea?


问:
Multiply context menus on dynamically created elements
I'm trying to manage multiply menus by jquery contextmenu plugin
lackofcarma://github.com/mar10/jquery-ui-contextmenu
on dynamically created elements.

Here I have 2 buttons created dynamically and menus for them are created on left mouse click.

```<code><dic id="cont">  </div>
<script>
$(document).ready(function(){
  $('#cont').html('<button id="1">button #1</button> <button id="2">button #2</button>');

  $('button').on('click', function(e){
        var $target = $(e.target);
    var id = '#'+$target.attr('id');
    $(document).contextmenu({
      delegate: id, // #1 or #2
      menu: [{title:'Menu for'}, {title:id}]
    });
    alert('Created menu for button '+id);
    // now trying to show menu on left mouse click
    // as suggested by https://github.com/mar10/jquery-ui-contextmenu/wiki
    $('button').on('click', function(event){
      if ( event.which === 1 ) {  // left-click
        // Pass click event to `open()`
        $(document).contextmenu("open", event);
      }

      // just trigger event
      $('button').triggerHandler('contextmenu') ;

      // emulate mouse events
      $('button').trigger('mousedown',{button:2}).trigger("mouseup");

      // none  works..
    });
  });
});
</script>
</code>```

CodePen is here: https://codepen.io/zzmaster/pen/xrKvpm/

So first, left clicking Button #1 we create menu for it and then, right clicking the same button  we can see that menu.
Next, left clicking Button #2 we attach next menu to button 2 and expecting to see it on right mouse click.
But right click on button 2 doesn't work and we can see menu created for 2-nd button (second menu item show button id) on first button right click!

Next mission - I'd like to show menu by left click, not right. There's a code suggested on plugin's wiki page, but it doesn't work. Also I try to emulate events - successless.

I'm totally frustrated...

答:
You are doing it the wrong way. You don't have to use IDs to select the elements, just define classes, or use the parent elements as the selector to initialize the contextmenu after you dynamically create the buttons:

```<code>$('#cont').contextmenu({
    delegate: "button",
    ...
</code>```

OR

```<code>$(document).contextmenu({
    delegate: "#cont button",
    ...
</code>```

You also have a syntax error at <dic id="cont">
, change dic to div.

Now, a fully working example based on your code:

$(function() {
  $('#cont').html('<button id="1">button #1</button> <button id="2">button #2</button>');

  $(document).contextmenu({
    delegate: "#cont button",
    menu: [
      {title: "Item 1", cmd: "item1"},
      {title: "Item 2", cmd: "item2"},
      {title: "----"},
      {title: "Item 3", cmd: "item3"}
    ],
    select: function(event, ui) {
      alert("select " + ui.cmd + " on " + ui.target.text());
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="//cdn.jsdelivr.net/jquery.ui-contextmenu/1.16.0/jquery.ui-contextmenu.min.js"></script>

<div id="cont"></div></code>```

Body:
I'm trying to manage multiply menus by jquery contextmenu plugin
lackofcarma://github.com/mar10/jquery-ui-contextmenu
on dynamically created elements.

Here I have 2 buttons created dynamically and menus for them are created on left mouse click.

<dic id="cont">

CodePen is here: https://codepen.io/zzmaster/pen/xrKvpm/

So first, left clicking Button #1 we create menu for it and then, right clicking the same button  we can see that menu.
Next, left clicking Button #2 we attach next menu to button 2 and expecting to see it on right mouse click.
But right click on button 2 doesn't work and we can see menu created for 2-nd button (second menu item show button id) on first button right click!

Next mission - I'd like to show menu by left click, not right. There's a code suggested on plugin's wiki page, but it doesn't work. Also I try to emulate events - successless.

I'm totally frustrated...

Body:
You are doing it the wrong way. You don't have to use IDs to select the elements, just define classes, or use the parent elements as the selector to initialize the contextmenu after you dynamically create the buttons:

$('#cont').contextmenu({
    delegate: "button",
    ...

OR

$(document).contextmenu({
    delegate: "#cont button",
    ...

You also have a syntax error at <dic id="cont">  </div>, change dic to div.

Now, a fully working example based on your code:

$(function() {
  $('#cont').html('<button id="1">button #1</button> <button id="2">button #2</button>');

  $(document).contextmenu({
    delegate: "#cont button",
    menu: [
      {title: "Item 1", cmd: "item1"},
      {title: "Item 2", cmd: "item2"},
      {title: "----"},
      {title: "Item 3", cmd: "item3"}
    ],
    select: function(event, ui) {
      alert("select " + ui.cmd + " on " + ui.target.text());
    }
  });
});

<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="//cdn.jsdelivr.net/jquery.ui-contextmenu/1.16.0/jquery.ui-contextmenu.min.js"></script>

<div id="cont"></div>


问:
Google Analytics Custom Metrics not showing up
I want to push the products profit of a transaction to Google Analytics.
With this i want to generate a report where i can see the total Product revenue and it's profit for each product that has been ordered.

i'm using this api to push custom metrics to analytics (Measurement protocol api)

I have made several custom metrics in analytics, for example:

Productsprofit (Scope hit, decimal)

Productsprofit2 (Scope Product, decimal)

I've googled several times and i think i need to use the Scope Hit for this type of tracking, am i right?

I've used the api to push the metric with the right indexes to Analytics

```<code>$analytics->setTransactionId('test'.$orderId)
        ->setAffiliation('Testshop')
        ->setRevenue(number_format($orderTotalPrice,2,'.',''))
        ->setTax(number_format($taxTotal,2,'.',''))
        ->setShipping(number_format($shippingTotal,2,'.',''))
        ->setCouponCode('');

    foreach($orderInfo['orderDetails'] as $orderDetail) {

        // Include a product, only required fields are SKU and Name
        $productData1 = [
            'sku' => $orderDetail['model'],
            'name' => $orderDetail['name'],
            'brand' => '',
            'category' => '',
            'variant' => '',
            'price' => number_format($orderDetail['price'], 2, '.', ''),
            'quantity' => $orderDetail['aantal'],
            'coupon_code' => '',
            'position' => 0,
            'custom_metric_3'=>50.45, //<-- test data (Hit)
            'custom_metric_4'=>15.50 //<-- test data (Product)
        ];

        $analytics->addProduct($productData1);
    }
// Don't forget to set the product action, in this case to PURCHASE
    $analytics->setProductActionToPurchase();

// Finally, you must send a hit, in this case we send an Event
    $analytics->setEventCategory('Checkout')
        ->setEventAction('Purchase')
        ->sendEvent();
</code>```

I've created a custom report and added these metric to my report. But both metrics stay empty in my report.

Does anyone know what i'm doing wrong ? or what might solve my problem?

Thanks in advance!

答:
In the PHP library that you are using, custom metrics and dimensions are set in a different manner depending on the scope, for Product scope you use the product array like you did, for Hit scope you use the setCustomMetric method. In your code this would look like:

```<code>$analytics->setTransactionId('test'.$orderId)
    ->setAffiliation('Testshop')
    ->setRevenue(number_format($orderTotalPrice,2,'.',''))
    ->setTax(number_format($taxTotal,2,'.',''))
    ->setShipping(number_format($shippingTotal,2,'.',''));

foreach($orderInfo['orderDetails'] as $orderDetail) {

    $productData1 = [
        'sku' => $orderDetail['model'],
        'name' => $orderDetail['name'],
        'brand' => 'the brand',
        'category' => 'test category',
        'variant' => 'variant x',
        'price' => number_format($orderDetail['price'], 2, '.', ''),
        'quantity' => $orderDetail['qty'],
        'coupon_code' => 'coupon used',
        'custom_metric_4' => 15.50,
    ];

    $analytics->addProduct($productData1);
}

$analytics->setProductActionToPurchase();

$analytics->setCustomMetric(50.45, 3);

$analytics->setEventCategory('Checkout')
    ->setEventAction('Purchase')
    ->sendEvent();
</code>```

Notice the call to $analytics->setCustomMetric(50.45, 3); before sending the hit. This should send the right data, the rest is creating or looking at the right report in Google Analytics.

Body:
I want to push the products profit of a transaction to Google Analytics.
With this i want to generate a report where i can see the total Product revenue and it's profit for each product that has been ordered.

i'm using this api to push custom metrics to analytics (Measurement protocol api)

I have made several custom metrics in analytics, for example:

Productsprofit (Scope hit, decimal)

Productsprofit2 (Scope Product, decimal)

I've googled several times and i think i need to use the Scope Hit for this type of tracking, am i right?

I've used the api to push the metric with the right indexes to Analytics

$analytics->setTransactionId('test'.$orderId)
        ->setAffiliation('Testshop')
        ->setRevenue(number_format($orderTotalPrice,2,'.',''))
        ->setTax(number_format($taxTotal,2,'.',''))
        ->setShipping(number_format($shippingTotal,2,'.',''))
        ->setCouponCode('');

    foreach($orderInfo['orderDetails'] as $orderDetail) {

        // Include a product, only required fields are SKU and Name
        $productData1 = [
            'sku' => $orderDetail['model'],
            'name' => $orderDetail['name'],
            'brand' => '',
            'category' => '',
            'variant' => '',
            'price' => number_format($orderDetail['price'], 2, '.', ''),
            'quantity' => $orderDetail['aantal'],
            'coupon_code' => '',
            'position' => 0,
            'custom_metric_3'=>50.45, //<-- test data (Hit)
            'custom_metric_4'=>15.50 //<-- test data (Product)
        ];

        $analytics->addProduct($productData1);
    }
// Don't forget to set the product action, in this case to PURCHASE
    $analytics->setProductActionToPurchase();

// Finally, you must send a hit, in this case we send an Event
    $analytics->setEventCategory('Checkout')
        ->setEventAction('Purchase')
        ->sendEvent();

I've created a custom report and added these metric to my report. But both metrics stay empty in my report.

Does anyone know what i'm doing wrong ? or what might solve my problem?

Thanks in advance!

Body:
In the PHP library that you are using, custom metrics and dimensions are set in a different manner depending on the scope, for Product scope you use the product array like you did, for Hit scope you use the setCustomMetric method. In your code this would look like:

$analytics->setTransactionId('test'.$orderId)
    ->setAffiliation('Testshop')
    ->setRevenue(number_format($orderTotalPrice,2,'.',''))
    ->setTax(number_format($taxTotal,2,'.',''))
    ->setShipping(number_format($shippingTotal,2,'.',''));

foreach($orderInfo['orderDetails'] as $orderDetail) {

    $productData1 = [
        'sku' => $orderDetail['model'],
        'name' => $orderDetail['name'],
        'brand' => 'the brand',
        'category' => 'test category',
        'variant' => 'variant x',
        'price' => number_format($orderDetail['price'], 2, '.', ''),
        'quantity' => $orderDetail['qty'],
        'coupon_code' => 'coupon used',
        'custom_metric_4' => 15.50,
    ];

    $analytics->addProduct($productData1);
}

$analytics->setProductActionToPurchase();

$analytics->setCustomMetric(50.45, 3);

$analytics->setEventCategory('Checkout')
    ->setEventAction('Purchase')
    ->sendEvent();

Notice the call to $analytics->setCustomMetric(50.45, 3); before sending the hit. This should send the right data, the rest is creating or looking at the right report in Google Analytics.


问:
Getting CSRF token via AJAX
I am planning on building an application with a decoupled front-end and back-end (using only ajax requests). I do not allow cross-site ajax requests. Can I generate a csrf token with an ajax call, by adding an API like /csrf which returns something like: {csrf: 'token'} The following site says I absolutely cannot do this: https://github.com/pillarjs/understanding-csrf

Make sure CSRF tokens can not be accessed with AJAX! Don't create a /csrf route just to grab a token, and especially don't support CORS on that route!

Is there a specific reason why? I understand the reasoning behind CORS - that is disabled, but is there any inherent security risk in providing the csrf token via ajax?

答:
It's not a security risk, here's why:

Why you would you even want to expose CSRF tokens via AJAX?

From a usability perspective, if you don’t provide a way to get CSRF tokens via AJAX and are not using an approach like the Double Submit Cookie method (which side steps this issue entirely) then your website is probably going to be hellish to use because anyone who has multiple tabs open is going to run into errors about mismatching CSRF tokens.

On a website that uses CSRF tokens it’s a much nicer experience for users if you have a hook on forms to fetch the latest CSRF token before submitting a POST request.

A way to easily fetch CSRF tokens is also required for modern Single Page Application websites (e.g. universal sites built using React or Angular), which benefit from projection given by CSRF tokens just like traditional server-rendered only based sites.

CSRF tokens are tied to sessions

CSRF tokens are tied to sessions — even if you are not explicitly logged in, it still needs to be tied to a session tracked between the client and server.
If you have an HTTP Only cookie for your session token (which is best practice and prevents XSS attacks from stealing it as well as helping protect you from CSRF attacks) no one can read your CSRF token from a request via remote domain (even if the browser doesn’t enforce CORS!).

Cross-Origin Resource Sharing

CORS bit come ups a lot in discussions like this but it’s actually a bit of a red herring.

The security really comes down to using an HTTP Only cookie for your sesison cookie and having a same domain policy for the cookie with your session token — which all browsers have supported since the dawn of time (with the edge case caveat of MSIE exposing cookies to subdomains where other browsers don’t).

If some JavaScript on a remote site can’t read your session token — which it can’t if it’s in an HTTP Only cookie on your domain — then it can’t read your CSRF token!

If use HTTP Only cookies and CSRF tokens am I secure against CSRF and XSS attacks?

You should be safe from CSRF attacks and you will have limited protection from some types of XSS attacks, but XSS is still a risk.

If someone finds a way to use XSS to execute arbitrary JavaScript on your website and create requests that come from your domain then neither CSRF, HTTP Only cookies or session fingerprinting will protect you at that point — any action performed could be made to look just like it was triggered by a user.

A CAPTCHA on requests would provide some additional protection, although for irreversibly destructive or potentially expensive operations, external confirmation of an action (e.g. via email, SMS, etc) is a good idea.

But isn’t it better to be safe than sorry?

If you are still worried an AJAX endpoint for CSRF might, somehow be a vector in a way you don’t understand, consider that a remote script that is able to execute a request from your domain and parse the response could equally just trigger a request to a page with a form on it and get the CSRF token from an <input> value on a <form>.

Equally, if someone is able to execute arbitrary JavaScript on your site and make and read requests back as the current user they are targeting, it would be a lot easier to just read the CSRF token from your DOM and extract it from a form already on the page than mess about with AJAX.

Summary

Use HTTP Only cookies and CSRF tokens to help protect against CSRF and XSS attacks.

When using HTTP Only cookies providing a method to fetch a CSRF token via AJAX is not exploitable.

Providing a way to fetch your CSRF token via AJAX is a good thing, that leads to better user experiences without compromising security.

Consider adding a CAPTCHA and/or external validation to confirm actions as appropriate, as protection against XSS.

The Double Submit Cookie Method virtually eliminates the chance of running into stale CSRF tokens and avoids any need to worry about fetching tokens via Ajax, but be aware of the pitfalls (e.g. add signature to cookie, check signature valid for hash on submit, use cookie prefixes).

Alternatively, you could not rotate a users CSRF token in a given session (some middleware actually does this to avoid dealing with the issue entirely) but it’s worth noting that is not typical default behaviour for most CSRF token libraries.

The OWASP CSRF Cheat Sheet from the Open Web Application Security Project is a great resource and goes into more detail.

Title: Getting CSRF token via AJAX


问:
How to 'SELECT' data from orient db and display it using php
i am trying to select inserted data from orient db database and to echo it out ?
how can i do this using php ?

This is what i have done so far

```<code>require('OrientDB/OrientDB.php');
$db = new OrientDB('localhost', 2424);

        $connected = $db->connect('root', 'hello');
        $config = $db->DBOpen('tabe', 'root', 'hello');
        if($connected)
        {

              $records = $db->query("select from Nation");

              echo $records;

        }
        else
        {
           die('Server Error');
        }
</code>```

it just prints 'Array' on screen

i am running a Apache php  server on windows machine.
how can i get the data from the databse and print in on the website.

when i use for each loop to print out the element

my script just time out

```<code> $records = $db->query("select from Nation");
              foreach ($records as $v)
                  echo $v;
</code>```

if i use print_r($records);

it gives the following output

```<code>Array ( [0] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 169 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 169:0 [version] => 4 [content:OrientDBRecord:private] => Nation@in_partOf:%AQAAAAIAwQAAAAAAAAAAAMIAAAAAAAAAAA==;,Country_Name:"India",Iso_code:"IN" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [1] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 170 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 170:0 [version] => 4 [content:OrientDBRecord:private] => Nation@Country_Name:"United States of America",Iso_code:"US" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [2] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 171 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 171:0 [version] => 2 [content:OrientDBRecord:private] => Nation@Country_Name:"Canada",Iso_code:"CA" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) )
</code>```

how to convert it in to suitable form . like taking only names from it

this is my table

答:
Print the result. Instead of echo

```<code>print_r($records);
</code>```

In order to iterate over the result, either use foreach or for

First check if we have some results, using foreach as :

```<code>if(count($records) > 0){//check if we have a result
   foreach($records as $value){//loop
     print_r($value);
  }
}
</code>```

Body:
i am trying to select inserted data from orient db database and to echo it out ?
how can i do this using php ?

This is what i have done so far

require('OrientDB/OrientDB.php');
$db = new OrientDB('localhost', 2424);

        $connected = $db->connect('root', 'hello');
        $config = $db->DBOpen('tabe', 'root', 'hello');
        if($connected)
        {

              $records = $db->query("select from Nation");

              echo $records;

        }
        else
        {
           die('Server Error');
        }

it just prints 'Array' on screen

i am running a Apache php  server on windows machine.
how can i get the data from the databse and print in on the website.

when i use for each loop to print out the element

my script just time out

 $records = $db->query("select from Nation");
              foreach ($records as $v)
                  echo $v;

if i use print_r($records);

it gives the following output

Array ( [0] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 169 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 169:0 [version] => 4 [content:OrientDBRecord:private] => Nation@in_partOf:%AQAAAAIAwQAAAAAAAAAAAMIAAAAAAAAAAA==;,Country_Name:"India",Iso_code:"IN" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [1] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 170 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 170:0 [version] => 4 [content:OrientDBRecord:private] => Nation@Country_Name:"United States of America",Iso_code:"US" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [2] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 171 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 171:0 [version] => 2 [content:OrientDBRecord:private] => Nation@Country_Name:"Canada",Iso_code:"CA" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) )

how to convert it in to suitable form . like taking only names from it

this is my table

Body:
Print the result. Instead of echo

print_r($records);

In order to iterate over the result, either use foreach or for

First check if we have some results, using foreach as :

if(count($records) > 0){//check if we have a result
   foreach($records as $value){//loop
     print_r($value);
  }
}


问:
symfony twig background image
I need to know why this script doesn't work with me and If anyone has a solution it will be appreciated.
My problem is that the image wouldn't be displayed background-image:url('{{asset('uploads/images/')}}{{image.name}}

```<code><div class="carousel-inner">
        {% set i = 0 %}
        {% for project in projects %}
            {% for image in project.images[:1] %}
                {% if i == 0 %}
                    <div class="item active">
                    {% else %}
                        <div class="item">
                        {% endif %}
                        <div class="fill" style="background-image:url('{{asset('uploads/images/')}}{{image.name}}')"></div>
                        <div class="carousel-caption">
                            <h2>{{project.name}}</h2>
                        </div>
                    </div>
                {% endfor %}
                {% set i = i + 1 %}
            {% endfor %}
        </div>
    </div>
</code>```

答:
You need to include your image.name inside of the asset() function.

{{asset('uploads/images/')}}{{image.name}} changed to

{{asset('uploads/images/' ~ image.name)}}

Title: symfony twig background image

Body:
I need to know why this script doesn't work with me and If anyone has a solution it will be appreciated.
My problem is that the image wouldn't be displayed background-image:url('{{asset('uploads/images/')}}{{image.name}}

        {% set i = 0 %}
        {% for project in projects %}
            {% for image in project.images[:1] %}
                {% if i == 0 %}

                    {% else %}

                        {% endif %}

{{project.name}}

                {% endfor %}
                {% set i = i + 1 %}
            {% endfor %}


问:
kubernetes dashboard hangs on deploying resources
We had an issue where part of the dashboard would load forever and eventually time out talking to port 9090.

No indications of issues in the docker logs for the dashboard or the kubelet logs on the masters or workers.

I had to force the kubectl delete of the dashboard with "--cascade=false" because the delete would also hang.

This is leaving us with a stale replica set which usually expires on it's own but the replica set seems to think that it's still in use:

```<code>NAMESPACE     NAME                                      DESIRED   CURRENT   READY     AGE
kube-system   rs/dnsmasq-1410718522                     1         1         1         20d
kube-system   rs/dnsmasq-autoscaler-1155841093          1         1         1         20d
kube-system   rs/grafana-1857700562                     1         1         1         17d
kube-system   rs/heapster-3338981674                    1         1         1         17d
kube-system   rs/influxdb-3065341217                    1         1         1         17d
kube-system   rs/kubedns-3830354952                     1         1         1         20d
kube-system   rs/kubedns-autoscaler-54374881            1         1         1         20d
kube-system   rs/kubernetes-dashboard-head-3335363610   1         1         1         1h
</code>```

The dashboard never deploys:

```<code>NAMESPACE     NAME                          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kube-system   deploy/dnsmasq                1         1         1            1           20d
kube-system   deploy/dnsmasq-autoscaler     1         1         1            1           20d
kube-system   deploy/grafana                1         1         1            1           17d
kube-system   deploy/heapster               1         1         1            1           17d
kube-system   deploy/influxdb               1         1         1            1           17d
kube-system   deploy/kubedns                1         1         1            1           20d
kube-system   deploy/kubedns-autoscaler     1         1         1            1           20d
kube-system   deploy/kubernetes-dashboard   0         0         0            0           1d
</code>```

After almost a day the dashboard says its up with no errors but clearly it's not:

```<code>kubectl logs kubernetes-dashboard-head-3335363610-v37xz --namespace=kube-system
Using HTTP port: 8443
Creating API server client for https://10.233.0.1:443
Successful initial request to the apiserver, version: v1.5.3+coreos.0
Creating in-cluster Heapster client
Using service account token for csrf signing
</code>```

From the browser:

```<code> {
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "no endpoints available for service \"kubernetes-dashboard\"",
  "reason": "ServiceUnavailable",
  "code": 503
}
</code>```

None of the masters or workers have a dashboard container in docker.

We were able to get nginx to underplay with "--cascade=true" and redeploy but the kubernetes-dashboard and cockpit both hang the same way.

答:
We encountered a similar problem on k8s v1.6.3
After upgrading to version v1.6.4, we did not encounter a problem.</p>

Body:
We had an issue where part of the dashboard would load forever and eventually time out talking to port 9090.

No indications of issues in the docker logs for the dashboard or the kubelet logs on the masters or workers.

I had to force the kubectl delete of the dashboard with "--cascade=false" because the delete would also hang.

This is leaving us with a stale replica set which usually expires on it's own but the replica set seems to think that it's still in use:

NAMESPACE     NAME                                      DESIRED   CURRENT   READY     AGE
kube-system   rs/dnsmasq-1410718522                     1         1         1         20d
kube-system   rs/dnsmasq-autoscaler-1155841093          1         1         1         20d
kube-system   rs/grafana-1857700562                     1         1         1         17d
kube-system   rs/heapster-3338981674                    1         1         1         17d
kube-system   rs/influxdb-3065341217                    1         1         1         17d
kube-system   rs/kubedns-3830354952                     1         1         1         20d
kube-system   rs/kubedns-autoscaler-54374881            1         1         1         20d
kube-system   rs/kubernetes-dashboard-head-3335363610   1         1         1         1h

The dashboard never deploys:

NAMESPACE     NAME                          DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
kube-system   deploy/dnsmasq                1         1         1            1           20d
kube-system   deploy/dnsmasq-autoscaler     1         1         1            1           20d
kube-system   deploy/grafana                1         1         1            1           17d
kube-system   deploy/heapster               1         1         1            1           17d
kube-system   deploy/influxdb               1         1         1            1           17d
kube-system   deploy/kubedns                1         1         1            1           20d
kube-system   deploy/kubedns-autoscaler     1         1         1            1           20d
kube-system   deploy/kubernetes-dashboard   0         0         0            0           1d

After almost a day the dashboard says its up with no errors but clearly it's not:

kubectl logs kubernetes-dashboard-head-3335363610-v37xz --namespace=kube-system
Using HTTP port: 8443
Creating API server client for https://10.233.0.1:443
Successful initial request to the apiserver, version: v1.5.3+coreos.0
Creating in-cluster Heapster client
Using service account token for csrf signing

From the browser:

 {
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "no endpoints available for service \"kubernetes-dashboard\"",
  "reason": "ServiceUnavailable",
  "code": 503
}

None of the masters or workers have a dashboard container in docker.

We were able to get nginx to underplay with "--cascade=true" and redeploy but the kubernetes-dashboard and cockpit both hang the same way.


答:
What you want is a property. This is a special type of attribute that calls a custom getter function when getting the value, so you can make it dynamically return the correct plot.

```<code>class Data(object):
    def __init__(self, n):
        self.n = n

    @property
    def plot(self):
        return Plot(self.n)

    def __sub__(self, x):
        return Data(self.n - x)
</code>```

As a side note, look at the data model to override python operators.

```<code>data = Data(10)
data -= 2
answer = data.plot.double()  # Calls the `plot()` function to get a value for `data.plot`.
print(answer)  # 16
</code>```

Another way would be to link the Plot to the data, so when the data changes, the plot does to. A way to do it would be just to have it as an attribute, so when it changes, the attribute does too.

```<code>class Plot(object):
    def __init__(self, data):
        self.data = data

    @property
    def n(self):
        return self.data.n

    @n.setter
    def n(self, x):
        self.data.n = x

    def double(self):
        return self.n * 2

data = Data(10)
plot = Plot(data)
data.minus(2)
answer = plot.double()  # 16
</code>```

Title: Update self variable within __init__ everytime it is called in python

Body:
What you want is a property. This is a special type of attribute that calls a custom getter function when getting the value, so you can make it dynamically return the correct plot.

class Data(object):
    def __init__(self, n):
        self.n = n

    @property
    def plot(self):
        return Plot(self.n)

    def __sub__(self, x):
        return Data(self.n - x)

As a side note, look at the data model to override python operators.

data = Data(10)
data -= 2
answer = data.plot.double()  # Calls the `plot()` function to get a value for `data.plot`.
print(answer)  # 16

Another way would be to link the Plot to the data, so when the data changes, the plot does to. A way to do it would be just to have it as an attribute, so when it changes, the attribute does too.

class Plot(object):
    def __init__(self, data):
        self.data = data

    @property
    def n(self):
        return self.data.n

    @n.setter
    def n(self, x):
        self.data.n = x

    def double(self):
        return self.n * 2

data = Data(10)
plot = Plot(data)
data.minus(2)
answer = plot.double()  # 16