问:
How to read pending messages from an ActiveMQ queue in Spring Boot
I like to read pending (not acknowledged) messages in a ActiveMQ queue using Spring boot. How to do that?

So far I can read a message the moment it is send to the queue:

```<code>@JmsListener(destination = "LOCAL.TEST",
  containerFactory = "myJmsListenerContainerFactory")
public void receiveMessage(final Message jsonMessage) throws JMSException {
    String messageData = null;
    // jsonMessage.acknowledge(); // dont consume message (for testing)
    LOGGER.info("=== Received message {}", jsonMessage);
}
</code>```

using a standard configuration for the mq-connection:

```<code>@Bean
public ActiveMQConnectionFactory getActiveMQConnectionFactory() {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
    activeMQConnectionFactory.setBrokerURL(BROKER_URL + ":" + BROKER_PORT);
    return activeMQConnectionFactory;
}
</code>```

and a standard ListenerContainerFactory:

```<code>@Bean
public DefaultJmsListenerContainerFactory myJmsListenerContainerFactory() {
  DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
  factory.setConnectionFactory(getActiveMQConnectionFactory());
  factory.setConcurrency("1-1");
  return factory;
}
</code>```

But this just loggs a message if I manually send one using

```<code>@Autowired
private JmsTemplate jmsTemplate;

public void send(String destination, String message) {
    LOGGER.info("sending message='{}' to destination='{}'", message, destination);
    jmsTemplate.convertAndSend(destination, message);
}
</code>```

with the standard template

```<code>@Bean
public JmsTemplate jmsTemplate() {
  JmsTemplate template = new JmsTemplate();
  template.setConnectionFactory(getActiveMQConnectionFactory());
  return template;
}
</code>```

I cannot read messages sent earlier that are still in the Queue (since I didn't .acknowledge() them)...

答:
To read all pending messages, you can do like this

```<code>    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?jms.redeliveryPolicy.maximumRedeliveries=1");
    Connection connection = connectionFactory.createConnection("admin", "admin");
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue("listenerQueue");
    MessageConsumer consumer = session.createConsumer(destination);

    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration elems = browser.getEnumeration();
    while (elems.hasMoreElements()) {
        Message message = (Message) consumer.receive();

        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Incoming Message: '" + textMessage.getText() + "'");
            message.acknowledge();
        }
    }
    connection.close();
</code>```

Step by step implementation of Spring boot ActiveMQ. Lets write some code to make it more clear. This will help to read all pending messages in current session only.

Add these dependencies in pom.xml file.

```<code><!-- Dependencies to setup JMS and active mq environment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
</code>```

Add @EnableJms into your main controller where your main() method exists.

Create connection factory by adding these 2 methods in application controller only.

```<code>@Bean
    public JmsListenerContainerFactory<?> myFactory(
        ConnectionFactory connectionFactory,
        DefaultJmsListenerContainerFactoryConfigurer configurer) {
      DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
      logger.info("configuring jms connection factory....");
      // anonymous class
      factory.setErrorHandler(
              new ErrorHandler() {
                  @Override
                  public void handleError(Throwable t) {
                      logger.error("An error has occurred in the transaction", t);
                  }
              });
      // lambda function
      factory.setErrorHandler(t -> logger.info("An error has occurred in the transaction"));
      configurer.configure(factory, connectionFactory);

      return factory;
    }

    // Serialize message content to json using TextMessage
    @Bean
    public MessageConverter jacksonJmsMessageConverter() {
      MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
      converter.setTargetType(MessageType.TEXT);
      converter.setTypeIdPropertyName("_type");
      return converter;
    }
</code>```

Mention credentials in in application.yml file as

```<code>spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.broker-url=tcp://localhost:61616?jms.redeliveryPolicy.maximumRedeliveries=1

</code>```

Autowire jmsTemplate in any spring bean class.

```<code>@Autowired
private JmsTemplate jmsTemplate;
</code>```

Now it is time to send message to a queue.

```<code>jmsTemplate.convertAndSend("anyQueueName", "value1");
jmsTemplate.convertAndSend("anyQueueName", "value2");
...
</code>```

Add a jmslistener. This method will be called automatically by JMS when any message will be pushed to queue.

```<code>@JmsListener(destination ="anyQueueName", containerFactory = "myFactory")
    public void receiveMessage(String user) {
        System.out.println("Received <" + user + ">");
    }
</code>```

Manually you can read the messages available in queue:-

```<code>import javax.jms.TextMessage;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;

public void readMessageFromQueue(){
jmsTemplate.browse("anyQueueName", new BrowserCallback<TextMessage>() {
            @Override
            public TextMessage doInJms(Session session, QueueBrowser browser) throws JMSException {
                Enumeration<TextMessage> messages = browser.getEnumeration();
                while (messages.hasMoreElements()) {
                    System.out.println("message found : -"+ messages.nextElement().getText());
                }
            }
        });
}
</code>```

Output :-

message found :- value1

message found :- value2

-Happy Coding

Body:
I like to read pending (not acknowledged) messages in a ActiveMQ queue using Spring boot. How to do that?

So far I can read a message the moment it is send to the queue:

@JmsListener(destination = "LOCAL.TEST",
  containerFactory = "myJmsListenerContainerFactory")
public void receiveMessage(final Message jsonMessage) throws JMSException {
    String messageData = null;
    // jsonMessage.acknowledge(); // dont consume message (for testing)
    LOGGER.info("=== Received message {}", jsonMessage);
}

using a standard configuration for the mq-connection:

@Bean
public ActiveMQConnectionFactory getActiveMQConnectionFactory() {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
    activeMQConnectionFactory.setBrokerURL(BROKER_URL + ":" + BROKER_PORT);
    return activeMQConnectionFactory;
}

and a standard ListenerContainerFactory:

@Bean
public DefaultJmsListenerContainerFactory myJmsListenerContainerFactory() {
  DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
  factory.setConnectionFactory(getActiveMQConnectionFactory());
  factory.setConcurrency("1-1");
  return factory;
}

But this just loggs a message if I manually send one using

@Autowired
private JmsTemplate jmsTemplate;

public void send(String destination, String message) {
    LOGGER.info("sending message='{}' to destination='{}'", message, destination);
    jmsTemplate.convertAndSend(destination, message);
}

with the standard template

@Bean
public JmsTemplate jmsTemplate() {
  JmsTemplate template = new JmsTemplate();
  template.setConnectionFactory(getActiveMQConnectionFactory());
  return template;
}

I cannot read messages sent earlier that are still in the Queue (since I didn't .acknowledge() them)...

Body:
To read all pending messages, you can do like this

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616?jms.redeliveryPolicy.maximumRedeliveries=1");
    Connection connection = connectionFactory.createConnection("admin", "admin");
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue("listenerQueue");
    MessageConsumer consumer = session.createConsumer(destination);

    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration elems = browser.getEnumeration();
    while (elems.hasMoreElements()) {
        Message message = (Message) consumer.receive();

        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Incoming Message: '" + textMessage.getText() + "'");
            message.acknowledge();
        }
    }
    connection.close();

Step by step implementation of Spring boot ActiveMQ. Lets write some code to make it more clear. This will help to read all pending messages in current session only.

Add these dependencies in pom.xml file.

<!-- Dependencies to setup JMS and active mq environment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>

Add @EnableJms into your main controller where your main() method exists.

Create connection factory by adding these 2 methods in application controller only.

@Bean
    public JmsListenerContainerFactory<?> myFactory(
        ConnectionFactory connectionFactory,
        DefaultJmsListenerContainerFactoryConfigurer configurer) {
      DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
      logger.info("configuring jms connection factory....");
      // anonymous class
      factory.setErrorHandler(
              new ErrorHandler() {
                  @Override
                  public void handleError(Throwable t) {
                      logger.error("An error has occurred in the transaction", t);
                  }
              });
      // lambda function
      factory.setErrorHandler(t -> logger.info("An error has occurred in the transaction"));
      configurer.configure(factory, connectionFactory);

      return factory;
    }

    // Serialize message content to json using TextMessage
    @Bean
    public MessageConverter jacksonJmsMessageConverter() {
      MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
      converter.setTargetType(MessageType.TEXT);
      converter.setTypeIdPropertyName("_type");
      return converter;
    }

Mention credentials in in application.yml file as

spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.broker-url=tcp://localhost:61616?jms.redeliveryPolicy.maximumRedeliveries=1

Autowire jmsTemplate in any spring bean class.

@Autowired
private JmsTemplate jmsTemplate;

Now it is time to send message to a queue.

jmsTemplate.convertAndSend("anyQueueName", "value1");
jmsTemplate.convertAndSend("anyQueueName", "value2");
...

Add a jmslistener. This method will be called automatically by JMS when any message will be pushed to queue.

@JmsListener(destination ="anyQueueName", containerFactory = "myFactory")
    public void receiveMessage(String user) {
        System.out.println("Received <" + user + ">");
    }

Manually you can read the messages available in queue:-

import javax.jms.TextMessage;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;

public void readMessageFromQueue(){
jmsTemplate.browse("anyQueueName", new BrowserCallback<TextMessage>() {
            @Override
            public TextMessage doInJms(Session session, QueueBrowser browser) throws JMSException {
                Enumeration<TextMessage> messages = browser.getEnumeration();
                while (messages.hasMoreElements()) {
                    System.out.println("message found : -"+ messages.nextElement().getText());
                }
            }
        });
}

Output :-

message found :- value1

message found :- value2

-Happy Coding


来源: stackexchange

问:
Minimizing time in transit
[Updates at bottom (including solution source code)]

I have a challenging business problem that a computer can help solve.

Along a mountainous region flows a long winding river with strong currents. Along certain parts of the river are plots of environmentally sensitive land suitable for growing a particular type of rare fruit that is in very high demand. Once field laborers harvest the fruit, the clock starts ticking to get the fruit to a processing plant. It's very costly to try and send the fruits upstream or over land or air. By far the most cost effective mechanism to ship them to the plant is downstream in containers powered solely by the river's constant current. We have the capacity to build 10 processing plants and need to locate these along the river to minimize the total time the fruits spend in transit. The fruits can take however long before reaching the nearest downstream plant but that time directly hurts the price at which they can be sold. Effectively, we want to minimize the sum of the distances to the nearest respective downstream plant. A plant can be located as little as 0 meters downstream from a fruit access point.

The question is: In order to maximize profits, how far up the river should we build the 10 processing plants if we have found 32 fruit growing regions, where the regions' distances upstream from the base of the river are (in meters):
10, 40, 90, 160, 250, 360, 490, ... (n^2)*10 ... 9000, 9610, 10320?

[It is hoped that all work going towards solving this problem and towards creating similar problems and usage scenarios can help raise awareness about and generate popular resistance towards the damaging and stifling nature of software/business method patents (to whatever degree those patents might be believed to be legal within a locality).]

UPDATES

Update1: Forgot to add: I believe this question is a special case of this one.

Update2: One algorithm I wrote gives an answer in a fraction of a second, and I believe is rather good (but it's not yet stable across sample values). I'll give more details later, but the short is as follows. Place the plants at equal spacings. Cycle over all the inner plants where at each plant you recalculate its position by testing every location between its two neighbors until the problem is solved within that space (greedy algorithm). So you optimize plant 2 holding 1 and 3 fixed. Then plant 3 holding 2 and 4 fixed... When you reach the end, you cycle back and repeat until you go a full cycle where every processing plant's recalculated position stops varying.. also at the end of each cycle, you try to move processing plants that are crowded next to each other and are all near each others' fruit dumps into a region that has fruit dumps far away. There are many ways to vary the details and hence the exact answer produced. I have other candidate algorithms, but all have glitches. [I'll post code later.] Just as Mike Dunlavey mentioned below, we likely just want "good enough".

To give an idea of what might be a "good enough" result:

```<code>10010 total length of travel from 32 locations to plants at
{10,490,1210,1960,2890,4000,5290,6760,8410,9610}
</code>```

Update3: mhum gave the correct exact solution first but did not (yet) post a program or algorithm, so I wrote one up that yields the same values.

```<code>/************************************************************
This program can be compiled and run (eg, on Linux):
$ gcc -std=c99 processing-plants.c -o processing-plants
$ ./processing-plants
************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//a: Data set of values. Add extra large number at the end

int a[]={
10,40,90,160,250,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240,99999
};

//numofa: size of data set

int numofa=sizeof(a)/sizeof(int);

//a2: will hold (pt to) unique data from a and in sorted order.

int *a2;

//max: size of a2

int max;

//num_fixed_loc: at 10 gives the solution for 10 plants

int num_fixed_loc;

//xx: holds index values of a2 from the lowest error winner of each cycle memoized. accessed via memoized offset value. Winner is based off lowest error sum from left boundary upto right ending boundary.
//FIX: to be dynamically sized.

int xx[1000000];

//xx_last: how much of xx has been used up

int xx_last=0;

//SavedBundle: data type to "hold" memoized values needed (total traval distance and plant locations)

typedef struct _SavedBundle {
    long e;
    int xx_offset;
} SavedBundle;

//sb: (pts to) lookup table of all calculated values memoized

SavedBundle *sb;  //holds winning values being memoized

//Sort in increasing order.

int sortfunc (const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

/****************************
Most interesting code in here
****************************/

long full_memh(int l, int n) {
    long e;
    long e_min=-1;
    int ti;

    if (sb[l*max+n].e) {
        return sb[l*max+n].e;  //convenience passing
    }
    for (int i=l+1; i<max-1; i++) {
        e=0;
        //sum first part
        for (int j=l+1; j<i; j++) {
            e+=a2[j]-a2[l];
        }
        //sum second part
        if (n!=1) //general case, recursively
            e+=full_memh(i, n-1);
        else      //base case, iteratively
            for (int j=i+1; j<max-1; j++) {
                e+=a2[j]-a2[i];
            }
        if (e_min==-1) {
            e_min=e;
            ti=i;
        }
        if (e<e_min) {
            e_min=e;
            ti=i;
        }
    }
    sb[l*max+n].e=e_min;
    sb[l*max+n].xx_offset=xx_last;
    xx[xx_last]=ti;      //later add a test or a realloc, etc, if approp
    for (int i=0; i<n-1; i++) {
        xx[xx_last+(i+1)]=xx[sb[ti*max+(n-1)].xx_offset+i];
    }
    xx_last+=n;
    return e_min;
}

/*************************************************************
Call to calculate and print results for given number of plants
*************************************************************/

int full_memoization(int num_fixed_loc) {
    char *str;
    long errorsum;  //for convenience

    //Call recursive workhorse
    errorsum=full_memh(0, num_fixed_loc-2);
    //Now print
    str=(char *) malloc(num_fixed_loc*20+100);
    sprintf (str,"\n%4d %6d {%d,",num_fixed_loc-1,errorsum,a2[0]);
    for (int i=0; i<num_fixed_loc-2; i++)
        sprintf (str+strlen(str),"%d%c",a2[ xx[ sb[0*max+(num_fixed_loc-2)].xx_offset+i ] ], (i<num_fixed_loc-3)?',':'}');
    printf ("%s",str);
    return 0;
}

/**************************************************
Initialize and call for plant numbers of many sizes
**************************************************/

int main (int x, char **y) {
    int t;
    int i2;

    qsort(a,numofa,sizeof(int),sortfunc);
    t=1;
    for (int i=1; i<numofa; i++)
        if (a[i]!=a[i-1])
            t++;
    max=t;
    i2=1;
    a2=(int *)malloc(sizeof(int)*t);
    a2[0]=a[0];
    for (int i=1; i<numofa; i++)
        if (a[i]!=a[i-1]) {
            a2[i2++]=a[i];
        }
    sb = (SavedBundle *)calloc(sizeof(SavedBundle),max*max);
    for (int i=3; i<=max; i++) {
        full_memoization(i);
    }
    free(sb);
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Minimizing time in transit

Body:
[Updates at bottom (including solution source code)]

I have a challenging business problem that a computer can help solve.

Along a mountainous region flows a long winding river with strong currents. Along certain parts of the river are plots of environmentally sensitive land suitable for growing a particular type of rare fruit that is in very high demand. Once field laborers harvest the fruit, the clock starts ticking to get the fruit to a processing plant. It's very costly to try and send the fruits upstream or over land or air. By far the most cost effective mechanism to ship them to the plant is downstream in containers powered solely by the river's constant current. We have the capacity to build 10 processing plants and need to locate these along the river to minimize the total time the fruits spend in transit. The fruits can take however long before reaching the nearest downstream plant but that time directly hurts the price at which they can be sold. Effectively, we want to minimize the sum of the distances to the nearest respective downstream plant. A plant can be located as little as 0 meters downstream from a fruit access point.

The question is: In order to maximize profits, how far up the river should we build the 10 processing plants if we have found 32 fruit growing regions, where the regions' distances upstream from the base of the river are (in meters):
10, 40, 90, 160, 250, 360, 490, ... (n^2)*10 ... 9000, 9610, 10320?

[It is hoped that all work going towards solving this problem and towards creating similar problems and usage scenarios can help raise awareness about and generate popular resistance towards the damaging and stifling nature of software/business method patents (to whatever degree those patents might be believed to be legal within a locality).]

UPDATES

Update1: Forgot to add: I believe this question is a special case of this one.

Update2: One algorithm I wrote gives an answer in a fraction of a second, and I believe is rather good (but it's not yet stable across sample values). I'll give more details later, but the short is as follows. Place the plants at equal spacings. Cycle over all the inner plants where at each plant you recalculate its position by testing every location between its two neighbors until the problem is solved within that space (greedy algorithm). So you optimize plant 2 holding 1 and 3 fixed. Then plant 3 holding 2 and 4 fixed... When you reach the end, you cycle back and repeat until you go a full cycle where every processing plant's recalculated position stops varying.. also at the end of each cycle, you try to move processing plants that are crowded next to each other and are all near each others' fruit dumps into a region that has fruit dumps far away. There are many ways to vary the details and hence the exact answer produced. I have other candidate algorithms, but all have glitches. [I'll post code later.] Just as Mike Dunlavey mentioned below, we likely just want "good enough".

To give an idea of what might be a "good enough" result:

10010 total length of travel from 32 locations to plants at
{10,490,1210,1960,2890,4000,5290,6760,8410,9610}

Update3: mhum gave the correct exact solution first but did not (yet) post a program or algorithm, so I wrote one up that yields the same values.

/************************************************************
This program can be compiled and run (eg, on Linux):
$ gcc -std=c99 processing-plants.c -o processing-plants
$ ./processing-plants
************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//a: Data set of values. Add extra large number at the end

int a[]={
10,40,90,160,250,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240,99999
};

//numofa: size of data set

int numofa=sizeof(a)/sizeof(int);

//a2: will hold (pt to) unique data from a and in sorted order.

int *a2;

//max: size of a2

int max;

//num_fixed_loc: at 10 gives the solution for 10 plants

int num_fixed_loc;

//xx: holds index values of a2 from the lowest error winner of each cycle memoized. accessed via memoized offset value. Winner is based off lowest error sum from left boundary upto right ending boundary.
//FIX: to be dynamically sized.

int xx[1000000];

//xx_last: how much of xx has been used up

int xx_last=0;

//SavedBundle: data type to "hold" memoized values needed (total traval distance and plant locations)

typedef struct _SavedBundle {
    long e;
    int xx_offset;
} SavedBundle;

//sb: (pts to) lookup table of all calculated values memoized

SavedBundle *sb;  //holds winning values being memoized

//Sort in increasing order.

int sortfunc (const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

/****************************
Most interesting code in here
****************************/

long full_memh(int l, int n) {
    long e;
    long e_min=-1;
    int ti;

    if (sb[l*max+n].e) {
        return sb[l*max+n].e;  //convenience passing
    }
    for (int i=l+1; i<max-1; i++) {
        e=0;
        //sum first part
        for (int j=l+1; j<i; j++) {
            e+=a2[j]-a2[l];
        }
        //sum second part
        if (n!=1) //general case, recursively
            e+=full_memh(i, n-1);
        else      //base case, iteratively
            for (int j=i+1; j<max-1; j++) {
                e+=a2[j]-a2[i];
            }
        if (e_min==-1) {
            e_min=e;
            ti=i;
        }
        if (e<e_min) {
            e_min=e;
            ti=i;
        }
    }
    sb[l*max+n].e=e_min;
    sb[l*max+n].xx_offset=xx_last;
    xx[xx_last]=ti;      //later add a test or a realloc, etc, if approp
    for (int i=0; i<n-1; i++) {
        xx[xx_last+(i+1)]=xx[sb[ti*max+(n-1)].xx_offset+i];
    }
    xx_last+=n;
    return e_min;
}

/*************************************************************
Call to calculate and print results for given number of plants
*************************************************************/

int full_memoization(int num_fixed_loc) {
    char *str;
    long errorsum;  //for convenience

    //Call recursive workhorse
    errorsum=full_memh(0, num_fixed_loc-2);
    //Now print
    str=(char *) malloc(num_fixed_loc*20+100);
    sprintf (str,"\n%4d %6d {%d,",num_fixed_loc-1,errorsum,a2[0]);
    for (int i=0; i<num_fixed_loc-2; i++)
        sprintf (str+strlen(str),"%d%c",a2[ xx[ sb[0*max+(num_fixed_loc-2)].xx_offset+i ] ], (i<num_fixed_loc-3)?',':'}');
    printf ("%s",str);
    return 0;
}

/**************************************************
Initialize and call for plant numbers of many sizes
**************************************************/

int main (int x, char **y) {
    int t;
    int i2;

    qsort(a,numofa,sizeof(int),sortfunc);
    t=1;
    for (int i=1; i<numofa; i++)
        if (a[i]!=a[i-1])
            t++;
    max=t;
    i2=1;
    a2=(int *)malloc(sizeof(int)*t);
    a2[0]=a[0];
    for (int i=1; i<numofa; i++)
        if (a[i]!=a[i-1]) {
            a2[i2++]=a[i];
        }
    sb = (SavedBundle *)calloc(sizeof(SavedBundle),max*max);
    for (int i=3; i<=max; i++) {
        full_memoization(i);
    }
    free(sb);
    return 0;
}

Body:
Unless I've made an error, here are exact solutions (obtained through a dynamic programming approach):

N  Dist  Sites
2  60950 {10,4840}
3  40910 {10,2890,6760}
4  30270 {10,2250,4840,7840}
5  23650 {10,1690,3610,5760,8410}
6  19170 {10,1210,2560,4410,6250,8410}
7  15840 {10,1000,2250,3610,5290,7290,9000}
8  13330 {10,810,1960,3240,4410,5760,7290,9000}
9  11460 {10,810,1690,2890,4000,5290,6760,8410,9610}
10 9850  {10,640,1440,2250,3240,4410,5760,7290,8410,9610}
11 8460  {10,640,1440,2250,3240,4410,5290,6250,7290,8410,9610}
12 7350  {10,490,1210,1960,2890,3610,4410,5290,6250,7290,8410,9610}
13 6470  {10,490,1000,1690,2250,2890,3610,4410,5290,6250,7290,8410,9610}
14 5800  {10,360,810,1440,1960,2560,3240,4000,4840,5760,6760,7840,9000,10240}
15 5190  {10,360,810,1440,1960,2560,3240,4000,4840,5760,6760,7840,9000,9610,10240}
16 4610  {10,360,810,1210,1690,2250,2890,3610,4410,5290,6250,7290,8410,9000,9610,10240}
17 4060  {10,360,810,1210,1690,2250,2890,3610,4410,5290,6250,7290,7840,8410,9000,9610,10240}
18 3550  {10,360,810,1210,1690,2250,2890,3610,4410,5290,6250,6760,7290,7840,8410,9000,9610,10240}
19 3080  {10,360,810,1210,1690,2250,2890,3610,4410,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
20 2640  {10,250,640,1000,1440,1960,2560,3240,4000,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
21 2230  {10,250,640,1000,1440,1960,2560,3240,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
22 1860  {10,250,640,1000,1440,1960,2560,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
23 1520  {10,250,490,810,1210,1690,2250,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
24 1210  {10,250,490,810,1210,1690,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
25 940   {10,250,490,810,1210,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
26 710   {10,160,360,640,1000,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
27 500   {10,160,360,640,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
28 330   {10,160,360,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
29 200   {10,160,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
30 100   {10,90,250,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
31 30    {10,90,160,250,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}
32 0     {10,40,90,160,250,360,490,640,810,1000,1210,1440,1690,1960,2250,2560,2890,3240,3610,4000,4410,4840,5290,5760,6250,6760,7290,7840,8410,9000,9610,10240}


问:
Python: Reversibly encode alphanumeric string to integer
I want to convert a string (composed of alphanumeric characters) into an integer and then convert this integer back into a string:

string --> int --> string

In other words, I want to represent an alphanumeric string by an integer.

I found a working solution, which I included in the answer, but I do not think it is the best solution, and I am interested in other ideas/methods.

Please don't tag this as duplicate just because a lot of similar questions already exist, I specifically want an easy way of transforming a string into an integer and vice versa.

This should work for strings that contain alphanumeric characters, i.e. strings containing numbers and letters.

答:
so I needed transfer a dictionary in terms of numbers,
it may look kinda ugly but it's efficient in the way that every char (english letters) is exactly 2 numbers but it's capable of transfering any kind of unicode char</p>
```<code>import json

myDict = {
    "le key": "le Valueue",
    2 : {
        "heya": 1234569,
        "3": 4
    },
    'Α α, Β β, Γ γ' : 'שלום'
}
def convertDictToNum(toBeConverted):
    return int(''.join([(lambda c: c if len(c) ==2 else '0'+c )(str(ord(c) - 26)) for c in str(json.dumps(toBeConverted))]))

def loadDictFromNum(toBeDecoded):
    toBeDecoded = str(toBeDecoded)
    return json.loads(''.join([chr(int(toBeDecoded[cut:cut + 2]) + 26) for cut in range(0, len(toBeDecoded), 2)]))

numbersDict = convertDictToNum(myDict)
print(numbersDict)
# 9708827506817595083206088....
recoveredDict = loadDictFromNum(numbersDict)
print(recoveredDict)
# {'le key': 'le Valueue', '2': {'heya': 1234569, '3': 4}, 'Α α, Β β, Γ γ': 'שלום'}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
so I needed transfer a dictionary in terms of numbers,
it may look kinda ugly but it's efficient in the way that every char (english letters) is exactly 2 numbers but it's capable of transfering any kind of unicode char

import json

myDict = {
    "le key": "le Valueue",
    2 : {
        "heya": 1234569,
        "3": 4
    },
    'Α α, Β β, Γ γ' : 'שלום'
}
def convertDictToNum(toBeConverted):
    return int(''.join([(lambda c: c if len(c) ==2 else '0'+c )(str(ord(c) - 26)) for c in str(json.dumps(toBeConverted))]))

def loadDictFromNum(toBeDecoded):
    toBeDecoded = str(toBeDecoded)
    return json.loads(''.join([chr(int(toBeDecoded[cut:cut + 2]) + 26) for cut in range(0, len(toBeDecoded), 2)]))

numbersDict = convertDictToNum(myDict)
print(numbersDict)
# 9708827506817595083206088....
recoveredDict = loadDictFromNum(numbersDict)
print(recoveredDict)
# {'le key': 'le Valueue', '2': {'heya': 1234569, '3': 4}, 'Α α, Β β, Γ γ': 'שלום'}


问:
Merge matplotlib subplots with shared x-axis
I have two graphs to where both have the same x-axis, but with different y-axis scalings.

The plot with regular axes is the data with a trend line depicting a decay while the y semi-log scaling depicts the accuracy of the fit.

```<code>fig1 = plt.figure(figsize=(15,6))
ax1 = fig1.add_subplot(111)

# Plot of the decay model
ax1.plot(FreqTime1,DecayCount1, '.', color='mediumaquamarine')

# Plot of the optimized fit
ax1.plot(x1, y1M, '-k', label='Fitting Function: $f(t) = %.3f e^{%.3f\t} \
         %+.3f$' % (aR1,kR1,bR1))

ax1.set_xlabel('Time (sec)')
ax1.set_ylabel('Count')
ax1.set_title('Run 1 of Cesium-137 Decay')

# Allows me to change scales
# ax1.set_yscale('log')
ax1.legend(bbox_to_anchor=(1.0, 1.0), prop={'size':15}, fancybox=True, shadow=True)
</code>```

Now, i'm trying to figure out to implement both close together like the examples supplied by this link
http://matplotlib.org/examples/pylab_examples/subplots_demo.html

In particular, this one

When looking at the code for the example, i'm a bit confused on how to implant 3 things:

1) Scaling the axes differently

2) Keeping the figure size the same for the exponential decay graph but having a the line graph have a smaller y size and same x size.

For example:

3) Keeping the label of the function to appear in just only the decay graph.

Any help would be most appreciated.

答:
Here is my solution:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, subplot_kw=dict(frameon=False)) # frameon=False removes frames

plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()

ax1.plot(x, y, color='r')
ax2.plot(x, y, color='b', linestyle='--')
</code>```

One more option is seaborn.FacetGrid but this requires Seaborn and Pandas libraries.

Body:
I have two graphs to where both have the same x-axis, but with different y-axis scalings.

The plot with regular axes is the data with a trend line depicting a decay while the y semi-log scaling depicts the accuracy of the fit.

fig1 = plt.figure(figsize=(15,6))
ax1 = fig1.add_subplot(111)

# Plot of the decay model
ax1.plot(FreqTime1,DecayCount1, '.', color='mediumaquamarine')

# Plot of the optimized fit
ax1.plot(x1, y1M, '-k', label='Fitting Function: $f(t) = %.3f e^{%.3f\t} \
         %+.3f$' % (aR1,kR1,bR1))

ax1.set_xlabel('Time (sec)')
ax1.set_ylabel('Count')
ax1.set_title('Run 1 of Cesium-137 Decay')

# Allows me to change scales
# ax1.set_yscale('log')
ax1.legend(bbox_to_anchor=(1.0, 1.0), prop={'size':15}, fancybox=True, shadow=True)

Now, i'm trying to figure out to implement both close together like the examples supplied by this link
http://matplotlib.org/examples/pylab_examples/subplots_demo.html

In particular, this one

When looking at the code for the example, i'm a bit confused on how to implant 3 things:

1) Scaling the axes differently

2) Keeping the figure size the same for the exponential decay graph but having a the line graph have a smaller y size and same x size.

For example:

3) Keeping the label of the function to appear in just only the decay graph.

Any help would be most appreciated.

Body:
Here is my solution:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, subplot_kw=dict(frameon=False)) # frameon=False removes frames

plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()

ax1.plot(x, y, color='r')
ax2.plot(x, y, color='b', linestyle='--')

One more option is seaborn.FacetGrid but this requires Seaborn and Pandas libraries.


问:
Fullcalendar how to remove resource?
I want allow user to add or remove resources from calendar. currently it is possible to add or remove events from calendar.

Currently i am removing all the events and reloading the calendar.
any better option i don't want o close the page and open it again

I have check the documentation https://fullcalendar.io/docs/Event-remove

答:
You can use the refetchResources, but how you handle it and how you can change data to change the resources is pending to you.

https://fullcalendar.io/docs/v3/refetchResources

```<code>  $('#calendar').fullCalendar('refetchResources');
</code>```

Title: Fullcalendar how to remove resource?

Body:
You can use the refetchResources, but how you handle it and how you can change data to change the resources is pending to you.

https://fullcalendar.io/docs/v3/refetchResources

  $('#calendar').fullCalendar('refetchResources');


问:
How do I set the class path on Linux?
I need an answer for the question in the title.

Thanks.

答:
I don't think you should have a system classpath environment variable on Linux or any other operating system.

Each and every project should have its own classpath settings.  They're usually set by scripts or convention, so there's no need for a system environment variable.

Besides, what would you do if two projects had conflicting JARs required?

Will that environment classpath include every JAR needed by every project on your machine?  That's not practical.

A classpath environment variable might have been the standard with Java 1.0, but I don't think it should be now.

ContentLicense: CC BY-SA 2.5

Title: How do I set the class path on Linux?

LastEditorDisplayName: Andrew Hare


问:
Many kubernetes secrets vs many keys in one k8s secret
Imagine a complex deployment with many dependencies that needs to connect to lots of things, and where the secrets is only used this current namespace with this one complex deployment.

Would you recommend having many secrets:

certificates.yaml

redis-password.yaml

gcp-credentials.yaml

etc....

Or one secret for the deployment with lots of keys:

```<code>apiVersion: v1
kind: Secret
metadata:
  name: all-the-secrets
data:
  redis-password: asdfa
  certificate-key: asdfadf
  certificatee-crt: adfadf
  ...
</code>```

The secrets will be used as environment variables:

```<code>name: redis-password
valueFrom:
  secretKeyRef:
    name: secret-name
    key: key-name

</code>```

And why is one better than the other?

Ps. They will all be encrypted with kubeseal

答:
You should only expose sensitive data to pods that use that data. Many smaller secrets have a tradeoff for managing many different objects but they have an important advantage - Isolation and separation of concerns.

If you check the docs, the secrets are sent only to nodes where the pod needs it. That being said, having 1 secret with all of your sensitive data kinda defeats the purpose as it will be deployed on possibly all nodes and be have all data exposed to all pods, even the data that a particular pod doesn't use will be visible.

Body:
Imagine a complex deployment with many dependencies that needs to connect to lots of things, and where the secrets is only used this current namespace with this one complex deployment.

Would you recommend having many secrets:

certificates.yaml

redis-password.yaml

gcp-credentials.yaml

etc....

Or one secret for the deployment with lots of keys:

apiVersion: v1
kind: Secret
metadata:
  name: all-the-secrets
data:
  redis-password: asdfa
  certificate-key: asdfadf
  certificatee-crt: adfadf
  ...

The secrets will be used as environment variables:

name: redis-password
valueFrom:
  secretKeyRef:
    name: secret-name
    key: key-name

And why is one better than the other?

Ps. They will all be encrypted with kubeseal


问:
Scrapy inconsisent number of items scraped with callbacks and following links
I'm crawling yellow pages results and getting an inconsistent number of scraped items when trying to follow both the yellow pages entries as well as the pagination links. I believe I have 2 issues, but I seem to be able to work around the first. Hopefully this workaround is not causing my second issue.

I have no problem getting the 121 search results I expect from here. I do this based on this example from the official tutorial:

```<code>class LinksSpider(scrapy.Spider):
    name = "links"
    start_urls = [
        r"https://www.paginasamarillas.es/search/administrador-de-fincas/all-ma/zaragoza/all-is/zaragoza/all-ba/all-pu/all-nc/1?what=Administrador%20de%20fincas&where=Zaragoza",
    ]

    def parse(self, response):
        for comercial in response.css('div.col-xs-11.comercial-nombre .row a'):
            href = comercial.attrib["href"]
            if '#' not in href:
                print('href = ', href)
                yield {
                    'name': comercial.css('h2 span::text').get(),
                    'link': href,
                }

        list_items = response.css('ul.pagination li')
        for li in list_items:
            anchor = li.css('a')
            i = anchor.css('i')
            if len(i) != 0:
                next_page = anchor.attrib['href']
                print('next_page = ', next_page)

        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)
</code>```

So my first issue is having to create the for loop involving the list_items as a workaround to get the next_page. This is because the button that takes you to the next page is not li > a like the shortcuts to pages 1, 2, ..., 5. The next page button is the only one with an  inside the , that is li > a > i. Ideally I would do something like

```<code>for href in response.xpath('/html/body/div[5]/div[2]/div[1]/div[2]/div/div[4]/div[31]/ul/li[6]/a/i/../@href'):
    yield response.follow(href, self.parse)
</code>```

but for some reason that div[5] is not found, although div[4] is. According to my research, a potential reason could be because that 5th div is generated by javascript and doesn't yet exist by the time the spider fetches the html. I doubt this is the real reason because I am able to see the div when I save the response into an html file. In any case, the workaround correctly results in the expected 121 items:

```<code>2020-02-17 17:37:07 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-17 17:37:07 [scrapy.extensions.feedexport] INFO: Stored json feed (121 items) in: links.json
</code>```

Assuming this workaround isn't messing with my next steps, I am ok with it and would like to focus on my second issue. In order to follow each yellow pages entry to gather each entry's info, I imitate the example in the tutorial:

```<code>class FullSpider(scrapy.Spider):
    name = "full"
    start_urls = [
        r"https://www.paginasamarillas.es/search/administrador-de-fincas/all-ma/zaragoza/all-is/zaragoza/all-ba/all-pu/all-nc/1?what=Administrador%20de%20fincas&where=Zaragoza",
    ]

    def parse(self, response):
        for comercial in response.css('div.col-xs-11.comercial-nombre .row a'):
            href = comercial.attrib["href"]
            # sleep(1)
            if '#' not in href:
                print('href = ', href)
                yield response.follow(href, self.parse_comercial, meta={'link': href})

        list_items = response.css('ul.pagination li')
        for li in list_items:
            anchor = li.css('a')
            i = anchor.css('i')
            if len(i) != 0:
                next_page = anchor.attrib['href']
                print('next_page = ', next_page)

        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

    def parse_comercial(self, response):

        def extract_with_css(query):
            return response.css(query).get(default='').strip()

        yield {
            'name': extract_with_css('div.titular > h1::text'),
            'link': response.meta.get('link'),
            'sitioWeb': extract_with_css('div.botonesCta > a:not([id^="cfContacta"])::attr(href)'),
        }
</code>```

This produces almost the exact results I want, except that, instead of 121, the number of items returned is sometimes 91, sometimes 94, etc.:

```<code>2020-02-17 18:01:50 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-17 18:01:50 [scrapy.extensions.feedexport] INFO: Stored json feed (94 items) in: full.json
</code>```

My research hints at the asynchronous nature of these requests and/or yields (two different things, I know, but maybe one of them is the culprit) but slowing down (ie, adding sleep()) or simplifying the code (asking it to yield fewer keys) don't seem to improve things.

As I type this, I'm noticing a scrapy stat referencing duplicate filtering, but I'm not really able to make sense of these stats. I'll dump them here in case it helps anyone help me.

After the first spider and the correct 121 results:

```<code>2020-02-17 17:37:07 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 3167,
 'downloader/request_count': 5,
 'downloader/request_method_count/GET': 5,
 'downloader/response_bytes': 134605,
 'downloader/response_count': 5,
 'downloader/response_status_count/200': 5,
 'dupefilter/filtered': 1,
 'elapsed_time_seconds': 4.895525,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 17, 16, 37, 7, 343129),
 'item_scraped_count': 121,
 'log_count/DEBUG': 127,
 'log_count/INFO': 11,
 'request_depth_max': 5,
 'response_received_count': 5,
 'scheduler/dequeued': 5,
 'scheduler/dequeued/memory': 5,
 'scheduler/enqueued': 5,
 'scheduler/enqueued/memory': 5,
 'start_time': datetime.datetime(2020, 2, 17, 16, 37, 2, 447604)}
</code>```

The second spider, with the inconsistent 90-94 results:

```<code>2020-02-17 18:01:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 62095,
 'downloader/request_count': 99,
 'downloader/request_method_count/GET': 99,
 'downloader/response_bytes': 2154817,
 'downloader/response_count': 99,
 'downloader/response_status_count/200': 99,
 'dupefilter/filtered': 28,
 'elapsed_time_seconds': 9.433248,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 17, 17, 1, 50, 120636),
 'item_scraped_count': 94,
 'log_count/DEBUG': 194,
 'log_count/INFO': 11,
 'request_depth_max': 5,
 'response_received_count': 99,
 'scheduler/dequeued': 99,
 'scheduler/dequeued/memory': 99,
 'scheduler/enqueued': 99,
 'scheduler/enqueued/memory': 99,
 'start_time': datetime.datetime(2020, 2, 17, 17, 1, 40, 687388)}
</code>```

Sorry for the length, but I appreciate any hints. Thanks!

EDIT: The first issue (the workaround) seems to be solved thanks to @furas. Still struggling with the second issue (inconsistent results) though.

答:
To get link to next page you can search  which has  with class "fa icon-flecha-derecha" which displays icon >. There can be other  with icon < so I have to use class to recognize correct icon.

Using xpath you can nest elements a[ i[@class="fa icon-flecha-derecha"] ] to get access to  instead of  and get @href

```<code>response.xpath('//ul[@class="pagination"]//li/a[i[@class="fa icon-flecha-derecha"]]/@href').get() #.getall()
</code>```

As for 93 and 121.

I saved urls in file and used pandas to compare them.

There are 121 links but only 93 links are unique - some of them are repeated on web pages.

First code saves all urls (even repeated), second code saves only urls of visited pages - because Scrapy doesn't visit again the same page so it visits only 93 pages.

Body:
I'm crawling yellow pages results and getting an inconsistent number of scraped items when trying to follow both the yellow pages entries as well as the pagination links. I believe I have 2 issues, but I seem to be able to work around the first. Hopefully this workaround is not causing my second issue.

I have no problem getting the 121 search results I expect from here. I do this based on this example from the official tutorial:

class LinksSpider(scrapy.Spider):
    name = "links"
    start_urls = [
        r"https://www.paginasamarillas.es/search/administrador-de-fincas/all-ma/zaragoza/all-is/zaragoza/all-ba/all-pu/all-nc/1?what=Administrador%20de%20fincas&where=Zaragoza",
    ]

    def parse(self, response):
        for comercial in response.css('div.col-xs-11.comercial-nombre .row a'):
            href = comercial.attrib["href"]
            if '#' not in href:
                print('href = ', href)
                yield {
                    'name': comercial.css('h2 span::text').get(),
                    'link': href,
                }

        list_items = response.css('ul.pagination li')
        for li in list_items:
            anchor = li.css('a')
            i = anchor.css('i')
            if len(i) != 0:
                next_page = anchor.attrib['href']
                print('next_page = ', next_page)

        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

So my first issue is having to create the for loop involving the list_items as a workaround to get the next_page. This is because the button that takes you to the next page is not li > a like the shortcuts to pages 1, 2, ..., 5. The next page button is the only one with an  inside the , that is li > a > i. Ideally I would do something like

for href in response.xpath('/html/body/div[5]/div[2]/div[1]/div[2]/div/div[4]/div[31]/ul/li[6]/a/i/../@href'):
    yield response.follow(href, self.parse)

but for some reason that div[5] is not found, although div[4] is. According to my research, a potential reason could be because that 5th div is generated by javascript and doesn't yet exist by the time the spider fetches the html. I doubt this is the real reason because I am able to see the div when I save the response into an html file. In any case, the workaround correctly results in the expected 121 items:

2020-02-17 17:37:07 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-17 17:37:07 [scrapy.extensions.feedexport] INFO: Stored json feed (121 items) in: links.json

Assuming this workaround isn't messing with my next steps, I am ok with it and would like to focus on my second issue. In order to follow each yellow pages entry to gather each entry's info, I imitate the example in the tutorial:

class FullSpider(scrapy.Spider):
    name = "full"
    start_urls = [
        r"https://www.paginasamarillas.es/search/administrador-de-fincas/all-ma/zaragoza/all-is/zaragoza/all-ba/all-pu/all-nc/1?what=Administrador%20de%20fincas&where=Zaragoza",
    ]

    def parse(self, response):
        for comercial in response.css('div.col-xs-11.comercial-nombre .row a'):
            href = comercial.attrib["href"]
            # sleep(1)
            if '#' not in href:
                print('href = ', href)
                yield response.follow(href, self.parse_comercial, meta={'link': href})

        list_items = response.css('ul.pagination li')
        for li in list_items:
            anchor = li.css('a')
            i = anchor.css('i')
            if len(i) != 0:
                next_page = anchor.attrib['href']
                print('next_page = ', next_page)

        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

    def parse_comercial(self, response):

        def extract_with_css(query):
            return response.css(query).get(default='').strip()

        yield {
            'name': extract_with_css('div.titular > h1::text'),
            'link': response.meta.get('link'),
            'sitioWeb': extract_with_css('div.botonesCta > a:not([id^="cfContacta"])::attr(href)'),
        }

This produces almost the exact results I want, except that, instead of 121, the number of items returned is sometimes 91, sometimes 94, etc.:

2020-02-17 18:01:50 [scrapy.core.engine] INFO: Closing spider (finished)
2020-02-17 18:01:50 [scrapy.extensions.feedexport] INFO: Stored json feed (94 items) in: full.json

My research hints at the asynchronous nature of these requests and/or yields (two different things, I know, but maybe one of them is the culprit) but slowing down (ie, adding sleep()) or simplifying the code (asking it to yield fewer keys) don't seem to improve things.

As I type this, I'm noticing a scrapy stat referencing duplicate filtering, but I'm not really able to make sense of these stats. I'll dump them here in case it helps anyone help me.

After the first spider and the correct 121 results:

2020-02-17 17:37:07 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 3167,
 'downloader/request_count': 5,
 'downloader/request_method_count/GET': 5,
 'downloader/response_bytes': 134605,
 'downloader/response_count': 5,
 'downloader/response_status_count/200': 5,
 'dupefilter/filtered': 1,
 'elapsed_time_seconds': 4.895525,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 17, 16, 37, 7, 343129),
 'item_scraped_count': 121,
 'log_count/DEBUG': 127,
 'log_count/INFO': 11,
 'request_depth_max': 5,
 'response_received_count': 5,
 'scheduler/dequeued': 5,
 'scheduler/dequeued/memory': 5,
 'scheduler/enqueued': 5,
 'scheduler/enqueued/memory': 5,
 'start_time': datetime.datetime(2020, 2, 17, 16, 37, 2, 447604)}

The second spider, with the inconsistent 90-94 results:

2020-02-17 18:01:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 62095,
 'downloader/request_count': 99,
 'downloader/request_method_count/GET': 99,
 'downloader/response_bytes': 2154817,
 'downloader/response_count': 99,
 'downloader/response_status_count/200': 99,
 'dupefilter/filtered': 28,
 'elapsed_time_seconds': 9.433248,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 2, 17, 17, 1, 50, 120636),
 'item_scraped_count': 94,
 'log_count/DEBUG': 194,
 'log_count/INFO': 11,
 'request_depth_max': 5,
 'response_received_count': 99,
 'scheduler/dequeued': 99,
 'scheduler/dequeued/memory': 99,
 'scheduler/enqueued': 99,
 'scheduler/enqueued/memory': 99,
 'start_time': datetime.datetime(2020, 2, 17, 17, 1, 40, 687388)}

Sorry for the length, but I appreciate any hints. Thanks!

EDIT: The first issue (the workaround) seems to be solved thanks to @furas. Still struggling with the second issue (inconsistent results) though.

Body:
To get link to next page you can search <a> which has <i> with class "fa icon-flecha-derecha" which displays icon >. There can be other <i> with icon < so I have to use class to recognize correct icon.

Using xpath you can nest elements a[ i[@class="fa icon-flecha-derecha"] ] to get access to <a> instead of <i> and get @href

response.xpath('//ul[@class="pagination"]//li/a[i[@class="fa icon-flecha-derecha"]]/@href').get() #.getall()

As for 93 and 121.

I saved urls in file and used pandas to compare them.

There are 121 links but only 93 links are unique - some of them are repeated on web pages.

First code saves all urls (even repeated), second code saves only urls of visited pages - because Scrapy doesn't visit again the same page so it visits only 93 pages.


问:
Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'
I am using Laravel to connect to MySQL database and got this exception:

```<code>PDOException
SQLSTATE[HY000] [1049] Unknown database 'forge'
</code>```

and this is my config.database.php

```<code>'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'Anastasie',
            'password'  => 'A@Laurent',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
</code>```

why is the error referring to PDO database? and why the forge database name? I have already changed it.

Should I do anything to tell Laravel that I am using MySQL database?

Update 1

I found this line
`protected $table = 'users';`
in my user.php file and I have changed it to
`protected $table = 'user';` because the table in my database is `user` not `users`

Update 2

I wrote this in my Route
```<code>Route::resource('users', 'UsersController');
</code>```

and I added UsersController.php in my controllers folder

and inside UsersController.php I have this:

```<code>class UsersController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();
        return View::make('users.index', compact('users'));
    }
</code>```

and I call this url http://localhost:8082/laravel/public/users/

I am using Windows 7 with Laravel 4.2

答: I did all of them but didn't work, I find out should stop php artisan serve(Ctrl + C) and start php artisan serve again.</p>

Body:
I am using Laravel to connect to MySQL database and got this exception:

PDOException
SQLSTATE[HY000] [1049] Unknown database 'forge'

and this is my config.database.php

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'laravel',
            'username'  => 'Anastasie',
            'password'  => 'A@Laurent',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

why is the error referring to PDO database? and why the forge database name? I have already changed it.

Should I do anything to tell Laravel that I am using MySQL database?

Update 1

I found this line
`protected $table = 'users';`
in my user.php file and I have changed it to
`protected $table = 'user';` because the table in my database is `user` not `users`

Update 2

I wrote this in my Route

Route::resource('users', 'UsersController');

and I added UsersController.php in my controllers folder

and inside UsersController.php I have this:

class UsersController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();
        return View::make('users.index', compact('users'));
    }

and I call this url http://localhost:8082/laravel/public/users/

I am using Windows 7 with Laravel 4.2


问:
Conversion of string to dictionary
I have captured a string from a REST get request and have placed it in a variable. The string is:

```<code> {"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}
</code>```

I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()

```<code>bucket_dict = eval(bucket_info)
</code>```

but the program errors out with a:

```<code>Traceback (most recent call last):
  File "./test.py", line 83, in <module>
    for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'
</code>```

When I print the value of bucket_dict I get:

```<code>({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})
</code>```

I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.

答:
Try this instead

```<code>import ast

string = '{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}'

result = ast.literal_eval(string)
print(result)
</code>```

result is returned as a dictionary

Title: Conversion of string to dictionary

Body:
I have captured a string from a REST get request and have placed it in a variable. The string is:

 {"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}

I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()

bucket_dict = eval(bucket_info)

but the program errors out with a:

Traceback (most recent call last):
  File "./test.py", line 83, in <module>
    for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'

When I print the value of bucket_dict I get:

({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})

I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.

Body:
Try this instead

import ast

string = '{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}'

result = ast.literal_eval(string)
print(result)

result is returned as a dictionary


问:
Change the color of UITableViewCellAccessoryDisclosureIndicator
A quick question, I want to change the color of the UITableViewCellAccessoryDisclosureIndicator (the arrow on the right side of tableView) from default gray to white color.

```<code>cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
</code>```

答:
You should create an image and use it instead!

cell. accessoryView = myAccessoryUIImageView;

Body:
A quick question, I want to change the color of the UITableViewCellAccessoryDisclosureIndicator (the arrow on the right side of tableView) from default gray to white color.

cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;


问:
Prevent glob from selecting a file with a specific file name
I have a folder with 5 html files. The files are called:

page-1.html

page-2.html

page-hello.html

page-32.html

yo-page-text.html

I wish to use glob function to return an array with only the files formatted: "page[number 0 - 1000]".
So essentially I wish the glob function to return the following pages from the example above:

page-1.html

page-2.html

page-32.html

This is the code that I have managed to write so far:

<?php
    $directory = "testfolder/";
    foreach (glob($directory . "page-*.html") as $filename) {
        echo basename($filename);
    }
?>
```

答:
The glob pattern is not as flexible as RegEx, so unless someone has some other magic, you can filter after the glob:

```<code>$files = preg_grep('/page-[0-9]+\.html/', glob($directory . '*.*'));
</code>```

If the glob pattern supported repetition + then it would be easy.  Bash and Korn shells offer it with +([0-9]) but PHP doesn't.

You could also check for one number and trust that what follows matched by * will be numbers with: glob($directory . 'page-[0-9]*.html'), but this could match page-0-hello.html as well.

Body:
The glob pattern is not as flexible as RegEx, so unless someone has some other magic, you can filter after the glob:

$files = preg_grep('/page-[0-9]+\.html/', glob($directory . '*.*'));

If the glob pattern supported repetition + then it would be easy.  Bash and Korn shells offer it with +([0-9]) but PHP doesn't.

You could also check for one number and trust that what follows matched by * will be numbers with: glob($directory . 'page-[0-9]*.html'), but this could match page-0-hello.html as well.


问:
How long do browsers cache HTTP 301s?
I am debugging a problem with a HTTP 301 Permanent Redirect. After a quick test, it seems that Safari clears its cache of 301s when it is restarted, but Firefox does not.

When do IE, Chrome, Firefox and Safari clear their cache of 301s?

For example, if I want to redirect 1.example to 2.example, but I accidentally set it to redirect to 3.example, that is a problem. I can correct the mistake, but anyone who has visited 1.example in the meantime will have cached the incorrect redirect to 3.example, and so they will not be able to reach either 1.example or 2.example until their cache is cleared. Upon investigation, I find that there were no Cache-Control and Expires headers set. The headers for the incorrect 301 response would have been like this:

```<code>HTTP/1.1 301 Moved Permanently
Date: Wed, 27 Feb 2013 12:05:53 GMT
Server: Apache/2.2.21 (Unix) DAV/2 PHP/5.3.8
X-Powered-By: PHP/5.3.8
Location: http://3.example/
Content-Type: text/html
</code>```

My own tests show that:

IE7, IE8, Android 2.3.4 do not cache at all.

Firefox 18.0.2, Safari 5.1.7 (on Windows 7), and Opera 12.14 all cache, and clear the cache on browser restart.

IE10 and Chrome 25 cache, but do not clear on browser restart, so when will they clear?

答:
On the latest Google Chrome Version 79, you can use the chrome://net-internals
and select on DNS from the left panel, then tap the Clear host cache button

Title: How long do browsers cache HTTP 301s?

Body:
I am debugging a problem with a HTTP 301 Permanent Redirect. After a quick test, it seems that Safari clears its cache of 301s when it is restarted, but Firefox does not.

When do IE, Chrome, Firefox and Safari clear their cache of 301s?

For example, if I want to redirect 1.example to 2.example, but I accidentally set it to redirect to 3.example, that is a problem. I can correct the mistake, but anyone who has visited 1.example in the meantime will have cached the incorrect redirect to 3.example, and so they will not be able to reach either 1.example or 2.example until their cache is cleared. Upon investigation, I find that there were no Cache-Control and Expires headers set. The headers for the incorrect 301 response would have been like this:

HTTP/1.1 301 Moved Permanently
Date: Wed, 27 Feb 2013 12:05:53 GMT
Server: Apache/2.2.21 (Unix) DAV/2 PHP/5.3.8
X-Powered-By: PHP/5.3.8
Location: http://3.example/
Content-Type: text/html

My own tests show that:

IE7, IE8, Android 2.3.4 do not cache at all.

Firefox 18.0.2, Safari 5.1.7 (on Windows 7), and Opera 12.14 all cache, and clear the cache on browser restart.

IE10 and Chrome 25 cache, but do not clear on browser restart, so when will they clear?


问:
Accuracy of FSIN and other x87 trigonometric instructions on AMD processors
On Intel processors, x87 trigonometric instructions such as FSIN have limited accuracy due to the use of a 66-bit approximation of pi even though the computation itself is otherwise accurate to the full 64-bit mantissa of an 80-bit extended-precision floating-point value. (Full accuracy for all valid inputs requires a 128-bit approximation of pi.) The omission in Intel's documentation was corrected after the issue was brought to their attention.

However, I cannot find similarly detailed information about the accuracy of AMD's implementation of x87 trigonometric instructions beyond this mention in the AMD64 Architecture Programmer's Manual, Volume 1:

6.4.5.1  Accuracy of Transcendental Results

x87 computations are carried out in double-extended-precision format, so that the transcendental functions provide results accurate to within one unit in the last place (ulp) for each of the floating-point data types.

Is AMD's implementation of x87 trigonometric instructions actually fully accurate to within one ULP in extended-precision format for all valid inputs, including a 128-bit or better approximation of pi? An answer that pertains to the Zen and Zen 2 architectures (Ryzen and EPYC) would be ideal.

答:
I found a program located at http://notabs.org/fpuaccuracy/ (direct download link; GPLv3) designed to test the accuracy of x87 trigonometric instructions. The reference output for fpuaccuracy examples supplied with the program, generated using an Intel Core i7-2600 (Sandy Bridge), is as follows:

```<code>sin with smallest failing argument
argument   4000 C10A 7DC0 DC46 D753   (decimal 3.0162653335001840718)
actual     3FFB FFFF BBF1 3588 24AF   (decimal 0.1249994929300478145)
x87 fpu    3FFB FFFF BBF1 3588 24AE   (decimal 0.12499949293004781449)
error      -1.0002171407788819287 ulp

sin near pi
argument   4000 C90F DAA2 2168 C235   (decimal 3.1415926535897932385)
actual     BFBE ECE6 75D1 FC8F 8CBB   (decimal -5.0165576126683320235E-20)
x87 fpu    BFBF 8000 0000 0000 0000   (decimal -5.42101086242752217E-20)
error      -1376283091369227076.6 ulp

sin with large argument
argument   403D FFFF FFFF 2D2A 9042   (decimal 9223372035086174241)
actual     BFDF E730 CF55 1180 63F3   (decimal -4.2053336735954077951E-10)
x87 fpu    BFF8 C28B 4641 7452 B463   (decimal -0.011874025925697012908)
error      -4.7037861121081250351E+26 ulp

cos with smallest failing argument
argument   3FFF C10E 8AC0 BFEB 5E80   (decimal 1.5082562867317745453)
actual     3FFA FFFF 3EA3 D2D7 355B   (decimal 0.062499279677629184442)
x87 fpu    3FFA FFFF 3EA3 D2D7 355A   (decimal 0.062499279677629184438)
error      -1.005468872258621479 ulp

cos near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     BFBD ECE6 75D1 FC8F 8CBB   (decimal -2.5082788063341660117E-20)
x87 fpu    BFBE 8000 0000 0000 0000   (decimal -2.710505431213761085E-20)
error      -1376283091369227076.6 ulp

cos with large argument
argument   403D FFFF FFFF 6CE1 B432   (decimal 9223372035620657689)
actual     3FDD DFD2 E369 AE25 7E4A   (decimal 1.0178327217734091432E-10)
x87 fpu    BFF8 C28B 45B2 1490 D117   (decimal -0.011874025404105249357)
error      -1.8815144449581111989E+27 ulp

tan with smallest failing argument
argument   3FFF B8B5 07B4 294A BD53   (decimal 1.4430245999997931928)
actual     4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
x87 fpu    4001 F915 0EE5 BAC8 446D   (decimal 7.7838205801874740726)
error      1.0017725812707024772 ulp

tan near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     C040 8A51 E04D AABD A35F   (decimal -39867976298117107068)
x87 fpu    C040 8000 0000 0000 0000   (decimal -36893488147419103232)
error      743622037674500958.81 ulp

tan with large argument
argument   403D FFFF FFFF DCF6 FE38   (decimal 9223372036560879388)
actual     4005 A86C 499C 14EA BD4A   (decimal 84.211499097398127292)
x87 fpu    401F C10C D618 50D5 E957   (decimal 6477687856.6315280604)
error      9.3353319161898434351E+26 ulp
</code>```

When run on a laptop with an AMD Ryzen 7 2700U (Zen), I get the following:

```<code>sin with smallest failing argument
argument   4000 C10A 7DC0 DC46 D753   (decimal 3.0162653335001840718)
actual     3FFB FFFF BBF1 3588 24AF   (decimal 0.1249994929300478145)
x87 fpu    3FFB FFFF BBF1 3588 24AE   (decimal 0.12499949293004781449)
error      -1.0002171407788819287 ulp

sin near pi
argument   4000 C90F DAA2 2168 C235   (decimal 3.1415926535897932385)
actual     BFBE ECE6 75D1 FC8F 8CBB   (decimal -5.0165576126683320235E-20)
x87 fpu    BFBF 8000 0000 0000 0000   (decimal -5.42101086242752217E-20)
error      -1376283091369227076.6 ulp

sin with large argument
argument   403D FFFF FFFF 2D2A 9042   (decimal 9223372035086174241)
actual     BFDF E730 CF55 1180 63F3   (decimal -4.2053336735954077951E-10)
x87 fpu    BFF8 C28B 4641 7452 B463   (decimal -0.011874025925697012908)
error      -4.7037861121081250351E+26 ulp

cos with smallest failing argument
argument   3FFF C10E 8AC0 BFEB 5E80   (decimal 1.5082562867317745453)
actual     3FFA FFFF 3EA3 D2D7 355B   (decimal 0.062499279677629184442)
x87 fpu    3FFA FFFF 3EA3 D2D7 355A   (decimal 0.062499279677629184438)
error      -1.005468872258621479 ulp

cos near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     BFBD ECE6 75D1 FC8F 8CBB   (decimal -2.5082788063341660117E-20)
x87 fpu    BFBE 8000 0000 0000 0000   (decimal -2.710505431213761085E-20)
error      -1376283091369227076.6 ulp

cos with large argument
argument   403D FFFF FFFF 6CE1 B432   (decimal 9223372035620657689)
actual     3FDD DFD2 E369 AE25 7E4A   (decimal 1.0178327217734091432E-10)
x87 fpu    BFF8 C28B 45B2 1490 D117   (decimal -0.011874025404105249357)
error      -1.8815144449581111989E+27 ulp

tan with smallest failing argument
argument   3FFF B8B5 07B4 294A BD53   (decimal 1.4430245999997931928)
actual     4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
x87 fpu    4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
error      0.0017725812707024772387 ulp

tan near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     C040 8A51 E04D AABD A35F   (decimal -39867976298117107068)
x87 fpu    C040 8000 0000 0000 0000   (decimal -36893488147419103232)
error      743622037674500958.81 ulp

tan with large argument
argument   403D FFFF FFFF DCF6 FE38   (decimal 9223372036560879388)
actual     4005 A86C 499C 14EA BD4A   (decimal 84.211499097398127292)
x87 fpu    401F C10C D618 50D5 E957   (decimal 6477687856.6315280604)
error      9.3353319161898434351E+26 ulp
</code>```

With one exception (tan with smallest failing argument), the results are identical. I also tested on my Ryzen 9 3950X (Zen 2) and got the same results.

In conclusion, recent AMD processors, including the Zen and Zen 2 architectures, use a 66-bit approximation of pi and will produce the same kinds of inaccuracies modern Intel processors give for x87 trigonometric instructions when given certain arguments.

Body:
I found a program located at http://notabs.org/fpuaccuracy/ (direct download link; GPLv3) designed to test the accuracy of x87 trigonometric instructions. The reference output for fpuaccuracy examples supplied with the program, generated using an Intel Core i7-2600 (Sandy Bridge), is as follows:

sin with smallest failing argument
argument   4000 C10A 7DC0 DC46 D753   (decimal 3.0162653335001840718)
actual     3FFB FFFF BBF1 3588 24AF   (decimal 0.1249994929300478145)
x87 fpu    3FFB FFFF BBF1 3588 24AE   (decimal 0.12499949293004781449)
error      -1.0002171407788819287 ulp

sin near pi
argument   4000 C90F DAA2 2168 C235   (decimal 3.1415926535897932385)
actual     BFBE ECE6 75D1 FC8F 8CBB   (decimal -5.0165576126683320235E-20)
x87 fpu    BFBF 8000 0000 0000 0000   (decimal -5.42101086242752217E-20)
error      -1376283091369227076.6 ulp

sin with large argument
argument   403D FFFF FFFF 2D2A 9042   (decimal 9223372035086174241)
actual     BFDF E730 CF55 1180 63F3   (decimal -4.2053336735954077951E-10)
x87 fpu    BFF8 C28B 4641 7452 B463   (decimal -0.011874025925697012908)
error      -4.7037861121081250351E+26 ulp

cos with smallest failing argument
argument   3FFF C10E 8AC0 BFEB 5E80   (decimal 1.5082562867317745453)
actual     3FFA FFFF 3EA3 D2D7 355B   (decimal 0.062499279677629184442)
x87 fpu    3FFA FFFF 3EA3 D2D7 355A   (decimal 0.062499279677629184438)
error      -1.005468872258621479 ulp

cos near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     BFBD ECE6 75D1 FC8F 8CBB   (decimal -2.5082788063341660117E-20)
x87 fpu    BFBE 8000 0000 0000 0000   (decimal -2.710505431213761085E-20)
error      -1376283091369227076.6 ulp

cos with large argument
argument   403D FFFF FFFF 6CE1 B432   (decimal 9223372035620657689)
actual     3FDD DFD2 E369 AE25 7E4A   (decimal 1.0178327217734091432E-10)
x87 fpu    BFF8 C28B 45B2 1490 D117   (decimal -0.011874025404105249357)
error      -1.8815144449581111989E+27 ulp

tan with smallest failing argument
argument   3FFF B8B5 07B4 294A BD53   (decimal 1.4430245999997931928)
actual     4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
x87 fpu    4001 F915 0EE5 BAC8 446D   (decimal 7.7838205801874740726)
error      1.0017725812707024772 ulp

tan near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     C040 8A51 E04D AABD A35F   (decimal -39867976298117107068)
x87 fpu    C040 8000 0000 0000 0000   (decimal -36893488147419103232)
error      743622037674500958.81 ulp

tan with large argument
argument   403D FFFF FFFF DCF6 FE38   (decimal 9223372036560879388)
actual     4005 A86C 499C 14EA BD4A   (decimal 84.211499097398127292)
x87 fpu    401F C10C D618 50D5 E957   (decimal 6477687856.6315280604)
error      9.3353319161898434351E+26 ulp

When run on a laptop with an AMD Ryzen 7 2700U (Zen), I get the following:

sin with smallest failing argument
argument   4000 C10A 7DC0 DC46 D753   (decimal 3.0162653335001840718)
actual     3FFB FFFF BBF1 3588 24AF   (decimal 0.1249994929300478145)
x87 fpu    3FFB FFFF BBF1 3588 24AE   (decimal 0.12499949293004781449)
error      -1.0002171407788819287 ulp

sin near pi
argument   4000 C90F DAA2 2168 C235   (decimal 3.1415926535897932385)
actual     BFBE ECE6 75D1 FC8F 8CBB   (decimal -5.0165576126683320235E-20)
x87 fpu    BFBF 8000 0000 0000 0000   (decimal -5.42101086242752217E-20)
error      -1376283091369227076.6 ulp

sin with large argument
argument   403D FFFF FFFF 2D2A 9042   (decimal 9223372035086174241)
actual     BFDF E730 CF55 1180 63F3   (decimal -4.2053336735954077951E-10)
x87 fpu    BFF8 C28B 4641 7452 B463   (decimal -0.011874025925697012908)
error      -4.7037861121081250351E+26 ulp

cos with smallest failing argument
argument   3FFF C10E 8AC0 BFEB 5E80   (decimal 1.5082562867317745453)
actual     3FFA FFFF 3EA3 D2D7 355B   (decimal 0.062499279677629184442)
x87 fpu    3FFA FFFF 3EA3 D2D7 355A   (decimal 0.062499279677629184438)
error      -1.005468872258621479 ulp

cos near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     BFBD ECE6 75D1 FC8F 8CBB   (decimal -2.5082788063341660117E-20)
x87 fpu    BFBE 8000 0000 0000 0000   (decimal -2.710505431213761085E-20)
error      -1376283091369227076.6 ulp

cos with large argument
argument   403D FFFF FFFF 6CE1 B432   (decimal 9223372035620657689)
actual     3FDD DFD2 E369 AE25 7E4A   (decimal 1.0178327217734091432E-10)
x87 fpu    BFF8 C28B 45B2 1490 D117   (decimal -0.011874025404105249357)
error      -1.8815144449581111989E+27 ulp

tan with smallest failing argument
argument   3FFF B8B5 07B4 294A BD53   (decimal 1.4430245999997931928)
actual     4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
x87 fpu    4001 F915 0EE5 BAC8 446C   (decimal 7.7838205801874740721)
error      0.0017725812707024772387 ulp

tan near pi/2
argument   3FFF C90F DAA2 2168 C235   (decimal 1.5707963267948966193)
actual     C040 8A51 E04D AABD A35F   (decimal -39867976298117107068)
x87 fpu    C040 8000 0000 0000 0000   (decimal -36893488147419103232)
error      743622037674500958.81 ulp

tan with large argument
argument   403D FFFF FFFF DCF6 FE38   (decimal 9223372036560879388)
actual     4005 A86C 499C 14EA BD4A   (decimal 84.211499097398127292)
x87 fpu    401F C10C D618 50D5 E957   (decimal 6477687856.6315280604)
error      9.3353319161898434351E+26 ulp

With one exception (tan with smallest failing argument), the results are identical. I also tested on my Ryzen 9 3950X (Zen 2) and got the same results.

In conclusion, recent AMD processors, including the Zen and Zen 2 architectures, use a 66-bit approximation of pi and will produce the same kinds of inaccuracies modern Intel processors give for x87 trigonometric instructions when given certain arguments.


问:
How do you determine the path of the file that a symlink points to?
In Linux, if you have a path to a file which you know is a symlink, how do you programmatically determine (in C or C++) the path to the file that it points to?</p>

答: On POSIX or BSD system use readlink()

Body: On POSIX or BSD system use readlink()


问:
Unable to build c code in visual studio code
1) using tmd-gcc
2) path is set

getting These errors while trying to Build the program

答:
It is a very bad idea to have C&C++ directory. Rename it to C_CPP for example and everything will work OK

Generally speaking try to avoid any non ASCII chars in the paths and filenames when programming. Even if theoretically speaking system allows them, the tools (like compilers, linkers etc) used in development might not.


问:
Undefined is not an object (evaluating '_this2.setState')
I'm new on react-native development and i try to add a login / register to my application, my login by email and by facebook is working fine (i'm in Firebase database, so it's ok). I want to show another view after the login of the user. Here is my firebaseconfig (imported in my login) :

```<code>    export async function loginUser(email, password) {
  try {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(response => {
        this.setState({ authentificated: true });
      });
  } catch (error) {
    console.log(error.toString);
  }
}

export async function facebookLogin() {
  Facebook.initializeAsync("928193664206969");
  const { type, token } = await Facebook.logInWithReadPermissionsAsync(
    "928193664206969",
    {
      permissions: ["public_profile"]
    }
  );

  if (type == "success") {
    const credential = firebase.auth.FacebookAuthProvider.credential(token);

    firebase
      .auth()
      .signInWithCredential(credential)
      .then(response => {
        this.setState({ authentificated: true });
      })
      .catch(error => {
        console.log(error);
      });
  }
}
</code>```

Here is my Login page :

```<code>import React from "react";
import { View, Text } from "react-native";
import EmailLoging from "../components/EmailLoging";
import { Welcome } from "../pages/Welcome";

export default class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      authentificated: false
    };
  }

  renderCurrentState() {
    if (this.state.authentificated) {
      return <Welcome />;
    } else {
      return <EmailLoging />;
    }
  }

  render() {
    return this.renderCurrentState();
  }
}
</code>```

In the application, when i click on login with facebook, it's work, then i go back to the login screen with this error :

```<code>undefined is not an object (evaluating '_this2.setState')
- node_modules\@firebase\auth\dist\auth.js:16:1054 in cb.prototype.toString
- node_modules\@firebase\auth\dist\auth.js:19:232 in <anonymous>
- node_modules\@firebase\auth\dist\auth.js:19:167 in xb
- node_modules\@firebase\auth\dist\auth.js:19:0 in wb
- node_modules\@firebase\auth\dist\auth.js:13:280 in <anonymous>
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue
</code>```

I have done some search on Stackoverflow, and i found this : TypeError: undefined is not an object (evaluating 'this.setState') but i have only arrow function so it's not the problem..

Thank you

Update :
Now i don't have the error, but the screen didn't change after the login, my code, login functions : (firebaseConfig.js)

```<code>export async function loginUser(email, password) {
  try {
    firebase.auth().signInWithEmailAndPassword(email, password);
  } catch (error) {
    console.log(error.toString);
  }
}

export async function facebookLogin() {
  Facebook.initializeAsync("928193664206969");
  const { type, token } = await Facebook.logInWithReadPermissionsAsync(
    "928193664206969",
    {
      permissions: ["public_profile"]
    }
  );

  if (type == "success") {
    const credential = firebase.auth.FacebookAuthProvider.credential(token);

    firebase
      .auth()
      .signInWithCredential(credential)
      .catch(error => {
        console.log(error);
      });
  }
}
</code>```

Login.js :

```<code>import React from "react";
import { View, Text } from "react-native";
import Welcome from "../pages/Welcome";
import Home from "../pages/Home";

export default class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      authentificated: false
    };

    this.renderCurrentState = this.renderCurrentState.bind(this);
  }

  renderCurrentState = () => {
    if (this.state.authentificated) {
      return <Home />;
    } else {
      return <Welcome />;
    }
  };

  render() {
    return this.renderCurrentState();
  }
}

Welcome.js :

import React from "react";
import { StyleSheet, Text, Image } from "react-native";
import { LinearGradient } from "expo-linear-gradient";

import logo from "../../assets/icon.png";
import { Button, Icon, Container } from "native-base";
import { Actions } from "react-native-router-flux";
import { facebookLogin } from "../components/firebaseConfig";

export default class Welcome extends React.Component {
  render() {
    return (
      <LinearGradient
        colors={["#004aaf", "#000"]}
        style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
      >
        <Container style={styles.backgroundImage}>
          <Image source={logo} style={styles.logo}></Image>
          <Text style={styles.loginText}>
            ─── Se connecter / S'inscrire avec ───
          </Text>
          <Button
            light
            full
            rounded
            style={{ padding: 10 }}
            onPress={() => Actions.login()}
          >
            <Icon type="FontAwesome" name="envelope" />
            <Text>Mon adresse email</Text>
          </Button>
          <Button
            full
            rounded
            style={{ padding: 10, marginTop: 20 }}
            onPress={() =>
              facebookLogin().then(() => {
                this.setState({ authentificated: true });
              })
            }
          >
            <Icon type="FontAwesome" name="facebook" />
            <Text style={{ color: "#fff" }}>Mon compte Facebook</Text>
          </Button>
        </Container>
      </LinearGradient>
    );
  }
}
const styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    width: "100%",
    height: "100%",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "transparent",
    padding: 25
  },
  logo: {
    width: 170,
    height: 130
  },
  loginText: {
    paddingTop: 50,
    paddingBottom: 50,
    color: "#fff"
  }
});
</code>```

答:
this.setState() should be called from inside the React component. You are wrongly calling it inside facebookLogin() and loginUser() functions.

You can fix it like this:

```<code>export async function loginUser(email, password) {
  try {
    return firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
  } catch (error) {
    console.log(error.toString);
  }
}
</code>```

then in your component, you call

```<code>  loginUser().then(() => {
    this.setState({ authentificated: true });
  });
</code>```

But please make sure the method where you call, this is properly bound.
The common practice is to define methods like this:

```<code>  renderCurrentState = () => {

  }
</code>```

Otherwise you would have to do the binding in component's constructor:

```<code> constructor(props) {
    super(props);

    // ...
    this.renderCurrentState = this.renderCurrentState.bind(this);
  }
</code>```

What I have done is change loginUser() to return a promise. Then you use the function inside your component.

EDIT:

You can add a prop, eg. onLogin which you can use in Login component to update the authenticated state.

```<code>  renderCurrentState() {
    if (this.state.authentificated) {
      return <Welcome />;
    } else {
      return <EmailLoging onLogin={this.updateState} />;
    }
  }

  updateState = () => {
    this.setState({ authentificated: true });
    // possibly other code

  }
</code>```

You should call onLogin on loginUser().then(() => { ... })

Body:
I'm new on react-native development and i try to add a login / register to my application, my login by email and by facebook is working fine (i'm in Firebase database, so it's ok). I want to show another view after the login of the user. Here is my firebaseconfig (imported in my login) :

    export async function loginUser(email, password) {
  try {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(response => {
        this.setState({ authentificated: true });
      });
  } catch (error) {
    console.log(error.toString);
  }
}

export async function facebookLogin() {
  Facebook.initializeAsync("928193664206969");
  const { type, token } = await Facebook.logInWithReadPermissionsAsync(
    "928193664206969",
    {
      permissions: ["public_profile"]
    }
  );

  if (type == "success") {
    const credential = firebase.auth.FacebookAuthProvider.credential(token);

    firebase
      .auth()
      .signInWithCredential(credential)
      .then(response => {
        this.setState({ authentificated: true });
      })
      .catch(error => {
        console.log(error);
      });
  }
}

Here is my Login page :

import React from "react";
import { View, Text } from "react-native";
import EmailLoging from "../components/EmailLoging";
import { Welcome } from "../pages/Welcome";

export default class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      authentificated: false
    };
  }

  renderCurrentState() {
    if (this.state.authentificated) {
      return <Welcome />;
    } else {
      return <EmailLoging />;
    }
  }

  render() {
    return this.renderCurrentState();
  }
}

In the application, when i click on login with facebook, it's work, then i go back to the login screen with this error :

undefined is not an object (evaluating '_this2.setState')
- node_modules\@firebase\auth\dist\auth.js:16:1054 in cb.prototype.toString
- node_modules\@firebase\auth\dist\auth.js:19:232 in <anonymous>
- node_modules\@firebase\auth\dist\auth.js:19:167 in xb
- node_modules\@firebase\auth\dist\auth.js:19:0 in wb
- node_modules\@firebase\auth\dist\auth.js:13:280 in <anonymous>
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

I have done some search on Stackoverflow, and i found this : TypeError: undefined is not an object (evaluating 'this.setState') but i have only arrow function so it's not the problem..

Thank you

Update :
Now i don't have the error, but the screen didn't change after the login, my code, login functions : (firebaseConfig.js)

export async function loginUser(email, password) {
  try {
    firebase.auth().signInWithEmailAndPassword(email, password);
  } catch (error) {
    console.log(error.toString);
  }
}

export async function facebookLogin() {
  Facebook.initializeAsync("928193664206969");
  const { type, token } = await Facebook.logInWithReadPermissionsAsync(
    "928193664206969",
    {
      permissions: ["public_profile"]
    }
  );

  if (type == "success") {
    const credential = firebase.auth.FacebookAuthProvider.credential(token);

    firebase
      .auth()
      .signInWithCredential(credential)
      .catch(error => {
        console.log(error);
      });
  }
}

Login.js :

import React from "react";
import { View, Text } from "react-native";
import Welcome from "../pages/Welcome";
import Home from "../pages/Home";

export default class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: "",
      password: "",
      authentificated: false
    };

    this.renderCurrentState = this.renderCurrentState.bind(this);
  }

  renderCurrentState = () => {
    if (this.state.authentificated) {
      return <Home />;
    } else {
      return <Welcome />;
    }
  };

  render() {
    return this.renderCurrentState();
  }
}

Welcome.js :

import React from "react";
import { StyleSheet, Text, Image } from "react-native";
import { LinearGradient } from "expo-linear-gradient";

import logo from "../../assets/icon.png";
import { Button, Icon, Container } from "native-base";
import { Actions } from "react-native-router-flux";
import { facebookLogin } from "../components/firebaseConfig";

export default class Welcome extends React.Component {
  render() {
    return (
      <LinearGradient
        colors={["#004aaf", "#000"]}
        style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
      >
        <Container style={styles.backgroundImage}>
          <Image source={logo} style={styles.logo}></Image>
          <Text style={styles.loginText}>
            ─── Se connecter / S'inscrire avec ───
          </Text>
          <Button
            light
            full
            rounded
            style={{ padding: 10 }}
            onPress={() => Actions.login()}
          >
            <Icon type="FontAwesome" name="envelope" />
            <Text>Mon adresse email</Text>
          </Button>
          <Button
            full
            rounded
            style={{ padding: 10, marginTop: 20 }}
            onPress={() =>
              facebookLogin().then(() => {
                this.setState({ authentificated: true });
              })
            }
          >
            <Icon type="FontAwesome" name="facebook" />
            <Text style={{ color: "#fff" }}>Mon compte Facebook</Text>
          </Button>
        </Container>
      </LinearGradient>
    );
  }
}
const styles = StyleSheet.create({
  backgroundImage: {
    flex: 1,
    width: "100%",
    height: "100%",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "transparent",
    padding: 25
  },
  logo: {
    width: 170,
    height: 130
  },
  loginText: {
    paddingTop: 50,
    paddingBottom: 50,
    color: "#fff"
  }
});

Body:
this.setState() should be called from inside the React component. You are wrongly calling it inside facebookLogin() and loginUser() functions.

You can fix it like this:

export async function loginUser(email, password) {
  try {
    return firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
  } catch (error) {
    console.log(error.toString);
  }
}

then in your component, you call

  loginUser().then(() => {
    this.setState({ authentificated: true });
  });

But please make sure the method where you call, this is properly bound.
The common practice is to define methods like this:

  renderCurrentState = () => {

  }

Otherwise you would have to do the binding in component's constructor:

 constructor(props) {
    super(props);

    // ...
    this.renderCurrentState = this.renderCurrentState.bind(this);
  }

What I have done is change loginUser() to return a promise. Then you use the function inside your component.

EDIT:

You can add a prop, eg. onLogin which you can use in Login component to update the authenticated state.

  renderCurrentState() {
    if (this.state.authentificated) {
      return <Welcome />;
    } else {
      return <EmailLoging onLogin={this.updateState} />;
    }
  }

  updateState = () => {
    this.setState({ authentificated: true });
    // possibly other code

  }

You should call onLogin on loginUser().then(() => { ... })