问:
Return Invoice Based on Invoice Items (INNER JOIN)
I have 2 tables in SQL Server: Invoice and InvoiceItem. Both tables have an InvoiceID column and the InvoiceItem table has an ItemID column.

What I need is a query that I can run to return an invoice if the InvoiceItems have exactly the ItemID's specified.

Example:

```<code>Invoice.InvoiceID = 1

InvoiceItem.InvoiceItemID = 1
InvoiceItem.InvoiceID = 1
InvoiceItem.ItemID = 1

InvoiceItem.InvoiceItemID = 2
InvoiceItem.InvoiceID = 1
InvoiceItem.ItemID = 2
</code>```

I need to query for any invoices that have EXACTLY 2 line items, one with an ItemID of 1 and one with an ItemID of 2.

I thought an INNER JOIN with an "IN" statement might get me there, but it returns more than just the one invoice. The following returns any invoice that has an ItemID of 1 or 2. It's kind of like I want an "and" instead of an "or" in the "IN".

```<code>SELECT InvoiceID FROM Invoice i INNER JOIN InvoiceItem ii ON i.InvoiceID = ii.InvoiceID WHERE ii.ItemID IN (1, 2)
</code>```

答:
And instead of Or in the IN

I understand what you mean but it wouldn't work because you're thinking across multiple rows, which are like different instances of the same kind of item. If you were looking for a row where itemid = 1 and itemid = 2 you'd never get anything because no single row satisfies this

Instead you can look at the whole collection of rows for a particular invoice, and look at them in aggregation. What you're effectively saying is "I want invoice ids where the number of detail lines is two, the lowest item ID is 1 and the highest is 2" - this is "looking across multiple rows" and selecting aggregate attributes:

```<code>SELECT InvoiceID
FROM InvoiceItems
GROUP BY InvoiceID
HAVING
  COUNT(*) = 2 AND
  MIN(ItemId) = 1 AND
  MAX(ItemID) = 2
</code>```

Notes:

you can omit the count check if InvoiceID,ItemID is unique

put this into a subquery and join in the Invoices table afterwards, if you want info from it

You asked for any variable number of items here's a technique for it:

```<code>SELECT InvoiceID
FROM InvoiceItems
GROUP BY InvoiceID
HAVING
  SUM(CASE ItemID
    WHEN 9 THEN 2
    WHEN 38 THEN 4
    WHEN 483 THEN 8
    ELSE 1 END
  ) = 14 AND
  COUNT(*) = 3
</code>```

By converting your numbers to 2,4 or 8 and mandating 3 items, there's only one way to get to 14..

Body:
I have 2 tables in SQL Server: Invoice and InvoiceItem. Both tables have an InvoiceID column and the InvoiceItem table has an ItemID column.

What I need is a query that I can run to return an invoice if the InvoiceItems have exactly the ItemID's specified.

Example:

Invoice.InvoiceID = 1

InvoiceItem.InvoiceItemID = 1
InvoiceItem.InvoiceID = 1
InvoiceItem.ItemID = 1

InvoiceItem.InvoiceItemID = 2
InvoiceItem.InvoiceID = 1
InvoiceItem.ItemID = 2

I need to query for any invoices that have EXACTLY 2 line items, one with an ItemID of 1 and one with an ItemID of 2.

I thought an INNER JOIN with an "IN" statement might get me there, but it returns more than just the one invoice. The following returns any invoice that has an ItemID of 1 or 2. It's kind of like I want an "and" instead of an "or" in the "IN".

SELECT InvoiceID FROM Invoice i INNER JOIN InvoiceItem ii ON i.InvoiceID = ii.InvoiceID WHERE ii.ItemID IN (1, 2)

Body:
And instead of Or in the IN

I understand what you mean but it wouldn't work because you're thinking across multiple rows, which are like different instances of the same kind of item. If you were looking for a row where itemid = 1 and itemid = 2 you'd never get anything because no single row satisfies this

Instead you can look at the whole collection of rows for a particular invoice, and look at them in aggregation. What you're effectively saying is "I want invoice ids where the number of detail lines is two, the lowest item ID is 1 and the highest is 2" - this is "looking across multiple rows" and selecting aggregate attributes:

SELECT InvoiceID
FROM InvoiceItems
GROUP BY InvoiceID
HAVING
  COUNT(*) = 2 AND
  MIN(ItemId) = 1 AND
  MAX(ItemID) = 2

Notes:

you can omit the count check if InvoiceID,ItemID is unique

put this into a subquery and join in the Invoices table afterwards, if you want info from it

You asked for any variable number of items here's a technique for it:

SELECT InvoiceID
FROM InvoiceItems
GROUP BY InvoiceID
HAVING
  SUM(CASE ItemID
    WHEN 9 THEN 2
    WHEN 38 THEN 4
    WHEN 483 THEN 8
    ELSE 1 END
  ) = 14 AND
  COUNT(*) = 3

By converting your numbers to 2,4 or 8 and mandating 3 items, there's only one way to get to 14..


来源: stackexchange

问:
Spring Cloud stream binder Kafka custom headers are not received in consumer
I'm using Spring cloud stream binder kafka, Edgware.SR4 release.

I have set custom headers to a message payload and published it but i can't see those headers in consumer end.

I have used Message object to bind payload and headers. I have tried adding the property spring.cloud.stream.kafka.binder.headers but it did not work

Producer:

Application.yml

```<code>spring:
  cloud:
    stream:
      bindings:
        sampleEvent:
          destination: sample-event
          content-type: application/json
      kafka:
        binder:
          brokers: localhost:9092
          zkNodes: localhost:2181
          autoCreateTopics: false
          zkConnectionTimeout: 36000
</code>```

MessageChannelConstants.java

```<code>public class MessageChannelConstants {
    public static final String SAMPLE_EVENT = "sampleEvent";
        private MessageChannelConstants() {}
}
</code>```

SampleMessageChannels.java

```<code>public interface SampleMessageChannels {

    @Output(MessageChannelConstants.SAMPLE_EVENT)
    MessageChannel sampleEvent();
}
</code>```

SampleEventPublisher.java

```<code>@Service
@EnableBinding(SampleMessageChannels.class)
public class SampleEventPublisher{

@Autowired
private SampleMessageChannels sampleMessageChannels;

public void publishSampleEvent(SampleEvent sampleEvent) {
        final Message<SampleEvent> message = MessageBuilder.withPayload(sampleEvent).setHeader("appId", "Demo").build();
    MessageChannel messageChannel = SampleMessageChannels.sampleEvent();
    if (messageChannel != null) {
        messageChannel.send(message);
    }
}
}
</code>```

Consumer:

application.yml

```<code>spring:
  cloud:
    stream:
      bindings:
        sampleEvent:
          destination: sample-event
          content-type: application/json
      kafka:
        binder:
          brokers: localhost:9092
          zkNodes: localhost:2181
          autoCreateTopics: false
          zkConnectionTimeout: 36000
</code>```

MessageChannelConstants.java

```<code>public class MessageChannelConstants {

    public static final String SAMPLE_EVENT = "sampleEvent";

    private MessageChannelConstants() {}
}
</code>```

SampleMessageChannels.java

```<code>public interface SampleMessageChannels {

    @Output(MessageChannelConstants.SAMPLE_EVENT)
    MessageChannel sampleEvent();
}
</code>```

SampleEventListener.java

```<code>@Service
@EnableBinding(SampleMessageChannels.class)
public class SampleEventListener{

@StreamListener(MessageChannelConstants.SAMPLE_EVENT)
public void listenSampleEvent(@Payload SampleEvent event,
    @Header(required = true, name = "appId") String appId) {

     // do something
}
</code>```

Below is the Exception I got,

```<code>org.springframework.messaging.MessageHandlingException: Missing header 'appId' for method parameter type [class java.lang.String]
    at org.springframework.messaging.handler.annotation.support.HeaderMethodArgumentResolver.handleMissingValue(HeaderMethodArgumentResolver.java:100)
    at org.springframework.messaging.handler.annotation.support.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:103)
    at org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:112)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:135)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:107)
    at org.springframework.cloud.stream.binding.StreamListenerMessageHandler.handleRequestMessage(StreamListenerMessageHandler.java:55)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:425)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:375)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:360)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:271)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:188)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:70)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:64)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:188)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$200(KafkaMessageDrivenChannelAdapter.java:63)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:372)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:352)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter$1.doWithRetry(RetryingAcknowledgingMessageListenerAdapter.java:79)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter$1.doWithRetry(RetryingAcknowledgingMessageListenerAdapter.java:73)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:180)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter.onMessage(RetryingAcknowledgingMessageListenerAdapter.java:73)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter.onMessage(RetryingAcknowledgingMessageListenerAdapter.java:39)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:792)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:736)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.access$2100(KafkaMessageListenerContainer.java:246)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer$ListenerInvoker.run(KafkaMessageListenerContainer.java:1025)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Note: I am using spring cloud sleuth and zipkin dependency as well.

答:
With Edgware (SCSt Ditmars), you have to specify which headers will be transferred.

See Kafka Binder Properties.

This is because Edgware was based on Kafka before it supported headers natively and we encode the headers into the payload.

spring.cloud.stream.kafka.binder.headers

The list of custom headers that will be transported by the binder.

Default: empty.

You should also be sure to upgrade spring-kafka to 1.3.9.RELEASE and kafka-clients to 0.11.0.2.

Preferably, though, upgrade to Finchley or Greemwich. Those versions support headers natively.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Spring cloud stream binder kafka, Edgware.SR4 release.

I have set custom headers to a message payload and published it but i can't see those headers in consumer end.

I have used Message object to bind payload and headers. I have tried adding the property spring.cloud.stream.kafka.binder.headers but it did not work

Producer:

Application.yml

spring:
  cloud:
    stream:
      bindings:
        sampleEvent:
          destination: sample-event
          content-type: application/json
      kafka:
        binder:
          brokers: localhost:9092
          zkNodes: localhost:2181
          autoCreateTopics: false
          zkConnectionTimeout: 36000

MessageChannelConstants.java

public class MessageChannelConstants {
    public static final String SAMPLE_EVENT = "sampleEvent";
        private MessageChannelConstants() {}
}

SampleMessageChannels.java

public interface SampleMessageChannels {

    @Output(MessageChannelConstants.SAMPLE_EVENT)
    MessageChannel sampleEvent();
}

SampleEventPublisher.java

@Service
@EnableBinding(SampleMessageChannels.class)
public class SampleEventPublisher{

@Autowired
private SampleMessageChannels sampleMessageChannels;

public void publishSampleEvent(SampleEvent sampleEvent) {
        final Message<SampleEvent> message = MessageBuilder.withPayload(sampleEvent).setHeader("appId", "Demo").build();
    MessageChannel messageChannel = SampleMessageChannels.sampleEvent();
    if (messageChannel != null) {
        messageChannel.send(message);
    }
}
}

Consumer:

application.yml

spring:
  cloud:
    stream:
      bindings:
        sampleEvent:
          destination: sample-event
          content-type: application/json
      kafka:
        binder:
          brokers: localhost:9092
          zkNodes: localhost:2181
          autoCreateTopics: false
          zkConnectionTimeout: 36000

MessageChannelConstants.java

public class MessageChannelConstants {

    public static final String SAMPLE_EVENT = "sampleEvent";

    private MessageChannelConstants() {}
}

SampleMessageChannels.java

public interface SampleMessageChannels {

    @Output(MessageChannelConstants.SAMPLE_EVENT)
    MessageChannel sampleEvent();
}

SampleEventListener.java

@Service
@EnableBinding(SampleMessageChannels.class)
public class SampleEventListener{

@StreamListener(MessageChannelConstants.SAMPLE_EVENT)
public void listenSampleEvent(@Payload SampleEvent event,
    @Header(required = true, name = "appId") String appId) {

     // do something
}

Below is the Exception I got,

org.springframework.messaging.MessageHandlingException: Missing header 'appId' for method parameter type [class java.lang.String]
    at org.springframework.messaging.handler.annotation.support.HeaderMethodArgumentResolver.handleMissingValue(HeaderMethodArgumentResolver.java:100)
    at org.springframework.messaging.handler.annotation.support.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:103)
    at org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:112)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:135)
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:107)
    at org.springframework.cloud.stream.binding.StreamListenerMessageHandler.handleRequestMessage(StreamListenerMessageHandler.java:55)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:425)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:375)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:360)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:271)
    at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:188)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:70)
    at org.springframework.integration.channel.FixedSubscriberChannel.send(FixedSubscriberChannel.java:64)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
    at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:188)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$200(KafkaMessageDrivenChannelAdapter.java:63)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:372)
    at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:352)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter$1.doWithRetry(RetryingAcknowledgingMessageListenerAdapter.java:79)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter$1.doWithRetry(RetryingAcknowledgingMessageListenerAdapter.java:73)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:180)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter.onMessage(RetryingAcknowledgingMessageListenerAdapter.java:73)
    at org.springframework.kafka.listener.adapter.RetryingAcknowledgingMessageListenerAdapter.onMessage(RetryingAcknowledgingMessageListenerAdapter.java:39)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:792)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:736)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.access$2100(KafkaMessageListenerContainer.java:246)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer$ListenerInvoker.run(KafkaMessageListenerContainer.java:1025)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)

Note: I am using spring cloud sleuth and zipkin dependency as well.


问:
docker compose building sequence
I have a multi-container app (Laravel+Nginx+PostgreSQL) and I using docker compose to build my app.

I need to run php artisan migrate inside my Laravel container in the building process, but I have an issue - Laravel container can start building first before Postgres container, so I got the error because my DB host is not ready.
How can I set something like "building sequence" in my docker-compose.yml?

My current docker-compose.yml:

```<code>version: '3.3'
services:

  phpfpm:
    build:
      context: laravel-docker
    depends_on:
      - db
    container_name: phpfpm
    restart: always
    volumes:
      - /var/www/html/vendor/
      - ./laravel-docker:/var/www/html
    networks:
      - app-network

  db:
    image: postgres:9.6.5-alpine
    container_name: db
    restart: always
    environment:
      POSTGRES_DB: blabla
      POSTGRES_USER: blabla
      POSTGRES_PASSWORD: blabla
    volumes:
      - ./db_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - app-network
</code>```

and laravel-docker/Dockerfile:

```<code>FROM php:7.3.0-fpm-alpine3.8

//...

RUN chown -R www-data:www-data /var/www/html
RUN chmod 755 -R /var/www/html && chmod -R o+w storage/

USER www-data

RUN composer install
RUN composer dump-autoload
COPY .env.example .env
// I need to migrate here when DB container will be ready
</code>```

答:
Dockerfile is not a good choice for database migration operations. The image should be able to build itself in isolation from other containers.

Database migration is more suited to be a boot-time operation, rather than a build-time operation. A good place for it would be image's entrypoint script, or as a separate "init" job when booting the docker stack - depending on what you feel more comfortable with.

Title: docker compose building sequence

Body:
I have a multi-container app (Laravel+Nginx+PostgreSQL) and I using docker compose to build my app.

I need to run php artisan migrate inside my Laravel container in the building process, but I have an issue - Laravel container can start building first before Postgres container, so I got the error because my DB host is not ready.
How can I set something like "building sequence" in my docker-compose.yml?

My current docker-compose.yml:

version: '3.3'
services:

  phpfpm:
    build:
      context: laravel-docker
    depends_on:
      - db
    container_name: phpfpm
    restart: always
    volumes:
      - /var/www/html/vendor/
      - ./laravel-docker:/var/www/html
    networks:
      - app-network

  db:
    image: postgres:9.6.5-alpine
    container_name: db
    restart: always
    environment:
      POSTGRES_DB: blabla
      POSTGRES_USER: blabla
      POSTGRES_PASSWORD: blabla
    volumes:
      - ./db_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - app-network

and laravel-docker/Dockerfile:

FROM php:7.3.0-fpm-alpine3.8

//...

RUN chown -R www-data:www-data /var/www/html
RUN chmod 755 -R /var/www/html && chmod -R o+w storage/

USER www-data

RUN composer install
RUN composer dump-autoload
COPY .env.example .env
// I need to migrate here when DB container will be ready


问:
How to delete cookie MEAN stack?
I try to delete a cookie of my Node API in my Angular client (MEAN stack) but it doesn't work.

I have on Node side a controller and a router, and on my Angular I subscribe the service.

// router node

```<code>authRouter.get('/logout', this.passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  logout()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse));
});
</code>```

// controller node

```<code>const logout = (res) => {
  res.cookie(process.env.COOKIE_NAME, '', {
    maxAge: -1,
    httpOnly: true
  });
};
</code>```

// service angular

```<code>public logout(): Observable < any > {
  // GET '/auth/logout'
  console.log('logout service ok');
  return this.HttpClient.get(`${environment.apiUrl}/auth/logout`)
}
</code>```

// component angular call logout

```<code>public logout = () => {
  return this.AuthService.logout()
};

ngOnInit() {
  this.logout();
};
</code>```

Do you think the code is OK ?

答:
```<code>maxAge: 0
</code>```

Setting to 0 means delete this cookie right now.

Title: How to delete cookie MEAN stack?

Body:
I try to delete a cookie of my Node API in my Angular client (MEAN stack) but it doesn't work.

I have on Node side a controller and a router, and on my Angular I subscribe the service.

// router node

authRouter.get('/logout', this.passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  logout()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse));
});

// controller node

const logout = (res) => {
  res.cookie(process.env.COOKIE_NAME, '', {
    maxAge: -1,
    httpOnly: true
  });
};

// service angular

public logout(): Observable < any > {
  // GET '/auth/logout'
  console.log('logout service ok');
  return this.HttpClient.get(`${environment.apiUrl}/auth/logout`)
}

// component angular call logout

public logout = () => {
  return this.AuthService.logout()
};

ngOnInit() {
  this.logout();
};

Do you think the code is OK ?

Body:
maxAge: 0

Setting to 0 means delete this cookie right now.


问:
React Native: How to get a "normal" SelectBox/Picker
I started with React Native a few days ago. Developing for Android is nice because of existing tools/simulators (Linux) and I am using Android for years on my mobile and tablet.

Because I do not have a Mac I bought an older iPhone for testing my first apps on iOS too.

So I was pretty astonished when I saw what a Picker looks like on iOS (this sort of twist wheel thing).

Is there any way to get a Picker that is more like HTMLs Select or the Android Picker?

答:
I recommend this package:

https://www.npmjs.com/package/react-native-picker-select

very popular and it works very well


问:
Click feature on marker of open layers version 5
I am using open layers library version 5. I need an onClick event on marker to do some business logic. Anybody could help me with this out thankyou. I have tried every code and snippets. I am using this library to react js.

```<code>import Feature from "ol/Feature";
  import point from "ol/geom/Point"
  import Style from "ol/style/Style";
  import Icon from "ol/style/Icon";

renderMap = (lat = 24.8856802, lng = 67.0830459) => {
    console.log(lat, lng);
    this.map = new Map({
      target: 'map',
      layers: [
        new TileLayer({
          source: new OSM()
        })
      ],
      view: new View({
        center: fromLonLat([lng, lat]),
        zoom: 17,

      })
    });

    this.makeMarker(24.8856802, 67.0830459, 0);

  }
//here is my marker function
makeMarker = (lat, lng, index) => {
    let marker = new Feature({
      geometry: new point(fromLonLat([lng, lat])),

    });
    marker.setStyle(new Style({
      image: new Icon(({
        // crossOrigin: 'anonymous',
        src: require("../../assets/images/location-pin.png"),
    enter code here`enter code here`

      }))
    }));
    let vectorSource = new Vector({ features: [marker] })
    var markerVectorLayer = new LVector({
      source: vectorSource,

    });
    this.map.addLayer(markerVectorLayer);
    marker.on("click", () => {
      alert()
    })

  }
</code>```

答:
Features don't have click events. Similar to this example https://openlayers.org/en/latest/examples/icon.html you will need to listen for click on the map, check if there is a feature at the click pixel and also that feature is your marker</p>

```<code>  map.on('click', function(evt) {
    var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });
    if (feature === marker) {
</code>```

Body:
I am using open layers library version 5. I need an onClick event on marker to do some business logic. Anybody could help me with this out thankyou. I have tried every code and snippets. I am using this library to react js.

import Feature from "ol/Feature";
  import point from "ol/geom/Point"
  import Style from "ol/style/Style";
  import Icon from "ol/style/Icon";

renderMap = (lat = 24.8856802, lng = 67.0830459) => {
    console.log(lat, lng);
    this.map = new Map({
      target: 'map',
      layers: [
        new TileLayer({
          source: new OSM()
        })
      ],
      view: new View({
        center: fromLonLat([lng, lat]),
        zoom: 17,

      })
    });

    this.makeMarker(24.8856802, 67.0830459, 0);

  }
//here is my marker function
makeMarker = (lat, lng, index) => {
    let marker = new Feature({
      geometry: new point(fromLonLat([lng, lat])),

    });
    marker.setStyle(new Style({
      image: new Icon(({
        // crossOrigin: 'anonymous',
        src: require("../../assets/images/location-pin.png"),
    enter code here`enter code here`

      }))
    }));
    let vectorSource = new Vector({ features: [marker] })
    var markerVectorLayer = new LVector({
      source: vectorSource,

    });
    this.map.addLayer(markerVectorLayer);
    marker.on("click", () => {
      alert()
    })

  }

Body:
Features don't have click events. Similar to this example https://openlayers.org/en/latest/examples/icon.html you will need to listen for click on the map, check if there is a feature at the click pixel and also that feature is your marker

  map.on('click', function(evt) {
    var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });
    if (feature === marker) {


问:
django models - Avoid possible circular reference in database design
I have a database design and relationships problem and I am concerned with possible circular references.

To give an example, Jack has on his stock Medicines A, B and C. Medicines A and B have an active_ingredient AI1 and medicine C has an active_ingredient AI2.

Jack goes to the doctor, who prescribes him AI1. For the Prescription object, it is indifferent if he takes Medicine A or B.

Here is an example code:

```<code>class ActiveIngredient(models.Model):
    ...

class Medicine(models.Model):
    quantity = models.IntegerField()
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)

class Person(models.Model):
    ...

class PersonStock(models.Model):
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    medicine = models.ForeignKey("Medicine", on_delete=models.CASCADE)
    expiration_date = models.DateField()

class Prescription(models.Model):
    ...
    quantity = models.IntegerField()
</code>```

What is the best solution to model this relationship?

Changing Prescription to this:

```<code>class Prescription(models.Model):
    ...
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)
    quantity = models.IntegerField()
</code>```

Seems wrong to me given that there is the PersonStock class already connecting Person and Medicine.

答:
You're right to be concerned about duplicated information; a major concern of database design (specifically database normalization) is avoiding that so as to eliminate the possibility of inconsistent data.

In this case, however, I think it makes more sense to keep prescriptions and their filling separate. These are two separate things, and in the real world it's very possible for mistakes to be made and the wrong medicine to be delivered. While one should endeavor to prevent such mistakes, that's very different from making it impossible to represent a mistake in your data model.

So my recommendation would be to validate the data at the application layer rather than building constraints into the data model itself. Something like:

```<code>class ActiveIngredient(models.Model):
    ...

class Medicine(models.Model):
    quantity = models.IntegerField()
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)

class Person(models.Model):
    ...

class Prescription(models.Model):
    ...
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)
    quantity = models.IntegerField()

class PersonStock(models.Model):
    prescription = models.ForeignKey("Prescription", on_delete=models.CASCADE)
    medicine = models.ForeignKey("Medicine", on_delete=models.CASCADE)
    expiration_date = models.DateField()

    # Make sure the supplied medicine is correct.
    def clean(self):
        if self.medicine.active_ingredient != self.prescription.active_ingredient:
            raise ValidationError("Wrong medicine!")
</code>```

Alternatively you could do the check only when a PersonStock is being created.

Body:
I have a database design and relationships problem and I am concerned with possible circular references.

To give an example, Jack has on his stock Medicines A, B and C. Medicines A and B have an active_ingredient AI1 and medicine C has an active_ingredient AI2.

Jack goes to the doctor, who prescribes him AI1. For the Prescription object, it is indifferent if he takes Medicine A or B.

Here is an example code:

class ActiveIngredient(models.Model):
    ...

class Medicine(models.Model):
    quantity = models.IntegerField()
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)

class Person(models.Model):
    ...

class PersonStock(models.Model):
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    medicine = models.ForeignKey("Medicine", on_delete=models.CASCADE)
    expiration_date = models.DateField()

class Prescription(models.Model):
    ...
    quantity = models.IntegerField()

What is the best solution to model this relationship?

Changing Prescription to this:

class Prescription(models.Model):
    ...
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)
    quantity = models.IntegerField()

Seems wrong to me given that there is the PersonStock class already connecting Person and Medicine.

Body:
You're right to be concerned about duplicated information; a major concern of database design (specifically database normalization) is avoiding that so as to eliminate the possibility of inconsistent data.

In this case, however, I think it makes more sense to keep prescriptions and their filling separate. These are two separate things, and in the real world it's very possible for mistakes to be made and the wrong medicine to be delivered. While one should endeavor to prevent such mistakes, that's very different from making it impossible to represent a mistake in your data model.

So my recommendation would be to validate the data at the application layer rather than building constraints into the data model itself. Something like:

class ActiveIngredient(models.Model):
    ...

class Medicine(models.Model):
    quantity = models.IntegerField()
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)

class Person(models.Model):
    ...

class Prescription(models.Model):
    ...
    customer = models.ForeignKey("Person", on_delete=models.CASCADE)
    active_ingredient = models.ForeignKey("ActiveIngredient", on_delete=models.CASCADE)
    quantity = models.IntegerField()

class PersonStock(models.Model):
    prescription = models.ForeignKey("Prescription", on_delete=models.CASCADE)
    medicine = models.ForeignKey("Medicine", on_delete=models.CASCADE)
    expiration_date = models.DateField()

    # Make sure the supplied medicine is correct.
    def clean(self):
        if self.medicine.active_ingredient != self.prescription.active_ingredient:
            raise ValidationError("Wrong medicine!")

Alternatively you could do the check only when a PersonStock is being created.


问:
Dynamically Copy Range of Cells from Closed Workbook?
I would like to copy a range of cells in a closed notebook that does not have a static set of rows. I would like to copy it into an active workbook.

I am trying to dynamically copy all entries under the column of F from file 'test.xlsx' from the 'exception' worksheet. The macro runs without issue if there I use static referencing instead. Here is the code that I am running, it gives me a runtime error for the line that copies the data.

```<code>Sub GetClassID()

Dim App As New Excel.Application

Dim wsActive As Worksheet
Set wsActive = ThisWorkbook.ActiveSheet

Dim wbImport As Workbook
Set wbImport = App.Workbooks.Open(Filename:="C:\Test.xlsx",
UpdateLinks:=True, ReadOnly:=True)

wbImport.Worksheets("Exception").Range("F2",Range("F2").end(xldown)).Copy
wsActive.Range("A2").PasteSpecial Paste:=xlPasteFormats
wsActive.Range("A2").PasteSpecial Paste:=xlPasteValues

App.CutCopyMode = False
wbImport.Close SaveChanges:=False
App.Quit

End Sub
</code>```

Error I get is runtime erorr '1004': Interface not registered

答:
Assuming you run this in an Excel VBA? You don't need to open the other workbook as an Excel.Application, just remove the app out of it and open the workbook normally:

Sub GetClassID()

Dim wsActive As Worksheet
Set wsActive = ThisWorkbook.Sheets("Another Sheet Name")

Dim wbImport As Workbook
Set wbImport = Workbooks.Open(Filename:="C:\Test.xlsx", UpdateLinks:=True, ReadOnly:=True)

With wbImport.Worksheets("Exception")
    .Range("F2", .Range("F2").End(xlDown)).Copy
End With
wsActive.Range("A2").PasteSpecial Paste:=xlPasteFormats
wsActive.Range("A2").PasteSpecial Paste:=xlPasteValues

App.CutCopyMode = False
wbImport.Close SaveChanges:=False
App.Quit

End Sub
```

Body:
I would like to copy a range of cells in a closed notebook that does not have a static set of rows. I would like to copy it into an active workbook.

I am trying to dynamically copy all entries under the column of F from file 'test.xlsx' from the 'exception' worksheet. The macro runs without issue if there I use static referencing instead. Here is the code that I am running, it gives me a runtime error for the line that copies the data.

Sub GetClassID()

Dim App As New Excel.Application

Dim wsActive As Worksheet
Set wsActive = ThisWorkbook.ActiveSheet

Dim wbImport As Workbook
Set wbImport = App.Workbooks.Open(Filename:="C:\Test.xlsx",
UpdateLinks:=True, ReadOnly:=True)

wbImport.Worksheets("Exception").Range("F2",Range("F2").end(xldown)).Copy
wsActive.Range("A2").PasteSpecial Paste:=xlPasteFormats
wsActive.Range("A2").PasteSpecial Paste:=xlPasteValues

App.CutCopyMode = False
wbImport.Close SaveChanges:=False
App.Quit

End Sub

Error I get is runtime erorr '1004': Interface not registered


问:
Can I create a WCF service without using attributes?
The way you seem to declare WCF services is to create an interface in C# or VB, and then tag it with ServiceContractAttribute and it's methods with OperationContractAttribute.

The issue is, I'd like to try creating one from IronRuby or IronPython, which (to my knowledge) don't support attributes.

Is this possible?

答:
Well, while I wouldn't (just preference, no need to flame me), you could use a language like Boo:

http://boo.codehaus.org/

Another alternative is to just build a piece in C# to do this communication for you then call that from IronyRuby or whatever language you want to use.

OwnerDisplayName: Orion Edwards

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: BobbyShaftoe

LastEditorDisplayName: BobbyShaftoe


问:
Is it correct to write [self.someproperty release]
When i implement dealloc method i used to write:

```<code>[preopertyX release];
</code>```

Today i found this code:

```<code>[self.propertyX release];
</code>```

I'm not sure that this method is completely correct. What do you think about ?
(we can take as assumption that propertyX is a retained and synthesized property).

答:
From my understanding, you should either set it to nil or you can release the instance variable.

```<code>[self setPropertyX:nil]
</code>```

or

```<code>[propertyX release]
</code>```

The method you list can have unwanted side effects, but if you want the side actions of your setter to happen, I suggest setting to nil.

The accepted answer here: iPhone - dealloc - Release vs. nil is pretty good.

This is a nice debate outlining, pretty vibrantly, the methods available to you.

http://iphonedevelopment.blogspot.com/2010/09/dealloc.html
followed up by
 http://www.red-sweater.com/blog/1423/dont-coddle-your-code

ContentLicense: CC BY-SA 3.0

Body:
When i implement dealloc method i used to write:

[preopertyX release];

Today i found this code:

[self.propertyX release];

I'm not sure that this method is completely correct. What do you think about ?
(we can take as assumption that propertyX is a retained and synthesized property).

Body:
From my understanding, you should either set it to nil or you can release the instance variable.

[self setPropertyX:nil]

or

[propertyX release]

The method you list can have unwanted side effects, but if you want the side actions of your setter to happen, I suggest setting to nil.

The accepted answer here: iPhone - dealloc - Release vs. nil is pretty good.

This is a nice debate outlining, pretty vibrantly, the methods available to you.

http://iphonedevelopment.blogspot.com/2010/09/dealloc.html
followed up by
 http://www.red-sweater.com/blog/1423/dont-coddle-your-code


问:
Bringing matching columns with criteria together across multiplle tables
So I'm in a bit of a complex mess.

I have a schema with multiple tables. I'm trying to pull information together across the tables.

Ex.

```<code>Table 1

    character_infos

col

    character_id , name

Table 2

    character_skills

col

    character_id, skill_id, active_skill_level
</code>```

I'm trying to join all of this information on a single table by character ID, Skill ID, and if active skill level is less than a number.

However, I'm losing myself in this.

I thought I could approach it like a programmer and just use and statements, but clearly not.

What I currently have, that works, only pulls from the character ID but can't define per skill_id.

```<code>SELECT character_id, skill_id, active_skill_level
FROM character_skills
WHERE character_id = 92692957 AND active_skill_level =< 4;
</code>```

Where do I go from here? Any help would be greatly appreciated.

答:
Not an expert by any means, but have been in your shoes before. From what I can see your tables only have 1 field that is common to both "character_id". On this column you can attempt an INNER JOIN.

Here's an example that may help you get going.

```<code>SELECT      character_infos.name,
            character_skills.active_skill_level
FROM        character_skills
INNER JOIN  character_skills
ON      character_infos.character_id = character_skills.character_id
WHERE       character_infos.character_id = 92692957
AND         character_skills.active_skill_level =< 4;
</code>```

Body:
So I'm in a bit of a complex mess.

I have a schema with multiple tables. I'm trying to pull information together across the tables.

Ex.

Table 1

    character_infos

col

    character_id , name

Table 2

    character_skills

col

    character_id, skill_id, active_skill_level

I'm trying to join all of this information on a single table by character ID, Skill ID, and if active skill level is less than a number.

However, I'm losing myself in this.

I thought I could approach it like a programmer and just use and statements, but clearly not.

What I currently have, that works, only pulls from the character ID but can't define per skill_id.

SELECT character_id, skill_id, active_skill_level
FROM character_skills
WHERE character_id = 92692957 AND active_skill_level =< 4;

Where do I go from here? Any help would be greatly appreciated.

Body:
Not an expert by any means, but have been in your shoes before. From what I can see your tables only have 1 field that is common to both "character_id". On this column you can attempt an INNER JOIN.

Here's an example that may help you get going.

SELECT      character_infos.name,
            character_skills.active_skill_level
FROM        character_skills
INNER JOIN  character_skills
ON      character_infos.character_id = character_skills.character_id
WHERE       character_infos.character_id = 92692957
AND         character_skills.active_skill_level =< 4;


问:
Joining two table with rows and column and sum them
I have a  table that looks like

```<code>ColA  ColB  ColC ColD  ColE  ColF
 A    B      C    D     E      F
</code>```

I want to join each rows of this table to another table

```<code>Column1  values
 A          1
 A          2
 B          1
 B          2
</code>```

The resulting output will be sum of the column values from table 2. For example,
First row of table 1 has A,B that are present in table 2 and their combined sum is 6.

```<code>ColA  ColB  ColC ColD  ColE  ColF    sum
 A    B      C    D     E      F      6
</code>```

Any ideas how to do that in MYSQL?

答:
You can do this with a subquery:</p>

```<code>select t.*,
       (select sum(t2.value)
        from t2
        where t2.column1 in (t.cola, t.colb, t.colc, t.cold, t.cole, t.colf)
       ) as total
from t;
</code>```

Body:
I have a  table that looks like

ColA  ColB  ColC ColD  ColE  ColF
 A    B      C    D     E      F

I want to join each rows of this table to another table

Column1  values
 A          1
 A          2
 B          1
 B          2

The resulting output will be sum of the column values from table 2. For example,
First row of table 1 has A,B that are present in table 2 and their combined sum is 6.

ColA  ColB  ColC ColD  ColE  ColF    sum
 A    B      C    D     E      F      6

Any ideas how to do that in MYSQL?

Body:
You can do this with a subquery:

select t.*,
       (select sum(t2.value)
        from t2
        where t2.column1 in (t.cola, t.colb, t.colc, t.cold, t.cole, t.colf)
       ) as total
from t;


问:
How to fix this code? Passing String from method to MainActivity
I can't pass the jsonParse method variables. I tried to save them in the "ArrayList " but the Array remains empty. With another method, ex. "test", it works.
Why?

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridView = findViewById(R.id.griglia);
    mQueue = Volley.newRequestQueue(this);
    txt = findViewById(R.id.titolo);
    movieList= new ArrayList<Movie>();
</code>```

//
I call the metod jsonParse for to fill my ArrayList

```<code>    jsonParse();
    if(movieList.isEmpty()){
        txt.setText("vuoto");
    }
    else{
        txt.setText("pieno");
    }

}
</code>```

// I have a problem with this code. He works, but don't fill the ArrayList

```<code>public void jsonParse(){
    String url ="https://api.myjson.com/bins/tn67c";
    JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray= response.getJSONArray("movie");

                        for(int i=0; i<jsonArray.length(); i++){
                            JSONObject emplyee = jsonArray.getJSONObject(i);

                            String titolo = emplyee.getString("titolo");
                            String url = emplyee.getString("url");
                            String icona= emplyee.getString("icona");

                            Movie movie= new Movie();
                            movie.setTitolo(titolo);
                            movie.setVideoFilePath(url);
                            movieList.add(i, movie);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);

}
</code>```

//
I trust with a example method "prova" and now work it. Why?

```<code>public void prova(){
    int i=0;

    for(i=0; i<2; i++){
        String test= "ciao " + i;
        Movie movie= new Movie();
        movie.setTitolo(test);
        movieList.add(movie);
    }

}
</code>```

答:
you are initialing movieList after calling request please call before , try to initialize your list before onCreate

```<code>  ArrayList<Movie>  movieList = new ArrayList<Movie>();
</code>```

And put this

```<code>if(movieList.isEmpty()){
  txt.setText("vuoto");
 } else{
  txt.setText("pieno");
  }
</code>```

right after you finish adding item in the list

Edit:

```<code>package com.example.zvideo2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    String url ="https://api.myjson.com/bins/tn67c";
    private RequestQueue mQueue;
    ArrayList<Movie> movieList= new ArrayList<Movie>();
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mQueue = Volley.newRequestQueue(this);
        txt = findViewById(R.id.titolo);

        jsonParse();
//        prova();

    }

    public void jsonParse(){

        String url ="https://api.myjson.com/bins/tn67c";

        JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray= response.getJSONArray("movie");

                            for(int i=0; i<jsonArray.length(); i++){
                                JSONObject emplyee = jsonArray.getJSONObject(i);

                                String titolo = emplyee.getString("titolo");
                                String url = emplyee.getString("url");
                                String icona= emplyee.getString("icona");

                                Movie movie= new Movie();
                                movie.setTitolo(titolo);
                                movie.setVideoFilePath(url);
                                movieList.add(i, movie);
                            }

                            Toast.makeText(getActivity(), "item add successfully", Toast.LENGTH_LONG).show();
                            if(movieList.isEmpty()){
                            txt.setText("vuoto");
                            }else{
                            txt.setText("pieno");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
        mQueue.start(request);

    }

    public void prova(){
        int i=0;

        for(i=0; i<2; i++){
            String test= "ciao " + i;
            Movie movie= new Movie();
            movie.setTitolo(test);
            movieList.add(movie);
        }

    }

}
</code>```

Body:
I can't pass the jsonParse method variables. I tried to save them in the "ArrayList " but the Array remains empty. With another method, ex. "test", it works.
Why?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridView = findViewById(R.id.griglia);
    mQueue = Volley.newRequestQueue(this);
    txt = findViewById(R.id.titolo);
    movieList= new ArrayList<Movie>();

//
I call the metod jsonParse for to fill my ArrayList

    jsonParse();
    if(movieList.isEmpty()){
        txt.setText("vuoto");
    }
    else{
        txt.setText("pieno");
    }

}

// I have a problem with this code. He works, but don't fill the ArrayList

public void jsonParse(){
    String url ="https://api.myjson.com/bins/tn67c";
    JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray= response.getJSONArray("movie");

                        for(int i=0; i<jsonArray.length(); i++){
                            JSONObject emplyee = jsonArray.getJSONObject(i);

                            String titolo = emplyee.getString("titolo");
                            String url = emplyee.getString("url");
                            String icona= emplyee.getString("icona");

                            Movie movie= new Movie();
                            movie.setTitolo(titolo);
                            movie.setVideoFilePath(url);
                            movieList.add(i, movie);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mQueue.add(request);

}

//
I trust with a example method "prova" and now work it. Why?

public void prova(){
    int i=0;

    for(i=0; i<2; i++){
        String test= "ciao " + i;
        Movie movie= new Movie();
        movie.setTitolo(test);
        movieList.add(movie);
    }

}

Body:
you are initialing movieList after calling request please call before , try to initialize your list before onCreate

  ArrayList<Movie>  movieList = new ArrayList<Movie>();

And put this

if(movieList.isEmpty()){
  txt.setText("vuoto");
 } else{
  txt.setText("pieno");
  }

right after you finish adding item in the list

Edit:

package com.example.zvideo2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    String url ="https://api.myjson.com/bins/tn67c";
    private RequestQueue mQueue;
    ArrayList<Movie> movieList= new ArrayList<Movie>();
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mQueue = Volley.newRequestQueue(this);
        txt = findViewById(R.id.titolo);

        jsonParse();
//        prova();

    }

    public void jsonParse(){

        String url ="https://api.myjson.com/bins/tn67c";

        JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray= response.getJSONArray("movie");

                            for(int i=0; i<jsonArray.length(); i++){
                                JSONObject emplyee = jsonArray.getJSONObject(i);

                                String titolo = emplyee.getString("titolo");
                                String url = emplyee.getString("url");
                                String icona= emplyee.getString("icona");

                                Movie movie= new Movie();
                                movie.setTitolo(titolo);
                                movie.setVideoFilePath(url);
                                movieList.add(i, movie);
                            }

                            Toast.makeText(getActivity(), "item add successfully", Toast.LENGTH_LONG).show();
                            if(movieList.isEmpty()){
                            txt.setText("vuoto");
                            }else{
                            txt.setText("pieno");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);
        mQueue.start(request);

    }

    public void prova(){
        int i=0;

        for(i=0; i<2; i++){
            String test= "ciao " + i;
            Movie movie= new Movie();
            movie.setTitolo(test);
            movieList.add(movie);
        }

    }

}


问:
Mailchimp Embedded Sign up form not displaying Captcha
I am using mailchimp embedded sign up form. It displays Email Account, First Name and Last Name, but captcha is not showing. I enabled captcha from Settings->List Name and Defaults.

What other steps do I need? Captcha is not showing in Preview Mode Option.

Please help, getting lot of fake emails. Double opt in is also enabled.

答: Had the same problem. Make sure its V2(checkbox) NOT V3. Documentation here: https://mailchimp.com/help/about-recaptcha-for-signup-forms/</p>


问:
Divide x into y parts by decreasing amount
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

How would I achieve that?

Thanks

Edit:

Formula:

```<code>int people = 20;
float prize = 1000;

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < people; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);
</code>```

答:
Adding answer to Ensure prize pool doesn't award tied participants less than participants who scored worse

Two things

Incorrect, when assigning prices start from first person to the n-1 one person does't get prize, correct is start from first person to the n

Valid basePrize noted with K is

k =  (2 * prize) / ((people) * (people + 1))

Now the answer the other question:

```<code>int totalPeople = 20;
float prize = 5000;

List<int> peopleScores = new List<int>();
Random r = new Random();
for (int i = 0; i < totalPeople; ++i)
{
    peopleScores.Add(r.Next(0, 100));
}

var totalPeopleWithScore = peopleScores.Where(x => x > 0).Count();

var groupedScores = peopleScores
    .Where(x => x > 0)
    .ToList()
    .GroupBy(x => x)
    .Select(grp => new
    {
        score = grp.Key,
        peopleScores = grp.ToList()
    })
    .OrderBy(g => g.score)
    .ToList();

var groupCount = groupedScores.Select(x => new { count = x.peopleScores.Count() }).Select(z => z.count).Count();

float basePrizeRate = 2 * prize / totalPeopleWithScore / (totalPeopleWithScore + 1);
Console.WriteLine("Base Price rate: " + basePrizeRate);
float sum = 0;
var leaderboardPosition = 0;
var totalWinners = 0;
foreach (var positionScore in groupedScores)
{
    var countWinner = positionScore.peopleScores.Count();
    Console.WriteLine();
    Console.WriteLine($"On leaderboard position : {groupedScores.Count() - leaderboardPosition} are {countWinner} winners with score: {positionScore.score}");

    float positionPrizePool = 0;
    for (int i = 1; i <= positionScore.peopleScores.Count(); ++i)
    {
        totalWinners++;
        positionPrizePool += totalWinners * basePrizeRate;
    }
    Console.WriteLine("Prize Pool " + positionPrizePool);
    var personPoolPrize = positionPrizePool / positionScore.peopleScores.Count();
    foreach (var x in positionScore.peopleScores)
    {
        Console.WriteLine($"Winner {totalWinners} won: {personPoolPrize}");
        sum += personPoolPrize;
    }
    leaderboardPosition++;
}
Console.WriteLine();

Console.WriteLine("Total Prize: " + sum);
Console.WriteLine("Total Winners: " + totalPeopleWithScore);
</code>```

Body:
If I had $1000(variable) and I want to split that amount up and give it to 20(variable) people, but rather than give it evenly to each person, I want to give more to the 1st person, and the 2nd person, etc.

So the 20th person gets the least, and the 5th person gets the 5th most.

How would I achieve that?

Thanks

Edit:

Formula:

int people = 20;
float prize = 1000;

float k = (2 * prize) / ((people) * (people - 1));
float sum = 0;

for (int i = 1; i < people; ++i)
{
    var personsPrize = i * k;
    sum += personsPrize;
    Console.WriteLine(personsPrize);
}
Console.WriteLine("sum = " + sum);

Body:
Adding answer to Ensure prize pool doesn't award tied participants less than participants who scored worse

Two things

Incorrect, when assigning prices start from first person to the n-1 one person does't get prize, correct is start from first person to the n

Valid basePrize noted with K is

k =  (2 * prize) / ((people) * (people + 1))

Now the answer the other question:

int totalPeople = 20;
float prize = 5000;

List<int> peopleScores = new List<int>();
Random r = new Random();
for (int i = 0; i < totalPeople; ++i)
{
    peopleScores.Add(r.Next(0, 100));
}

var totalPeopleWithScore = peopleScores.Where(x => x > 0).Count();

var groupedScores = peopleScores
    .Where(x => x > 0)
    .ToList()
    .GroupBy(x => x)
    .Select(grp => new
    {
        score = grp.Key,
        peopleScores = grp.ToList()
    })
    .OrderBy(g => g.score)
    .ToList();

var groupCount = groupedScores.Select(x => new { count = x.peopleScores.Count() }).Select(z => z.count).Count();

float basePrizeRate = 2 * prize / totalPeopleWithScore / (totalPeopleWithScore + 1);
Console.WriteLine("Base Price rate: " + basePrizeRate);
float sum = 0;
var leaderboardPosition = 0;
var totalWinners = 0;
foreach (var positionScore in groupedScores)
{
    var countWinner = positionScore.peopleScores.Count();
    Console.WriteLine();
    Console.WriteLine($"On leaderboard position : {groupedScores.Count() - leaderboardPosition} are {countWinner} winners with score: {positionScore.score}");

    float positionPrizePool = 0;
    for (int i = 1; i <= positionScore.peopleScores.Count(); ++i)
    {
        totalWinners++;
        positionPrizePool += totalWinners * basePrizeRate;
    }
    Console.WriteLine("Prize Pool " + positionPrizePool);
    var personPoolPrize = positionPrizePool / positionScore.peopleScores.Count();
    foreach (var x in positionScore.peopleScores)
    {
        Console.WriteLine($"Winner {totalWinners} won: {personPoolPrize}");
        sum += personPoolPrize;
    }
    leaderboardPosition++;
}
Console.WriteLine();

Console.WriteLine("Total Prize: " + sum);
Console.WriteLine("Total Winners: " + totalPeopleWithScore);


问:
How to disable the custom directive action on the first column of the table row?
I have a custom directive which opens the table row related data in a new window. When i click on the first column of the table row which is a checkbox selection, it is opening a new window, how should i avoid the custom directive actions on first column of the table row.</p>

```<code><tr mat-row *matRowDef="let row; test: results;" [routerLink]="row" appNewWindow></tr>
</code>```

答: Adding or removing directives dynamically is not supported in Angular. Its has to be determined when you are coding your template. For your situation components would be right way.</p>


问:
Put existing virtualenv projects into virtualwrapper
Let's say that I have already created a virtualenv project by virtualenv venv. What is the best way to add this project to virtualwrapper? The way I can think of is creating a virtualwrapper folder, figuring out package dependencies, put the virtualenv project directory into virtualwrapper folder, and then install necessary packages. Is possible to avoid this tedious process?

答:
No, virtualenvs are not portable, you cannot move existing virtualenv to $HOME/.virtualenvs where virtualwrapper stores it virtualenvs. Recreating is the only way.

There is one thing you can simplify — list installed projects with their versions and reinstall exactly that versions:

```<code># In the venv
pip freeze > requirements.txt
deactivate

# Activate a new virtualwrapper-managed venv
workon newenv
pip install -r requirements.txt
</code>```

Body:
No, virtualenvs are not portable, you cannot move existing virtualenv to $HOME/.virtualenvs where virtualwrapper stores it virtualenvs. Recreating is the only way.

There is one thing you can simplify — list installed projects with their versions and reinstall exactly that versions:

# In the venv
pip freeze > requirements.txt
deactivate

# Activate a new virtualwrapper-managed venv
workon newenv
pip install -r requirements.txt


问:
How do you find top level text nodes without duplication
I am scraping articles from different sites using R (rvest) that are often structured in different ways and would like to extract all html nodes (without duplication) whose descendants contain some text using xpath.

Simplifying, the structure could be something like (without the whitespaces that have been introduced for readbility):

```<code><html>
<body>
    <a name="SomeMarker">
            <font style="FONT-SIZE: 12pt;"><b>Sports article</b></font>
    </a>
<div>
<b>This is possibly an article heading</b>
<font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font
<font style="FONT-SIZE: 10pt;"> It could have <i><b>interesting tags</b></i> embedded in the text</font>
</div>

<p id="SomeId"><b>This is another article heading</b>
    <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article</font>
    <p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p>
</p>

</body>
</html>
</code>```

I have tried several different xpaths -- but they seem to always select duplicate nodes

```<code>"//a/following::*//*[text()]"
"//a/following::*/*[normalize-space(text())]"
"//a/following::*/*[normalize-space(text())]/parent::*"
</code>```

and so on -- but all of them result in various permutations of text nodes

Currently, I get quite a few duplicate nodes, for e.g.:

```<code>[1] <div>\n<b>This is possibly an article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font><font style="FONT-SIZE: 10pt;"> It could have <i><b>interes ...
[2] <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font>
[3] <i><b>interesting tags</b></i>
[4] <p id="SomeId"><b>This is another article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font></p>\n
[5] <font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font>
[6] <p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p>
[7] <b><u>interesting tags</u></b>
</code>```

Preferred outcome is to get only the top-level nodes whose descendants contain some text, ie, in the above case:

```<code>[1] <div><b>This is possibly an article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the article.</font><font style="FONT-SIZE: 10pt;"> It could have <i><b>interesting tags</b></i> embedded in the text</font></div>
[2] <p id="SomeId"><b>This is another article heading</b><font style="FONT-SIZE: 10pt;"> This is the <i>body</i> of the second article.</font><p><font style="FONT-SIZE: 10pt;"> It could have further <i><b><u>interesting tags</u></b></i> embedded in the text</font></p></p>
</code>```

I know the xpath for just extracting the text -- I actually want the html nodes with the tags intact as I would like to do further processing on the top level nodes (for e.g. to extract the headings). Thanks much.

答:
Option 1: Using following-sibling::

//a/following-sibling::[[text()]]

Option 2: Using parent with following::

//a/following::[[text()]][parent::body]

Body:
I am scraping articles from different sites using R (rvest) that are often structured in different ways and would like to extract all html nodes (without duplication) whose descendants contain some text using xpath.

Simplifying, the structure could be something like (without the whitespaces that have been introduced for readbility):

            Sports article

This is possibly an article heading
 This is the body of the article.</font
 It could have interesting tags embedded in the text

This is another article heading
     This is the body of the second article

 It could have further interesting tags embedded in the text

I have tried several different xpaths -- but they seem to always select duplicate nodes

"//a/following::*//*[text()]"
"//a/following::*/*[normalize-space(text())]"
"//a/following::*/*[normalize-space(text())]/parent::*"

and so on -- but all of them result in various permutations of text nodes

Currently, I get quite a few duplicate nodes, for e.g.:

[1]
\nThis is possibly an article heading This is the body of the article. It could have interes ...
[2]  This is the body of the article.
[3] interesting tags
[4]
This is another article heading This is the body of the second article.
\n
[5]  This is the body of the second article.
[6]
 It could have further interesting tags embedded in the text

[7] interesting tags

Preferred outcome is to get only the top-level nodes whose descendants contain some text, ie, in the above case:

[1]
This is possibly an article heading This is the body of the article. It could have interesting tags embedded in the text

[2]
This is another article heading This is the body of the second article.
 It could have further interesting tags embedded in the text

I know the xpath for just extracting the text -- I actually want the html nodes with the tags intact as I would like to do further processing on the top level nodes (for e.g. to extract the headings). Thanks much.


问:
Convert from String to JsonArray using gson
I would like to know how to convert a linear String (on mysql) into gson JsonArray.

So to resume:

```<code>"{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}"
</code>```

-> {"name":"john","age":22,"class":"mca"} (As JsonArray using gson)

Thank you very much <3

答:
This should work.    </p>

```<code>import com.google.gson.*;

JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(yourString);
JsonArray jsonArray = tradeElement.getAsJsonArray();
System.out.println(jsonArray);
</code>```

Body:
I would like to know how to convert a linear String (on mysql) into gson JsonArray.

So to resume:

"{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}"

-> {"name":"john","age":22,"class":"mca"} (As JsonArray using gson)

Thank you very much <3

Body:
This should work.

import com.google.gson.*;

JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(yourString);
JsonArray jsonArray = tradeElement.getAsJsonArray();
System.out.println(jsonArray);


问:
Summation of each column by selected few specific rows - in R
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

```<code>dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"
</code>```

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

```<code>sum  1819   913
</code>```

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

```<code>sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric
</code>```

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

答:
In base R you can do:

```<code># Load your data first
dd <- read.table(header = TRUE, text = '
"Category" "A"    "B"
"ONE"      "23"   "45"
"TWO"      "234"  "23"
"THREE"    "565"  "324"
"FOUR"     "676"  "343"
"FIVE"     "1231" "544"')

# Summarize by selected catagories
colSums(subset(dd, Category %in% c("ONE", "THREE", "FIVE"), select = -Category))
#   A    B
#1819  913
</code>```

Or alternatively using aggregate:

```<code>aggregate(cbind(A, B) ~ 1,
          data = subset(dd, Category %in% c("ONE", "THREE", "FIVE")),
          FUN = sum)
#     A   B
#1 1819 913
</code>```

and perhaps more R idiomatic:

```<code>dd$ofInterest <- dd$Category %in% c("ONE", "THREE", "FIVE")
aggregate(cbind(A, B) ~ ofInterest, data = dd, FUN = sum)
#  ofInterest    A   B
#1      FALSE  910 366
#2       TRUE 1819 913
</code>```

Body:
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

sum  1819   913

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

Body:
In base R you can do:

# Load your data first
dd <- read.table(header = TRUE, text = '
"Category" "A"    "B"
"ONE"      "23"   "45"
"TWO"      "234"  "23"
"THREE"    "565"  "324"
"FOUR"     "676"  "343"
"FIVE"     "1231" "544"')

# Summarize by selected catagories
colSums(subset(dd, Category %in% c("ONE", "THREE", "FIVE"), select = -Category))
#   A    B
#1819  913

Or alternatively using aggregate:

aggregate(cbind(A, B) ~ 1,
          data = subset(dd, Category %in% c("ONE", "THREE", "FIVE")),
          FUN = sum)
#     A   B
#1 1819 913

and perhaps more R idiomatic:

dd$ofInterest <- dd$Category %in% c("ONE", "THREE", "FIVE")
aggregate(cbind(A, B) ~ ofInterest, data = dd, FUN = sum)
#  ofInterest    A   B
#1      FALSE  910 366
#2       TRUE 1819 913


问:
Bootstrap 4 : Each row fill the same amount of height
I'm making a preloader and i'm struggling with the rows. I want my grey rectangle to be filled with 3 rows of 33% height.

Then I need:

in the row 1, a svg logo

in the row 2, a loader

in the row 3, some text

Here's what I want:

Here's my code :

#loader-modal {
    width: 100vw;
    height: 100vh;
    position: fixed;
    background-color: rgba(0,0,0, 0.9);
    z-index: 100000;
}

.rectangle-chargement {
    width: 25%;
    height: 50%;
    top: 25%;
    left: 37.5%;
    position: absolute;
    background-color: #E2E2E2;
    border-radius: 0.15rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<div id="loader-modal">
    <div class="d-flex justify-content-center mx-auto rectangle-chargement">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <!--<svg width="100%" >My SVG</svg>-->
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="d-flex justify-content-center" id="loader-circulaire">
                        <div id="chargement-loader"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <p class="d-flex justify-content-center mx-auto patienter-chargement">Veuillez patienter ...</p>
                </div>
            </div>
        </div>
    </div>
</div></code>```

Do you guys know a cleaner way to do it ? (and a working one of course)

答:
You can certainly hard code the heights, but since you ask if there is any cleaner way to do it, my opinion is to use flexbox with column flow direction, and let flexbox children grow by setting their flex-grow to 1.

This way doesn't require you to hard code the height for each row, and allows you to have as many rows as you "want".

        Logo

        Loader

        Some text

```

<p><img src="https://i.stack.imgur.com/3xFp0.png" alt="enter image description here"></p>

<p><strong>demo:</strong> https://jsfiddle.net/davidliang2008/sngkbLcq/32/</p>

<p>If you want to "centralize" the content in each row, you can mark each row as <em>flexbox</em> as well, and set its <code>justify-content</code> and <code>align-items</code> to center.</p>

<pre class="lang-html prettyprint-override"><code><div class="rectangle-chargement d-flex flex-column">
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Logo
    </div>
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Loader
    </div>
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Some text
    </div>
</div>
</code>```

demo: https://jsfiddle.net/davidliang2008/sngkbLcq/36/

Body:
I'm making a preloader and i'm struggling with the rows. I want my grey rectangle to be filled with 3 rows of 33% height.

Then I need:

in the row 1, a svg logo

in the row 2, a loader

in the row 3, some text

Here's what I want:

Here's my code :

#loader-modal {
    width: 100vw;
    height: 100vh;
    position: fixed;
    background-color: rgba(0,0,0, 0.9);
    z-index: 100000;
}

.rectangle-chargement {
    width: 25%;
    height: 50%;
    top: 25%;
    left: 37.5%;
    position: absolute;
    background-color: #E2E2E2;
    border-radius: 0.15rem;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Veuillez patienter ...

Do you guys know a cleaner way to do it ? (and a working one of course)

Body:
You can certainly hard code the heights, but since you ask if there is any cleaner way to do it, my opinion is to use flexbox with column flow direction, and let flexbox children grow by setting their flex-grow to 1.

This way doesn't require you to hard code the height for each row, and allows you to have as many rows as you "want".

<div class="rectangle-chargement d-flex flex-column">
    <div class="rectangle-chargement-row flex-grow-1">
        Logo
    </div>
    <div class="rectangle-chargement-row flex-grow-1">
        Loader
    </div>
    <div class="rectangle-chargement-row flex-grow-1">
        Some text
    </div>
</div>

demo: https://jsfiddle.net/davidliang2008/sngkbLcq/32/

If you want to "centralize" the content in each row, you can mark each row as flexbox as well, and set its justify-content and align-items to center.

<div class="rectangle-chargement d-flex flex-column">
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Logo
    </div>
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Loader
    </div>
    <div class="rectangle-chargement-row flex-grow-1
        d-flex justify-content-center align-items-center">
        Some text
    </div>
</div>

demo: https://jsfiddle.net/davidliang2008/sngkbLcq/36/


问:
Get all results of rows with matching criteria from a range
As mentioned in another question, I'm on a few Discord servers that allow players to auction in-game content for trade.  Use sheets to keep track of my own auctions, I copy the tag (name#xxxx) and ID (long number) into a list so I can filter out anyone who fails to follow through on a winning auction.

What I'm looking to do now is two fold.

One is to have an automated list of duplicate ID's that have different tags (someone changed their name).  The list would show the ID number in one cell, then in the next cell, show all of the tags they have used (using textJoin() and sort() to make it easier to read).

The second is to grab a list of tags used based on a separate list of ID's (known list of users who have failed to follow through).

I've tried and failed with vlookup(), filter(), query(), and regular lookup().  When I tried filter() for using a list, it only seems to look at the first item, but ignores anything after that.  If I try to expand the length of the list (instead of F2 I make it F2:F) it turns red and won't work.

Using conditional formatting, I'm able to get duplicates to highlight within the range.  However, I'm trying to take it a step further and retrieve matches.  Sort of like an automated filter system to show known duplicates.

What am I not thinking of here?

Edit:
Here is some dummy info to give an idea...

```<code>Alred         970192322624802134
Barry         493288047120884104
Clark         648567312202297155
Dick          336368714780211631
Enigma        513446866409315771
Flash         493288047120884104
Green Arrow   382294342593163268
Harley        894386762337961412
Ivy           192571739320652789
Jimmy         662344040550649441
Krypto        944264752128564134
Lois          608531705193876711
Mera          461451144314768165
Nyssa         533348352505340666
Oliver        382294342593163268
Perry         877529730964781752
Robin         336368714780211631
Superman      648567312202297155
Thomas        969367121152160055
</code>```

Obviously the names would have a # sign followed by a 4 digit number, but it's an irrelevant factor for this matter.

Looking at the list, you can see that some of the ID's (column of numbers) are the same, but with different names.

So the goal is to have a separate column that would go through, find ID's that are duplicated, and then list all names with that matching ID.

Example:

```<code>648567312202297155   Clark, Superman
336368714780211631   Dick, Robin
382294342593163268   Green Arrow, Oliver
etc
</code>```

For the second one, a list of ID's where matching ID's would show all matching names.  Sort of like if the above only listed ID's that have more than one entry, and then that list were to be used to find names, except the list of ID's could be generated by other means.  To break it down into two simplified tasks...  One finds duplicate ID's and simply lists those ID's (one time each), then another looks up those ID's and lists all matching entries (ie, the names).

Edit:
This link is an example of what I'm trying to do, but it's not working for me.
Google Sheet Query - Group / concatenate multiple rows

I have A(A2:A)=Names/tag, B(B2:B)=ID, F(F2:F)=ID's to filter.
When I try =join(",",filter(A:A,B:B=F2)) it returns the first entry but then stops.

Also, when I try to simulate the other page (values and formulas), it only returns the results for Bill (Red,Blue,Yellow), but not for Sarah.

By simulate, I mean that I added an empty sheet and filled in the values and formulas as shown in the image.

答:
If I understand your problem correctly, you are trying to match a username against a range of user names in a column, in order to see if it matches.

One way to do it would be to use match in a query, for example:

=QUERY("Charleston!A2:H"," where Col6 matches '" & join("|", A2:A246) & "' Order By Col8")```

If that does not help, please provide us some use cases, and your code if you can.

Body:
As mentioned in another question, I'm on a few Discord servers that allow players to auction in-game content for trade.  Use sheets to keep track of my own auctions, I copy the tag (name#xxxx) and ID (long number) into a list so I can filter out anyone who fails to follow through on a winning auction.

What I'm looking to do now is two fold.

One is to have an automated list of duplicate ID's that have different tags (someone changed their name).  The list would show the ID number in one cell, then in the next cell, show all of the tags they have used (using textJoin() and sort() to make it easier to read).

The second is to grab a list of tags used based on a separate list of ID's (known list of users who have failed to follow through).

I've tried and failed with vlookup(), filter(), query(), and regular lookup().  When I tried filter() for using a list, it only seems to look at the first item, but ignores anything after that.  If I try to expand the length of the list (instead of F2 I make it F2:F) it turns red and won't work.

Using conditional formatting, I'm able to get duplicates to highlight within the range.  However, I'm trying to take it a step further and retrieve matches.  Sort of like an automated filter system to show known duplicates.

What am I not thinking of here?

Edit:
Here is some dummy info to give an idea...

Alred         970192322624802134
Barry         493288047120884104
Clark         648567312202297155
Dick          336368714780211631
Enigma        513446866409315771
Flash         493288047120884104
Green Arrow   382294342593163268
Harley        894386762337961412
Ivy           192571739320652789
Jimmy         662344040550649441
Krypto        944264752128564134
Lois          608531705193876711
Mera          461451144314768165
Nyssa         533348352505340666
Oliver        382294342593163268
Perry         877529730964781752
Robin         336368714780211631
Superman      648567312202297155
Thomas        969367121152160055

Obviously the names would have a # sign followed by a 4 digit number, but it's an irrelevant factor for this matter.

Looking at the list, you can see that some of the ID's (column of numbers) are the same, but with different names.

So the goal is to have a separate column that would go through, find ID's that are duplicated, and then list all names with that matching ID.

Example:

648567312202297155   Clark, Superman
336368714780211631   Dick, Robin
382294342593163268   Green Arrow, Oliver
etc

For the second one, a list of ID's where matching ID's would show all matching names.  Sort of like if the above only listed ID's that have more than one entry, and then that list were to be used to find names, except the list of ID's could be generated by other means.  To break it down into two simplified tasks...  One finds duplicate ID's and simply lists those ID's (one time each), then another looks up those ID's and lists all matching entries (ie, the names).

Edit:
This link is an example of what I'm trying to do, but it's not working for me.
Google Sheet Query - Group / concatenate multiple rows

I have A(A2:A)=Names/tag, B(B2:B)=ID, F(F2:F)=ID's to filter.
When I try =join(",",filter(A:A,B:B=F2)) it returns the first entry but then stops.

Also, when I try to simulate the other page (values and formulas), it only returns the results for Bill (Red,Blue,Yellow), but not for Sarah.

By simulate, I mean that I added an empty sheet and filled in the values and formulas as shown in the image.

Body:
If I understand your problem correctly, you are trying to match a username against a range of user names in a column, in order to see if it matches.

One way to do it would be to use match in a query, for example:

=QUERY("Charleston!A2:H"," where Col6 matches '" & join("|", A2:A246) & "' Order By Col8")

If that does not help, please provide us some use cases, and your code if you can.


问:
How to stop console window from closing immediately | GNAT - GPS
I have Ada program that runs and compile perfectly using GNAT - GPS. When I run its exe file and provide user input then instead of saying "Press any key to continue", the exe closes immediately.

I have searched for it online alot but i only found info related to c/c++/visual studio console window using system('pause'); OR Console.Readline().

Is there any way around for this in Ada lanaguage?

答:
Apart from using Get_Line or Get, you can also use Get_Immediate from the Ada.Text_IO package. The difference is that Get_Line and Get will continue to read user input until <Enter> has been hit, while Get_Immediate will block only until a single key has been pressed when standard input is connected to an interactive device (e.g. a keyboard).

Here's an example:

```<code>with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
begin

   --  Do some interesting stuff here...

   declare
      User_Response : Character;
   begin
      Put_Line ("Press any key to continue...");
      Get_Immediate (User_Response);
   end;

end Main;
</code>```

NOTES

You should run the program in an interactive terminal (Bash, PowerShell, etc.) to actually see the effect of Get_Immediate. When you run the program from within GPS, then you still have to press enter to actually exit the program.

This might be too much detail, but I think that Get still waits for <Enter> to be pressed because it uses fgetc from the C standard library (libc) under the hood (see here and here). The function fgetc reads from a C stream. C streams are initially line-buffered for interactive devices (source).

Body:
Apart from using Get_Line or Get, you can also use Get_Immediate from the Ada.Text_IO package. The difference is that Get_Line and Get will continue to read user input until <Enter> has been hit, while Get_Immediate will block only until a single key has been pressed when standard input is connected to an interactive device (e.g. a keyboard).

Here's an example:

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
begin

   --  Do some interesting stuff here...

   declare
      User_Response : Character;
   begin
      Put_Line ("Press any key to continue...");
      Get_Immediate (User_Response);
   end;

end Main;

NOTES

You should run the program in an interactive terminal (Bash, PowerShell, etc.) to actually see the effect of Get_Immediate. When you run the program from within GPS, then you still have to press enter to actually exit the program.

This might be too much detail, but I think that Get still waits for <Enter> to be pressed because it uses fgetc from the C standard library (libc) under the hood (see here and here). The function fgetc reads from a C stream. C streams are initially line-buffered for interactive devices (source).


问:
Getting only Month and Year from SQL DATE
I need to access only Month.Year from Date field in SQL Server.</p>

答:
I had a specific requirement to do something similar where it would show month-year which can be done by the following:

SELECT DATENAME(month, GETDATE()) + '-' +  CAST(YEAR(GETDATE()) AS nvarchar) AS 'Month-Year'

In my particular case, I needed to have it down to the 3 letter month abreviation with a 2 digit year, looking something like this:
SELECT LEFT(DATENAME(month, GETDATE()), 3) + '-' +  CAST(RIGHT(YEAR(GETDATE()),2) AS nvarchar(2)) AS 'Month-Year'


问:
RegEx for extracting placeholder matches
I have this string

template = "Hello my name is <name>, I'm <age>."
```

<p>And I want to test if my strings match that template and anything can be in place of the placeholders. The placeholders start and end with brackets like this <code><place holder here></code>. E.g this string would match</p>

<pre class="lang-py prettyprint-override"><code>string = "Hello my name is John Doe, I'm 30 years old."
</code>```

I also want to extract parts of the string that substitute the placeholders. For the example above, I want to get the list:

['John Doe', '30 years old']
```

I'm able to extract the placeholders of the template using the pattern <(.*?)> for regex, but I'm currently stuck on how to extract the actual substitutions from the string. I need a generic approach and I don't want to hardcode the pattern to match the full template because I have many templates to check. Is there a clever way to do this?

答:
You can dynamically build a regex using the template. Then match it against any input string.

```<code>import re

template = "Hello my name is <name>, I'm <age>."
pattern = "^" + re.escape(template) + "$"
pattern = re.sub("<[^>]+>", "(?P\g<0>.*)", pattern)
regex = re.compile(pattern, re.DOTALL)

string = "Hello my name is John Doe, I'm 30 years old."
match = regex.match(string)

match.group(0)
#=> "Hello my name is John Doe, I'm 30 years old."
match.group("name")
#=> 'John Doe'
match.group("age")
#=> '30 years old'
match.groups()
#=> ('John Doe', '30 years old')
</code>```

The only restriction upon the template is that valid regex group names should be used.

You could lift this, by simply not using named regex groups.

```<code># replacing
pattern = re.sub("<[^>]+>", "(?P\g<0>.*)", pattern)
# with
pattern = re.sub("<[^>]+>", "(.*)", pattern)
</code>```

Combine this with cross-referencing the placeholders from the template and you have more naming options.

```<code>placeholders = re.findall("<[^>]+>", template)
placeholders = list(map(lambda match: match[1:-1], placeholders))

dict(zip(placeholders, match.groups()))
#=> {'name': 'John Doe', 'age': '30 years old'}
</code>```

Body:
I have this string

template = "Hello my name is <name>, I'm <age>."

And I want to test if my strings match that template and anything can be in place of the placeholders. The placeholders start and end with brackets like this <place holder here>. E.g this string would match

string = "Hello my name is John Doe, I'm 30 years old."

I also want to extract parts of the string that substitute the placeholders. For the example above, I want to get the list:

['John Doe', '30 years old']

I'm able to extract the placeholders of the template using the pattern <(.*?)> for regex, but I'm currently stuck on how to extract the actual substitutions from the string. I need a generic approach and I don't want to hardcode the pattern to match the full template because I have many templates to check. Is there a clever way to do this?

Body:
You can dynamically build a regex using the template. Then match it against any input string.

import re

template = "Hello my name is <name>, I'm <age>."
pattern = "^" + re.escape(template) + "$"
pattern = re.sub("<[^>]+>", "(?P\g<0>.*)", pattern)
regex = re.compile(pattern, re.DOTALL)

string = "Hello my name is John Doe, I'm 30 years old."
match = regex.match(string)

match.group(0)
#=> "Hello my name is John Doe, I'm 30 years old."
match.group("name")
#=> 'John Doe'
match.group("age")
#=> '30 years old'
match.groups()
#=> ('John Doe', '30 years old')

The only restriction upon the template is that valid regex group names should be used.

You could lift this, by simply not using named regex groups.

# replacing
pattern = re.sub("<[^>]+>", "(?P\g<0>.*)", pattern)
# with
pattern = re.sub("<[^>]+>", "(.*)", pattern)

Combine this with cross-referencing the placeholders from the template and you have more naming options.

placeholders = re.findall("<[^>]+>", template)
placeholders = list(map(lambda match: match[1:-1], placeholders))

dict(zip(placeholders, match.groups()))
#=> {'name': 'John Doe', 'age': '30 years old'}


问:
java persistance query language limit resultset
Suppose I have following rows in a table "mytable"
id

1

2

3

...
...

500

and my query is like select m from mytable m where m.id < 300
how can I get following output in the same order?

201

202

...
...
...

299

I am using setMaxResult(100) but it returns me output like this

1

2

...
...

100

any advice?

答:
```<code>String ql = "select m from mytable m where m.id < 300 order by m.id";
Query query = em.createQuery(ql);
query.setFirstResult(200);
query.setMaxResults(100);
</code>```