text:
Q: why spring config server client failed get config from config server? I set up a local spring boot config server with a gitlab as the config remote. It worked fine. And I set up a config server client web app and it can successfully connect to this config server and get the configs from git repro through this config server. But now I want to do integration tests to my config server and I moved the client web app to the test directory of the config server, and I modify the client's spring.application.config.name to "configserver-tes" so the client web app will not read the default application.yml in the main classpath and read bootstrap.yml in the test class path. In this case, both two web applications could start with different context and ports. Question is the client web app could not read configs from the config server. Could you guys tell my how can I resolve this issue? Or how can I debug it. Thanks.
error log:
2016-09-22 16:49:06,477 DEBUG jndi [main] Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@dffa30b
2016-09-22 16:49:06,477 DEBUG jndi [main] Looking up name="SPRINGCLOUDCONFIGSERVERBOOTSTRAP"
2016-09-22 16:49:06,477 DEBUG o.s.j.JndiPropertySource [main] JNDI lookup for name [SPRINGCLOUDCONFIGSERVERBOOTSTRAP] threw NamingException with message: null. Returning null.
2016-09-22 16:49:06,477 TRACE o.s.b.a.c.OnPropertyCondition [main] Condition OnPropertyCondition on org.springframework.cloud.config.server.bootstrap.ConfigServerBootstrapConfiguration$LocalPropertySourceLocatorConfiguration did not match due to @ConditionalOnProperty missing required properties spring.cloud.config.server.bootstrap
2016-09-22 16:49:06,477 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'
2016-09-22 16:49:06,521 DEBUG o.s.c.t.c.AnnotationAttributesReadingVisitor [main] Failed to class-load type while reading annotation metadata. This is a non-fatal error, but certain annotation metadata may be unavailable.
java.lang.ClassNotFoundException: org.springframework.retry.annotation.EnableRetry
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_101]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_101]
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[?:1.8.0_101]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_101]
        at org.springframework.core.type.classreading.RecursiveAnnotationAttributesVisitor.visitEnd(RecursiveAnnotationAttributesVisitor.java:47) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.asm.ClassReader.readAnnotationValues(ClassReader.java:1802) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.asm.ClassReader.accept(ClassReader.java:642) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.asm.ClassReader.accept(ClassReader.java:508) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:64) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:98) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:93) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:621) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:593) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getMemberClasses(ConfigurationClassParser.java:750) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.processMemberClasses(ConfigurationClassParser.java:328) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:232) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:168) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:140) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:84) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:62) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:166) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:138) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:121) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:65) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:330) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at com.yrd.configserver.test.ConfigserverClient.main(ConfigserverClient.java:30) [test-classes/:?]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_101]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_101]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_101]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_101]
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:?]
2016-09-22 16:49:06,542 TRACE o.s.b.a.c.OnClassCondition [main] Condition OnClassCondition on org.springframework.cloud.config.client.ConfigServiceBootstrapConfiguration$RetryConfiguration did not match due to required @ConditionalOnClass classes not found: org.springframework.retry.annotation.Retryable,org.aspectj.lang.annotation.Aspect
2016-09-22 16:49:06,543 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'
2016-09-22 16:49:06,559 TRACE o.s.b.a.c.OnClassCondition [main] Condition OnClassCondition on org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration matched due to @ConditionalOnClass classes found: org.springframework.security.crypto.encrypt.TextEncryptor
2016-09-22 16:49:06,559 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'
2016-09-22 16:49:06,570 TRACE o.s.b.a.c.OnClassCondition [main] Condition OnClassCondition on org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration$VanillaEncryptionConfiguration did not match due to required @ConditionalOnMissing classes found: org.springframework.security.rsa.crypto.RsaSecretEncryptor
2016-09-22 16:49:06,570 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'
2016-09-22 16:49:06,570 TRACE o.s.b.a.c.OnClassCondition [main] Condition OnClassCondition on org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration$RsaEncryptionConfiguration matched due to @ConditionalOnClass classes found: org.springframework.security.rsa.crypto.RsaSecretEncryptor
2016-09-22 16:49:06,571 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'
2016-09-22 16:49:06,571 TRACE o.s.c.e.PropertySourcesPropertyResolver [main] getProperty("encrypt.keyStore.location", String)
2016-09-22 16:49:06,571 DEBUG o.s.c.e.PropertySourcesPropertyResolver [main] Searching for key 'encrypt.keyStore.location' in [bootstrap]
2016-09-22 16:49:06,571 DEBUG o.s.c.e.PropertySourcesPropertyResolver [main] Searching for key 'encrypt.keyStore.location' in [servletConfigInitParams]
2016-09-22 16:49:06,571 DEBUG o.s.c.e.PropertySourcesPropertyResolver [main] Searching for key 'encrypt.keyStore.location' in [servletContextInitParams]
2016-09-22 16:49:06,571 DEBUG o.s.c.e.PropertySourcesPropertyResolver [main] Searching for key 'encrypt.keyStore.location' in [jndiProperties]
2016-09-22 16:49:06,571 DEBUG o.s.j.JndiTemplate [main] Looking up JNDI object with name [java:comp/env/encrypt.keyStore.location]
2016-09-22 16:49:06,571 DEBUG jndi [main] InitialContextFactory.getInitialContext()
2016-09-22 16:49:06,571 DEBUG jndi [main] Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@f8f56b9
] not found - trying original name [SPRINGCLOUDCONFIGSERVERBOOTSTRAP]. javax.naming.NameNotFoundException; remaining name 'env/SPR
INGCLOUDCONFIGSERVERBOOTSTRAP'
2016-09-22 16:49:06,477 DEBUG o.s.j.JndiTemplate [main] Looking up JNDI object with name [SPRINGCLOUDCONFIGSERVERBOOTSTRAP]
2016-09-22 16:49:06,477 DEBUG jndi [main] InitialContextFactory.getInitialContext()
2016-09-22 16:49:06,477 DEBUG jndi [main] Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localC
ontextRoot@dffa30b
2016-09-22 16:49:06,477 DEBUG jndi [main] Looking up name="SPRINGCLOUDCONFIGSERVERBOOTSTRAP"
2016-09-22 16:49:06,477 DEBUG o.s.j.JndiPropertySource [main] JNDI lookup for name [SPRINGCLOUDCONFIGSERVERBOOTSTRAP] threw Naming
Exception with message: null. Returning null.
2016-09-22 16:49:06,477 TRACE o.s.b.a.c.OnPropertyCondition [main] Condition OnPropertyCondition on org.springframework.cloud.conf
ig.server.bootstrap.ConfigServerBootstrapConfiguration$LocalPropertySourceLocatorConfiguration did not match due to @ConditionalOn
Property missing required properties spring.cloud.config.server.bootstrap
2016-09-22 16:49:06,477 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigu
rationReport'
2016-09-22 16:49:06,521 DEBUG o.s.c.t.c.AnnotationAttributesReadingVisitor [main] Failed to class-load type while reading annotati
on metadata. This is a non-fatal error, but certain annotation metadata may be unavailable.
java.lang.ClassNotFoundException: org.springframework.retry.annotation.EnableRetry
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_101]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_101]
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[?:1.8.0_101]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_101]
        at org.springframework.core.type.classreading.RecursiveAnnotationAttributesVisitor.visitEnd(RecursiveAnnotationAttributesV
isitor.java:47) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.asm.ClassReader.readAnnotationValues(ClassReader.java:1802) [spring-core-4.2.6.RELEASE.jar:4.2.6.RE
LEASE]
        at org.springframework.asm.ClassReader.accept(ClassReader.java:642) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.asm.ClassReader.accept(ClassReader.java:508) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:64) [spring-core-4.2.6
.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.ja
va:98) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.
java:102) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.ja
va:93) [spring-core-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:621) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:593) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getMemberClasses(ConfigurationClassParser.java:750) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.processMemberClasses(ConfigurationClassParser.java:328) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:249) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:232) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:168) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:140) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:84) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:62) [spring-cloud-context-1.1.1.RELEASE.jar:1.1.1.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:166) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:138) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:121) [spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
        at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:65) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:330) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
        at com.yrd.configserver.test.ConfigserverClient.main(ConfigserverClient.java:30) [test-classes/:?]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_101]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_101]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_101]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_101]
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:?]
2016-09-22 16:49:06,542 TRACE o.s.b.a.c.OnClassCondition [main] Condition OnClassCondition on org.springframework.cloud.config.client.ConfigServiceBootstrapConfiguration$RetryConfiguration did not match due to required @ConditionalOnClass classes not found: org.springframework.retry.annotation.Retryable,org.aspectj.lang.annotation.Aspect
2016-09-22 16:49:06,543 DEBUG o.s.b.f.s.DefaultListableBeanFactory [main] Returning cached instance of singleton bean 'autoConfigurationReport'

A: I get this block resolved somehow. Here is my test class and bootstrap.yml.
package com.yrd.configserver.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * This is a embedded spring boot web application for integration test.
 */
@SpringBootApplication
@RestController
public class ConfigserverClient {

  static {
    System.setProperty("spring.cloud.config.enabled", "true");
  }

  @Autowired
  private ConfigurableEnvironment environment;

  public static void main(final String... args) {
    SpringApplication.run(ConfigserverClient.class, args);
  }

  /**
   * This method is a way to get the specific configuration from the web application.
   * @param propertyName: property name of the configuration.
   * @return
   */
  @RequestMapping("/show")
  public String getPropertyByName(final @RequestParam String propertyName) {
    return environment.getProperty(propertyName);
  }
}

bootstrap.yml
spring:
  cloud:
    config:
      enabled: true
      discovery:
        enabled: false

      profile: env_${ENV:development}

      label: master
      uri: http://user:user_pass@localhost:8888

  application:
    name: configserver-test
  config:
    name: configserver-test  # This config is to stop the client web app to read the application.yml in the path.

security.basic.enabled: false
management.security.enabled: false
server.port: ${app.port:8080}


text:
Q: class R не создается при слиянии исходного кода библиотеки с проектом Есть проект и его исходный код лежит в main/java/example так же есть код в папке main/java/com В com исходный код библиотеки.
Вот в директории, где создаются R классы в папке example создается R класс, а папка com с R классом не появляется. А должна, так как в коде есть импорт этого класса. Если подключить aar библиотеку через зависимости этот R класс появляется.
Ну я думаю мне копать надо начиная с вопроса:
В какой момент создается R класс, может надо где то запись добавить какую-то? Пока что я просто скопировал R класс, который появляется при подключении библиотеки, но ведь он должен как то сам появиться.
UPD
Копирование R класса не помогает, при запуске приложения он удаляется.. Зачем он нужен этот класс я знаю ну очень поверхностно, пока не вникал и это не суть вопроса. Мне нужен ответ на то, как мне его создать. А со смыслом я позже разберусь
UPD1
По пути AndroidStudioProjects\app\src\main\java\example\i лежал код моего проекта. Код библиотеки добавил по пути AndroidStudioProjects\app\src\main\java\com\vk\sdk . Не важно какая это библиотека. Я пробовал разные библиотеки добавлять, но R класс создается только для кода лежащего по пути AndroidStudioProjects\app\src\main\java\example\i    И естественно ругается на отсутствие класса  import com.vk.sdk.R; и всё подобное findViewById(R.id.captchaAnswer); подсвечено красным, т.к. нет идентификаторов ресурсов.
UPD2
папка где появляются R классы C:\Android\AndroidStudioProjects\AndroidStudioProjects\app\build\generated\source\r\debug   Если подлючить библиотеку через зависимости ,  R класс появится.  Я его вырезаю. отключаю зависимости. вставляю вырезанный класс. Но при запуске приложения он удаляется. Т.е. где то есть Указание для какого кода R class создается.
Очистки проекта, кэша и пересборку пробовал.
UPD3
Если переформулировать вопрос короче, то не создаются R.class для других package ,которые лежат в папке src\main\java\ , кроме первого созданного package

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does effective quantum field theory mean? By renormalization, we have renormalized quantum field theory, usually, we call the theory by effective QFT. What does effective quantum field theory mean?  It means we have different quantum field theories that are effective in different case? Or we cann't have unified quantum field theory?

A:
In theoretical physics, quantum field theory (QFT) is a theoretical framework that combines classical field theory, special relativity, and quantum mechanics.

Italics mine.
QFT  can be used to model quantum mechanical effects. In that sense there are many quantum field theories.
There is the elementary particle  standard model quantum field theory. There are other field theories, as for condensed matter. Back in 1961 I was taught a quantum field theory for nuclear physics, and here is a link called "effective field theory in nuclear physics" .
The "effective" for a field theoretical model means that re-normalization is not a proven effect in the theory. Because the theory fits the data and is predictive in a certain phase space, the problem of renormalization is put under the rug and the theory is used with the title "effective". A prominent example is the use of an effective gravitational field theory in cosmological models, an example.


text:
Q: Email inline image in email not working on MacOS email I'm sending HTML emails from java, using spring boot. Emails include signature with image logo of our firm. It works perfectly fine f.e. on gmail. But in MacOS app Email the logo is sent as attachment and is not inlined.
Non-related parts of code replaced by ...
final Locale locale = ...;
final MimeMessage mail = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
try {
    helper = new MimeMessageHelper(mail, true, "UTF-8");
    helper.setTo(...);
    helper.setCc(...);
    helper.setBcc(...);
    helper.setFrom(...);

    final String htmlContent = templateEngine.process(..., new Context(locale, ...));
    helper.setText(htmlContent, true);
    helper.addInline("myImg", new ClassPathResource(".../myImg.png"));
} catch (UnsupportedEncodingException | MessagingException e) {
    throw new MailSendException(..., e);
}
javaMailSender.send(mail);

HTML is generated by thymeleaf and is following:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
...
<img src=".../myImg.png" th:src="'cid:' + ${'myImg'}" />

</body>
</html>

A: Have a look at the code of this extension Spring Boot Email Tools, where maybe you can find a better way to create emails.
Personally, I think that you may save some time if you use it directly to send emails via the EmailService bean. From the docs (the example is based on Freemarker template engine):
@Autowired
public EmailService emailService;

public void sendEmailWithTemplating(){
   Arrays.asList(new Cospirator("cassius@sic-semper.tyrannis", "Gaius Cassius Longinus"),
            new Cospirator("brutus@sic-semper.tyrannis", "Marcus Iunius Brutus Caepio"))
        .stream.forEach(tyrannicida -> {
       final Email email = DefaultEmail.builder()
            .from(new InternetAddress("divus.iulius@mala-tempora.currunt", "Gaius Iulius Caesar"))
            .to(Lists.newArrayList(new InternetAddress(tyrannicida.getEmail(), tyrannicida.getName())))
            .subject("Idus Martii")
            .body("")//Empty body
            .encoding(Charset.forName("UTF-8")).build();
        //Defining the model object for the given Freemarker template
        final Map<String, Object> modelObject = new HashMap<>();
        modelObject.put("tyrannicida", tyrannicida.getName());

       emailService.send(email, "idus_martii.ftl", modelObject);
   };
}

private static class Cospirator {
  private String email;
  private String name;
  public Cospirator(final String email, final String name){
    this.email = email;
    this.name = name;
  }

  //getters
}

The dependencies you need are
<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-email-core</artifactId>
    <version>0.4.0</version>
</dependency>
<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-thymeleaf-email</artifactId>
    <version>0.4.0</version>
</dependency>

Pretty convenient, ain't it?


text:
Q: How to decode a nested JSON file into a swift class with an unowned property I have a custom model with several classes that I've written in Swift for a document-based Mac app. As the user inputs data to their document, instances of one class Itinerary are created and stored within an array which is a property of another "root" object of a different class Course. On top of that, multiple courses can be created and are stored in an array in the app's Document class. I'd like the user to be able to save their data and load it back up again at a later point. So I'm attempting to implement the Codable protocol on my custom types.
The Encodable conformance works fine; when I attempt to save, the desired JSON file is produced. The problem comes when decoding.
When attempting to decode each itinerary, its course property needs to be set before the end of initialization because it was defined as an unowned var that points back to the course it belong's to. The place where that happens is within the course's addItinerary(_:) func, which is called from directly within the Itinerary's designated initializer. That means that I also need to pass a Course to the Itinerary's designated init. Therein lies the problem...when I try to reinitialize an itinerary from within the decodable initializer I don't have access to the course that the itinerary needs to be added to and so can't set the course property during initialization.
The issue seems to revolve around how I am attempting to initialize itineraries along with how I am attempting to manage the memory. A little research has pointed me in the direction of changing the course property either to an optional weak var, i.e. weak var course: Course? or marking it as an implicitly unwrapped optional, i.e. var course: Course!. Both of those options seem as though they may be introducing more complexity into the model than is necessary because of how I'll need to rewrite the Itinerary initializers. According to Apple's docs, it's appropriate to mark a property as unowned when the other instance has the same lifetime or a longer lifetime, which accurately describes the scenario here.
My question is sort of two-fold; there seems to be an inherent flaw with how I am attempting to initialize my model:

*

*If not, how would I go about reassembling my model when decoding? Do I need to reconsider my initialization logic?

*If so, what is the flaw? Am I using the right ARC strategy to manage the memory? Should I be considering a data structure other than JSON?

In the interest of brevity I excluded all the properties from the classes that seemed irrelevant. But I'll include more code if people feel it would be necessary to offer a complete solution.
Cliff notes of the important points:

*

*the desired JSON is produced w/ out encoding the course property of the Itinerary class.

*course's addItinerary(_:) func is when the itinerary's course property is set...it's called within Itinerary's designated init.

*BUT...I can't call that init while decoding because I never encoded a course...when I try to encode a course in the Itinerary's encode(to:), Xcode throws BAD ACCESS  errors and points to an address in memory that I am unsure of how to debug.
class Document: NSDocument {
    var masterCourseList = [Course]()
}

class Course: NSObject {
    // ...other properties
    private(set) var itineraries: [Itinerary]() {
        didSet {
            // sorting code
        }
    }

    func addItinerary(_ itinerary: Itinerary) {
        itinerary.course = self
        self.itineraries.append(itinerary)
    }

    // encodable conformance
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        // ...encode other properties
        try container.encode(itineraries, forKey: .itineraries)
    }

    // decodable conformance
    required convenience init decode(from: Decoder) throws {
        let decoder = try decoder.container(keyedBy: CodingKeys.self)
        // ...decode other properties
        let decodedItineraries = container.decode(Array<Itinerary>.self, forKey: .itineraries)

        self.init()

        for itinerary in decodedItineraries {
            self.addItinerary(itinerary)
        }
    }

    enum CodingKeys: CodingKey {
        case itineraries, // other keys... //
    }
}

class Itinerary: NSObject {
    @objc dynamic let date: Date
    unowned var course: Course
    // ...other properties

    private init(date: Date, course: Course) {
        self.course = course
        self.date = date
        super.init()
        course.addItinerary(self)
    }

    // encodable conformance
    func encode(to encoder: Encoder) throws {
        // ...encode all the desired properties of itinerary class
        // ...never encoded the 'course' property but still got the desired JSON file
    }

    // decodable conformance
    required convenience init(from decoder: Decoder) throws {
        // ...decode all the properties
        // ...never decoded the 'course' property because it was never encoded

        self.init(date: decodedDate, course: decodedCourse)
    }
}

And a sample of the JSON that is being produced...
[
  {
    "itineraries" : [
      {
        "date" : 587357150.51135898
      },
      {
        "date" : 587443563.588081
      }
    ],
    "title" : "sample course 1",
    "startDate" : 587357146.98558402,
    "endDate" : 587789146.98558402
  },
  {
    "itineraries" : [
      {
        "date" : 587357150.51135898
      },
      {
        "date" : 587443563.588081
      },
      {
        "date" : 587443563.588081
      }
    ],
    "title" : "sample course 2",
    "startDate" : 587957146.98558402,
    "endDate" : 588389146.98558402
  }
]


text:
Q: My Xcode for C++ won't Read/open My File? sorry if this is an amateur question but I am new to coding and I am trying to open/read a file through a function?
My code for the function is kind of like this:
struct_name ReadInFile(std::string fileName)
{
    std::ifstream readFile("fileName");
    assert(readFile.is_open());
...
...
}

but it fails at this assert stage? (I know assert isn't good coding practice!)
The main programme looks like this:
struct_name TESTING = ReadInFile("thefile.dat");
std::cout << TESTING.struct_variable;

I am not sure why the file won't open - I assume it's because it's not saved in the right place on my computer (I think it needs to be stored wherever my executable file gets built right?) but I have tried saving it in 50+ different locations and still nothing works!?

/Users/MyName/Library/Developer/Xcode/DerivedData

is where I'm told my build system is but I have saved it in numerous locations around here and still nothing!
I would really appreciate some help! Thank you so much


text:
Q: How function that returns structure work? I am learning rust currently, and I found some interesting behavior about function returning structure.
Suppose struct User is defined like this.
struct User {
    email: String,
    username: String,
    age: i32,
}

And a function to generate the User struct defined like this.
fn build_user(email: String, username: String, age: i32) -> User {
    let built_user = User {
        email,
        username,
        age,
    };

    println!("&built_user : {:p}", &built_user);
    built_user
}

So, now in function main, I print the pointer of build_user's return value.
fn main() {
    let user1 = build_user(String::from("asd"), String::from("def"), 32);
    println!("&user1 : {:p}", &user1);
}

If you run it you will see two pointers printed out is same!
Since assigning a struct to new variable (either copy or move) will make new struct object on stack, any other assignment like
let user2 = user1;

will result different pointers.
And even more weird thing is that if structure only contains types with copy trait, something like this,
struct User {
    age: i32,
    login_counts: i32,
}

would behave differently and two pointers will not be equal.
I experimented a lot applying small changes to struct and fn, but this explicit case (struct that doesn't implements copy trait / fn returning only struct, not tuple) seems to be the only one behaving differently to normal assignment.
Can anyone explain why it behaves like this?
Thanks


text:
Q: Django Admin. How to Change position of field labels I need to work with Persian language. Persian is right aligned so I want the labels of model fields to appear on the right side of the input box.
I tried to change the admin page CSS but it didn't work.(I changed text-aligned to right-aligned).

A: Could try adding this to the css:
.form-row div {
    display:flex;
    flex-direction: row-reverse;
}

You could also use direction: rtl instead of flex-direction: row-reverse This works because the structure of the generated html will be something like:

        <input ...>

Depending on how complicated the layout it, this might not work 100%, I've not looked at how it will affect inlines and other ways you can lay things out in the django-admin, but some variation of it should fix your basic problem.


text:
Q: Adding class on i+3 type iteration I am pulling some info from array, and I'm wrapping it in wrapper so that every 6 items are in a wrapper. This gives me some number of wrappers. Now I need to add classes that repeat based on i+3 iteration. So I need to have something like this:

My current code is (incomplete):
foreach ($tables_completed[$content_count]['table_match'] as $tbm_k => $tbm_v) {
    $wrap_count = 1;
    $swipe_title = '';
    array_shift($tbm_v);
    foreach ($tbm_v as $ind_match_k => $ind_match_v) {
        if( $wrap_count % 6 == 1 ){
            if ($wrap_count) {
                $swipe_title = 'total';
            } elseif($wrap_count){
                $swipe_title = 'hemma';
            } else{
                $swipe_title = 'borta';
            }
            $out .= '
';
        }
        $out .= ''.$ind_match_v.'';
        if( $wrap_count % 6 == 0){
            $out .= '
';
        }
        $wrap_count++;
    }

}

The $tables_completed has entries like this:
[1] => Array
        (
            [table_match] => Array
                (
                    [0] => Array
                        (
                            [1] => 2
                            [2] => 2
                            [3] => 0
                            [4] => 0
                            [6] => 9
                            [7] => 6
                            [8] => 1
                            [9] => 1
                            [10] => 0
                            [11] => 0
                            [13] => 5
                            [14] => 3
                            [15] => 1
                            [16] => 1
                            [17] => 0
                            [18] => 0
                            [20] => 4
                            [21] => 3
                        )

                    [1] => Array
                        (
                            [1] => 3
                            [2] => 2
                            [3] => 0
                            [4] => 1
                            [6] => 3
                            [7] => 6
                            [8] => 2
                            [9] => 1
                            [10] => 0
                            [11] => 1
                            [13] => 0
                            [14] => 3
                            [15] => 1
                            [16] => 1
                            [17] => 0
                            [18] => 0
                            [20] => 3
                            [21] => 3
                        )

Wrapping works perfectly, I get 6 numbers wrapped for each entry, but I need to add repeating classes to them, and my head is just empty.
EDIT
So in theory this should work:
<?php

$i = 1;

for( $i; $i < 14; $i++ ) {
    if( ($i-2/3) % 3 == 0 ){
        print_r('TRUE for '.$i."\r\n");
    } else {
        print_r('false for '.$i."\r\n");
    }
}

So for 1, 4, 7, 10, 13, ... the check should be
($i-2/3) % 3 == 0

Because the nth term of that sequence is:
a_n = 3n-2; n= 1, 2, 3, ...

Likewise for 2, 5, 8, 11, 14, ... the formula for the nth term is
a_n = 3n-1; n= 1, 2, 3, ...

That is,
($i-1/3) % 3 == 0

But when I try with
if( $wrap_count % 6 == 1 ){
    if ( ($wrap_count-2/3) % 3 == 0 ) {
        $swipe_title = 'total';
    } elseif( ($wrap_count-1/3) % 3 == 0){
        $swipe_title = 'hemma';
    } else{
        $swipe_title = 'borta';
    }
    if ($wrap_count % 18 == 1) {
        $out .= '

';
    } else{
        $out .= '
';
    }
}

I only get the total out. I added a wrapper around every 3 smaller wrappers so that it looks like

        220096

        110053

        110043

The math is sound, but the programming logic is obviously faulty somewhere...

A: So I added
data-num="'.$wrap_count.'"

To my
$out .= '
';

And I always got 1, 7, 13. Which makes sense since I want to wrap 6 of them.
So I just added:
if ( $wrap_count == 1 ) {
    $swipe_title = 'total';
}

if ( $wrap_count == 7 ){
    $swipe_title = 'hemma';
}

if ( $wrap_count == 13 ) {
    $swipe_title = 'borta';
}

I need to check it for other results, but this should work.


text:
Q: Sudden drop in SQL Azure query performance after moving web app to Azure What could explain this big drop in performance in an Azure SQL DB after moving the app from an hosted VPS to an Azure App service?

Here's a typical chart from Query Store's High Variation chart over the past two weeks. The red arrow indicates when I moved the production app from another hosting provider to an Azure App. Prior to moving the app, I experienced zero timeouts. Now, using the same Azure SQL DB, timeouts are triggering frequently for longish queries (but by no means too arduous).
The only other change I made was change the user principle in the connection string. This user only has SELECT, INSERT, UPDATE, DELETE and EXECUTE permissions.
My theories are:
 - something to do with networking between the app and the db. Resiliency? But I have a SQL exec plan specified
 - something wrong with the user I set up?
 - bad plan regression (I have now enabled auto FORCE PLAN tuning)
 - a problem caused by Hangfire running on two servers simultaneously (now mitigated by moving HF tables to a new DB)
 - something is triggering some kind of throttling that I cannot figure out.
Here is a chart of timeouts from Log Analytics:

All help appreciated. Note: this site has had almost identical traffic over the past 30 days.
In fact, take a look at this from the SQL DB metrics over the past week:

And here is some Wait info - last 6 hours:
Blue = PARALLELISM
Orange = BUFFERIO


text:
Q: two dictionaries from text file where values are columns and key line counts My file has this pattern (this is an example). I want to create two dictionaries with each column as values, and key as integers.
John  Moor
Age   22
id    112
grade 60

Amy  Ling
Age  22
id   114
grade 67

The dictionaries should look like this:
dict1 = {1 : ["John", "Age", "id", "grade"], 2 : ["Amy", "Age", "id", "grade"]}
dict2 = {1 : ["Moor", 22, 112, 60], 2 : ["Ling", 22, 114, 67]}

I did some digging but most solution given is - first column as key and second column as value.
This much I could think of, tried to split column by readlines().split()[0] but did not work.
f = open(fname)
d = {}
for line in f:
    name, info = line.split()
    d[name] = info
print(d)

Any suggestion? Any Help? how should I do it? :)

A: You can use defaultdict to store data and strip and split** function to manipulate the line that you read.
file.txt
John  Moor
Age   22
id    112
grade 60

Amy  Ling
Age  22
id   114
grade 67

Here is the Code:
from collections import defaultdict

dict1 = defaultdict(list)
dict2 = defaultdict(list)

with open("file.txt") as file:
    idx = 1
    for line in file.readlines():
        stripped_line = line.strip()
        if stripped_line:
            items = stripped_line.split(" ")
            dict1[idx].append(items[0])
            try:
                dict2[idx].append(int(items[-1]))
            except:
                dict2[idx].append(items[-1])
        else:
            idx += 1

print(f"dict1: {dict(dict1)}")
print(f"dict2: {dict(dict2)}")

Output:
dict1: {1: ['John', 'Age', 'id', 'grade'], 2: ['Amy', 'Age', 'id', 'grade']}
dict2: {1: ['Moor', 22, 112, 60], 2: ['Ling', 22, 114, 67]}

Update
It would be more meaningful if you could store data like:
from collections import defaultdict

dict1 = defaultdict(list)

with open("file.txt") as file:
    is_first_line = True
    key = None
    for line in file.readlines():
        stripped_line = line.strip()
        if stripped_line:
            items = stripped_line.split(" ")

            if is_first_line:
                key = items[0] + ' ' + items[-1]
            else:
                try:
                    dict1[key].append({items[0]: int(items[-1])})
                except:
                    dict1[key].append({items[0]: items[-1]})
            is_first_line = False
        else:
            is_first_line = True

print(f"dict1: {dict(dict1)}")

output:
dict1: {'John Moor': [{'Age': 22}, {'id': 112}, {'grade': 60}], 'Amy Ling': [{'Age': 22}, {'id': 114}, {'grade': 67}]}


text:
Q: Is inclusion map not the same as identity? Wikipedia says $i$ is an inclusion means $i: A \to B$ with $A \subset B$ means $i(x) = x$ for each $x\in A$.
But doesn't this mean $i(A) = A$, so this is actually identity?

A: No it isn't the identity since it isn't surjective. In the case when $B=A$ then this injection is the identity.

A: Map i is not identity map,to be identity codomain and domain has to be same.
Also, we can say map i is identity on A.

A: Recall the definition: Two functions are equal if they have the same domain, codomain and if for each $x$ in the domain they take the same value...
You are missing the bolded part.

A: Two maps $f,g$ are the same if their domain is the same and $f(x)=g(x) \hspace{0.5cm}\forall \hspace{0.2cm}x \in D=D(f)=D(g)$. In your case the first condition is not satisfied.


text: Q: MikTeX Package Manager keeps the download status as 'downloading' even after the package had finished downloading and installing For example while installing the 'cancel' package the package had finished downloading and installing but the download dialogbox keeps showing the status as downloading as shown below in my Windows 8.1. This happens for any package I install via MikTeX package manager:


text:
Q: C++ Builder 6 - how to change very old looking Widgets to Windows look? I'm using C++ Builder 6 and f.e. Button or ProgressBar has very old look, like from Windows 95/98. :P
How can I change it? I actually want to make them like in Windows.
I mean make program in Builder and this program will show button in Windows 7 like it(button) looks in Windows 7, show ProgressBar in W10/W8 like it looks in W10/W8.
I want to make it depend on the OS.
I'm a beginner in C++ so please... make it really simple unless it is too hard.

A: C++Builder 6 predates XP and the Visual Styles feature, so its VCL has no built-in support for theming/styling at all (there are 3rd party components for custom skinning, though).  That is why your UI looks "old".
Many of the native VCL components are based on standard Win32 controls that support Visual Styles if a ComCtrl v6 manifest is added to your application.  However, several VCL components exhibit run-time problems when styled, since they were not designed to handle styling correctly.
Fortunately, you can install SoftGems XP Theme Manager to address these issues (SoftGems' code was integrated directly into the VCL in a later C++Builder version).
SoftGems' TThemeManager component dynamically hooks into various VCL components at runtime (and also allows user-defined hooks for custom controls) to fix styling-related bugs in them.  Just drop it on your MainForm, and optionally set a few properties to control what type of UI controls it hooks.
SoftGems' TXPManifest component has an embedded ComCtrl v6 manifest resource to enable Visual Styles.  Just drop it on your MainForm, there is nothing to configure.
However, enabling Visual Styles is all that TXPManifest does.  An app can only have one manifest, and if you need to customize the manifest (such as for handling UAC, specifying Windows compatibility flags, etc - things which most modern apps pretty much need to do nowadays), don't use TXPManifest at all.  You will have to create your own custom manifest, compiled into a .res file that is linked into the resources of your application's .exe file.  The easiest way to do that is to define the manifest content in an external .manifest file and then compile it into a .res file using an .rc file, eg:
myapp.exe.manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="*"
    name="CompanyName.ProductName.YourApplication"
    type="win32"
  />
  <description>Your application description here.</description>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
        type="win32"
        name="Microsoft.Windows.Common-Controls"
        version="6.0.0.0"
        processorArchitecture="*"
        publicKeyToken="6595b64144ccf1df"
        language="*"
      />
    </dependentAssembly>
  </dependency>

  <!-- other manifest elements as needed -->

</assembly>

mymanifest.rc:
#define APP_MANIFEST 1
#define RT_MANIFEST 24

APP_MANIFEST RT_MANIFEST "myapp.exe.manifest"

If you add the .rc file to your project, the .manifest file will be compiled and linked into the .exe automatically.  Otherwise, you will have to manually compile the .rc file into a .res file using C++Builder's command-line brcc32 tool, and then you can add the resulting .res file to your project:
brcc32 mymanifest.rc

Otherwise, forget all of this and just use 3rd-party component suites that provide advanced UIs and functionality, such as TMS, DevExpress, Raize, etc.


text:
Q: Add new class to dataset mscoco, object detection tensorflow I would like to add a new class(example: Handgun) to the coco dataset(90 classes) so I would detect 91 different classes.
I have this:
dataset: 300 image about Handgun
labelmap.pbtxt:
item {
    id: 1
    name: 'Handgun'
}

pipeline.config:
num_classes: 1
fine_tune_checkpoint: "/media/Shared/faster_rcnn_resnet101_coco_2018_01_28/model.ckpt"
from_detection_checkpoint: true
load_all_detection_checkpoint_vars: true

Possible solution: Change num_classes: 1 to num_classes: 90+1?
Thank you so much for answer me.

A: Unfortunately you cannot just add one class, retrain and able to recognize all 91 classes. If you want to have model trained for all 91 classes, download the coco dataset , add your own dataset with labels and then train the model. Other option is to retrain a second model only with one class and infer that one class using this newly trained second model. You will have to infer other 90 classes using the available model seperately. You can learn about doing custom object detection using response in following post
Tensorflow real time object detection

A: The one way you can do it is to use the new dataset and the existing dataset like COCO and club them, create a new training record and then train it


text:
Q: Visual Studio VSIX template with Nuget Packages I'm trying to follow this tutorial (https://samritchie.net/2012/09/17/nuget-packages-in-vs2012-templates/) to create a Visual Studio VSIX template with Nuget package dependencies that just auto-install when you download the template, but I'm running into issues.
I can't get the packages to auto-install. It's like the VSIX project is completely ignoring the <Wizard> tags in the .vstemplate. I think I must have skipped some essential step. Here's an equivalent tutorial I've been following too: http://docs.nuget.org/create/packages-in-visual-studio-templates
I think this part is the source of my confusion:

There is no such place to insert these tags in my .vsixmanifest file -- it's an editor thing where you have to fill in fields. I'm not sure how this translates.

The assets tab has a "New" option, but you can't choose a type that looks like .nupkg -- there's no option for that.
Thanks for any help.

A: You can right-click the template file in the code file and choose "view code". This way you can see and edit the actual XML File.
Mine looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
  <Metadata>
    <Identity Id="<My VSIXProjectTemplateCode>" Version="1.0" Language="en-US" Publisher="Marcio Sales" />
    <DisplayName>FSharp Report Template</DisplayName>
    <Description xml:space="preserve">F# project template for analyzing data</Description>
  </Metadata>
  <Installation>
    <InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[14.0]" />
  </Installation>
  <Dependencies>
    <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.5,)" />
  </Dependencies>
  <Assets>
    <Asset Type="fsharp.formatting.2.14.4.nupkg" d:Source="File" Path="Packages\fsharp.formatting.2.14.4.nupkg" d:VsixSubPath="Packages" />
    <Asset Type="Microsoft.VisualStudio.ProjectTemplate" d:Source="File" Path="ProjectTemplates" d:TargetPath="ProjectTemplates\FSReport.zip" />
  </Assets>
</PackageManifest>


text:
Q: adding digital signature to PDF with visible timestamp and Reason field using ESIG/DSS I am trying to understand and implement a solution based on European Commission-sponsored Digital Signature Service project. I currently have succeeded in using the abstraction provided by the DSS-DEMO application, mentioned in the aforementioned github link, with the help of Nowina NexU client software. My wish is to digitally sign a PDF document with the following configuration:

*

*no container

*PAdES signature form

*enveloped

*PAdES_BASELINE_LT signature level

*SHA256 digest algorithm

I want the signature to have a visible part, i.e. to be seen on the first page of the document. This is somewhat demonstrated here. Personally, I need the actual signing timestamp and the name of the signer from her certificate. In the above demonstration this is done by providing "parameters" to the signing function.
I also want to fill the Reason field of the signature - it is then subsequently displayed when you view the Signature properties with a program like Adobe Acrobat Reader.
My problems so far are the following, and I can't seem to find neither examples nor other sort of information about them.

*

*If I want to display the signing timestamp that I would get from a Timestamp Authority service, how would I get it, since the communication with the timestamp server is done during the signing process, i.e. after specifying the parameters as I mention above. I guess I have to dig into DSS code and do all the steps done there for me myself.

*Currently, a strange thing happens. It appears that the signatures are deemed valid, or at least UNKNOWN, when I specify a hardcoded Reason (like 'testtest'), or no Reason at all. When I fill it from results of something else, the signature is not valid. Because things like this don't usually happen by magic, I must be doing something awfully wrong.

The code is organized approximately like this - there's a REST communication between two machines - a server and a client with NexU installed. NexU does all the communication with the smart card or any other certificate store on the client machine - it exchanges the digest value and the signed digest value with the server. There are, among others, two specific phases in the server code :

*

*getDataToSign - here a digest is calculated from the PDF content

*signDocument - here the actual signing - (embedding of the signature into the document, i guess?) takes place.

I am giving to both these phases a host of parameters, that, among other things, specify the signing timestamp, the Reason, and the visual parameters of the text I want to appear on the first page. I am doing this with the same parameters for both of the phases (because I am not sure on which phase I should give which)
My signing date - isn't it logical for it to be as close to the timestamp authority server's timestamp as can be? Okay - I am setting it to the current timestamp of my own server at the time of the beginning of the signing process.
I am setting Reason using PAdESSignatureParameters.setReason.
Any helpful insight is appreciated - thanks.

A: *

*I have solved the weird issue with the Reason field of the Signature.

*I don't seem to see any way around the Signing Date being different from the Timestamping Authority-provided Timestamp.

Explanation follows.
As far as the first case, it was my fault. To elaborate, following my understanding, the signature parameters are provided to the DSS methods two times using SigningService.fillParameters() method.

*

*in SigningService.getDataToSign(...) and then

*in SigningService.signDocument(...)

This is important to be done in both methods, because during the first time, the hash/digest of the document-to-be-signed is calculated. Since I have chosen the signature to be enveloped, i.e. to be contained within the document that is going to be signed, we need to first apply the signature, and then calculate the digest basing on that "final" document.
As far as I saw in the DSS code (approximately), the in-memory representation of the uploaded PDF is signed, and its digest is calculated, during getDataToSign - but the outcome is discarded.
During the actual signDocument method (in between, the digest has travelled back to the client with NexU installed, and returned back to the server signed), the uploaded PDF is signed again, its digest calculated again, but this time the actual signed digest (we got from the client) is also applied to the document - and the in-memory outcome of this operation is sent back to the client as a signed PDF document.
What I was doing wrong is that during the first time, I was losing the variable that I was going to add as the Reason (it was lost somewhere in the model attributes - i was not passing it somewhere in between requests), with the result of my first map of parameters passed to getDataToSign differing from the second map of parameters - so it is only logical, that the actual hash/digest of the document was different from the digest in the saved signature (because at the time the digest-to-be-signed was calculated, i wasn't passing the Reason). That's why when I was passing a hardcoded value, because it was hardcoded, it was present during both calls to fillParameters. It was such a stupid mistake, I know. I should have known this because there was absolutely nothing about any difficulties with passing Reason (or other fields like Location) to the Signature.
BTW the signing is done using Apache PDFBox, and it is done incrementally.
As for the second thing, we decided to leave it as it is, although there is a comparatively impressive gap between the signing timestamp and the timestamp authority one. I don't really know what should be the allowed gaps in cases like this. I guess that this happens because

*

*My server might have a slightly off-normal local time

*Because the whole process of signing is going on between two machines (server and client with NexU installed, as well as the smart card), and because there are different dialog windows appearing asking for password etc. - it all postpones the actual signing and the call to the timestamping authority is done during the very last step. Of course, I am not sure if it is an issue, since theoretically timestamping authority doesn't know about the actual contents being changed - the previous error would have been triggered in that case..

That's more like it - of course I am open to other comments and answers. Thank you!


text:
Q: Linking Boost Libraries in Linux Cent OS 7.0 My IDE is Clion, but I think it doesn't matter since it uses CMakeLists.txt.
Here is my main.cpp in which I include boost filesystem.hpp:
#include <iostream>
#include <boost/filesystem.hpp>

using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

Here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.2)
project(AsioFirst)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories("/usr/local/src/boost_1_60_0/boost_1_60_0/")

link_directories("/usr/local/src/boost_1_60_0/boost_1_60_0/stage/lib")

set(SOURCE_FILES main.cpp)
add_executable(AsioFirst ${SOURCE_FILES})

But when I run that (using arguments -lboost_system  -lboost_filesystem), I get the following error which is probably a linking error:
boost::system::generic_category()

Directories are double checked, and they are correct.

A: Do not hardcode your dependencies/library paths. Better use find_package command to find Boosts include directories and libraries:
cmake_minimum_required(VERSION 3.2)
project(AsioFirst)

#Add a hint about your boost copy
set(BOOST_ROOT "/usr/local/src/boost_1_60_0/boost_1_60_0/")
find_package(Boost REQUIRED COMPONENTS filesystem system)

set(SOURCE_FILES main.cpp)
add_executable(AsioFirst ${SOURCE_FILES})

#More portable than setting CMAKE_CXX_FLAGS
set_property(TARGET AsioFirst PROPERTY CXX_STANDARD 11)
target_include_directories(AsioFirst PRIVATE ${Boost_INCLUDE_DIRS})
target_link_libraries(AsioFirst PRIVATE ${Boost_LIBRARIES})

A: I post this for future visitors:
The solution was that I should have added the exact link to the libraries used:
link_libraries("/usr/local/src/boost_1_60_0/boost_1_60_0/stage/lib/libboost_system.so")
link_libraries("/usr/local/src/boost_1_60_0/boost_1_60_0/stage/lib/libboost_filesystem.so")

It seems the arguments lboost_system  -lboost_filesystem did not resolve the linking.


text:
Q: Why is the Turf Javascript library's 'transformTranslate' function distorting geometries? I'm working on a webapp using MapBoxGL and TurfJS and I've encountered an issue using Turf's transformTranslate, which is defined here.
Now, the issue is that a geometry that is being transformed is getting distorted.
For example, this is the original geometry:

And this is the translated geometry:

And the relevant section of code is this:
  console.log(typology)

  var typologyCentroid = centroid(typology)
  var mapCenter = this.$store.state.map.getCenter()
  var mapCenterToTurf = lngLatToTurfPoint(mapCenter)

  var typologyDistToMapCenter = rhumbDistance(typologyCentroid, mapCenterToTurf)
  var typologyBearingToMapCenter = rhumbBearing(typologyCentroid, mapCenterToTurf)

  var translatedPoly = transformTranslate(typology, typologyDistToMapCenter, typologyBearingToMapCenter)

  console.log(translatedPoly)

The actual goal is to get a feature and shift it to be in the centre of the current map display. I can't understand why the translate is twisting and distorting the feature though.
Edit: it turns out that I can achieve what I want by just using a simple shift (adding deltaX and deltaY to each coordinate). I'm surprised that the Turf function doesn't work as expected, though... I'm leaving the question up.


text:
Q: Full width landscape image in koma script I need an image the biggest possible and then show it in landscape. I use koma options in a classic thesis flavour. I don't find any solution to have it bigger than the textwidth but staying in the center of the page.
I have tried with
\KOMAoptions{paper=landscape}

\begin{addmargin}

can anyone help? no solution
Thank you


text:
Q: Can't bind to 'lazyLoad' since it isn't a known property of 'img' - Ionic 4 - ng-lazy-load I am trying to get lazyLoad to work on my Ionic 4 app. I have imported it on my app.module.ts, and are trying to use it on my page. I'm not sure what the issue is and any help is greatly appreciated.
app.module.ts
import { LazyLoadImageModule, intersectionObserverPreset } from 'ng-lazyload-image';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule, IonicStorageModule.forRoot(),LazyLoadImageModule.forRoot({preset: intersectionObserverPreset})],
  providers: [
    StatusBar,
    SplashScreen,
    Insomnia,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

my page.html
<ion-col size="2" *ngFor="let movie of browseResults| keyvalue">

☆ {{movie.value.rating}}

      </ion-col>

And I'm importing it on the component.ts for this page but not sure what else to do. It's not really being used on the component.


text:
Q: How can I use a Rails helper inside Jbuilder with the Gon gem? I'm using Jbuilder and Gon to structure my JSON responses into variables and pass them to my JS front-end. In the Jbuilder files, I'd like to access the helper methods I'm using from the Money-Rails gem. However, if I try something like this...
// edit.json.jbuilder

json.minimum_premium money_without_cents limit.minimum_premium

I get an undefined method `money_without_cents' for #<Gon::Jbuilder::Parser:0x00007fbb6ebca198> error.
Is there a trick to using helper methods inside Jbuilder when using the Gon gem?

A: This worked, though there might be better solutions...
// edit.json.jbuilder

json.minimum_premium ActionController::Base.helpers.money_without_cents limit.minimum_premium


text:
Q: Generating PDF using itestsharp I'm trying to generate a pdf file using itextsharp.
Here is the method that's supposed to generate the PDF:
private void Page_onPreRenderComplete(object sender, EventArgs e)
{
    // createPdf.GeneratePDF(htmlMarkup);
    MemoryStream memoryStream = new MemoryStream();

    StringBuilder sBuilder = new StringBuilder();
    StringWriter sw = new StringWriter(sBuilder);
    HtmlTextWriter htmlText = new HtmlTextWriter(sw);

    Page.RenderControl(htmlText);
    string pdfBody = sBuilder.ToString();

    Document document = new Document();
    PdfWriter.GetInstance(document, memoryStream);

    document.Open();
    StyleSheet styles = new StyleSheet();
    HTMLWorker hw = new HTMLWorker(document);

    try
    {
        hw.Parse(new StringReader(pdfBody));
    }
    catch (Exception ex)
    {
       string msg = ex.Message;
    }
    finally
    {
        document.Close();
    }

    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpContext.Current.Response.Write(memoryStream);
    HttpContext.Current.Response.End();
}

an error is generated on the line within the try block. How can I fix this?

A: may be the image tags etc are in relative paths instead of absolute paths in the rendered HTML


text:
Q: How to create dict object from a casted string? I'm trying to edit some dictionary values using Regular Expression and change them back into a dict object.
I am checking IP data using Shodan API, this returns a set of results, more than I need.
Shodan Ip
ipinfo {'city': None, 'region_code': None, 'os': None, 'tags': ['vpn'], 'ip': 771247238, 'isp': 'Host Universal Pty', 'area_code': None, 'dma_code': None, 'last_update': '2019-05-01T06:53:53.130508', 'country_code3': 'AUS', 'country_name': 'Australia', 'hostnames': [], 'postal_code': None, 'longitude': 143.2104, 'country_code': 'AU', 'ip_str': '45.248.76.134', 'latitude': -33.494, 'org': 'Host Universal Pty', 'data': [{'_shodan': {'id': 'bc2dc252-5b9d-4b3d-975f-0156860c8849', 'options': {}, 'ptr': True, 'module': 'https', 'crawler': '65e79faecee26516a8ed6f16c1142432f303fbdc'}, 'hash': 0, 'os': None, 'opts': {}, 'ip': 771247238, 'isp': 'Host Universal Pty', 'port': 443, 'hostnames': [], 'location': {'city': None, 'region_code': None, 'area_code': None, 'longitude': 143.2104, 'country_code3': 'AUS', 'country_name': 'Australia', 'postal_code': None, 'dma_code': None, 'country_code': 'AU', 'latitude': -33.494}, 'timestamp': '2019-05-01T06:53:53.130508', 'domains': [], 'org': 'Host Universal Pty', 'data': '', 'asn': 'AS136557', 'transport': 'tcp', 'ip_str': '45.248.76.134'}, {'_shodan': {'id': 'cdce36e7-588f-4377-8cc6-f9bedd426e6b', 'options': {}, 'ptr': True, 'module': 'https', 'crawler': '0636e1e6dd371760aeaf808ed839236e73a9e74d'}, 'hash': 0, 'os': None, 'opts': {}, 'ip': 771247238, 'isp': 'Host Universal Pty', 'port': 8443, 'hostnames': [], 'location': {'city': None, 'region_code': None, 'area_code': None, 'longitude': 143.2104, 'country_code3': 'AUS', 'country_name': 'Australia', 'postal_code': None, 'dma_code': None, 'country_code': 'AU', 'latitude': -33.494}, 'timestamp': '2019-04-26T18:31:18.138759', 'domains': [], 'org': 'Host Universal Pty', 'data': '', 'asn': 'AS136557', 'transport': 'tcp', 'ip_str': '45.248.76.134'}, {'_shodan': {'id': '27e5f5e0-662e-4621-b043-56d64d25f38d', 'options': {}, 'ptr': True, 'module': 'http', 'crawler': 'c9b639b99e5410a46f656e1508a68f1e6e5d6f99'}, 'hash': 0, 'os': None, 'opts': {}, 'ip': 771247238, 'isp': 'Host Universal Pty', 'http': {'robots_hash': None, 'redirects': [], 'securitytxt': None, 'title': None, 'sitemap_hash': None, 'robots': None, 'server': None, 'host': '45.248.76.134', 'html': None, 'location': '/', 'html_hash': None, 'sitemap': None, 'securitytxt_hash': None}, 'port': 8080, 'hostnames': [], 'location': {'city': None, 'region_code': None, 'area_code': None, 'longitude': 143.2104, 'country_code3': 'AUS', 'country_name': 'Australia', 'postal_code': None, 'dma_code': None, 'country_code': 'AU', 'latitude': -33.494}, 'timestamp': '2019-04-21T03:00:14.986062', 'domains': [], 'org': 'Host Universal Pty', 'data': '', 'asn': 'AS136557', 'transport': 'tcp', 'ip_str': '45.248.76.134'}, {'_shodan': {'id': 'bfbc3556-d00d-4512-8cb3-32ef6cae9964', 'options': {}, 'ptr': True, 'module': 'ike', 'crawler': '8cd926590a400feb4b683f8337a77287ddf3d2c7'}, 'hash': -451677272, 'os': None, 'tags': ['vpn'], 'opts': {'raw': '61713862726c6c3764627037343033792920252800000000000000240000000800000005'}, 'ip': 771247238, 'isp': 'Host Universal Pty', 'port': 500, 'isakmp': {'initiator_spi': '61713862726c6c37', 'responder_spi': '6462703734303379', 'msg_id': '00000000', 'next_payload': 41, 'exchange_type': 37, 'length': 36, 'version': '2.0', 'flags': {'encryption': False, 'authentication': False, 'commit': False}, 'aggressive': {'initiator_spi': 'a6517b6a97dca862', 'responder_spi': '1655d8123c9f2104', 'msg_id': 'd14144c6', 'next_payload': 11, 'exchange_type': 5, 'length': 40, 'version': '1.0', 'flags': {'encryption': False, 'authentication': False, 'commit': False}, 'vendor_ids': []}, 'vendor_ids': []}, 'hostnames': [], 'location': {'city': None, 'region_code': None, 'area_code': None, 'longitude': 143.2104, 'country_code3': 'AUS', 'country_name': 'Australia', 'postal_code': None, 'dma_code': None, 'country_code': 'AU', 'latitude': -33.494}, 'timestamp': '2019-04-13T11:18:42.166709', 'domains': [], 'org': 'Host Universal Pty', 'data': 'VPN (IKE)\n\nInitiator SPI: 61713862726c6c37\nResponder SPI: 6462703734303379\nNext Payload: RESERVED\nVersion: 2.0\nExchange Type: DOI Specific Use\nFlags:\n    Encryption:     False\n    Commit:         False\n    Authentication: False\nMessage ID: 00000000\nLength: 36', 'asn': 'AS136557', 'transport': 'udp', 'ip_str': '45.248.76.134'}], 'asn': 'AS136557', 'ports': [443, 8443, 8080, 500]}

I use Regular Expression to delete the data I don't need. This deletes anything from the fields' data' onwards.
osint_ip1 = re.sub("..'data':.*", "}", str(ipinfo))

Heres the problem... Since Showdan returns inconsistently depending on the IP, I need to use a Dirctwriter to write the corresponding values to there fields.
The problem with this is I have to cast ipinfo as a string to edit the data, and the string object canot be used in the CSV Directwriter.
How do I turn the string back into direction format?
OSINT(STRING)
rejoin : ["{'city': None", " 'region_code': None", " 'os': None", " 'tags': ['vpn']", " 'ip': 771247238", " 'isp': 'Host Universal Pty'", " 'area_code': None", " 'dma_code': None", " 'last_update': '2019-05-01T06:53:53.130508'", " 'country_code3': 'AUS'", " 'country_name': 'Australia'", " 'hostnames': []", " 'postal_code': None", " 'longitude': 143.2104", " 'country_code': 'AU'", " 'ip_str': '45.248.76.134'", " 'latitude': -33.494", " 'org': 'Host Universal Pty'}"]

Full code below
import csv
import os
import re
import time

import shodan
from shodan import Shodan

def OPSINT():
    for x in ip:
        print(x)
        try:
            ipinfo = api.host(x)
        except shodan.exception.APIError:
            ipinfo = None
            pass
        filename = 'C:\\ProgramData\\FDA\\output\\processed\\OSINT.csv'

        if ipinfo != None:
            osint_ip1 = re.sub("..'data':.*", "}", str(ipinfo))
            osint_ip = osint_ip1.split(',')
            print("rejoin :", osint_ip)

           # print(osint_ip)
            print("ipinfo", ipinfo)

            with open("C:\\ProgramData\\FDA\\output\\processed\\OSINT.csv", 'a') as csvfile:
                fieldnames = ['city', 'region_code', 'os', 'tags', 'ip', 'isp', 'area_code', 'dma_code', 'last_update',
                              'country_code3', 'country_name', 'hostnames', 'postal_code', 'longitude', 'country_code',
                              'ip_str', 'latitude', 'org']
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                fileEmpty = os.stat(filename).st_size == 0
                if fileEmpty:
                    writer.writeheader()
                else:
                    writer.writerows(osint_ip)

                csvfile.close()

A: A dict is a well-structured data type meant to be accessed and/or manipulated via keys. Manipulating a dict by converting it to a string and performing regex substitution is wholly unnecessary and error-prone.
Since you've already defined the exact keys you want as fieldnames, you can simply use operator.itemgetter to get the values of these keys from the dict ipinfo, and zip them with the key names to construct a new dict for csv.DictWriter.writerow to write from:
from operator import itemgetter
...
writer.writerow(dict(zip(fieldnames, itemgetter(*fieldnames)(ipinfo))))


text:
Q: Any advantage in linking Facebook login app with Facebook fan page? I am creating an ecommerce website for which I will have FB login supported. I also will have a FB fan page. While supporting the facebook login app, there is an option to attach the FB page to the login app (App -> app-name -> App Details -> Contact Info -> App page). The problem I am facing is that to connect the FB page, I need to categorize my page as an 'App Page' under the 'Brands and Products' category, and I don't feel comfortable in doing that.
Hence, want to know what advantages I get if I connect the facebook page to the login app?

A: If you are not comfortable changing the category of your page, then I would like to inform you that it is not permanent. You can change the Category back to what you had previously once you've linked the page. You can follow this thread for more information.
The advantage of a Fan Page is that it provides information and updates to the users using your application. It is better to create a fan page for an app, than maintaining a separate website.


text:
Q: Semitransparent background and opaque foreground wpf I currently have the following xaml code:
<Grid
    Name="rootGrid"
    Opacity=".25"
    Background="Black"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Stretch">
    <Border
        Background="Black"
        Margin="120">
        <Grid
            Background="White"
            Margin="8">
            <TextBlock
                Name="popupContent">
                Test
            </TextBlock>
            <Button
                Click="Button_Click">
                Test
            </Button>
        </Grid>
    </Border>
</Grid>

Currently, the Opacity setting on the Grid is also applied on its children.
I only want this opacity to be applied on its background color, to achieve a darkening effect, not on the foreground. How can I do this?

A: Use a semi-transparent background, either as a SolidColorBrush like
<Grid ...>
    <Grid.Background>
        <SolidColorBrush Color="Black" Opacity="0.25"/>
    </Grid.Background>
    ...
</Grid>

or by specifying an alpha value in the color, like
<Grid Background="#3F000000" ...>

A: The trick is to not add the Opacity to the entire Grid element:
<Grid>
    <Grid.Background>
        <SolidColorBrush Color="Black" Opacity=".75"/>
    </Grid.Background>
    <!--(Other elements)-->
</Grid>

A: This worked for me. I have two Grids a Root grid and RootContent sub-grid.  I control the Opacity of the RootContent. Any controls in the "Root" will not be effected.
<Grid x:Name="Root" KeyDown="Root_KeyDown" Tapped="Root_Tapped">
      <!--(Other elements)-->
   <Grid x:Name="RootContent">
          <!--(Other elements)-->
   </Grid>
</Grid>

A: The opacity will always apply to children, so I tend to use a Canvas at the same level to achieve this affect:
<Grid>
    <Canvas Opacity=".25"
        Background="Black"/>
    <Grid Name="rootGrid"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch">
        <Border
            Background="Black"
            Margin="120">
            <Grid
                Background="White"
                Margin="8">
                <TextBlock
                    Name="popupContent">
                    Test
                </TextBlock>
                <Button
                    Click="Button_Click">
                    Test
                </Button>
            </Grid>
        </Border>
    </Grid>
</Grid>


text:
Q: A de Bruijn sequence of infinite length? A de Bruijn sequence is a (typically) binary string of length $2^k$ which contains every binary string of length $k$ as a substring exactly once, if you allow it to wrap around. For example, 00010111 works for $k=3$.
I was wondering whether you could have one of infinite length, and brief consideration reveals that no, you can't; among other things, it would have to contain all possible binary sequences—themselves of infinite length—which would push it up to the cardinality of the continuum.
However, is it possible to make an optimal attempt at it? If we define optimal as the infinitely-long binary string for which the average distance in you need to look to first encounter any given substring is minimized, where 'average' is taken over all possible strings of some fixed length. It seems like you would also have to weight it so that shorter substrings are favored before longer ones, and repetitions of substrings of a given length avoided as much as possible.
If nothing else, I can reasonably say that it wouldn't start with 00000, but rather with something like 0110001... perhaps gluing de Bruijn sequences together for increasing $k$ is the best we can do?


text:
Q: Turning off part of a monitor I'm trying to disable the right third of my monitor, since it's broken. I can get less to be displayed using xrandr, but the monitor will then center the displayed stuff, so that's not quite what I want.
I'm using Ubuntu 14.04. Please let me know if more information would be useful, preferably along with a method for finding that info :P.

A: Monitor settings
You said you already got xrandr to display on a smaller portion of the screen, but that it's centered. If there is any way in your monitor settings to move the displayed portion to the left edge of the screen, then you're done.
Nesting X Servers
Try Xephyr or Xnest. They allow you to run an X server inside another X server. So something like this might work:
Xephyr -screen 1200x1080 :1

Set the resolution to whatever viewable area you have on your screen. Then you have an X server that only takes a portion of the screen.
For your first X server, you may not need to run a window manager, if you can get your .xinitrc to start Xephyr in the right size and location on the screen. Xephyr -geometry 800x600+0+0 doesn't work for me though.
You'll need to run a window manager/desktop environment inside Xephyr. I don't know the best way to do this at the moment.
Making your window manager avoid part of the screen
This is kind of an ugly fix, but you could create a large panel with nothing in it that covers the dead part of the screen. Set the panel so that no windows can cover it. This won't help if a program (like a video player) tries to draw on the full screen.
Reference
Question on Stack Overflow: X in a window in X


text:
Q: command execute with error when use expect in shell script while work fine in pure shell I try to start all the exited docker containers deployed in separated servers, so basically i should execute the essential command below
[ $(docker ps -a | grep Exited | wc -l) -ne 0 ] && docker start $(docker ps -a | grep Exited | cut -d' ' -f1)

It worked fine like in pure linux shell , but then error occured(show below) when i try to use expect to "send" the "essential" command. (local ip is 241,remote end is 209)
[root@localhost start_shell_dir]# spawn ssh root@192.168.1.209
root@192.168.1.209's password:
Last login: Fri Oct 15 22:23:25 2021 from 192.168.1.241
[root@localhost ~]# invalid command name "0"
    while executing
"0 -ne 0 "
    invoked from within
"send "[ 0 -ne 0 ] && docker start ""

The error log shows i have already log in the remote machine, and something wrong when i execute the docker command.
Glenn jackman from the comment area shows me the basic rule for tcl,then i realize expect does command substitutions before sending real command. We may see it from execute bash -x script.sh .
[root@localhost start_shell_dir]# bash -x startContainer.sh
+ read ip pass
+ read ip pass
+ /usr/bin/expect
[root@localhost start_shell_dir]# ++ docker ps -a
++ grep Exited
++ wc -l
++ docker ps -a
++ grep Exited
++ cut '-d ' -f1
spawn ssh root@192.168.1.209
root@192.168.1.209's password:
Last login: Fri Oct 15 22:37:56 2021 from 192.168.1.241
[root@localhost ~]# invalid command name "0"
    while executing
"0 -ne 0 "
    invoked from within
"send "[ 0 -ne 0 ] && docker start ""

Anyway, the final command that work for me is the command showed below(replace double quotes with braces and with backslash before $() to keep it as an ordinary character rather than pre-parse it).
send {[ \$(docker ps -a | grep Exited | wc -l) -ne 0 ] && docker start \$(docker ps -a | grep Exited | cut -d' ' -f1)}

#!/bin/bash
# my original script with error
while read ip pass
do
                {
                /usr/bin/expect <<-END
                spawn ssh root@$ip
                expect {
                "yes/no" { send "yes\r";exp_continue }
                "password:" { send "$pass\r" }
                }
                expect "#"
                send "[ $(docker ps -a | grep Exited | wc -l) -ne 0 ] && docker start $(docker ps -a | grep Exited | cut -d' ' -f1)"
                expect eof
                END
                }&

done<apps_ip.txt

A: Like the shell, Tcl (and expect) allows interpolation with double quotes. Tcl uses square brackets for command substitution (in the same way that the shell uses $(...))
Use curly braces to protect the contents of that string (analogous to the shell's single quotes):
send {[ $(docker ps -a | grep Exited | wc -l) -ne 0 ] && docker start $(docker ps -a | grep Exited | cut -d' ' -f1)}
#....^.............................................................................................................^
# and don't forget to hit Enter
send "\r"

See https://www.tcl-lang.org/man/tcl8.6/TclCmd/Tcl.htm for the few syntax rules of Tcl.


text:
Q: How to write a postman test to compare the response json against another json? I have the below json response after running a postMan test of a Rest API:
    {
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Now I would like to compare the above json against a predefined json. Say, its the same as above.
How can I compare two jsons via the Postman test?

A: I had a similar problem to solve except that my JSON also contained an array of objects. I used the following technique that can be modified to deal with the simple array of strings in your question.I created an array of global functions called "assert", which contained helper functions such as "areEqual" and "areArraysOfObjectsEqual" and saved these under the "Tests" tab at a top folder level of my tests.
assert = {
    areEqual: (actual, expected, objectName) => {
        pm.test(`Actual ${objectName} '` + actual + `' matches Expected ${objectName} '` + expected + `'`, () => {
            pm.expect(_.isEqual(actual, expected)).to.be.true;
        });
    },
    areArraysOfObjectsEqual: (actual, expected, objectName) => {
        if (!_.isEqual(actual, expected)) {

            // Arrays are not equal so report what the differences are
            for (var indexItem = 0; indexItem < expected.length; indexItem++) {
                assert.compareArrayObject(actual[indexItem], expected[indexItem], objectName);
            }
        }
        else
        {
            // This fake test will always pass and is just here for displaying output to highlight that the array has been verified as part of the test run
            pm.test(`actual '${objectName}' array matches expected '${objectName}' array`);
        }
    },
    compareArrayObject: (actualObject, expectedObject, objectName) => {
        for (var key in expectedObject) {
            if (expectedObject.hasOwnProperty(key)) {
                assert.areEqual(expectedObject[key], actualObject[key], objectName + " - " + key);
            }
        }
    }
};

Your "Pre-request Script" for a test would set your expected object
 const expectedResponse =
    {
        "id": "3726b0d7-b449-4088-8dd0-74ece139f2bf",
        "array": [
            {
                "item": "ABC",
                "value": 1
            },
            {
                "item": "XYZ",
                "value": 2
            }
        ]
    };

    pm.globals.set("expectedResponse", expectedResponse);

Your Test would test each item individually or at the array level like so:
const actualResponse = JSON.parse(responseBody);
const expectedResponse = pm.globals.get("expectedResponse");

assert.areEqual(
    actualResponse.id,
    expectedResponse.id,
    "id");

assert.areArraysOfObjectsEqual(
    actualResponse.myArray,
    expectedResponse.myArray,
    "myArrayName");

This technique will give nice "property name actual value matches expected value" output and works with arrays of objects being part of the JSON being compared.
Update:
To test your array of strings "GlossSeeAlso", simply call the supplied global helper method in any of your tests like so:
assert.compareArrayObject(
    actualResponse.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,
    expectedResponse.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,
    "glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso");

Primitive types in JSON key value pairs can be tested like so:
assert.areEqual(
    actualResponse.glossary.title,
    expectedResponse.glossary.title,
    "glossary.title");

A: I got it after a while. Add test into your request and use Runner to run all your requests in the collection.
Postman info: Version 7.10.0 for Mac.
Test scripts:
pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.eql({
        "key1": "value1",
        "key2": 100
    });
});

A: You can write javascript code inside Tests tab of Postman. Just write simple code to compare and check result in Tests.
var serverData = JSON.parse(responseBody);
var JSONtoCompare = {}; //set your predefined JSON here.
tests["Body is correct"] = serverData === JSONtoCompare;

A: You can paste this code into your collection or single request tests tab.
What this code do is to save the request into a global variable with a key for that request. You can change your enviroment and hit the same request and if the response are different the test will fail.
const responseKey = [pm.info.requestName, 'response'].join('/');
let res = '';
try {
    res = JSON.stringify(pm.response.json());
} catch(e) {
    res = pm.response.text();
}

if (!pm.globals.has(responseKey)) {
    pm.globals.set(responseKey, res);
} else {
    pm.test(responseKey, function () {
        const response = pm.globals.get(responseKey);
        pm.globals.unset(responseKey);
        try {
            const data = pm.response.json();
            pm.expect(JSON.stringify(data)).to.eql(response);
        } catch(e) {
            const data = pm.response.text();
            pm.expect(data).to.eql(response);
        }
    });
}

Hope this help.

A: Looks like the same question asked at POSTMAN: Comparing object Environment variable with response's object which also lists a solution that works, which is to use JSON.stringify() to turn the objects into strings and then compare the strings.

A: Came across this issue when migrating from a legacy API to a new one and wanting to assert the new API is exactly the same as the old under different scenarios
For context this clones params of the original get request to the legacy endpoint and validates both match up
LEGACY_API_URL should be defined in the environment and the Request is going to the new API

const { Url } = require('postman-collection');

// Setup the URL for the Legacy API
const legacyRequestUrl = new Url({ host: pm.variables.replaceIn("http://{{LEGACY_API_HOST}}/blah")});

// Add All Parameters From the Source Query
legacyRequestUrl.addQueryParams(pm.request.url.query.all());

// Log out the URL For Debugging Purposes
console.log("URL", legacyRequestUrl.toString());

pm.sendRequest(legacyRequestUrl.toString(), function (err, response) {
    pm.test('New API Response Matches Legacy API Response', function () {

        // Log Out Responses for Debugging Purposes
        console.log("New API Response", pm.response.json())
        console.log("Legacy API Response", response.json())

        // Assert Both Responses are Equal
        pm.expect(_.isEqual(pm.response.json(), response.json())).to.be.true
    });
});

Link to an example collection

https://www.getpostman.com/collections/4ff9953237c0ab1bce99

A: Write JavaScript code under 'Tests' section. Refer below link for more info.
Click Here


text:
Q: Not able to access NSMutableArray from another class I've read through many posts here but I can't seem to make my array available in another class.
I want to access the array plusTransactions in CPPHistoryViewController (a table controller, in a container as a child of CPPSecondViewController) from class CPPSecondViewController.
CPPSecondViewController.h
#import <UIKit/UIKit.h>
@interface CPPSecondViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedController;
@property (weak, nonatomic) NSMutableArray *plustransactions;
@property (weak, nonatomic) NSMutableArray *campustransactions;
@property (weak, nonatomic) NSMutableArray *mealtransactions;

@end

CPPSecondViewController.m
#import "CPPSecondViewController.h"
@interface CPPSecondViewController ()
@implementation CPPSecondViewController
@end

@synthesize plustransactions = _plustransactions;
@synthesize campustransactions = _campustransactions;
@synthesize mealtransactions = _mealtransactions;

...

_plustransactions = newPlustransactions;
NSLog(@"%@", newPlustransactions);
NSLog(@"%@%lu", @"That's how many: ", (unsigned long)_plustransactions.count);
CPPHistoryViewController *historyView = [[CPPHistoryViewController alloc]init];
[historyView.tableView reloadData];

This is good, returns all of my array items and count is 7.
CPPHistoryViewController.h
#import <UIKit/UIKit.h>

@interface CPPHistoryViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
@end

CPPHistoryViewController.m
#import "CPPHistoryViewController.h"
#import "CPPSecondViewController.h"
#import "CPPPlusTransaction.h"
#import "CPPCampusTransaction.h"
#import "CPPMealTransaction.h"
#import "CPPHistoryCell.h"

@interface CPPHistoryViewController ()

@end

@implementation CPPHistoryViewController

...

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    CPPSecondViewController *secondView = [[CPPSecondViewController alloc] init];
    NSMutableArray *plusTransactions = [[NSMutableArray alloc]init];
    plusTransactions = secondView.plustransactions;
    NSMutableArray *campusTransactions = [[NSMutableArray alloc]init];
    campusTransactions = secondView.campustransactions;
    NSMutableArray *mealTransactions = [[NSMutableArray alloc]init];
    mealTransactions = secondView.mealtransactions;
    NSLog(@"Table formatting called");
    NSLog(@"%ld", (long)secondView.segmentedController.selectedSegmentIndex);
    switch (secondView.segmentedController.selectedSegmentIndex) {
        case 0:
            NSLog(@"%@%lu", @"PlusTransactions", (unsigned long)plusTransactions.count);
            return plusTransactions.count;
            break;
        case 1:
            NSLog(@"%@%lu", @"CampusTransactions", (unsigned long)campusTransactions.count);
            return campusTransactions.count;
            break;
        case 2:
            NSLog(@"%@%lu", @"MealTransactions", (unsigned long)mealTransactions.count);
            return mealTransactions.count;
            break;
    }
    return 1;
}

...

@end

Here's where things get weird. Any array I call from here returns with a count of 0. Any ideas?

A:  CPPSecondViewController *secondView = [[CPPSecondViewController alloc] init];

Here you are creating a new object, So all values are nill.
Here you can only set values in to second view controller.
in your History class, you nedd to create a property of a second class they you can set value in to Second class
@property (nonatomic, retain) Secondclass* secondclass;

[secondClass setAry: ary];

A: I assume what you want is to get the array data stored in CPPSecondViewController to be availalbe in CPPHistoryViewController. But as per the code you posted,
CPPHistoryViewController *historyView = [[CPPHistoryViewController alloc]init];
[historyView.tableView reloadData];

This just create new instance and the tableView inside the view is reloaded. But in cellForRowAtIndexPath, you are creating new instance of CPPSecondViewController, thats wrong.
What you can do is, simply pass the CPPSecondViewController instance before reloading tableView.
In CPPHistoryViewController.h, create a property for keeping secondView like this
@property (strong, nonatomic) CPPSecondViewController *secondView;

then, change your code in CPPSecondViewController like below:
CPPHistoryViewController *historyView = [[CPPHistoryViewController alloc]init];
historyView.secondView = self;
[historyView.tableView reloadData];

Also, remove alloc init statements from cellForRowAtIndexPath, just use secondView.plustransactions here.
Hope this helps!

A: CPPSecondViewController *secondView = [[CPPSecondViewController alloc] init];

in this code, the view controller is just init, the properties is all nil, it's a new view controller instance.
setup properties in init method, or access the second view's view property, to load view, to trigger the property initialize.
if you want reference the second view controller from history view controller, you can add a property in history view controller refer to second view controller.
in CPPHistoryViewController.h
@property (weak, nonatomic) CPPSecondViewController *secondViewController;

and set this property in your show code.
in CPPSecondViewController.m
_plustransactions = newPlustransactions;
NSLog(@"%@", newPlustransactions);
NSLog(@"%@%lu", @"That's how many: ", (unsigned long)_plustransactions.count);
CPPHistoryViewController *historyView = [[CPPHistoryViewController alloc]init];
historyView.secondViewController = self;
[historyView.tableView reloadData];