问:
MessageConversionException: Failed to convert message content
I have a SpringBoot Application which makes use of Spring AMQP. At the moment I am implementing the receiver side of it using JavaConfig classes as directed by official Spring docs examples. However, I am receiving a MessageConversionException and the message is not even reaching my ClientHandler class to process the message. Here are the console logs for the incident:

```<code>Caused by: org.springframework.amqp.support.converter.MessageConversionException: Failed to      convert Message content
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:105) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.onMessage(MessageListenerAdapter.java:243) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:756) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of byte out of START_OBJECT token
 at [Source: java.io.StringReader@33b39883; line: 1, column: 1]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseByte(StdDeserializer.java:214) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:749) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:736) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.springframework.amqp.support.converter.JsonMessageConverter.convertBytesToObject(JsonMessageConverter.java:131) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:100) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    ... 13 common frames omitted
2016-10-25 12:51:42,020 WARN  t:[SimpleAsyncTaskExecutor-1] ConditionalRejectingErrorHandler: Fatal message conversion error; message rejected; it will be dropped or routed to a dead letter exchange, if so configured: (Body:'{"messageDTOList":[{"createdDate":1477396301061,"message":"{\"mac\":-99,\"device\":444,\"ifindex\":55,\"ip\":668,\"arpdevice\":99,\"aprifindex\":\"\",\"vlanindex\":111,\"enddevice\":133}","crudOperation":"UPDATE"}],"senderServerId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b","messageId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b20","rebasoftServerType":"AC","taskType":"MAC"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=[53, 98, 51, 54, 97, 55, 97, 49, 45, 99, 49, 55, 100, 45, 52, 55, 49, 102, 45, 98, 49, 54, 101, 45, 101, 56, 101, 48, 98, 102, 52, 97, 102, 98, 53, 98, 50, 48], replyTo=null, contentType=application/json, contentEncoding=null, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=X, receivedRoutingKey=data.core.macs, deliveryTag=2, messageCount=0])
org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:864) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:759) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:679) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:83) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:170) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1253) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:660) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1021) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1005) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:83) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1115) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]
Caused by: org.springframework.amqp.support.converter.MessageConversionException: Failed to convert Message content
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:105) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.onMessage(MessageListenerAdapter.java:243) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:756) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of byte out of START_OBJECT token
 at [Source: java.io.StringReader@33b39883; line: 1, column: 1]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseByte(StdDeserializer.java:214) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:749) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:736) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.springframework.amqp.support.converter.JsonMessageConverter.convertBytesToObject(JsonMessageConverter.java:131) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:100) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    ... 13 common frames omitted
</code>```

My client classes are below:

AbstractEMCRabbitConfiguration.java

```<code>@Configuration
public abstract class AbstractEMCRabbitConfiguration {

//@Value("${emc.rabbit.exchange.core}")
protected static String CORE_DATA_EXCHANGE_NAME = "X";

@Value("${emc.rabbit.queue.core.macs}")
protected static String MAC_REQUEST_QUEUE_NAME = "data.core.macs";

protected static String MAC_REQUEST_ROUTING_KEY = MAC_REQUEST_QUEUE_NAME;

//@Value("${emc.rabbit.hostname}")
protected String hostname;

//@Value("${emc.rabbit.username}")
protected String username;

//@Value("${emc.rabbit.password}")
protected String password;

//@Value("${emc.rabbit.port:5672}")
protected Integer port = 5672;

protected abstract void configureRabbitTemplate(RabbitTemplate template);

@Bean
public ConnectionFactory connectionFactory(){
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
    connectionFactory.setUsername("test");
    connectionFactory.setPassword("test");
    connectionFactory.setPort(port);
    connectionFactory.setRequestedHeartBeat(60);
    return connectionFactory;
}

@Bean
public RabbitTemplate rabbitTemplate(){
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setMessageConverter(jsonMessageConverter());
    configureRabbitTemplate(template);
    return template;
}

@Bean
public MessageConverter jsonMessageConverter() {
    JsonMessageConverter jsonMessageConverter = new JsonMessageConverter();
    jsonMessageConverter.setClassMapper(defaultClassMapper());
    return jsonMessageConverter;
}

@Bean
public DefaultClassMapper defaultClassMapper() {
    DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
    defaultClassMapper.setDefaultType(byte.class);
    return defaultClassMapper;
}

@Bean
public DirectExchange coreDataExchange() { return new DirectExchange(CORE_DATA_EXCHANGE_NAME); }

@Bean
public AmqpAdmin amqpAdmin() {
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
    return rabbitAdmin;
}
}
</code>```

RabbitClientConfiguration.java

```<code>@Configuration
@Import({JacksonConfiguration.class, MessagingConfiguration.class})
public class RabbitClientConfiguration extends AbstractEMCRabbitConfiguration {

@Inject
private JacksonConfiguration jacksonConfiguration;

@Inject
private MessagingConfiguration messagingConfiguration;

//@Value("${data.core.pattern}")
//private String coreDataRoutingKey;

//@Inject
//private ClientHandler clientHandler;

@Override
public void configureRabbitTemplate(RabbitTemplate rabbitTemplate) {
    rabbitTemplate.setRoutingKey("data.core.macs");
}

@Bean
public SimpleMessageListenerContainer messageListenerContainer(){
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory());
    container.setQueues(macsDataQueue());
    container.setMessageListener(messageListenerAdapter());
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    return container;
}

@Bean
MessageListenerAdapter messageListenerAdapter(){
    return new MessageListenerAdapter(clientHandler(jacksonConfiguration.objectMapper(),messagingConfiguration.macMessageHandler(messagingConfiguration.messagingFactory())),jsonMessageConverter());
    //return new MessageListenerAdapter(clientHandler,"receiveMessage");
}

@Bean
ClientHandler clientHandler(ObjectMapper objectMapper, IMessageHandler macMessageHandler){
    ClientHandler clientHandler = new ClientHandler();
    clientHandler.setObjectMapper(objectMapper);
    clientHandler.setMacMessageHandler(macMessageHandler);
    return clientHandler;
}

@Bean
public Queue macsDataQueue(){
    return rabbitAdmin().declareQueue();
}

@Bean
public Binding macsDataBinding(){
    return BindingBuilder.bind(macsDataQueue()).to(coreDataExchange()).with("data.core.macs");
}

@Bean
public AmqpAdmin rabbitAdmin() { return new RabbitAdmin(connectionFactory());}

}
</code>```

A typical message received from the broker would look like this:

(Body:'{"messageDTOList":[{"createdDate":1477396301061,"message":"{\"mac\":-99,\"device\":444,\"ifindex\":55,\"ip\":668,\"arpdevice\":99,\"aprifindex\":\"\",\"vlanindex\":111,\"enddevice\":133}","crudOperation":"UPDATE"}],"senderServerId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b","messageId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b20","rebasoftServerType":"AC","taskType":"MAC"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=[53, 98, 51, 54, 97, 55, 97, 49, 45, 99, 49, 55, 100, 45, 52, 55, 49, 102, 45, 98, 49, 54, 101, 45, 101, 56, 101, 48, 98, 102, 52, 97, 102, 98, 53, 98, 50, 48], replyTo=null, contentType=application/json, contentEncoding=null, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=X, receivedRoutingKey=data.core.macs, deliveryTag=2, messageCount=0])

Note: The content type is 'application/json'

Any help would me much appreciated.

答: No argument constructor is required in your payload/data class.</p>

Body:
I have a SpringBoot Application which makes use of Spring AMQP. At the moment I am implementing the receiver side of it using JavaConfig classes as directed by official Spring docs examples. However, I am receiving a MessageConversionException and the message is not even reaching my ClientHandler class to process the message. Here are the console logs for the incident:

Caused by: org.springframework.amqp.support.converter.MessageConversionException: Failed to      convert Message content
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:105) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.onMessage(MessageListenerAdapter.java:243) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:756) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of byte out of START_OBJECT token
 at [Source: java.io.StringReader@33b39883; line: 1, column: 1]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseByte(StdDeserializer.java:214) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:749) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:736) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.springframework.amqp.support.converter.JsonMessageConverter.convertBytesToObject(JsonMessageConverter.java:131) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:100) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    ... 13 common frames omitted
2016-10-25 12:51:42,020 WARN  t:[SimpleAsyncTaskExecutor-1] ConditionalRejectingErrorHandler: Fatal message conversion error; message rejected; it will be dropped or routed to a dead letter exchange, if so configured: (Body:'{"messageDTOList":[{"createdDate":1477396301061,"message":"{\"mac\":-99,\"device\":444,\"ifindex\":55,\"ip\":668,\"arpdevice\":99,\"aprifindex\":\"\",\"vlanindex\":111,\"enddevice\":133}","crudOperation":"UPDATE"}],"senderServerId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b","messageId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b20","rebasoftServerType":"AC","taskType":"MAC"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=[53, 98, 51, 54, 97, 55, 97, 49, 45, 99, 49, 55, 100, 45, 52, 55, 49, 102, 45, 98, 49, 54, 101, 45, 101, 56, 101, 48, 98, 102, 52, 97, 102, 98, 53, 98, 50, 48], replyTo=null, contentType=application/json, contentEncoding=null, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=X, receivedRoutingKey=data.core.macs, deliveryTag=2, messageCount=0])
org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:864) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:759) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:679) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:83) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:170) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1253) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:660) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1021) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1005) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:83) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1115) [spring-rabbit-1.4.6.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]
Caused by: org.springframework.amqp.support.converter.MessageConversionException: Failed to convert Message content
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:105) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:185) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.onMessage(MessageListenerAdapter.java:243) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:756) ~[spring-rabbit-1.4.6.RELEASE.jar:na]
    ... 10 common frames omitted
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of byte out of START_OBJECT token
 at [Source: java.io.StringReader@33b39883; line: 1, column: 1]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseByte(StdDeserializer.java:214) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:749) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.deser.std.StdDeserializer$ByteDeserializer.deserialize(StdDeserializer.java:736) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
    at org.springframework.amqp.support.converter.JsonMessageConverter.convertBytesToObject(JsonMessageConverter.java:131) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    at org.springframework.amqp.support.converter.JsonMessageConverter.fromMessage(JsonMessageConverter.java:100) ~[spring-amqp-1.4.6.RELEASE.jar:na]
    ... 13 common frames omitted

My client classes are below:

AbstractEMCRabbitConfiguration.java

@Configuration
public abstract class AbstractEMCRabbitConfiguration {

//@Value("${emc.rabbit.exchange.core}")
protected static String CORE_DATA_EXCHANGE_NAME = "X";

@Value("${emc.rabbit.queue.core.macs}")
protected static String MAC_REQUEST_QUEUE_NAME = "data.core.macs";

protected static String MAC_REQUEST_ROUTING_KEY = MAC_REQUEST_QUEUE_NAME;

//@Value("${emc.rabbit.hostname}")
protected String hostname;

//@Value("${emc.rabbit.username}")
protected String username;

//@Value("${emc.rabbit.password}")
protected String password;

//@Value("${emc.rabbit.port:5672}")
protected Integer port = 5672;

protected abstract void configureRabbitTemplate(RabbitTemplate template);

@Bean
public ConnectionFactory connectionFactory(){
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
    connectionFactory.setUsername("test");
    connectionFactory.setPassword("test");
    connectionFactory.setPort(port);
    connectionFactory.setRequestedHeartBeat(60);
    return connectionFactory;
}

@Bean
public RabbitTemplate rabbitTemplate(){
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setMessageConverter(jsonMessageConverter());
    configureRabbitTemplate(template);
    return template;
}

@Bean
public MessageConverter jsonMessageConverter() {
    JsonMessageConverter jsonMessageConverter = new JsonMessageConverter();
    jsonMessageConverter.setClassMapper(defaultClassMapper());
    return jsonMessageConverter;
}

@Bean
public DefaultClassMapper defaultClassMapper() {
    DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
    defaultClassMapper.setDefaultType(byte.class);
    return defaultClassMapper;
}

@Bean
public DirectExchange coreDataExchange() { return new DirectExchange(CORE_DATA_EXCHANGE_NAME); }

@Bean
public AmqpAdmin amqpAdmin() {
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
    return rabbitAdmin;
}
}

RabbitClientConfiguration.java

@Configuration
@Import({JacksonConfiguration.class, MessagingConfiguration.class})
public class RabbitClientConfiguration extends AbstractEMCRabbitConfiguration {

@Inject
private JacksonConfiguration jacksonConfiguration;

@Inject
private MessagingConfiguration messagingConfiguration;

//@Value("${data.core.pattern}")
//private String coreDataRoutingKey;

//@Inject
//private ClientHandler clientHandler;

@Override
public void configureRabbitTemplate(RabbitTemplate rabbitTemplate) {
    rabbitTemplate.setRoutingKey("data.core.macs");
}

@Bean
public SimpleMessageListenerContainer messageListenerContainer(){
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory());
    container.setQueues(macsDataQueue());
    container.setMessageListener(messageListenerAdapter());
    container.setAcknowledgeMode(AcknowledgeMode.AUTO);
    return container;
}

@Bean
MessageListenerAdapter messageListenerAdapter(){
    return new MessageListenerAdapter(clientHandler(jacksonConfiguration.objectMapper(),messagingConfiguration.macMessageHandler(messagingConfiguration.messagingFactory())),jsonMessageConverter());
    //return new MessageListenerAdapter(clientHandler,"receiveMessage");
}

@Bean
ClientHandler clientHandler(ObjectMapper objectMapper, IMessageHandler macMessageHandler){
    ClientHandler clientHandler = new ClientHandler();
    clientHandler.setObjectMapper(objectMapper);
    clientHandler.setMacMessageHandler(macMessageHandler);
    return clientHandler;
}

@Bean
public Queue macsDataQueue(){
    return rabbitAdmin().declareQueue();
}

@Bean
public Binding macsDataBinding(){
    return BindingBuilder.bind(macsDataQueue()).to(coreDataExchange()).with("data.core.macs");
}

@Bean
public AmqpAdmin rabbitAdmin() { return new RabbitAdmin(connectionFactory());}

}

A typical message received from the broker would look like this:

(Body:'{"messageDTOList":[{"createdDate":1477396301061,"message":"{\"mac\":-99,\"device\":444,\"ifindex\":55,\"ip\":668,\"arpdevice\":99,\"aprifindex\":\"\",\"vlanindex\":111,\"enddevice\":133}","crudOperation":"UPDATE"}],"senderServerId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b","messageId":"5b36a7a1-c17d-471f-b16e-e8e0bf4afb5b20","rebasoftServerType":"AC","taskType":"MAC"}'MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, appId=null, clusterId=null, type=null, correlationId=[53, 98, 51, 54, 97, 55, 97, 49, 45, 99, 49, 55, 100, 45, 52, 55, 49, 102, 45, 98, 49, 54, 101, 45, 101, 56, 101, 48, 98, 102, 52, 97, 102, 98, 53, 98, 50, 48], replyTo=null, contentType=application/json, contentEncoding=null, contentLength=0, deliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=X, receivedRoutingKey=data.core.macs, deliveryTag=2, messageCount=0])

Note: The content type is 'application/json'

Any help would me much appreciated.


来源: stackexchange

问:
Start twitter app

Possible Duplicate:

  Android Intent for Twitter application

I want to go to follow page from my android app and i want this to be done by starting the native twitter app.

How can i do this and also if a twitter client is not there in user's mobile it should go in mobile web site of twitter.

答: List all packages that reply to ACTION_SEND and filter them on most popular known twitter clients. http://regis.decamps.info/blog/2011/06/intent-to-open-twitter-client-on-android/

ContentLicense: CC BY-SA 3.0

Title: Start twitter app


问:
Plot equation showing a circle
The following formula is used to classify points from a 2-dimensional space:

```<code>f(x1,x2) = np.sign(x1^2+x2^2-.6)
</code>```

All points are in space X = [-1,1] x [-1,1] with a uniform probability of picking each x.

Now I would like to visualize the circle that equals:

```<code>0 = x1^2+x2^2-.6
</code>```

The values of x1 should be on the x-axis and values of x2 on the y-axis.

It must be possible but I have difficulty transforming the equation to a plot.

答:
Plotting a circle using complex numbers

The idea: multiplying a point by complex exponential () rotates the point on a circle

import numpy as np
import matplotlib.pyplot as plt

import numpy as np
import matplotlib.pyplot as plt

```<code>num_pts=20 # number of points on the circle
ps = np.arange(num_pts+1)
# j = np.sqrt(-1)
pts = np.exp(2j*np.pi/num_pts *(ps))

fig, ax = plt.subplots(1)
ax.plot(pts.real, pts.imag , '-o')
ax.set_aspect(1)
plt.show()
</code>```

Title: Plot equation showing a circle

Body:
The following formula is used to classify points from a 2-dimensional space:

f(x1,x2) = np.sign(x1^2+x2^2-.6)

All points are in space X = [-1,1] x [-1,1] with a uniform probability of picking each x.

Now I would like to visualize the circle that equals:

0 = x1^2+x2^2-.6

The values of x1 should be on the x-axis and values of x2 on the y-axis.

It must be possible but I have difficulty transforming the equation to a plot.

Body:
Plotting a circle using complex numbers

The idea: multiplying a point by complex exponential () rotates the point on a circle

import numpy as np
import matplotlib.pyplot as plt

import numpy as np
import matplotlib.pyplot as plt

num_pts=20 # number of points on the circle
ps = np.arange(num_pts+1)
# j = np.sqrt(-1)
pts = np.exp(2j*np.pi/num_pts *(ps))

fig, ax = plt.subplots(1)
ax.plot(pts.real, pts.imag , '-o')
ax.set_aspect(1)
plt.show()

ContentLicense: CC BY-SA 4.0


问:
Logo getting cut off on facebook like button
I am having a problem where my logo is getting cut off at the bottom on my facebook like button. You can see what i mean here on my home page http://www.organicgrowshop.co.uk

I have tried changing the height in the code and this does change the height of the iframe but not the actual image that is generated??

this is the code im using :

```<code><iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FThe-Organic-Grow-Shop%2F229793147037672&width=180&colorscheme=light&show_faces=false&stream=false&header=true&height=120" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:180px; height:120px;" allowTransparency="true"></iframe>
</code>```

please help! Im a total noob at all this.

Thanks

答:
It's a setting. Log into the facebook account the button is linked to, click the "change profile picture" link that pops up if you hover over your current image. Once there, click "edit miniature image" (or something like, that, facebook is in dutch for me). Select the "scale to fit" checkbox. That should fix it. If not, Upload your logo again, but make sure it's a square image, and once again make sure "scale to fit" is checked. </p>

<p>That should do it. </p>

Body:
I am having a problem where my logo is getting cut off at the bottom on my facebook like button. You can see what i mean here on my home page http://www.organicgrowshop.co.uk

I have tried changing the height in the code and this does change the height of the iframe but not the actual image that is generated??

this is the code im using :

please help! Im a total noob at all this.

Thanks

Body:
It's a setting. Log into the facebook account the button is linked to, click the "change profile picture" link that pops up if you hover over your current image. Once there, click "edit miniature image" (or something like, that, facebook is in dutch for me). Select the "scale to fit" checkbox. That should fix it. If not, Upload your logo again, but make sure it's a square image, and once again make sure "scale to fit" is checked.

That should do it.


问:
What make an image to be displayed only in IOS
As the title say

What make an image to be displayed only in IOS

in Android , it display a blank white image

the source fetched from a remote url

```<code>import { Image } from 'react-native';

image = {uri : "correct_image_url"}

<Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />
</code>```

I use Expo , if this can help

答:
I found the issue (I miss-formulated the uri and typed it as url)

looks {url : "image_source"} works only in IOS

but {uri : "image_source"} works on both

this "i" was the bug which took many days with me

Body:
As the title say

What make an image to be displayed only in IOS

in Android , it display a blank white image

the source fetched from a remote url

import { Image } from 'react-native';

image = {uri : "correct_image_url"}

<Image style={{width : 100 , zIndex : 999 , height : 100}} source={image} />

I use Expo , if this can help


问:
Append a Laravel collection with another collection
I am trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3.

This is what I've done so far:

```<code>$entries = Entry::all();
$posts   = Post::all();

$entries->merge($posts);
</code>```

I tried to use merge() as shown in the code above, but it seems that I'm stuck with this kind of problem (since some of them have the same id with the same value):

Collection merge eating up some rows

Any ideas?

答:
Here's the link: laravel7.X</p>

```<code>$collection = collect(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();
</code>```

Body:
I am trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3.

This is what I've done so far:

$entries = Entry::all();
$posts   = Post::all();

$entries->merge($posts);

I tried to use merge() as shown in the code above, but it seems that I'm stuck with this kind of problem (since some of them have the same id with the same value):

Collection merge eating up some rows

Any ideas?

Body:
Here's the link: laravel7.X

$collection = collect(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();


问:
Generate Neighbour List object for spatial lines in R
My goal is to generate an object of neighbourhood relationships between spatial lines in a road network. If my data were spatial polygons I could use spdep::poly2nb to do this, but I'm having trouble working out how to do this for spatial lines.

In the reprex below I try using igraph::as_adjacency_matrix create an adjacency matrix and then convert that to a neighbours list object using spdep::mat2listw. But is this the correct way to go?

Once I have the Neighours list I also want to label with the road_id attribute.

```<code>library(sfnetworks)
library(sf)
library(spdep)
library(igraph)

net <- as_sfnetwork(roxel, directed = FALSE) %>%
  activate("edges") %>%
  mutate(road_id = row_number()+1000)

# Make adjacency matrix
B_net <- igraph::as_adjacency_matrix(net, edges = TRUE, attr = names)

# Make neighbour list
nb_net <- mat2listw(B_net)$neighbours
# Can't use row.names in mat2listw because how do I set row.names in igraph::as_adjacency_matrix

</code>```

EDIT: New approach using methof in this sfnetworks issue https://github.com/luukvdmeer/sfnetworks/issues/10 gives a neighbour list.

```<code>net_sf <- st_as_sf(net)

net_neigh <- st_touches(net_sf)

# define ad-hoc function to translate sgbp into nb (as documented in
# https://r-spatial.github.io/spdep/articles/nb_sf.html#creating-neighbours-using-sf-objects)
as.nb.sgbp <- function(x) {
  attrs <- attributes(x)
  x <- lapply(x, function(i) { if(length(i) == 0L) 0L else i } )
  attributes(x) <- attrs
  class(x) <- "nb"
  x
}

net_nb <- as.nb.sgbp(net_neigh)
net_lw <- nb2listw(net_nb)
</code>```

答: EDITED to show solution in this sfnetworks issue https://github.com/luukvdmeer/sfnetworks/issues/10

Body:
My goal is to generate an object of neighbourhood relationships between spatial lines in a road network. If my data were spatial polygons I could use spdep::poly2nb to do this, but I'm having trouble working out how to do this for spatial lines.

In the reprex below I try using igraph::as_adjacency_matrix create an adjacency matrix and then convert that to a neighbours list object using spdep::mat2listw. But is this the correct way to go?

Once I have the Neighours list I also want to label with the road_id attribute.

library(sfnetworks)
library(sf)
library(spdep)
library(igraph)

net <- as_sfnetwork(roxel, directed = FALSE) %>%
  activate("edges") %>%
  mutate(road_id = row_number()+1000)

# Make adjacency matrix
B_net <- igraph::as_adjacency_matrix(net, edges = TRUE, attr = names)

# Make neighbour list
nb_net <- mat2listw(B_net)$neighbours
# Can't use row.names in mat2listw because how do I set row.names in igraph::as_adjacency_matrix

EDIT: New approach using methof in this sfnetworks issue https://github.com/luukvdmeer/sfnetworks/issues/10 gives a neighbour list.

net_sf <- st_as_sf(net)

net_neigh <- st_touches(net_sf)

# define ad-hoc function to translate sgbp into nb (as documented in
# https://r-spatial.github.io/spdep/articles/nb_sf.html#creating-neighbours-using-sf-objects)
as.nb.sgbp <- function(x) {
  attrs <- attributes(x)
  x <- lapply(x, function(i) { if(length(i) == 0L) 0L else i } )
  attributes(x) <- attrs
  class(x) <- "nb"
  x
}

net_nb <- as.nb.sgbp(net_neigh)
net_lw <- nb2listw(net_nb)


问:
Microsoft graph notification when new channel created in teams
I would like to receive a webhook notification when a new channel is created in a group in microsoft teams.

I already implemented receiving notifications when user is added to a group through teams (using this API - https://learn.microsoft.com/en-us/graph/api/resources/subscription?view=graph-rest-1.0). Unfortunately, it seems like group subscription is not triggered when a new channel is added.

Is there any other subscription I can use? Thank you in advance.

答: If you have the possibility to add a bot to the Team, then bots can receive this using the bot event mechanisms. Have a look at Handle bot events, and in particular this section. Once your bot has received the notification, you can of course do whatever you need to do.</p>


问:
What is the easiest way I can create a 'beep' sound from a Ruby program?
I'm making a small ruby command line script and I wanted to know what the simplest way to have the program emit a beep is.</p>

答:
For windows, use the win32-sound gem - Adding Sound to Your Ruby Apps.

To install:

```<code>gem install win32-sound
</code>```

Then in Ruby:

```<code>require 'win32/sound'
include Win32
...
Sound.beep(100, 500)
</code>```

For non-windows, looks like this could work: How to make beep sounds?

```<code>puts 7.chr
</code>```

OwnerDisplayName: Daniel X Moore

ContentLicense: CC BY-SA 2.5

Body:
For windows, use the win32-sound gem - Adding Sound to Your Ruby Apps.

To install:

gem install win32-sound

Then in Ruby:

require 'win32/sound'
include Win32
...
Sound.beep(100, 500)

For non-windows, looks like this could work: How to make beep sounds?

puts 7.chr

OwnerDisplayName: Chris Hynes


问:
Does C++ calls member object 's overloaded operator?
```<code> #include <stdio.h>

 class InnerOne {
     int m_iDummy;
     public:
     InnerOne(int iDummy) {
         m_iDummy=iDummy;
     }

     InnerOne& operator=(InnerOne &obj) {
         printf("In InnerOne Operator=\n");
         m_iDummy = obj.m_iDummy;
         return *this;
     }

 };

 class OuterOne {
     InnerOne m_innerOne;
     public:
     OuterOne(int iVal) : m_innerOne(iVal) {
     }

 };

 int main() {
     OuterOne a(1);
     OuterOne b(2);
     a = b;
     return 1;
 }
</code>```

Will InnerOne 's operator = get called?
If yes then how and why?

答: Yes. The automatically generated assignment operator for OuterOne will call the assignment operator of InnerOne.

Body:
 #include <stdio.h>

 class InnerOne {
     int m_iDummy;
     public:
     InnerOne(int iDummy) {
         m_iDummy=iDummy;
     }

     InnerOne& operator=(InnerOne &obj) {
         printf("In InnerOne Operator=\n");
         m_iDummy = obj.m_iDummy;
         return *this;
     }

 };

 class OuterOne {
     InnerOne m_innerOne;
     public:
     OuterOne(int iVal) : m_innerOne(iVal) {
     }

 };

 int main() {
     OuterOne a(1);
     OuterOne b(2);
     a = b;
     return 1;
 }

Will InnerOne 's operator = get called?
If yes then how and why?


问:
C++ - operator= self assignment checking
```<code>class Person {
private:
    string name;
    int id;

public:
    Person(string name, int id): name(name), id(id) {}
    const Person& operator=(const Person &another) {
        if (*this == another) // What is the problem here?
            return *this;
        // do copy
        return *this;
    }
};
</code>```

I want to make a operator= overloading function. In the self assignment checking, if I do the checking as above, it will show error saying Invalid operands to binary expression (Person and const Person). But if I do this == &another, no error will be shown.

Is the error saying that type of this and type of another are different? But if so, how come this == &another will work?

答:
In *this == another you are trying to check whether both objects have the same value. For this to work, you have to define the operator== for Person. That is, Person::operator==() will determine whether two Person objects have the same value.

However, since you want to protect against self-assignment, what you really need is to compare the identity of both objects – as opposed to their value. You can achieve this by comparing their addresses in memory, i.e.:

```<code>if (this == &another) // Is "another" the same object?
   return *this; // skip assignment
</code>```

The operands to this operator== are pointers to Person, not Person objects.

Body:
class Person {
private:
    string name;
    int id;

public:
    Person(string name, int id): name(name), id(id) {}
    const Person& operator=(const Person &another) {
        if (*this == another) // What is the problem here?
            return *this;
        // do copy
        return *this;
    }
};

I want to make a operator= overloading function. In the self assignment checking, if I do the checking as above, it will show error saying Invalid operands to binary expression (Person and const Person). But if I do this == &another, no error will be shown.

Is the error saying that type of this and type of another are different? But if so, how come this == &another will work?

Body:
In *this == another you are trying to check whether both objects have the same value. For this to work, you have to define the operator== for Person. That is, Person::operator==() will determine whether two Person objects have the same value.

However, since you want to protect against self-assignment, what you really need is to compare the identity of both objects – as opposed to their value. You can achieve this by comparing their addresses in memory, i.e.:

if (this == &another) // Is "another" the same object?
   return *this; // skip assignment

The operands to this operator== are pointers to Person, not Person objects.


问:
EF Core check if object in related table exists, if not - add it
I have the following class:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}
</code>```

and an ItemCategory class:

```<code>public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}
</code>```

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

答:
I would create a function that gets or creates the unique ItemCategory. You did not post the full code so I am not sure how your repository looks like. But here is an idea:

```<code>    // assuming _dbServices is the injected dbcontext
    public void AddItem()
    {
        var item = _dbServices.Context.Entry(new Item()
        {
            Name = "First book",
            Category = GetOrCreateItemCategory(new ItemCategory() { Name = "Book" })
        }).State = EntityState.Added;
        _dbServices.Context.SaveChanges();
    }
    public ItemCategory GetOrCreateItemCategory(ItemCategory category)
    {
        var findCategory = _dbServices.Context.Set<ItemCategory>().Where(x => x.ID == category.ID).FirstOrDefault();
        if (findCategory == null)
        {
            _dbServices.Context.Entry(category).State = EntityState.Added;
            _dbServices.Context.SaveChanges();
            return category;
        }
        return findCategory;
    }
</code>```

I havent tested this but should be ok. If not, please comment and I would fix it.
Also I would create unique index for ItemCategory.Name field.

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ItemCategory>()
        .HasIndex(p => new { p.Name })
        .IsUnique(true);
}
</code>```

Body:
I have the following class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}

and an ItemCategory class:

public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

Body:
I would create a function that gets or creates the unique ItemCategory. You did not post the full code so I am not sure how your repository looks like. But here is an idea:

    // assuming _dbServices is the injected dbcontext
    public void AddItem()
    {
        var item = _dbServices.Context.Entry(new Item()
        {
            Name = "First book",
            Category = GetOrCreateItemCategory(new ItemCategory() { Name = "Book" })
        }).State = EntityState.Added;
        _dbServices.Context.SaveChanges();
    }
    public ItemCategory GetOrCreateItemCategory(ItemCategory category)
    {
        var findCategory = _dbServices.Context.Set<ItemCategory>().Where(x => x.ID == category.ID).FirstOrDefault();
        if (findCategory == null)
        {
            _dbServices.Context.Entry(category).State = EntityState.Added;
            _dbServices.Context.SaveChanges();
            return category;
        }
        return findCategory;
    }

I havent tested this but should be ok. If not, please comment and I would fix it.
Also I would create unique index for ItemCategory.Name field.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ItemCategory>()
        .HasIndex(p => new { p.Name })
        .IsUnique(true);
}


问:
Command for loading postgres through docker?
Does anyone know the command for loading postgres through docker? Here is the recommended command on their documentation:

```<code>docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres
</code>```

Forgive the naive question, how do you find what values for "some-network" are supposed to be and what values "some-postgres" is supposed to be?

答:
You don't need docker run or the elevated permissions this requires just to access the database.  Install the PostgreSQL client on your host if you haven't already.  If you started the database with

```<code>docker run -p 5678:5432 ... postgres
</code>```

or an equivalent Docker Compose ports: option, then you can access the database with

```<code>psql -h localhost -p 5678
</code>```

using the first port number.

This psql command runs on the host and thinks it's talking to a remote database.  PostgreSQL COPY commands and the psql -f option will use the file system where the client is running; if you're using psql directly, that's your current host directory that you can ls, and you won't have to do extra tricks to make the host content available to a client running in a container.

Body:
Does anyone know the command for loading postgres through docker? Here is the recommended command on their documentation:

docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres

Forgive the naive question, how do you find what values for "some-network" are supposed to be and what values "some-postgres" is supposed to be?

Body:
You don't need docker run or the elevated permissions this requires just to access the database.  Install the PostgreSQL client on your host if you haven't already.  If you started the database with

docker run -p 5678:5432 ... postgres

or an equivalent Docker Compose ports: option, then you can access the database with

psql -h localhost -p 5678

using the first port number.

This psql command runs on the host and thinks it's talking to a remote database.  PostgreSQL COPY commands and the psql -f option will use the file system where the client is running; if you're using psql directly, that's your current host directory that you can ls, and you won't have to do extra tricks to make the host content available to a client running in a container.


问:
How can I work with Iterables in my JSP pages?
I'm using an API that makes heavy use of Iterables (java.lang.Iterable), but I can't use them directly on my JSP pages because JSTL tags and EL can not process them. Right now, I'm transforming each iterable to a list prior to rendering them.

What would be the cleanest and simplest approach to make it work without previous transformations?
Do newest JSTL-Jasper-EL-taglibs-etc. versions support it? Where can I found that information? I don't find anything about it googling...

I know I can use Iterable.iterator(), but I can't call that method inside the JSP, only in my controller class, and this is very limiting.

答:
You can create a Map with your Iterables as a key, and their Iterators as values. Then you should be able to access the Iterators using your Iterables in your JSP using JSTL/EL.

Further reading:

Calculate total sum of all numbers in c:forEach loop, a very interesting and thought provoking post -- having several apt solutions.


问:
Rasa Form Action - Slot getting filled with same data twice
I am trying to use FormAction of Rasa. Below are my details:

MyForm

```<code>class MyForm(FormAction):
    """My form action"""
    def name(self):
        return "my_form"

    @staticmethod
    def required_slots(tracker: Tracker) -> List[Text]:
        """A list of required slots that the form has to fill"""
        return ["slot_a", "slot_b", "slot_c",  "slot_d"]

    def slot_mappings(self):
        # type: () -> Dict[Text: Union[Dict, List[Dict]]]
        """A dictionary to map required slots to
            - an extracted entity
            - intent: value pairs
            - a whole message
            or a list of them, where a first match will be picked"""
        return {"slot_a":[self.from_entity(entity="slot_a", intent=["inform"])],
                "slot_b": [self.from_entity(entity="slot_b", intent=["inform"])],
                "slot_c": [self.from_entity(entity="slot_c", intent=["inform"])],
                "slot_d": [self.from_entity(entity="slot_d", intent=["inform"])]}

    def submit(self, dispatcher: CollectingDispatcher,
               tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        """Define what the form has to do
                after all required slots are filled"""
        dispatcher.utter_template('utter_submit', tracker)
        return []
</code>```

Below is my domain.yml file with just the slots and forms value being shown for NDA reasons.
MyDomain

```<code># actions, entities, intents, templates
slots:
  slot_c:
    type: unfeaturized
    auto_fill: false
  slot_b:
    type: unfeaturized
    auto_fill: false
  slot_d:
    type: unfeaturized
    auto_fill: false
  slot_a:
    type: unfeaturized
    auto_fill: false
  slot_e:
    type: text
    auto_fill: false
  slot_f:
    type: categorical
    values:
    - val_1
    - val_2
    - val_3

forms:
    - my_form
</code>```

Below is my stories.yml:

```<code>## Story 1
* greet
  - utter_greet
* create_slot_vals
  - my_form
  - form{"name": "my_form"}
  - form{"name": null}
  - utter_saving_slots_values
* thank_you
  - utter_thanks
</code>```

After filling the form, I have an utter action which shows all the slot values filled by form.

Rasa Utter Action

```<code> The form details are:
 - Slot A: Software
 - Slot B: Anderson
 - Slot C: 12
 - Slot D: ['permanent', 'permanent']
</code>```

The problem is, even though the user enters the value of slot_d as 'permanent' only once, the same slot gets requested again and the same value is filled automatically twice in a list and saved.

Has anyone ever faced such an issue in Rasa?

答: This error is caused if you use multiple entity extractor in the config file so run  rasa shell nlu to know what kind of entity extractor are grabbing the value

Body:
I am trying to use FormAction of Rasa. Below are my details:

MyForm

class MyForm(FormAction):
    """My form action"""
    def name(self):
        return "my_form"

    @staticmethod
    def required_slots(tracker: Tracker) -> List[Text]:
        """A list of required slots that the form has to fill"""
        return ["slot_a", "slot_b", "slot_c",  "slot_d"]

    def slot_mappings(self):
        # type: () -> Dict[Text: Union[Dict, List[Dict]]]
        """A dictionary to map required slots to
            - an extracted entity
            - intent: value pairs
            - a whole message
            or a list of them, where a first match will be picked"""
        return {"slot_a":[self.from_entity(entity="slot_a", intent=["inform"])],
                "slot_b": [self.from_entity(entity="slot_b", intent=["inform"])],
                "slot_c": [self.from_entity(entity="slot_c", intent=["inform"])],
                "slot_d": [self.from_entity(entity="slot_d", intent=["inform"])]}

    def submit(self, dispatcher: CollectingDispatcher,
               tracker: Tracker,
               domain: Dict[Text, Any]) -> List[Dict]:
        """Define what the form has to do
                after all required slots are filled"""
        dispatcher.utter_template('utter_submit', tracker)
        return []

Below is my domain.yml file with just the slots and forms value being shown for NDA reasons.
MyDomain

# actions, entities, intents, templates
slots:
  slot_c:
    type: unfeaturized
    auto_fill: false
  slot_b:
    type: unfeaturized
    auto_fill: false
  slot_d:
    type: unfeaturized
    auto_fill: false
  slot_a:
    type: unfeaturized
    auto_fill: false
  slot_e:
    type: text
    auto_fill: false
  slot_f:
    type: categorical
    values:
    - val_1
    - val_2
    - val_3

forms:
    - my_form

Below is my stories.yml:

## Story 1
* greet
  - utter_greet
* create_slot_vals
  - my_form
  - form{"name": "my_form"}
  - form{"name": null}
  - utter_saving_slots_values
* thank_you
  - utter_thanks

After filling the form, I have an utter action which shows all the slot values filled by form.

Rasa Utter Action

 The form details are:
 - Slot A: Software
 - Slot B: Anderson
 - Slot C: 12
 - Slot D: ['permanent', 'permanent']

The problem is, even though the user enters the value of slot_d as 'permanent' only once, the same slot gets requested again and the same value is filled automatically twice in a list and saved.

Has anyone ever faced such an issue in Rasa?


问:
How to redefine a Vee Validate error message for one Vue component?
I have a global validation rule, for example:

import { extend } from 'vee-validate';
import { required } from 'vee-validate/dist/rules';

extend('required', {
  ...required,
  message: 'Please fill the field'
});
```

This rule is using for all Vue components across the project. But for one exact component I need to redefine the message Please fill the field to another one. Is it possible to change the message just for one Vue component?

答:
You can specifiy specific messages for each ValidationProvider component using the custom-messages prop

<ValidationProvider rules="required" :custom-messages="{ required: 'required message' }">

</ValidationProvider>
```

<p>You can extract it on a data prop and use it for the providers in your component:</p>

<pre class="lang-html prettyprint-override"><code><template>
  <ValidationProvider rules="required" :custom-messages="customMessages">
    <!-- ... -->
  </ValidationProvider>

  <ValidationProvider rules="required" :custom-messages="customMessages">
    <!-- ... -->
  </ValidationProvider>
</template>

<script>
export default {
 // ....
 data: () => ({
    customMessages: {
      required: 'custom message'
    }
  }),
  // ...
};
</script>
</code>```

Body:
I have a global validation rule, for example:

import { extend } from 'vee-validate';
import { required } from 'vee-validate/dist/rules';

extend('required', {
  ...required,
  message: 'Please fill the field'
});

This rule is using for all Vue components across the project. But for one exact component I need to redefine the message Please fill the field to another one. Is it possible to change the message just for one Vue component?

Body:
You can specifiy specific messages for each ValidationProvider component using the custom-messages prop

<ValidationProvider rules="required" :custom-messages="{ required: 'required message' }">
  <!-- ... -->
</ValidationProvider>

You can extract it on a data prop and use it for the providers in your component:

<template>
  <ValidationProvider rules="required" :custom-messages="customMessages">
    <!-- ... -->
  </ValidationProvider>

  <ValidationProvider rules="required" :custom-messages="customMessages">
    <!-- ... -->
  </ValidationProvider>
</template>

<script>
export default {
 // ....
 data: () => ({
    customMessages: {
      required: 'custom message'
    }
  }),
  // ...
};
</script>


问:
How do I type a JS file in node_modules?
I installed module foo which has this package.json:

```<code>{
  "name": "foo",
  "version": "0.0.1",
  "exports": {
    ".": ["./index.js"]
  },
  "types": "./index.d.ts"
}
</code>```

foo comes with its own types for the module entry point. However, I need to import bar.js from foo. Because it isn't exported in index.js, I have to do this:

```<code>import {bar} from './node_modules/foo/bar'
</code>```

This is because if I use import bar from 'foo/bar', I get the error Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './bar' is not defined by "exports" in /path/to/project/node_modules/foo/package.json.

I have typed foo/bar like this:

```<code>export const bar: 'bar'
</code>```

Where would I put this file and what will I need to put in my tsconfig.json?

I've already tried putting my typings in ./types/foo/bar.d.ts and using "typeRoots": ["node_modules/@types", "./types"] in my tsconfig compilerOptions, but TS couldn't find my declaration file:

```<code>Could not find a declaration file for module './node_modules/foo/bar'. '/path/to/project/node_modules/foo/bar.js' implicitly has an 'any' type.
</code>```

I've also tried /// <reference types="./types/foo/bar" />, but the same error persisted.

If I wasn't typing a file from an npm module, I would have just put the types in ./node_modules/foo/bar.d.ts, but I don't want to manually put anything in node_modules.

答:
As a temporary solution, I put all my types in ./typings and added this to scripts in my package.json:

```<code>"prepare": "for f in typings/**/*; do cp \"$f\" \"node_modules/${f#*/}\"; done"
</code>```

Body:
I installed module foo which has this package.json:

{
  "name": "foo",
  "version": "0.0.1",
  "exports": {
    ".": ["./index.js"]
  },
  "types": "./index.d.ts"
}

foo comes with its own types for the module entry point. However, I need to import bar.js from foo. Because it isn't exported in index.js, I have to do this:

import {bar} from './node_modules/foo/bar'

This is because if I use import bar from 'foo/bar', I get the error Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './bar' is not defined by "exports" in /path/to/project/node_modules/foo/package.json.

I have typed foo/bar like this:

export const bar: 'bar'

Where would I put this file and what will I need to put in my tsconfig.json?

I've already tried putting my typings in ./types/foo/bar.d.ts and using "typeRoots": ["node_modules/@types", "./types"] in my tsconfig compilerOptions, but TS couldn't find my declaration file:

Could not find a declaration file for module './node_modules/foo/bar'. '/path/to/project/node_modules/foo/bar.js' implicitly has an 'any' type.

I've also tried /// <reference types="./types/foo/bar" />, but the same error persisted.

If I wasn't typing a file from an npm module, I would have just put the types in ./node_modules/foo/bar.d.ts, but I don't want to manually put anything in node_modules.

Body:
As a temporary solution, I put all my types in ./typings and added this to scripts in my package.json:

"prepare": "for f in typings/**/*; do cp \"$f\" \"node_modules/${f#*/}\"; done"


答:
Self assignment checking is done by comparing addresses of the two objects

```<code>if (this == &another)
</code>```

C++ has a built in operator== for pointers of the same type.

Your code is comparing the values of the two objects, and clearly you haven't defined operator== for your Person class.

But comparing the values is not the right thing to do because there's no special action needed when you are assigning two objects which have the same value, but sometimes there is when you are assigning two identical objects.

In fact there's no need in the class you have shown to do any self-assignment testing. Simply this is OK

```<code>Person& operator=(const Person &another) {
    name = another.name;
    id = another.id;
    return *this;
}
</code>```

Don't think that testing for self-assignment is any kind of efficiency gain, because self-assignment is rare. So if you can avoid the test, then generally you should.

Also worth saying that the generally prefered method for assignment is the copy and swap idiom which also doesn't require any self-assignment testing.

Title: C++ - operator= self assignment checking

Body:
Self assignment checking is done by comparing addresses of the two objects

if (this == &another)

C++ has a built in operator== for pointers of the same type.

Your code is comparing the values of the two objects, and clearly you haven't defined operator== for your Person class.

But comparing the values is not the right thing to do because there's no special action needed when you are assigning two objects which have the same value, but sometimes there is when you are assigning two identical objects.

In fact there's no need in the class you have shown to do any self-assignment testing. Simply this is OK

Person& operator=(const Person &another) {
    name = another.name;
    id = another.id;
    return *this;
}

Don't think that testing for self-assignment is any kind of efficiency gain, because self-assignment is rare. So if you can avoid the test, then generally you should.

Also worth saying that the generally prefered method for assignment is the copy and swap idiom which also doesn't require any self-assignment testing.


问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
For ubuntu 14.04

Open your terminal

```<code>sudo su
wget https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA01N000000rfBO -O SHA-2_Root_USERTrust_RSA_Certification_Authority.crt --no-check-certificate
cp SHA-2_Root_USERTrust_RSA_Certification_Authority.crt /usr/share/ca-certificates/mozilla/
</code>```

Then
dpkg-reconfigure ca-certificates and uncheck mozilla/AddTrust_External_Root.crt and check mozilla/2_Root_USERTrust_RSA_Certification_Authority.crt

or run sudo update-ca-certificates for uncheck those.

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);

Body:
For ubuntu 14.04

Open your terminal

sudo su
wget https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA01N000000rfBO -O SHA-2_Root_USERTrust_RSA_Certification_Authority.crt --no-check-certificate
cp SHA-2_Root_USERTrust_RSA_Certification_Authority.crt /usr/share/ca-certificates/mozilla/

Then
dpkg-reconfigure ca-certificates and uncheck mozilla/AddTrust_External_Root.crt and check mozilla/2_Root_USERTrust_RSA_Certification_Authority.crt

or run sudo update-ca-certificates for uncheck those.


问:
Create Custom SQL Server Role in SQL 2008 Server
I want to add new custom SQL Server Role and assign the new users to these appropriate roles respectively.  I try to find how to create role, but I could not find the place to add that.  Could you please guide me how to achieve my requirement?</p>

答:
You'd simply GRANT the rights you want to a login rather than a role pre SQL Server 2011. Not ideal of course but it works.

We use this to enable app teams to see what is going on without hassling the DBAs.

For example,

```<code>CREATE LOGIN [MyDOmain\FolkITrustGroup] FROM WINDOWS;
GO
GRANT VIEW SERVER STATE TO  [MyDOmain\FolkITrustGroup]
GRANT VIEW ANY DEFINITION TO  [MyDOmain\FolkITrustGroup]
GO
</code>```

Edit: This achieves your requirement without using server roles which don't exist yet...

Body:
You'd simply GRANT the rights you want to a login rather than a role pre SQL Server 2011. Not ideal of course but it works.

We use this to enable app teams to see what is going on without hassling the DBAs.

For example,

CREATE LOGIN [MyDOmain\FolkITrustGroup] FROM WINDOWS;
GO
GRANT VIEW SERVER STATE TO  [MyDOmain\FolkITrustGroup]
GRANT VIEW ANY DEFINITION TO  [MyDOmain\FolkITrustGroup]
GO

Edit: This achieves your requirement without using server roles which don't exist yet...


问:
Apache, PHP 5.6 or 7.0: Library not loaded: openssl/lib/libcrypto.1.0.0.dylib using Homebrew
I am trying to load either PHP 5.6 or PHP 7.0 module in the Apache httpd.conf config file on macOS 10.15 Catalina. But what I receive when starting the Apache server using sudo apachectl start in Terminal is the following error:

```<code>httpd: Syntax error on line 187 of /private/etc/apache2/httpd.conf: Cannot load /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so into server: dlopen(/usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so, 10): Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib\n Referenced from: /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so\n  Reason: image not found
</code>```

Since PHP versions 5.6, 7.0 and 7.1 have been deprecated and removed from Homebrew, following this guide, I had to use an older deprecated tap and installed both PHP 5.6 and 7.0 by running:

```<code>brew tap exolnet/homebrew-deprecated
brew install php@5.6
brew install php@7.0
</code>```

For the sake of complete information, I have tried both the Apache which comes with macOS and the latest Apache 2.4.43 installed via Homebrew, but this should not make a difference.

So the question is, how can I solve these errors and make PHP 5.6 and 7.0 running on macOS using Homebrew?

答:
The solution is to install an older version of the openssl library. To be more specific, PHP 5.6 and php 7.0 require openssl 1.0.2, which you can install via Homebrew by running the following in Terminal:

```<code>brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8b9d6d688f483a0f33fcfc93d433de501b9c3513/Formula/openssl.rb
brew switch openssl 1.0.2t
</code>```

However, after running the above, when using PHP 5.6, php 7.0 or php 7.1, another "Library not loaded" error might occur., in particular, this one:

```<code>httpd: Syntax error on line 183 of /usr/local/etc/httpd/httpd.conf: Cannot load /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so into server: dlopen(/usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so, 10): Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib\n  Referenced from: /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so\n  Reason: image not found
</code>```

Here, another older library is required, icu4C in this case. The solution is to run the following:

```<code>brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/a806a621ed3722fb580a58000fb274a2f2d86a6d/Formula/icu4c.rb
brew switch icu4c 64.2
</code>```

Note for switching to PHP 7.2, PHP 7.3 or PHP 7.4

Since PHP 7.2, PHP 7.3 and PHP 7.4 do not work with the above mentioned older, 64.3, version of the icu4c library, whenever you need to switch to these PHP versions, e.g., by using this easy  brew PHP switcher script, you also hav to switch the version of the icu4c library by running this command:

```<code>brew switch icu4c 67.1
</code>```

Resources

OpenSSL 1.0.2m on macOS - Stack Overflow.

homebrew-core/openssl.rb at 75b573845a17aaf3f7c84dc58e97cf5fe39a502b · Homebrew/homebrew-core.

node.js - dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac - Stack Overflow.

macOS 10.15 Catalina Apache Setup: Multiple PHP Versions | Official home of Grav CMS.

Body:
I am trying to load either PHP 5.6 or PHP 7.0 module in the Apache httpd.conf config file on macOS 10.15 Catalina. But what I receive when starting the Apache server using sudo apachectl start in Terminal is the following error:

httpd: Syntax error on line 187 of /private/etc/apache2/httpd.conf: Cannot load /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so into server: dlopen(/usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so, 10): Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib\n Referenced from: /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so\n  Reason: image not found

Since PHP versions 5.6, 7.0 and 7.1 have been deprecated and removed from Homebrew, following this guide, I had to use an older deprecated tap and installed both PHP 5.6 and 7.0 by running:

brew tap exolnet/homebrew-deprecated
brew install php@5.6
brew install php@7.0

For the sake of complete information, I have tried both the Apache which comes with macOS and the latest Apache 2.4.43 installed via Homebrew, but this should not make a difference.

So the question is, how can I solve these errors and make PHP 5.6 and 7.0 running on macOS using Homebrew?

Body:
The solution is to install an older version of the openssl library. To be more specific, PHP 5.6 and php 7.0 require openssl 1.0.2, which you can install via Homebrew by running the following in Terminal:

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8b9d6d688f483a0f33fcfc93d433de501b9c3513/Formula/openssl.rb
brew switch openssl 1.0.2t

However, after running the above, when using PHP 5.6, php 7.0 or php 7.1, another "Library not loaded" error might occur., in particular, this one:

httpd: Syntax error on line 183 of /usr/local/etc/httpd/httpd.conf: Cannot load /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so into server: dlopen(/usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so, 10): Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib\n  Referenced from: /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so\n  Reason: image not found

Here, another older library is required, icu4C in this case. The solution is to run the following:

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/a806a621ed3722fb580a58000fb274a2f2d86a6d/Formula/icu4c.rb
brew switch icu4c 64.2

Note for switching to PHP 7.2, PHP 7.3 or PHP 7.4

Since PHP 7.2, PHP 7.3 and PHP 7.4 do not work with the above mentioned older, 64.3, version of the icu4c library, whenever you need to switch to these PHP versions, e.g., by using this easy  brew PHP switcher script, you also hav to switch the version of the icu4c library by running this command:

brew switch icu4c 67.1

Resources

OpenSSL 1.0.2m on macOS - Stack Overflow.

homebrew-core/openssl.rb at 75b573845a17aaf3f7c84dc58e97cf5fe39a502b · Homebrew/homebrew-core.

node.js - dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac - Stack Overflow.

macOS 10.15 Catalina Apache Setup: Multiple PHP Versions | Official home of Grav CMS.


问:
BigQuery data model for nearest places by travel time
I have a following requirement and new to BigQuery.

Requirement,

We have bunch of stores and there are competitor stores as well.
  When i choose a competitor store and travel time( Say, within 15mins, within 30mins, within 45mins, within 60mins), it has to return our store within the selected travel time. Here, travel time is based on the standard time not based on traffic and we will have only 4 options(15, 30, 45, 60).

My data model based on my knowledge,

```<code>**competitor_store_id | traveltime | stores(comma_separated)**

  Example Data,

C1 | 15 | S1,S2,S3,S4,S5  ---> Here there are 5 stores with in 15 mins
C2 | 30 | S6,S7,S8,S9,S10  --> Here there are 10 stores within 30 mins travel time. So storing delta b/w 15 mins and 30 mins, so the data will be 15mins+30mins for 30 mins traveltime
</code>```

Is there any better approach?

Sample Request:-

```<code>stores/C1?time=15
</code>```

Output:-

```<code>S1,S2,S3,S4,S5
</code>```

Sample Request:-

```<code>stores/C1?time=30
</code>```

Output:-

```<code>S1,S2,S3,S4,S5,S6,S7,S8,S9,S10
</code>```

答:
After you uploaded your sample request and output, I understood you wanted a query to create a view with the sample request and output you shared. Thus, I was able to come up with a helpful query. I have used the following sample data, in order to replicate your case.

```<code>WITH data as (
SELECT "C1" as competitor_store_id, 15 AS traveltime, "S1,S2,S3,S4,S5" as stores UNION ALL
SELECT "C1" as competitor_store_id, 30 AS traveltime, "S6,S7,S8,S9,S10" as stores UNION ALL
SELECT "C2" as competitor_store_id, 15 AS traveltime, "S1,S2,S3,S4,S5" as stores UNION ALL
SELECT "C2" as competitor_store_id, 30 AS traveltime, "S6,S7" as stores UNION ALL
SELECT "C2" as competitor_store_id, 45 AS traveltime, "S8" as stores
)
</code>```

Using the STRING_AGG() method, and the query is as below:

```<code>select competitor_store_id, STRING_AGG(stores) as stores from data
where traveltime <= 30
group by 1
</code>```

And the output,

Therefore, you will be able to select the stores within a range of time for each competitor_store_id. In the above example I used 30 as traveltime. So, as you can see, in the output it is not shown S8 for C2(competitor_store_id) at 45 as traveltime. Whereas, for C1 all 10 stores were listed.

Body:
I have a following requirement and new to BigQuery.

Requirement,

We have bunch of stores and there are competitor stores as well.
  When i choose a competitor store and travel time( Say, within 15mins, within 30mins, within 45mins, within 60mins), it has to return our store within the selected travel time. Here, travel time is based on the standard time not based on traffic and we will have only 4 options(15, 30, 45, 60).

My data model based on my knowledge,

**competitor_store_id | traveltime | stores(comma_separated)**

  Example Data,

C1 | 15 | S1,S2,S3,S4,S5  ---> Here there are 5 stores with in 15 mins
C2 | 30 | S6,S7,S8,S9,S10  --> Here there are 10 stores within 30 mins travel time. So storing delta b/w 15 mins and 30 mins, so the data will be 15mins+30mins for 30 mins traveltime

Is there any better approach?

Sample Request:-

stores/C1?time=15

Output:-

S1,S2,S3,S4,S5

Sample Request:-

stores/C1?time=30

Output:-

S1,S2,S3,S4,S5,S6,S7,S8,S9,S10

Body:
After you uploaded your sample request and output, I understood you wanted a query to create a view with the sample request and output you shared. Thus, I was able to come up with a helpful query. I have used the following sample data, in order to replicate your case.

WITH data as (
SELECT "C1" as competitor_store_id, 15 AS traveltime, "S1,S2,S3,S4,S5" as stores UNION ALL
SELECT "C1" as competitor_store_id, 30 AS traveltime, "S6,S7,S8,S9,S10" as stores UNION ALL
SELECT "C2" as competitor_store_id, 15 AS traveltime, "S1,S2,S3,S4,S5" as stores UNION ALL
SELECT "C2" as competitor_store_id, 30 AS traveltime, "S6,S7" as stores UNION ALL
SELECT "C2" as competitor_store_id, 45 AS traveltime, "S8" as stores
)

Using the STRING_AGG() method, and the query is as below:

select competitor_store_id, STRING_AGG(stores) as stores from data
where traveltime <= 30
group by 1

And the output,

Therefore, you will be able to select the stores within a range of time for each competitor_store_id. In the above example I used 30 as traveltime. So, as you can see, in the output it is not shown S8 for C2(competitor_store_id) at 45 as traveltime. Whereas, for C1 all 10 stores were listed.


问:
Prevent table from resizing when adding border to specific cell
Here is my code. The problem is: When i click a td cell, add border to it, and the border makes the table changes size.

For some reasons, i dont want the table increase its size when adding border to td tag, and i can not use outline in css.

I tried to add this line of css code : box-sizing: border-box; but it does not seem to work.

Thank you for any idea!!

Array.prototype.forEach.call(
  document.querySelectorAll('td'),
  function(td) {
    td.addEventListener('click', function(e) {
      e.target.classList.add('myBorder')
    })
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
  box-sizing: border-box;
}
.myBorder {
  border: 2px solid #4b89ff;
}</code>```

      id
      Name
      Gender

      1
      Bob
      Male

      2
      Anna
      Female

      3
      Christ
      Male

```

答:
Inspecting the td with Chrome i found that adding the class to the cell was also generating a padding of 1px. And if you set padding-bottom: 0px; on .myBorder class will solve the problem.

Array.prototype.forEach.call(
  document.querySelectorAll('td'),
  function(td) {
    td.addEventListener('click', function(e) {
      e.target.classList.add('myBorder')
    })
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
}
.myBorder {
  border: 2px solid #4b89ff;
  padding-bottom: 0px;
}</code>```

      id
      Name
      Gender

      1
      Bob
      Male

      2
      Anna
      Female

      3
      Christ
      Male

```

Body:
Here is my code. The problem is: When i click a td cell, add border to it, and the border makes the table changes size.

For some reasons, i dont want the table increase its size when adding border to td tag, and i can not use outline in css.

I tried to add this line of css code : box-sizing: border-box; but it does not seem to work.

Thank you for any idea!!

Array.prototype.forEach.call(
  document.querySelectorAll('td'),
  function(td) {
    td.addEventListener('click', function(e) {
      e.target.classList.add('myBorder')
    })
  })

table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
  box-sizing: border-box;
}
.myBorder {
  border: 2px solid #4b89ff;
}

      id
      Name
      Gender

      1
      Bob
      Male

      2
      Anna
      Female

      3
      Christ
      Male

Body:
Inspecting the td with Chrome i found that adding the class to the cell was also generating a padding of 1px. And if you set padding-bottom: 0px; on .myBorder class will solve the problem.

Array.prototype.forEach.call(
  document.querySelectorAll('td'),
  function(td) {
    td.addEventListener('click', function(e) {
      e.target.classList.add('myBorder')
    })
  })

table {
  border-collapse: collapse;
}
th, td {
  border: 1px solid black;
}
.myBorder {
  border: 2px solid #4b89ff;
  padding-bottom: 0px;
}

<table>
  <thead>
    <tr>
      <th>id</th>
      <th>Name</th>
      <th>Gender</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Bob</td>
      <td>Male</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Anna</td>
      <td>Female</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Christ</td>
      <td>Male</td>
    </tr>
  </tbody>
</table>


问:
Android emulator not running with my React Native App
Trying to run my React Native app in Android emulator but it keeps throwing error:

"Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html
error spawnSync ./gradlew EACCES. Run CLI with --verbose flag for more details."

Tried react-native run-android, npm start, react-native start... nothing worked!!!

Am I missing out something here?? struggling with this since morning. Please help....

Update:

Ran "adb devices" in terminal. Still its not working :/ Same error!!!

答:
Check if you actually have a device connected by typing this in terminal

```<code>adb devices
</code>```

If there is no device detected.

Try typing this in terminal

```<code>adb kill-server
adb connect 127.0.0.1:62001
adb devices
</code>```

If it looks like this

Then you have no problem with Android devices.
Try running the app again with

```<code>react-native run-android
</code>```

If it's not working, try

```<code>cd android
./gradlew clean
cd ..
react-native run-android
</code>```

Body:
Check if you actually have a device connected by typing this in terminal

adb devices

If there is no device detected.

Try typing this in terminal

adb kill-server
adb connect 127.0.0.1:62001
adb devices

If it looks like this

Then you have no problem with Android devices.
Try running the app again with

react-native run-android

If it's not working, try

cd android
./gradlew clean
cd ..
react-native run-android


问:
Airflow BigQueryOperator Label issue: Label value has invalid characters
I have been trying to leverage the Airflow macros reference default variables and BigQuery labels to log metadata for queries submitted through Airflow BigQueryOperator. Here is the operator definition:

```<code>BigQuery_Labels_Test_Task = BigQueryOperator(
    task_id="BigQuery_Labels_Test_Task",
    bql="SELECT 1",
    use_legacy_sql=False,
    bigquery_conn_id="gcp_bq_connection",
    destination_dataset_table=f"test_dataset.test_table",
    create_disposition="CREATE_IF_NEEDED",
    write_disposition="WRITE_TRUNCATE",
    labels={
        "dag_id": "{{ dag.dag_id }}",
        "task_id": "{{ task.task_id }}",
        "run_id": "{{ run_id }}",
    },
    dag=dag,
)
</code>```

But when it executes it is throwing up the following error:

```<code>[2020-06-01 08:15:13,495] {{taskinstance.py:887}} INFO - Executing <Task(BigQueryOperator): BigQuery_Labels_Test_Task> on 2020-06-01T07:51:40.752935+00:00
[2020-06-01 08:15:13,499] {{standard_task_runner.py:53}} INFO - Started process 16317 to run task
[2020-06-01 08:15:13,567] {{logging_mixin.py:112}} INFO - Running %s on host %s <TaskInstance: BigQuery_Labels_Test_DAG.BigQuery_Labels_Test_Task 2020-06-01T07:51:40.752935+00:00 [running]> b438a71d2d52
[2020-06-01 08:15:13,592] {{bigquery_operator.py:255}} INFO - Executing: SELECT 1
[2020-06-01 08:15:14,161] {{taskinstance.py:1128}} ERROR - <HttpError 400 when requesting https://bigquery.googleapis.com/bigquery/v2/projects/test-project/jobs?alt=json returned "Label value "manual__2020-06-01T07:51:40.752935+00:00" has invalid characters.">
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/models/taskinstance.py", line 966, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/operators/bigquery_operator.py", line 282, in execute
    encryption_configuration=self.encryption_configuration
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/hooks/bigquery_hook.py", line 910, in run_query
    return self.run_with_configuration(configuration)
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/hooks/bigquery_hook.py", line 1318, in run_with_configuration
    .execute(num_retries=self.num_retries)
  File "/usr/local/airflow/.local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/airflow/.local/lib/python3.7/site-packages/googleapiclient/http.py", line 907, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://bigquery.googleapis.com/bigquery/v2/projects/test-project/jobs?alt=json returned "Label value "manual__2020-06-01T07:51:40.752935+00:00" has invalid characters.">
[2020-06-01 08:15:14,165] {{taskinstance.py:1151}} INFO - Marking task as UP_FOR_RETRY
</code>```

Did anyone encounter anything like this? Does the label field in bq have any character restriction?

PS: When I hardcode something like the following for the label values, it works.:

```<code>labels={
    "dag_id": "dag_id",
    "task_id": "task_id",
},
</code>```

Only lower case values works with hardcoding too.

答:
This issue is not related to airflow but is to BigQuery.
For defining labels,run_id doesn't fulfill below requirements(run_id has +,:):

Keys and values can contain only lowercase letters, numeric
  characters, underscores, and dashes. All characters must use UTF-8
  encoding, and international characters are allowed.

For more info on BigQuery labels, please refer to this.

Body:
I have been trying to leverage the Airflow macros reference default variables and BigQuery labels to log metadata for queries submitted through Airflow BigQueryOperator. Here is the operator definition:

BigQuery_Labels_Test_Task = BigQueryOperator(
    task_id="BigQuery_Labels_Test_Task",
    bql="SELECT 1",
    use_legacy_sql=False,
    bigquery_conn_id="gcp_bq_connection",
    destination_dataset_table=f"test_dataset.test_table",
    create_disposition="CREATE_IF_NEEDED",
    write_disposition="WRITE_TRUNCATE",
    labels={
        "dag_id": "{{ dag.dag_id }}",
        "task_id": "{{ task.task_id }}",
        "run_id": "{{ run_id }}",
    },
    dag=dag,
)

But when it executes it is throwing up the following error:

[2020-06-01 08:15:13,495] {{taskinstance.py:887}} INFO - Executing <Task(BigQueryOperator): BigQuery_Labels_Test_Task> on 2020-06-01T07:51:40.752935+00:00
[2020-06-01 08:15:13,499] {{standard_task_runner.py:53}} INFO - Started process 16317 to run task
[2020-06-01 08:15:13,567] {{logging_mixin.py:112}} INFO - Running %s on host %s <TaskInstance: BigQuery_Labels_Test_DAG.BigQuery_Labels_Test_Task 2020-06-01T07:51:40.752935+00:00 [running]> b438a71d2d52
[2020-06-01 08:15:13,592] {{bigquery_operator.py:255}} INFO - Executing: SELECT 1
[2020-06-01 08:15:14,161] {{taskinstance.py:1128}} ERROR - <HttpError 400 when requesting https://bigquery.googleapis.com/bigquery/v2/projects/test-project/jobs?alt=json returned "Label value "manual__2020-06-01T07:51:40.752935+00:00" has invalid characters.">
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/models/taskinstance.py", line 966, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/operators/bigquery_operator.py", line 282, in execute
    encryption_configuration=self.encryption_configuration
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/hooks/bigquery_hook.py", line 910, in run_query
    return self.run_with_configuration(configuration)
  File "/usr/local/lib/python3.7/site-packages/airflow/contrib/hooks/bigquery_hook.py", line 1318, in run_with_configuration
    .execute(num_retries=self.num_retries)
  File "/usr/local/airflow/.local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/airflow/.local/lib/python3.7/site-packages/googleapiclient/http.py", line 907, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://bigquery.googleapis.com/bigquery/v2/projects/test-project/jobs?alt=json returned "Label value "manual__2020-06-01T07:51:40.752935+00:00" has invalid characters.">
[2020-06-01 08:15:14,165] {{taskinstance.py:1151}} INFO - Marking task as UP_FOR_RETRY

Did anyone encounter anything like this? Does the label field in bq have any character restriction?

PS: When I hardcode something like the following for the label values, it works.:

labels={
    "dag_id": "dag_id",
    "task_id": "task_id",
},

Only lower case values works with hardcoding too.