问:
singleton implementation question
```<code>template <class T>
class Singleton
{
public:
  static T& instance()
  {
    boost::call_once(init, flag);
    return *t;
  }

  static void init()
  {
    t.reset(new T());
  }

protected:
  ~Singleton() {}
   Singleton() {}

private:
   static boost::scoped_ptr <T> t;
   static boost::once_flag flag;
};

template <class T> boost::scoped_ptr<T> Singleton<T>::t(0);
template <class T> boost::once_flag Singleton<T>::flag = BOOST_ONCE_INIT;

class TestClass : public Singleton<TestClass>
{
  friend class Singleton<TestClass>;
  private:
     TestClass(){}
};
</code>```

For the above implemenation, I have a question below:

```<code>TestClass class1 = TestClass::instance();
TestClass class2 = TestClass::instance();
</code>```

I found &class1 != &class2, is this a singleton?

答:
```<code> TestClass class1 = TestClass::instance();
</code>```

You're making a copy of the object returned by the factory, so you get a different object each time.

To prevent this, get references to your singleton:

```<code> TestClass& class1 = TestClass::instance();
</code>```

Still there is something strange because making a copy of MyClass issues compiler error (it inherit from boost::noncopyable via Singleton, so I'm not sure how you can compiled the code you posted.

Title: singleton implementation question

Body:
template <class T>
class Singleton
{
public:
  static T& instance()
  {
    boost::call_once(init, flag);
    return *t;
  }

  static void init()
  {
    t.reset(new T());
  }

protected:
  ~Singleton() {}
   Singleton() {}

private:
   static boost::scoped_ptr <T> t;
   static boost::once_flag flag;
};

template <class T> boost::scoped_ptr<T> Singleton<T>::t(0);
template <class T> boost::once_flag Singleton<T>::flag = BOOST_ONCE_INIT;

class TestClass : public Singleton<TestClass>
{
  friend class Singleton<TestClass>;
  private:
     TestClass(){}
};

For the above implemenation, I have a question below:

TestClass class1 = TestClass::instance();
TestClass class2 = TestClass::instance();

I found &class1 != &class2, is this a singleton?

Body:
 TestClass class1 = TestClass::instance();

You're making a copy of the object returned by the factory, so you get a different object each time.

To prevent this, get references to your singleton:

 TestClass& class1 = TestClass::instance();

Still there is something strange because making a copy of MyClass issues compiler error (it inherit from boost::noncopyable via Singleton, so I'm not sure how you can compiled the code you posted.


来源: stackexchange

问:
mutate list of dataframes with another list
I've got a list of 17 dataframes and a list of 17 dates. They are ordered and correspond to each other. In other words, list_of_dfs[[1]] corresponds to dates[[1]] and so forth. The list of dates, below, are date objects using lubridate::ymd.

```<code>> dates
[1] "2004-10-10" "2005-10-10" "2006-10-10" "2007-10-10" "2008-10-10" "2009-10-10" "2010-10-10" "2011-10-10" "2012-10-10" "2013-10-10" "2014-10-10" "2015-10-10" "2016-10-10" "2017-10-10"
[15] "2018-10-10" "2019-10-10" "2020-10-10"
</code>```

I would like to mutate a subset of variables in each dataframe such that I am subtracting the subset from the corresponding object in dates. For example, I could do the following for the first item.

```<code>list_of_dfs[[1]] <- list_of_dfs[[1]] %>% `
  mutate_at(.vars = vars(contains('string')),
            .funs = funs(dates[[1]] - .)
</code>```

Is there a way that I incorporate the above into a map or lapply like command that will allow me to iterate through dates?

My closet approximation would be something like

```<code>list_of_dfs <- list_of_dfs %>%
      map(., function(x) mutate_at(x,
                               .vars = vars(contains('string')),
                               .funs =  funs(dates - .)))
</code>```

which can't take a list object in .funs as shown above.

答:
We can use map2 as we are doing the subtraction from corresponding elements of 'dates' list

```<code>library(dplyr)
library(purrr)
list_of_dfs2 <- map2(list_of_dfs, dates, ~ {date <- .y
                    .x   %>%
                          mutate_at(vars(contains('string')), ~ date - as.Date(.))})
</code>```

In the devel version of dplyr, across can be used along with mutate

```<code>list_of_dfs2 <- map2(list_of_dfs, dates, ~ { date <- .y
                 .x %>%
                    mutate(across(contains('string'), ~ date - as.Date(.x)))
   })
</code>```

data

```<code>list_of_dfs <- list(data.frame(string1 = Sys.Date() -   1:6, string2 = Sys.Date()),
          data.frame(string1 = Sys.Date() -   1:6, string2 = Sys.Date()))
dates <- Sys.Date() + 1:2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a list of 17 dataframes and a list of 17 dates. They are ordered and correspond to each other. In other words, list_of_dfs[[1]] corresponds to dates[[1]] and so forth. The list of dates, below, are date objects using lubridate::ymd.

> dates
[1] "2004-10-10" "2005-10-10" "2006-10-10" "2007-10-10" "2008-10-10" "2009-10-10" "2010-10-10" "2011-10-10" "2012-10-10" "2013-10-10" "2014-10-10" "2015-10-10" "2016-10-10" "2017-10-10"
[15] "2018-10-10" "2019-10-10" "2020-10-10"

I would like to mutate a subset of variables in each dataframe such that I am subtracting the subset from the corresponding object in dates. For example, I could do the following for the first item.

list_of_dfs[[1]] <- list_of_dfs[[1]] %>% `
  mutate_at(.vars = vars(contains('string')),
            .funs = funs(dates[[1]] - .)

Is there a way that I incorporate the above into a map or lapply like command that will allow me to iterate through dates?

My closet approximation would be something like

list_of_dfs <- list_of_dfs %>%
      map(., function(x) mutate_at(x,
                               .vars = vars(contains('string')),
                               .funs =  funs(dates - .)))

which can't take a list object in .funs as shown above.

Body:
We can use map2 as we are doing the subtraction from corresponding elements of 'dates' list

library(dplyr)
library(purrr)
list_of_dfs2 <- map2(list_of_dfs, dates, ~ {date <- .y
                    .x   %>%
                          mutate_at(vars(contains('string')), ~ date - as.Date(.))})

In the devel version of dplyr, across can be used along with mutate

list_of_dfs2 <- map2(list_of_dfs, dates, ~ { date <- .y
                 .x %>%
                    mutate(across(contains('string'), ~ date - as.Date(.x)))
   })

data

list_of_dfs <- list(data.frame(string1 = Sys.Date() -   1:6, string2 = Sys.Date()),
          data.frame(string1 = Sys.Date() -   1:6, string2 = Sys.Date()))
dates <- Sys.Date() + 1:2


问:
Spring Kafka Unit Tests Triggers the listener, but the method cannot get the message using consumer.poll
We are using spring-kafka-test-2.2.8-RELEASE.
When I use the template to send the message, it triggers the listener correctly, but I can't get the message content in the consumer.poll. If i instantiate the KafkaTemplate without "wiring" it in a class attribute and Instantiate it based on a producer factory, it sends the message, but does not trigger the @KafkaListener, only work if I setup a Message Listener inside the @Test Method. I need to trigger the kafka listener and realize which Topic will be called next("sucess" topic when executed without errors, and "errorTopic" the listener throws an Exception) and the message content.</p>

```<code>    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
    public class InvoicingServiceTest {

         @Autowired
         private NFKafkaListener nfKafkaListener;

         @ClassRule
         public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "tp-in-gco-mao-
         notasfiscais");

         @Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
         private String brokerAddresses;

         @Autowired
         private KafkaTemplate<Object, Object> template;

         @BeforeClass
         public static void setup() {
                System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
              "spring.kafka.bootstrap-servers");
         }

         @Test
         public void testTemplate() throws Exception {
               NFServiceTest nfServiceTest = spy(new NFServiceTest());

               nfKafkaListener.setNfServiceClient(nfServiceTest);
               Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker.getEmbeddedKafka());
               consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
               consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
               consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);
               consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

               DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
            consumerProps);

           Consumer<Integer, Object> consumer = cf.createConsumer();

           broker.getEmbeddedKafka().consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

           ZfifNfMao zf = new ZfifNfMao();
           zf.setItItensnf(new Zfietb011());

           Zfietb011 zfietb011 = new Zfietb011();
           Zfie011 zfie011 = new Zfie011();
           zfie011.setMatkl("TESTE");
           zfietb011.getItem().add(zfie011);
           zf.setItItensnf(zfietb011);

           template.send("tp-in-gco-mao-notasfiscais", zf);
           List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
           int n = 0;
           while (received.size() < 1 && n++ < 10) {
                ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
                //records1  is always empty
                if (!records1.isEmpty()) {
                    records1.forEach(rec -> received.add(rec));
                }
           }

           assertThat(received).extracting(rec -> {
               ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
               return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
            }).contains("TESTE");
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.shutdown());
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.awaitShutdown());
            consumer.close();
        }

        public static class NFServiceTest implements INFServiceClient {
            CountDownLatch latch = new CountDownLatch(1);

            @Override
            public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
                ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
                zfifNfMaoResponse.setItItensnf(new Zfietb011());

                Zfietb011 zfietb011 = new Zfietb011();
                Zfie011 zfie011 = new Zfie011();
                zfie011.setMatkl("TESTE");
                zfietb011.getItem().add(zfie011);
                zfifNfMaoResponse.setItItensnf(zfietb011);
                return zfifNfMaoResponse;
            }
        }
    }
</code>```

答:
I've followed your advice but it keeps triggering the listener, but consumer.poll does not capture the topic content.</p>

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
public class InvoicingServiceTest {

     @Autowired
     private NFKafkaListener nfKafkaListener;

 @Autowired
 public EmbeddedKafkaBroker broker;

 @Autowired
 private KafkaTemplate<Object, Object> template;

 @BeforeClass
 public static void setup() {
        System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
      "spring.kafka.bootstrap-servers");
 }

 @Test
 public void testTemplate() throws Exception {
       NFServiceTest nfServiceTest = spy(new NFServiceTest());

       nfKafkaListener.setNfServiceClient(nfServiceTest);
       Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker);
       consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
       consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
       consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);

       DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
    consumerProps);

   Consumer<Integer, Object> consumer = cf.createConsumer();

   broker.consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

   ZfifNfMao zf = new ZfifNfMao();
   zf.setItItensnf(new Zfietb011());

   Zfietb011 zfietb011 = new Zfietb011();
   Zfie011 zfie011 = new Zfie011();
   zfie011.setMatkl("TESTE");
   zfietb011.getItem().add(zfie011);
   zf.setItItensnf(zfietb011);

   template.send("tp-in-gco-mao-notasfiscais", zf);
   List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
   int n = 0;
   while (received.size() < 1 && n++ < 10) {
        ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
        //records1  is always empty
        if (!records1.isEmpty()) {
            records1.forEach(rec -> received.add(rec));
        }
   }

   assertThat(received).extracting(rec -> {
       ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
       return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
    }).contains("TESTE");
    broker.getKafkaServers().forEach(b -> b.shutdown());
    broker.getKafkaServers().forEach(b -> b.awaitShutdown());
    consumer.close();
}

public static class NFServiceTest implements INFServiceClient {
    CountDownLatch latch = new CountDownLatch(1);

    @Override
    public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
        ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
        zfifNfMaoResponse.setItItensnf(new Zfietb011());

        Zfietb011 zfietb011 = new Zfietb011();
        Zfie011 zfie011 = new Zfie011();
        zfie011.setMatkl("TESTE");
        zfietb011.getItem().add(zfie011);
        zfifNfMaoResponse.setItItensnf(zfietb011);
        return zfifNfMaoResponse;
    }
}
}
</code>```

Body:
We are using spring-kafka-test-2.2.8-RELEASE.
When I use the template to send the message, it triggers the listener correctly, but I can't get the message content in the consumer.poll. If i instantiate the KafkaTemplate without "wiring" it in a class attribute and Instantiate it based on a producer factory, it sends the message, but does not trigger the @KafkaListener, only work if I setup a Message Listener inside the @Test Method. I need to trigger the kafka listener and realize which Topic will be called next("sucess" topic when executed without errors, and "errorTopic" the listener throws an Exception) and the message content.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
    public class InvoicingServiceTest {

         @Autowired
         private NFKafkaListener nfKafkaListener;

         @ClassRule
         public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1, false, "tp-in-gco-mao-
         notasfiscais");

         @Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
         private String brokerAddresses;

         @Autowired
         private KafkaTemplate<Object, Object> template;

         @BeforeClass
         public static void setup() {
                System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
              "spring.kafka.bootstrap-servers");
         }

         @Test
         public void testTemplate() throws Exception {
               NFServiceTest nfServiceTest = spy(new NFServiceTest());

               nfKafkaListener.setNfServiceClient(nfServiceTest);
               Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker.getEmbeddedKafka());
               consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
               consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
               consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);
               consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

               DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
            consumerProps);

           Consumer<Integer, Object> consumer = cf.createConsumer();

           broker.getEmbeddedKafka().consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

           ZfifNfMao zf = new ZfifNfMao();
           zf.setItItensnf(new Zfietb011());

           Zfietb011 zfietb011 = new Zfietb011();
           Zfie011 zfie011 = new Zfie011();
           zfie011.setMatkl("TESTE");
           zfietb011.getItem().add(zfie011);
           zf.setItItensnf(zfietb011);

           template.send("tp-in-gco-mao-notasfiscais", zf);
           List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
           int n = 0;
           while (received.size() < 1 && n++ < 10) {
                ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
                //records1  is always empty
                if (!records1.isEmpty()) {
                    records1.forEach(rec -> received.add(rec));
                }
           }

           assertThat(received).extracting(rec -> {
               ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
               return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
            }).contains("TESTE");
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.shutdown());
            broker.getEmbeddedKafka().getKafkaServers().forEach(b -> b.awaitShutdown());
            consumer.close();
        }

        public static class NFServiceTest implements INFServiceClient {
            CountDownLatch latch = new CountDownLatch(1);

            @Override
            public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
                ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
                zfifNfMaoResponse.setItItensnf(new Zfietb011());

                Zfietb011 zfietb011 = new Zfietb011();
                Zfie011 zfie011 = new Zfie011();
                zfie011.setMatkl("TESTE");
                zfietb011.getItem().add(zfie011);
                zfifNfMaoResponse.setItItensnf(zfietb011);
                return zfifNfMaoResponse;
            }
        }
    }

Body:
I've followed your advice but it keeps triggering the listener, but consumer.poll does not capture the topic content.

@RunWith(SpringRunner.class)
@SpringBootTest
@EmbeddedKafka(partitions = 1, topics = { "tp-in-gco-mao-notasfiscais" })
public class InvoicingServiceTest {

     @Autowired
     private NFKafkaListener nfKafkaListener;

 @Autowired
 public EmbeddedKafkaBroker broker;

 @Autowired
 private KafkaTemplate<Object, Object> template;

 @BeforeClass
 public static void setup() {
        System.setProperty(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY,
      "spring.kafka.bootstrap-servers");
 }

 @Test
 public void testTemplate() throws Exception {
       NFServiceTest nfServiceTest = spy(new NFServiceTest());

       nfKafkaListener.setNfServiceClient(nfServiceTest);
       Map<String, Object> consumerProps =  KafkaTestUtils.consumerProps("teste9", "false", broker);
       consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
       consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
       consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, InvoiceDeserializer.class);

       DefaultKafkaConsumerFactory<Integer, Object> cf = new DefaultKafkaConsumerFactory<Integer, Object>(
    consumerProps);

   Consumer<Integer, Object> consumer = cf.createConsumer();

   broker.consumeFromAnEmbeddedTopic(consumer, "tp-in-gco-mao-notasfiscais");

   ZfifNfMao zf = new ZfifNfMao();
   zf.setItItensnf(new Zfietb011());

   Zfietb011 zfietb011 = new Zfietb011();
   Zfie011 zfie011 = new Zfie011();
   zfie011.setMatkl("TESTE");
   zfietb011.getItem().add(zfie011);
   zf.setItItensnf(zfietb011);

   template.send("tp-in-gco-mao-notasfiscais", zf);
   List<ConsumerRecord<Integer, Object>> received = new ArrayList<>();
   int n = 0;
   while (received.size() < 1 && n++ < 10) {
        ConsumerRecords<Integer, Object> records1 = consumer.poll(Duration.ofSeconds(10));
        //records1  is always empty
        if (!records1.isEmpty()) {
            records1.forEach(rec -> received.add(rec));
        }
   }

   assertThat(received).extracting(rec -> {
       ZfifNfMao zfifNfMaoRdesponse = (ZfifNfMao) rec.value();
       return zfifNfMaoRdesponse.getItItensnf().getItem().get(0).getMatkl();
    }).contains("TESTE");
    broker.getKafkaServers().forEach(b -> b.shutdown());
    broker.getKafkaServers().forEach(b -> b.awaitShutdown());
    consumer.close();
}

public static class NFServiceTest implements INFServiceClient {
    CountDownLatch latch = new CountDownLatch(1);

    @Override
    public ZfifNfMaoResponse enviarSap(ZfifNfMao zfifNfMao) {
        ZfifNfMaoResponse zfifNfMaoResponse = new ZfifNfMaoResponse();
        zfifNfMaoResponse.setItItensnf(new Zfietb011());

        Zfietb011 zfietb011 = new Zfietb011();
        Zfie011 zfie011 = new Zfie011();
        zfie011.setMatkl("TESTE");
        zfietb011.getItem().add(zfie011);
        zfifNfMaoResponse.setItItensnf(zfietb011);
        return zfifNfMaoResponse;
    }
}
}


问:
Using a 64 bit driver in a 32 bit program. Windows
This is only a half-way programming question. First of all I have a PCI-Express card and 32/64 bit drivers. The target operating system has to be a Windows 64 bit system. I read that under Vista64 all drivers have to be certified 64 bit drivers. Is this a general restriction under 64 bit operating systems and does this also apply to "XP 64" or any Linux system?

So for simplicity let's say I use a 64 bit driver for my PCIe card under Vista64 and have a bunch of 64 bit DLLs to use the cards functionality. On the other side there's a large, legacy 32 bit exe program which needs to use the PCIe device. Converting the program to 64 bit would be a really huge effort.

So what can be done to bring that 32 bit program and the 64 bit driver together? I read that mixing 32/64 bit binaries and DLLs is not possible at all but this is hard to believe for me. I'm sure you can print out a document under Vista64 from within a 32 bit app and Windows will somehow wrap this around to a 64 bit printer driver.

答:
Does your 32-bit application directly call the driver? (I'm guessing a simulator for the driver!)

The only way to communicate between 32-bit and 64-bit dlls is to write a COM server that manages the communication (read: wrap EITHER the applications calls OR the 64-bit driver responses) in between.

One thing that came back to bite me: When I first wrote this COM server (yes, I too had to bear many sleepless nights before I came to know of this trick) I only built the 32-bit version of the (auto-generated) proxy/stub dll. Another bout of sleepless nights ensued before I came to know of the solution: Build the proxy/stub dll for both 32-bit and 64-bit. The 32-bit side deals with the 32-bit side (in your case the application) and the 64-bit with the 64-bit side (the driver). COM manages how the differnt versions of the proxy/stub talk to each other. And oh, do get the server registered on your system. Easy, right?

OwnerDisplayName: asdrubael

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: asdrubael

OwnerDisplayName: dirkgently

LastEditorDisplayName: dirkgently


问:
TypeScript method in parent class access Type in subclass
I have one class:

```<code>export class DataAccess {
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: any, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}
</code>```

And a subclass:

```<code>import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess {
  columns: { [P in keyof UsersTable]: string };
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}
</code>```

And using the Users class:

```<code>await users.getWhere(
  {
    email: user,
    password
  },
  {
    single: true
  }
);
</code>```

How can I set the Type of where: any in the parent DataAccess Class, so it knows that its the Users subclass that's called it?

答:
It looks like you are only extending the class to get specialisation of the data shape. In that case, you could do something like this: </p>

```<code>class DataAccess<T> {
  columns: { [P in keyof T]: string };
  tableName: string;
  constructor({ tableName, columns }: { tableName: string, columns: { [P in keyof T]: string } }) {
    this.tableName = tableName;
    this.columns = columns;
  }
  async getWhere(where: Partial<T>, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

const user = new DataAccess<UsersTable>({tableName: ""users", columns: {
  id: "id",
  email: "email",
  password: "password",
  createdAt: "createdAt"
};})

</code>```

Body:
I have one class:

export class DataAccess {
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: any, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

And a subclass:

import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess {
  columns: { [P in keyof UsersTable]: string };
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}

And using the Users class:

await users.getWhere(
  {
    email: user,
    password
  },
  {
    single: true
  }
);

How can I set the Type of where: any in the parent DataAccess Class, so it knows that its the Users subclass that's called it?

Body:
It looks like you are only extending the class to get specialisation of the data shape. In that case, you could do something like this:

class DataAccess<T> {
  columns: { [P in keyof T]: string };
  tableName: string;
  constructor({ tableName, columns }: { tableName: string, columns: { [P in keyof T]: string } }) {
    this.tableName = tableName;
    this.columns = columns;
  }
  async getWhere(where: Partial<T>, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

const user = new DataAccess<UsersTable>({tableName: ""users", columns: {
  id: "id",
  email: "email",
  password: "password",
  createdAt: "createdAt"
};})


问:
MySQL geometry function, points and polygons
I have a table name 'polygon_csa', which has two columns 'element_id' as an integer and 'poly' as a four point polygon

I am trying to find which polygons enclose a point of my choice. I have tired the following code:

```<code>    Set @x = -60;
    Set @y = 10;

    set @xy=ST_geomfromtext(concat('Point (',@x, ' ', @y,')'));
    Select element_id from polygon_csa where ST_Contains(poly.polygons_csa,@xy);
</code>```

This returns error 1054 'unknown column Poly.polygons_csa in where clause'. I am running MySQL 5.7, is this a bug, or have I misunderstood the syntax?

I have also tried:

```<code>    set @xy=ST_geomfromtext(concat('Point (',@x, ' ', @y,')'));
    Select element_id from polygon_csa where (MRBContains(poly.polygons_csa,@xy));
</code>```

this also returns error 1054

答: MRBContains function can only return a 1 or 0 result so it is not suitable for this application, a procedure with an if statement is what is needed.</p>

Body:
I have a table name 'polygon_csa', which has two columns 'element_id' as an integer and 'poly' as a four point polygon

I am trying to find which polygons enclose a point of my choice. I have tired the following code:

    Set @x = -60;
    Set @y = 10;

    set @xy=ST_geomfromtext(concat('Point (',@x, ' ', @y,')'));
    Select element_id from polygon_csa where ST_Contains(poly.polygons_csa,@xy);

This returns error 1054 'unknown column Poly.polygons_csa in where clause'. I am running MySQL 5.7, is this a bug, or have I misunderstood the syntax?

I have also tried:

    set @xy=ST_geomfromtext(concat('Point (',@x, ' ', @y,')'));
    Select element_id from polygon_csa where (MRBContains(poly.polygons_csa,@xy));

this also returns error 1054


问:
fscanf() in C, format for varying length line
So I have a file which contains data in the form:

```<code>...
5,25,15,16,1,3,Dwyfor_Meirionnydd
5,34,33,26,12,22,Gower
5,7,28,35,4,23,Islwyn
2,20,12,Llanelli
5,4,5,17,7,21,Merthyr_Tydfil_and_Rhymney
5,5,4,35,28,27,Monmouth
4,5,14,19,15,Montgomeryshire
7,0,32,17,5,12,20,33,Neath
2,38,24,Newport_East
...
</code>```

And I need to read each line and put it in the structure such that the first unsigned integer is stored, the next n unsigned integers are stored in an array and then the string at the end is stored. So as an example the second line would be:

```<code>number-of-elements: 5
array: {34,33,26,12,22}
name: "Gower"
</code>```

The number tells us howmany items are in the array. I have a struct for this data. How would I go about creating a format for this?

答:
The scanf function doesn't support a variable number of formats.  You would need to change what you pass to the function based on the number of elements.

The best way to handle this is to read a line, then use strtok to split it into tokens, then use sscanf to parse out each individual element in a loop.

```<code>char line[100];
while (fgets(line, sizeof(line), fp)) {
    int count, i;
    int *array;
    char *name, *p;

    // read the count
    p = strtok(line, ",");
    sscanf(p, "%d", &count);

    // allocate space for the array
    array = malloc(count * sizeof(int));
    // read each element
    for (i=0; i<count; i++) {
        p = strtok(NULL, ",");
        sscanf(p, "%d", array + i);
    }

    // read the name
    p = strtok(NULL, "\n");
    name = strdup(p);

    // do something with count, array, and name
}
</code>```

Note that this assumes each line in the file is well formed and therefore doesn't validate the format.

Body:
So I have a file which contains data in the form:

...
5,25,15,16,1,3,Dwyfor_Meirionnydd
5,34,33,26,12,22,Gower
5,7,28,35,4,23,Islwyn
2,20,12,Llanelli
5,4,5,17,7,21,Merthyr_Tydfil_and_Rhymney
5,5,4,35,28,27,Monmouth
4,5,14,19,15,Montgomeryshire
7,0,32,17,5,12,20,33,Neath
2,38,24,Newport_East
...

And I need to read each line and put it in the structure such that the first unsigned integer is stored, the next n unsigned integers are stored in an array and then the string at the end is stored. So as an example the second line would be:

number-of-elements: 5
array: {34,33,26,12,22}
name: "Gower"

The number tells us howmany items are in the array. I have a struct for this data. How would I go about creating a format for this?

Body:
The scanf function doesn't support a variable number of formats.  You would need to change what you pass to the function based on the number of elements.

The best way to handle this is to read a line, then use strtok to split it into tokens, then use sscanf to parse out each individual element in a loop.

char line[100];
while (fgets(line, sizeof(line), fp)) {
    int count, i;
    int *array;
    char *name, *p;

    // read the count
    p = strtok(line, ",");
    sscanf(p, "%d", &count);

    // allocate space for the array
    array = malloc(count * sizeof(int));
    // read each element
    for (i=0; i<count; i++) {
        p = strtok(NULL, ",");
        sscanf(p, "%d", array + i);
    }

    // read the name
    p = strtok(NULL, "\n");
    name = strdup(p);

    // do something with count, array, and name
}

Note that this assumes each line in the file is well formed and therefore doesn't validate the format.


问:
Passing WebElement as parameter to implicit wait method
I wrote the below method in my Page.class for reusing implicit wait.

```<code>public WebDriver waitForElementToLoad(WebElement element)
{
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
        return (driver);
}
</code>```

In my test.class I am using page factory elements, for example:

```<code>//Save button
@FindBy(xpath = "//*[@*='Save']")
private WebElement saveButton;
</code>```

Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.

"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
  cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
  org.openqa.selenium.By are in unnamed module of loader 'app')"

I also tried

```<code>WebElement saveButton = driver.findElement(By.xpath("//*[@*='Save']"));
waitForElementToLoad(saveButton);
</code>```

but no luck.

How can I make this work?

答:
This error message...

```<code>java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and org.openqa.selenium.By are in unnamed module of loader 'app')
</code>```

...implies that the ClassCastException occured while trying to cast a proxy object.

You need to consider a few things as follows:

The wait you introduced within waitForElementToLoad() isn't implicit wait as such but an ExplicitWait. See: What is the internal working difference between Implicit Wait and Explicit Wait

presenceOfElementLocated() doesn't garuntees the visibility or interactablity of any element. So for visibility or interactablity you need to use the matching ExpectedConditions either visibilityOf(WebElement element) or elementToBeClickable(By locator). For details, see: Selenium: How selenium identifies elements visible or not? Is is possible that it is loaded in DOM but not rendered on UI?

If your usecase involves inducing WebDriverWait you pass the WebElement saveButton in the form of a proxy object within waitForElementToLoad() as follows:

```<code>package com.pol.zoho.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ZohoLoginPage {

    WebDriver driver;
    public ZohoLoginPage(WebDriver driver)
    {
    PageFactory.initElements(driver, this);
    }

    //Save button
    @FindBy(xpath = "//*[@*='Save']")
    private WebElement saveButton;

    public void waitForElementToLoad()
    {
    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
    saveButton.click();
    }

    public WebElement getWebElement()
    {
    return saveButton;
    }

}
</code>```

Reference

You can find a couple of relevant discussions in:

How to add explicit wait in PageFactory in PageObjectModel?

How to wait for invisibility of an element through PageFactory using Selenium and Java

Body:
I wrote the below method in my Page.class for reusing implicit wait.

public WebDriver waitForElementToLoad(WebElement element)
{
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
        return (driver);
}

In my test.class I am using page factory elements, for example:

//Save button
@FindBy(xpath = "//*[@*='Save']")
private WebElement saveButton;

Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.

"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
  cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
  org.openqa.selenium.By are in unnamed module of loader 'app')"

I also tried

WebElement saveButton = driver.findElement(By.xpath("//*[@*='Save']"));
waitForElementToLoad(saveButton);

but no luck.

How can I make this work?

Body:
This error message...

java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and org.openqa.selenium.By are in unnamed module of loader 'app')

...implies that the ClassCastException occured while trying to cast a proxy object.

You need to consider a few things as follows:

The wait you introduced within waitForElementToLoad() isn't implicit wait as such but an ExplicitWait. See: What is the internal working difference between Implicit Wait and Explicit Wait

presenceOfElementLocated() doesn't garuntees the visibility or interactablity of any element. So for visibility or interactablity you need to use the matching ExpectedConditions either visibilityOf(WebElement element) or elementToBeClickable(By locator). For details, see: Selenium: How selenium identifies elements visible or not? Is is possible that it is loaded in DOM but not rendered on UI?

If your usecase involves inducing WebDriverWait you pass the WebElement saveButton in the form of a proxy object within waitForElementToLoad() as follows:

package com.pol.zoho.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ZohoLoginPage {

    WebDriver driver;
    public ZohoLoginPage(WebDriver driver)
    {
    PageFactory.initElements(driver, this);
    }

    //Save button
    @FindBy(xpath = "//*[@*='Save']")
    private WebElement saveButton;

    public void waitForElementToLoad()
    {
    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
    saveButton.click();
    }

    public WebElement getWebElement()
    {
    return saveButton;
    }

}

Reference

You can find a couple of relevant discussions in:

How to add explicit wait in PageFactory in PageObjectModel?

How to wait for invisibility of an element through PageFactory using Selenium and Java


问:
Form's Apps Script returning Cannot read property 'value' of undefined error
I have a simple script to generate a doc and PDF upon form submission. I checked all of my code and have submitted a test form to test it out but I kept getting the error of 'values' being undefined when the script is trying to read from the spreadsheet result from the form.

I also tried adding the script in spreadsheet that stores the form submissioon result instead of the form, but I got the same error.

Can anybody points out what have I done wrong?

I set a trigger to execute the script upon form submission:

Here's my code:

function myFunction(e) {
  //e.values is an array of form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var title = e.values[3];
  Logger.log(e.values[0]);

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById('google-doc-template-file-id');

  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById('my-drive-folder-id')
  var copy = file.makeCopy(lastName + ',' + firstName, folder);

  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId());

  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody();

  //Then we call all of our replaceText methods
  body.replaceText('{{First name}}', firstName);
  body.replaceText('{{Last name}}', lastName);
  body.replaceText('{{Company}}', company);

  doc.getAs(pdf);
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose();
}
```

The error occured at line 3 - var timestamp = e.values[0];.

答:
I'm pretty sure I know the issue with your original script, as it came from an article on my site. There are two things that need to be changed if you want the original script to work:

The script needs to be bound to the spreadsheet accepting form responses, not the form itself.

You need to change the 'Event Source' on the trigger to 'from Spreadsheet' instead of 'from Form'

Body:
I have a simple script to generate a doc and PDF upon form submission. I checked all of my code and have submitted a test form to test it out but I kept getting the error of 'values' being undefined when the script is trying to read from the spreadsheet result from the form.

I also tried adding the script in spreadsheet that stores the form submissioon result instead of the form, but I got the same error.

Can anybody points out what have I done wrong?

I set a trigger to execute the script upon form submission:

Here's my code:

function myFunction(e) {
  //e.values is an array of form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var title = e.values[3];
  Logger.log(e.values[0]);

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById('google-doc-template-file-id');

  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById('my-drive-folder-id')
  var copy = file.makeCopy(lastName + ',' + firstName, folder);

  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId());

  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody();

  //Then we call all of our replaceText methods
  body.replaceText('{{First name}}', firstName);
  body.replaceText('{{Last name}}', lastName);
  body.replaceText('{{Company}}', company);

  doc.getAs(pdf);
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose();
}

The error occured at line 3 - var timestamp = e.values[0];.


问:
AS3 Render Shape to Bitmap with Antialias
I have a drawn a Circle Shape in AS3. I want to render the Circle into a Bitmap with nice/antialiased Edges. Because I want it to work on Mobile Devices (Air Apps are limited to stagequality = low) I need a workaround. Any custom shape to bitmap renderer available?</p>

答:
If it is only something simple as circle, you can synthesize smooth image pixel by pixel. Create BitmapData of sufficient size and loop on pixels. On every pixel, compute distance from center - if it less than circle radius - half of pixel diagonal, set pixel to circle color. If it greater than circle radius + half of pixel diagonal, call setPixel32(x, y, 0).

Pixels that won't pass both conditions are near the edge - to do exact antialiasing, you must compute how much of pixel is covered by circle. Maybe you can find some convincing simple approximation. Good luck!

Update:
OK, I think I can remember simpler approach... You can draw your circle or any shapes two times bigger than they should be, then draw that bitmap into another with scale 0.5 (set through matrix) and smoothing on. That would be supersampling 4x. If stage quality doesn't affect bitmap smoothing, it should work.

ContentLicense: CC BY-SA 3.0


问:
How to render local images in React js
I just want to render my local images which I have saved locally in my 'images' Folder. I Have imported the whole images folder. In my state I have added the Src properties ( Please see the image below). SomeWhere I am making very stupid mistake, I have tried to google and see some of the Youtube videos. But Nothing getting the answer I want. When i run the Code I dont see any image there. Any Help Will be Appreciated! Thanks</p>

```<code>import * as React from 'react';
import "../setStateFunctionExample/images/";
class ImageSlider extends React.Component {
    state= {
        images: [ {
            id: 1, src: "./images/image1.jpg", alt: "fruitLogo"
        }
        ,
        {
            id: 2, src: "./images/image2.jpg", alt: "fruitLogo1"
        }
        ,
        {
            id: 2, src: "./images/image3.jpg", alt: "fruitLogo2"
        }
        ],
        idx: 0
    }
    ;
    render() {
        return( <div> <h3>setState() example</h3> <img src= {
            this.state.images[0].src
        }
        alt= {
            this.state.images[0].alt
        }
        /> </div>)
    }
}

export default ImageSlider;

</code>```

答:
You can import images dynamically with require:</p>

```<code>state= {
    images: [ {
        id: 1, src: "image1.jpg", alt: "fruitLogo"
    }
    ,
    {
        id: 2, src: "image2.jpg", alt: "fruitLogo1"
    }
    ,
    {
        id: 2, src: "image3.jpg", alt: "fruitLogo2"
    }
    ],
    idx: 0
}

....
{this.state.images.map(item => <img src={require(`./images/${item.src}`)} />)}
</code>```

Title: How to render local images in React js

Body:
I just want to render my local images which I have saved locally in my 'images' Folder. I Have imported the whole images folder. In my state I have added the Src properties ( Please see the image below). SomeWhere I am making very stupid mistake, I have tried to google and see some of the Youtube videos. But Nothing getting the answer I want. When i run the Code I dont see any image there. Any Help Will be Appreciated! Thanks

import * as React from 'react';
import "../setStateFunctionExample/images/";
class ImageSlider extends React.Component {
    state= {
        images: [ {
            id: 1, src: "./images/image1.jpg", alt: "fruitLogo"
        }
        ,
        {
            id: 2, src: "./images/image2.jpg", alt: "fruitLogo1"
        }
        ,
        {
            id: 2, src: "./images/image3.jpg", alt: "fruitLogo2"
        }
        ],
        idx: 0
    }
    ;
    render() {
        return(

setState() example

)
    }
}

export default ImageSlider;

Body:
You can import images dynamically with require:

state= {
    images: [ {
        id: 1, src: "image1.jpg", alt: "fruitLogo"
    }
    ,
    {
        id: 2, src: "image2.jpg", alt: "fruitLogo1"
    }
    ,
    {
        id: 2, src: "image3.jpg", alt: "fruitLogo2"
    }
    ],
    idx: 0
}

....
{this.state.images.map(item => <img src={require(`./images/${item.src}`)} />)}


问:
Kafka connect MongoDB Kafka connector using JSONConverter not working
I'm trying to configure the Kafka connector to use mongoDB as the source and send the records into Kakfa topics.
I've successfully done so, but I'm trying to do it with the JSONConverter in order to also save the schema with the payload.

My problem is that the connector is saving the data as follows:

```<code>{ "schema": { "type": "string" } , "payload": "{....}" }
</code>```

In other words, it's automatically assuming the actual JSON is a string and it's saving the schema as String.

This is how I'm setting up the connector:

```<code>curl -X POST http://localhost:8083/connectors -H "Content-Type: application/json" -d '{
 "name": "newtopic",
 "config": {
"tasks.max":1,
 "connector.class":"com.mongodb.kafka.connect.MongoSourceConnector",
 "key.converter":"org.apache.kafka.connect.json.JsonConverter",
 "key.converter.schemas.enabled": "true",
 "value.converter":"org.apache.kafka.connect.json.JsonConverter",
 "value.converter.schemas.enabled": "true",
 "connection.uri":"[MONGOURL]",
 "database":"dbname",
 "collection":"collname",
 "pipeline":"[]",
 "topic.prefix": "",
 "publish.full.document.only": "true"
 }}'
</code>```

Am I missing something for the configuration? Is it simply not able to guess the schema of the document stored in MongoDB, so it goes with String?

答:
There's nothing to guess. Mongo is schemaless, last I checked, so the schema is a string or bytes. I would suggest using AvroConverter or setting schema enabled to false </p>

<p>You may also want to try using Debezium to see if you get different results </p>

Body:
I'm trying to configure the Kafka connector to use mongoDB as the source and send the records into Kakfa topics.
I've successfully done so, but I'm trying to do it with the JSONConverter in order to also save the schema with the payload.

My problem is that the connector is saving the data as follows:

{ "schema": { "type": "string" } , "payload": "{....}" }

In other words, it's automatically assuming the actual JSON is a string and it's saving the schema as String.

This is how I'm setting up the connector:

curl -X POST http://localhost:8083/connectors -H "Content-Type: application/json" -d '{
 "name": "newtopic",
 "config": {
"tasks.max":1,
 "connector.class":"com.mongodb.kafka.connect.MongoSourceConnector",
 "key.converter":"org.apache.kafka.connect.json.JsonConverter",
 "key.converter.schemas.enabled": "true",
 "value.converter":"org.apache.kafka.connect.json.JsonConverter",
 "value.converter.schemas.enabled": "true",
 "connection.uri":"[MONGOURL]",
 "database":"dbname",
 "collection":"collname",
 "pipeline":"[]",
 "topic.prefix": "",
 "publish.full.document.only": "true"
 }}'

Am I missing something for the configuration? Is it simply not able to guess the schema of the document stored in MongoDB, so it goes with String?

Body:
There's nothing to guess. Mongo is schemaless, last I checked, so the schema is a string or bytes. I would suggest using AvroConverter or setting schema enabled to false

You may also want to try using Debezium to see if you get different results


问:
Excel Vlookup Formula
Hello Excel Vlookup Experts,

I am trying to get a VLOOKUP formula to do the following.  Using the columns E, F, and G as references, I am trying to populate data to column C. Column A and B must match column E and F to populate column C.  Notice that column B has hours with the Date.  I just want the data from column C to populate regardless of the hour, if it matches(Column A and B must match column E and F).

End result as shown:

答:
This one should do it, make sure to apply it with Ctrl + Shift + Enter

```<code>=INDEX($G$2:$G$21,MATCH(A1&ROUND(B1,0),$E$2:$E$21&$F$2:$FE$21,0))
</code>```

Title: Excel Vlookup Formula

Body:
This one should do it, make sure to apply it with Ctrl + Shift + Enter

=INDEX($G$2:$G$21,MATCH(A1&ROUND(B1,0),$E$2:$E$21&$F$2:$FE$21,0))


问:
No-crop canvas increase to 2:1 aspect ratio with ImageMagick
I am in a situation where I have a set of images with variable width and height and I need to ensure that those images comply with an aspect ratio of 2:1.

The only assumption I can make is that those images have an aspect ratio greater than 2 so I need to expand the canvas.

With ImageMagick I can do this:

magick input.jpg -background black -gravity north -extent 2:1 output.jpg

But this crops instead of adding canvas as desired. Is there an option to avoid cropping, i.e. force image padding? Remember I do not know the image resolution beforehand.

Of course with a more complex script I can extract the image dimensions and compute the desired resolution but I am trying to keep things simple if possible.

P.S.: The images comes from a laser scanner and are going to be used in a 360 panorama viewer hence the need to meet an aspect ration without cropping.

答:
With ImageMagick v7 you can do some inline calculations that will adjust the results of the -extent operation to pad any size input to a 2:1 ratio. See this command as an example...

```<code>magick input.png -gravity center -extent "%[fx:max(w,h*2)]x%[fx:max(w/2,h)]" result.png
</code>```

That will pad any extra space with black. Add -background <somecolor> before the extent operation to change the padding color.

Body:
With ImageMagick v7 you can do some inline calculations that will adjust the results of the -extent operation to pad any size input to a 2:1 ratio. See this command as an example...

magick input.png -gravity center -extent "%[fx:max(w,h*2)]x%[fx:max(w/2,h)]" result.png

That will pad any extra space with black. Add -background <somecolor> before the extent operation to change the padding color.


问:
Make parent div behind child element
I'm using jQuery.Gantt in a project and I need do many customization in this plugin.

One of this is pass mouse over an element (blue cells) and show a tooltip (in example I put a title).

I have some divs that "highlight" weekends and these divs is over gantt elements (blue cells)

If I change z-index of cells they will overlay the header (month and day) in horizontal scroll.
I trying to find a way to get the following order: weekend div with z-index 0, gantt cells (blue) with z-index 1 and header with z-index 2. I need this order to display the title on gantt cells and use mouseover event on weekend cells.

How can I achieve this with the example below?

.dataPanel {
  outline: 1px solid #DDD;
  background-position-y: 15px;
  background-size: 30px 48px;
  background-image: linear-gradient(to left, rgba(153, 152, 153, 0.7) 1px, transparent 1px), linear-gradient(0deg, #E7ECEF 0%, #E7ECEF 53%, #ECF1F4 53%, #ECF1F4 100%);
  background-repeat: repeat;
  position: relative;
  font-family: 'Verdana, sans-serif';
}

.header {
  position: sticky;
  top: 0;
  z-index: 600;
  width: 241px;
  background: #fff;
  height: 63px;
}

.row {
  float: left;
  height: 24px;
  line-height: 24px;
  margin: 0;
}

.dayPosition {
  top: 46px;
}

.monthPosition {
  top: 15px;
}

.day {
  background-color: #fff;
  width: 24px;
  line-height: 24px;
  text-align: center;
  border-bottom: 1px solid #DDD;
  border-right: 1px solid #DDD;
  font-size: 10px;
  color: #007E7A;
}

.row .sa,
.row .sn,
.row .wd {
  height: 24px;
  text-align: center;
  width: 29px;
}

.bar {
  background-color: #D0E4FD;
  height: 18px;
  margin: 0 3px 3px 0;
  position: absolute;
  text-align: center;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.25) inset;
  border-radius: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dataPanel" style="width: 27540px; height: 732px;">
<div class="header">
 <div class="row header monthPosition">
  JAN
 </div>
    <div class="row header dayPosition">
        <div class="row day wd" id="dw-1559098800000" data-repdate="1559098800000">
            <div class="fn-label">WED</div>
        </div>
        <div class="row day wd" id="dw-1559185200000" data-repdate="1559185200000">
            <div class="fn-label">THU</div>
        </div>
        <div class="row day wd" id="dw-1559271600000" data-repdate="1559271600000">
            <div class="fn-label">FRI</div>
        </div>
        <div class="row day sa" id="dw-1559358000000" data-repdate="1559358000000">
            <div class="fn-label">SAT</div>
   <div style="background-color: rgba(100, 100, 100, 0.1); height: 673px; width: 30px; bottom: 0px; top: 245px; position: initial;"></div>
        </div>
        <div class="row day sn" id="dw-1559444400000" data-repdate="1559444400000">
            <div class="fn-label">SUN</div>
            <div style="background-color: rgba(100, 100, 100, 0.1); height: 673px; width: 30px; bottom: 0px; top: 245px; position: initial;"></div>
        </div>
        <div class="row day wd" id="dw-1559530800000" data-repdate="1559530800000">
            <div class="fn-label">MON</div>
        </div>
        <div class="row day wd" id="dw-1559617200000" data-repdate="1559617200000">
            <div class="fn-label">TUE</div>
        </div>
        <div class="row day wd" id="dw-1559703600000" data-repdate="1559703600000">
            <div class="fn-label">WED</div>
        </div>
 </div>
</div>
<div title="Saturday" class="bar" style="top: 63px; left: 90px; width: 29px;"><div class="fn-label">24</div></div>
<div title="Sunday" class="bar" style="top: 63px; left: 120px; width: 29px;"><div class="fn-label">24</div></div>
<div title="Monday" class="bar" style="top: 63px; left: 150px; width: 29px;"><div class="fn-label">24</div></div>
<div title="Tuesday" class="bar" style="top: 63px; left: 180px; width: 29px;"><div class="fn-label">24</div></div>
</div></code>```

Code in JSFiddle

答: You just need to add pointer-events: none; to the overlay div.

Title: Make parent div behind child element

Body:
I'm using jQuery.Gantt in a project and I need do many customization in this plugin.

One of this is pass mouse over an element (blue cells) and show a tooltip (in example I put a title).

I have some divs that "highlight" weekends and these divs is over gantt elements (blue cells)

If I change z-index of cells they will overlay the header (month and day) in horizontal scroll.
I trying to find a way to get the following order: weekend div with z-index 0, gantt cells (blue) with z-index 1 and header with z-index 2. I need this order to display the title on gantt cells and use mouseover event on weekend cells.

How can I achieve this with the example below?

.dataPanel {
  outline: 1px solid #DDD;
  background-position-y: 15px;
  background-size: 30px 48px;
  background-image: linear-gradient(to left, rgba(153, 152, 153, 0.7) 1px, transparent 1px), linear-gradient(0deg, #E7ECEF 0%, #E7ECEF 53%, #ECF1F4 53%, #ECF1F4 100%);
  background-repeat: repeat;
  position: relative;
  font-family: 'Verdana, sans-serif';
}

.header {
  position: sticky;
  top: 0;
  z-index: 600;
  width: 241px;
  background: #fff;
  height: 63px;
}

.row {
  float: left;
  height: 24px;
  line-height: 24px;
  margin: 0;
}

.dayPosition {
  top: 46px;
}

.monthPosition {
  top: 15px;
}

.day {
  background-color: #fff;
  width: 24px;
  line-height: 24px;
  text-align: center;
  border-bottom: 1px solid #DDD;
  border-right: 1px solid #DDD;
  font-size: 10px;
  color: #007E7A;
}

.row .sa,
.row .sn,
.row .wd {
  height: 24px;
  text-align: center;
  width: 29px;
}

.bar {
  background-color: #D0E4FD;
  height: 18px;
  margin: 0 3px 3px 0;
  position: absolute;
  text-align: center;
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.25) inset;
  border-radius: 3px;
}

  JAN

WED

THU

FRI

SAT

SUN

MON

TUE

WED

24

24

24

24

Code in JSFiddle


问:
WebDriverException: 'chromedriver.exe' executable may have wrong permissions
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

```<code>chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)
</code>```

The Error

```<code>Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code>```

And if I change the code and place '' around chromedriver like this

```<code>chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
</code>```

I get this

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

```<code>chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
</code>```

And it seems to maybe pass it? As now I am on to this error :

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

```<code> if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())
</code>```

答:
Here is part of a little script I made to login and check for new questions on here. It is in a different library in C# but maybe it is still relevant and will help you discover the issue. Anyways the code is below hope it helps.

The only thing you aren't doing that I am is setting the BinaryLocation on the ChromeOptions and I am discovering the driver directory at run-time.

Also, sometimes the error messages like those are caused by exactly what they say is wrong. Maybe in order to run the selenium driver it may require more elevated windows permissions like when you right click and say run as administrator on programs sometimes. Have you tried running the terminal/command line that you are trying to run the python script on as an admin?

```<code>ChromeOptions options = new ChromeOptions();
options.BinaryLocation = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";

using (IWebDriver driver = new ChromeDriver(GetChromeDriverDirectory(), options))
{
    driver.NavigateToUrl("https://stackoverflow.com/questions/tagged?sort=Newest&filters=NoAnswers&tagMode=Watched");
}

// Here is the method I use to get the Chrome driver directory.
private static string GetChromeDriverDirectory() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
</code>```

Body:
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

The Error

Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

And if I change the code and place '' around chromedriver like this

chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

I get this

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

And it seems to maybe pass it? As now I am on to this error :

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

 if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())

Body:
Here is part of a little script I made to login and check for new questions on here. It is in a different library in C# but maybe it is still relevant and will help you discover the issue. Anyways the code is below hope it helps.

The only thing you aren't doing that I am is setting the BinaryLocation on the ChromeOptions and I am discovering the driver directory at run-time.

Also, sometimes the error messages like those are caused by exactly what they say is wrong. Maybe in order to run the selenium driver it may require more elevated windows permissions like when you right click and say run as administrator on programs sometimes. Have you tried running the terminal/command line that you are trying to run the python script on as an admin?

ChromeOptions options = new ChromeOptions();
options.BinaryLocation = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";

using (IWebDriver driver = new ChromeDriver(GetChromeDriverDirectory(), options))
{
    driver.NavigateToUrl("https://stackoverflow.com/questions/tagged?sort=Newest&filters=NoAnswers&tagMode=Watched");
}

// Here is the method I use to get the Chrome driver directory.
private static string GetChromeDriverDirectory() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);


问:
C#: Drawing a timestamp onto an image
I was just browsing some questions when I stumbled upon this one. I am not experienced in System.Drawing, so I'm just wondering, how would you draw a timestamp onto an image? Also, as I'm very interested in System.Drawing, what are the best resources for learning how to use it well, and its application in various situations? Thank you!</p>

答:
I am using the code below to do this.  It has a format parameter which you can use to specify how you want the timestamp to look.  It also puts a black rectangle behind the timestamp for readability.</p>

```<code>    protected void Stamp(Bitmap b, DateTime dt, string format)
    {
        string stampString;

        if (!string.IsNullOrEmpty(format)) { stampString = dt.ToString(format); }
        else { stampString = dt.ToString(); }

        Graphics g = Graphics.FromImage(b);
        g.FillRectangle(Brushes.Black, 0, 0, b.Width, 20);

        g.DrawString(stampString, new Font("Arial", 12f), Brushes.White, 2, 2);
    }
</code>```

Title: C#: Drawing a timestamp onto an image

Body:
I am using the code below to do this.  It has a format parameter which you can use to specify how you want the timestamp to look.  It also puts a black rectangle behind the timestamp for readability.

    protected void Stamp(Bitmap b, DateTime dt, string format)
    {
        string stampString;

        if (!string.IsNullOrEmpty(format)) { stampString = dt.ToString(format); }
        else { stampString = dt.ToString(); }

        Graphics g = Graphics.FromImage(b);
        g.FillRectangle(Brushes.Black, 0, 0, b.Width, 20);

        g.DrawString(stampString, new Font("Arial", 12f), Brushes.White, 2, 2);
    }


问:
Is Python 3 continue loop statement a problem in compute methods in Odoo 13?
I am migrating a module to version 13.0, which uses continue in a loop inside a compute method, and an error was driving me crazy for a while.

I simplified the code to the minimum until I had this kind of nosense:

```<code>@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })
</code>```

But I was still receiving the error, which by the way was this (and only was shown when creating new pickings):

```<code>stock.picking(<NewId 0x7f5404ba5eb8>,).amount_untaxed
</code>```

So I realised that the problem was the continue statement, if I removed it, it worked. And I tried to use continue in several loops of other compute methods of standard Odoo modules, with same result.

Until now, if you did not assign a value for a field in a computed method, it automatically took False, so continue was not a problem.

Does anyone experience this problem with continue too?

答:
It is required to set value for each record set. If we use continue and don't set value for that specific recordset, will get issue as you mentioned.

Try with following code:

```<code>@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        amount_untaxed = 0.0
        if picking.picking_type_id.code == 'internal':
            amount_untaxed = 3.0
        picking.update({
            'amount_untaxed': amount_untaxed,
        })
</code>```

Continue will work if we do code something like:

```<code>@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        picking.update({
            'amount_untaxed': 0.0,
        })
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })
</code>```

Body:
I am migrating a module to version 13.0, which uses continue in a loop inside a compute method, and an error was driving me crazy for a while.

I simplified the code to the minimum until I had this kind of nosense:

@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })

But I was still receiving the error, which by the way was this (and only was shown when creating new pickings):

stock.picking(<NewId 0x7f5404ba5eb8>,).amount_untaxed

So I realised that the problem was the continue statement, if I removed it, it worked. And I tried to use continue in several loops of other compute methods of standard Odoo modules, with same result.

Until now, if you did not assign a value for a field in a computed method, it automatically took False, so continue was not a problem.

Does anyone experience this problem with continue too?

Body:
It is required to set value for each record set. If we use continue and don't set value for that specific recordset, will get issue as you mentioned.

Try with following code:

@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        amount_untaxed = 0.0
        if picking.picking_type_id.code == 'internal':
            amount_untaxed = 3.0
        picking.update({
            'amount_untaxed': amount_untaxed,
        })

Continue will work if we do code something like:

@api.depends('move_lines', 'move_lines.price_subtotal')
def _compute_subtotal(self):
    for picking in self:
        picking.update({
            'amount_untaxed': 0.0,
        })
        if picking.picking_type_id.code not in ['incoming', 'outgoing']:
            continue
        picking.update({
            'amount_untaxed': 3.0,
        })


问:
How to save Powershell's output to file when I create synthetic voice audio with Text-to-Speech using the command line
please teach me how to make Powershell automatically save its tts output to TEXT file, as I'm getting just a long string like this:

{
  "audioContent": "//NExAAQ4oIMABhEuDRESizqE7uehfMY8A...........

I have to process more than 1400 files :( what to do?
Also is there a way to upload text more than 5000 symbols long?
Also is it possible to automatically create SSML from HTML?

I've made everything as described in this Document

答:
I'm still not quite sure what you mean here.. Are you saying that you have a lot of text files that now have content { "audioContent": "//NExAAQ4oIMABhEuDRESizqE7uehfMY8A........... and you need to replace that content with just the part between the curly brackets?

If that is the case, you can do

```<code>Get-ChildItem -Path 'ThePathToLookForTheFiles' -File | ForEach-Object {
    $_ | Set-Content -Value (($_ | Get-Content -Raw) -replace '^\{\s*"audioContent":\s*"([^}]+)\}', '$1')
}
</code>```

For any new textfile, change the code from here a bit by capturing the result from the Invoke-WebRequest and saving the audioContent property to text file:

```<code>$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

$params = @{
    Method      = 'POST'
    Headers     = $headers
    ContentType = "application/json; charset=utf-8"
    InFile      = 'request.json'
    Uri         = "https://texttospeech.googleapis.com/v1/text:synthesize"
}

$content = Invoke-WebRequest @params | Select-Object -Expand Content
# save the textfile with just the base64 string:
Set-Content -Path 'TheFullPathAndFileName' -Value $content.audioContent
</code>```

Hope that helps

Body:
I'm still not quite sure what you mean here.. Are you saying that you have a lot of text files that now have content { "audioContent": "//NExAAQ4oIMABhEuDRESizqE7uehfMY8A........... and you need to replace that content with just the part between the curly brackets?

If that is the case, you can do

Get-ChildItem -Path 'ThePathToLookForTheFiles' -File | ForEach-Object {
    $_ | Set-Content -Value (($_ | Get-Content -Raw) -replace '^\{\s*"audioContent":\s*"([^}]+)\}', '$1')
}

For any new textfile, change the code from here a bit by capturing the result from the Invoke-WebRequest and saving the audioContent property to text file:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

$params = @{
    Method      = 'POST'
    Headers     = $headers
    ContentType = "application/json; charset=utf-8"
    InFile      = 'request.json'
    Uri         = "https://texttospeech.googleapis.com/v1/text:synthesize"
}

$content = Invoke-WebRequest @params | Select-Object -Expand Content
# save the textfile with just the base64 string:
Set-Content -Path 'TheFullPathAndFileName' -Value $content.audioContent

Hope that helps


问:
How to convert date to timestamp in PHP?
How do I get timestamp from e.g. 22-09-2008?

答:
With DateTime API:

```<code>$dateTime = new DateTime('2008-09-22');
echo $dateTime->format('U');

// or

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();
</code>```

The same with the procedural API:

```<code>$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);
</code>```

If the above fails because you are using a unsupported format, you can use

```<code>$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U');

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');
</code>```

Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

Yet another alternative is to use the IntlDateFormatter API:

```<code>$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');
</code>```

Unless you are working with localized date strings, the easier choice is likely DateTime.

Body:
With DateTime API:

$dateTime = new DateTime('2008-09-22');
echo $dateTime->format('U');

// or

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();

The same with the procedural API:

$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);

If the above fails because you are using a unsupported format, you can use

$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U');

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');

Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

Yet another alternative is to use the IntlDateFormatter API:

$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');

Unless you are working with localized date strings, the easier choice is likely DateTime.


问:
How to get user's full DN in Spring Data LDAP repositories
I'm creating an extension to a user management application that maintains users in an OpenLDAP server for authentication (in addition to an internal database) using the Spring Data Ldap repositories as the application is already using Spring 5 and Spring Data repositories.

The basic User and Group repositories work for finding, creating and updating, with one exception: group membership, because the member attribute requires a full DN (distinguished name) and unfortunately the user repository's @Id key is a relative DN.

```
My Ldap base is              "dc=example,dc=com"
The UserRepository returns   "cn=user1,ou=users"
but I need the full DN:      "cn=user1,ou=users,dc=example,dc=com"
```

The base name is loaded in a ContextSource from ApplicationConfig.java, but since the repositories are generated dynamically and I have defined only an interface, I don't know how to inject that or the property and write code using it.

I have not found any method that returns the full DN. I have found what looks like a solution through this question and the user admin example from Spring LDAP. However this involves falling back on the Spring LDAP LdapTemplate, which is a step back from the Spring Data LDAP repositories to a more generic query model. Also, I can't get the example to build or run by itself due to dependency conflicts, so I'm worried about the longevity of a solution that mixes Spring Data LDAP and Spring Ldap Templates.

What I'm looking for is any way to retrieve the full DN or the base name from within the User, Group or their repository classes, so that I can supply these when adding members to a group or looking for groups for a member.

答:
After some trials and many errors, I've found a decently clean way to obtain the Ldap base path, injecting the ContextSource as defined in ApplicationConfig also in the Service class. For anyone else looking for this:

ApplicationConfig.java

```<code>@Configuration
@PropertySource("classpath:ldap.properties")

...

@Value("${ldap.url}") String ldapUrl;
@Value("${ldap.base}") String ldapBase;
@Value("${ldap.user}") String ldapUser;
@Value("${ldap.password}") String ldapPassword;

@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUser);
    contextSource.setPassword(ldapPassword);
    return contextSource;
}

@Bean
LdapTemplate ldapTemplate(ContextSource contextSource) {
    return new LdapTemplate(contextSource);
}
</code>```

MyServiceImpl.java

```<code>@Repository
@Transactional
public class MyServiceImpl implements MyService {

    @Autowired
    private LdapUserRepository userRepository;

    @Autowired
    private LdapGroupRepository groupRepository;

    @Autowired
    LdapContextSource contextSource;

    ...

    @Override
    public Collection<LdapGroup> findGroupByMember(Name name) {
        LdapName dName = LdapUtils.prepend(LdapUtils.removeFirst(name,
            contextSource.getBaseLdapName()), contextSource.getBaseLdapName());

        return groupRepository.findByMember(dName);
    }
}
</code>```

With the help of LdapUtils methods to remove and prepend the base path, I can clean up any incoming name to the full DN. This keeps the LdapGroupRepository simple, with only an interface class and the rest done by Spring Data LDAP:

LdapGroupRepository.java

```<code>public interface LdapGroupRepository extends LdapRepository<LdapGroup> {

    Optional<LdapGroup> findByName(String groupName);

    @Query("(member={0})")
    Collection<LdapGroup> findByMember(Name member);
}
</code>```

Body:
I'm creating an extension to a user management application that maintains users in an OpenLDAP server for authentication (in addition to an internal database) using the Spring Data Ldap repositories as the application is already using Spring 5 and Spring Data repositories.

The basic User and Group repositories work for finding, creating and updating, with one exception: group membership, because the member attribute requires a full DN (distinguished name) and unfortunately the user repository's @Id key is a relative DN.

My Ldap base is              "dc=example,dc=com"
The UserRepository returns   "cn=user1,ou=users"
but I need the full DN:      "cn=user1,ou=users,dc=example,dc=com"

The base name is loaded in a ContextSource from ApplicationConfig.java, but since the repositories are generated dynamically and I have defined only an interface, I don't know how to inject that or the property and write code using it.

I have not found any method that returns the full DN. I have found what looks like a solution through this question and the user admin example from Spring LDAP. However this involves falling back on the Spring LDAP LdapTemplate, which is a step back from the Spring Data LDAP repositories to a more generic query model. Also, I can't get the example to build or run by itself due to dependency conflicts, so I'm worried about the longevity of a solution that mixes Spring Data LDAP and Spring Ldap Templates.

What I'm looking for is any way to retrieve the full DN or the base name from within the User, Group or their repository classes, so that I can supply these when adding members to a group or looking for groups for a member.

Body:
After some trials and many errors, I've found a decently clean way to obtain the Ldap base path, injecting the ContextSource as defined in ApplicationConfig also in the Service class. For anyone else looking for this:

ApplicationConfig.java

@Configuration
@PropertySource("classpath:ldap.properties")

...

@Value("${ldap.url}") String ldapUrl;
@Value("${ldap.base}") String ldapBase;
@Value("${ldap.user}") String ldapUser;
@Value("${ldap.password}") String ldapPassword;

@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(ldapUrl);
    contextSource.setBase(ldapBase);
    contextSource.setUserDn(ldapUser);
    contextSource.setPassword(ldapPassword);
    return contextSource;
}

@Bean
LdapTemplate ldapTemplate(ContextSource contextSource) {
    return new LdapTemplate(contextSource);
}

MyServiceImpl.java

@Repository
@Transactional
public class MyServiceImpl implements MyService {

    @Autowired
    private LdapUserRepository userRepository;

    @Autowired
    private LdapGroupRepository groupRepository;

    @Autowired
    LdapContextSource contextSource;

    ...

    @Override
    public Collection<LdapGroup> findGroupByMember(Name name) {
        LdapName dName = LdapUtils.prepend(LdapUtils.removeFirst(name,
            contextSource.getBaseLdapName()), contextSource.getBaseLdapName());

        return groupRepository.findByMember(dName);
    }
}

With the help of LdapUtils methods to remove and prepend the base path, I can clean up any incoming name to the full DN. This keeps the LdapGroupRepository simple, with only an interface class and the rest done by Spring Data LDAP:

LdapGroupRepository.java

public interface LdapGroupRepository extends LdapRepository<LdapGroup> {

    Optional<LdapGroup> findByName(String groupName);

    @Query("(member={0})")
    Collection<LdapGroup> findByMember(Name member);
}


问:
How to collapse multiple variables by column in csv file with R
I've written code to collapse my table, and it works, however whenever I write to a new csv the table seems to not be in the collapsed state. Perhaps this has to do with the summarize function I am using? I am collapsing variables d1, d2, d3 for region_ID. Is there a way for me put all 3 variables together and save to a new csv?

```<code>#Collapse the bsu_re_dec.csv table

HI_csv<- read.csv("C:\\filepath\\bsu_re_dec.csv")

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d1))

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d2))

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d3))
</code>```

答:
We can use summarise_at to summarise multiple variables

```<code>library(dplyr)
HI_csv %>%
     group_by(region_ID) %>%
     summarise_at(vars(matches('^d\\d+$')), sum)
</code>```

In the devel version of dplyr, another option is across with `summarise

```<code>HI_csv %>%
     group_by(region_ID) %>%
     summarise(across(matches('^d\\d+'), sum))
</code>```

Or with a reproducible example

```<code>iris %>%
    group_by(Species) %>%
    summarise(across(everything(), sum))
# A tibble: 3 x 5
#  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
#  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
#1 setosa             250.        171.         73.1        12.3
#2 versicolor         297.        138.        213          66.3
#3 virginica          329.        149.        278.        101.
</code>```

Body:
I've written code to collapse my table, and it works, however whenever I write to a new csv the table seems to not be in the collapsed state. Perhaps this has to do with the summarize function I am using? I am collapsing variables d1, d2, d3 for region_ID. Is there a way for me put all 3 variables together and save to a new csv?

#Collapse the bsu_re_dec.csv table

HI_csv<- read.csv("C:\\filepath\\bsu_re_dec.csv")

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d1))

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d2))

HI_csv %>%
group_by(region_ID) %>%
summarize(sum(d3))

Body:
We can use summarise_at to summarise multiple variables

library(dplyr)
HI_csv %>%
     group_by(region_ID) %>%
     summarise_at(vars(matches('^d\\d+$')), sum)

In the devel version of dplyr, another option is across with `summarise

HI_csv %>%
     group_by(region_ID) %>%
     summarise(across(matches('^d\\d+'), sum))

Or with a reproducible example

iris %>%
    group_by(Species) %>%
    summarise(across(everything(), sum))
# A tibble: 3 x 5
#  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
#  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
#1 setosa             250.        171.         73.1        12.3
#2 versicolor         297.        138.        213          66.3
#3 virginica          329.        149.        278.        101.


问:
Printing Javascript Template Strings with Line Breaks
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);```

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).

答:
I think it may be related to the OS you're using since Windows and Mac have different character lengths for their line endings.

To answer the particular question which seems to work for me.

```<code>const os = require('os');

let someVar = 'a';

let tsString = `here goes ${someVar} ${os.EOL} some other line ${os.EOL} some other line`;

console.log(tsString);
</code>```

You can read about the os middleware on the nodejs docs here: https://nodejs.org/api/os.html#os_os_eol

This seems to be a similar duplicate of: How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?

Body:
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).

Body:
I think it may be related to the OS you're using since Windows and Mac have different character lengths for their line endings.

To answer the particular question which seems to work for me.

const os = require('os');

let someVar = 'a';

let tsString = `here goes ${someVar} ${os.EOL} some other line ${os.EOL} some other line`;

console.log(tsString);

You can read about the os middleware on the nodejs docs here: https://nodejs.org/api/os.html#os_os_eol

This seems to be a similar duplicate of: How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?