问:
@EntityScan doesn't scan
I have Spring boot application with Integration and Spring Data JPA. The configuration is as follows:

Application.class:

```<code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

IntegrationConfiguration.class

```<code>@Configuration
@EnableIntegration
public class IntegrationConfiguration {
    private static final String FILE_PATTERN = "*.XML";

    @Value("${spring.integration.input-directory}")
    private String inputDirectory;
    @Value("${spring.integration.output-directory}")
    private String outputDirectory;
    @Value("${spring.integration.threads}")
    private int threadsCount;
    @Resource
    private ActualStatusRepository actualStatusRepository;

    //. . . removed file splitter and channels

    @Bean(name = "fiasEntityRouter")
    @Router(inputChannel = "afterSplitChannel")
    AbstractMappingMessageRouter fiasEntityRouter() {
        Map<String, String> routingMap = ImmutableMap.<String, String>builder()
                .put("ru.ecoteck.entity.ActualStatus", "actualStatusChannel")
                .build();
        PayloadTypeRouter router = new PayloadTypeRouter();
        router.setChannelMappings(routingMap);
        router.setDefaultOutputChannel(logChannel());
        return router;
    }

    @Bean(name = "actualStatusChannel")
    public MessageChannel actualStatusChannel() {
        return new DirectChannel();
    }

    @Bean(name = "actualStatusHandler")
    @ServiceActivator(inputChannel = "actualStatusChannel")
    public MessageHandler actualStatusHandler() {
        return new ActualStatusHandler(actualStatusRepository);
    }
}
</code>```

So, the application starts read XML files, splits them into pieces, deserialize (by XStream) and then the object saves, I get an error that table actual_statuses doesn't exist. But in my @Entity annotated class I using a table with name ActualStatuses

```<code>@XStreamAlias("ActualStatus")
@Entity
@Table(name = "ActualStatuses")
public class ActualStatus {

    @XStreamAsAttribute
    @XStreamAlias("ACTSTATID")
    @Id
    @Column(name = "ACTSTATID", nullable = false)
    private int id;

    // . . .
}
</code>```

ActualStatusHandler is just calling repository.save(message.getPayload) but with a couple of protection code. Seems like the problem only with searching @Entity classes.
Spring boot version is 2.1.5.RELEASE.
I have tried explicit annotation @EntityScan("my.package.entity"), but with no effect. I don't use any custom database layer configuration. Just application.properties

```<code>#database
spring.datasource.url=jdbc:postgresql://localhost:5432/fias
spring.datasource.username=fias
spring.datasource.password=fias
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect
# for debug
spring.jpa.show-sql=true
</code>```

What's going wrong?
Many thanks for helping me.

答:
So, parameter

```<code>spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

did the trick and now application works as expected. Thanks to Patrick for pointing me right direction to dig.

Title: @EntityScan doesn't scan

Body:
I have Spring boot application with Integration and Spring Data JPA. The configuration is as follows:

Application.class:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

IntegrationConfiguration.class

@Configuration
@EnableIntegration
public class IntegrationConfiguration {
    private static final String FILE_PATTERN = "*.XML";

    @Value("${spring.integration.input-directory}")
    private String inputDirectory;
    @Value("${spring.integration.output-directory}")
    private String outputDirectory;
    @Value("${spring.integration.threads}")
    private int threadsCount;
    @Resource
    private ActualStatusRepository actualStatusRepository;

    //. . . removed file splitter and channels

    @Bean(name = "fiasEntityRouter")
    @Router(inputChannel = "afterSplitChannel")
    AbstractMappingMessageRouter fiasEntityRouter() {
        Map<String, String> routingMap = ImmutableMap.<String, String>builder()
                .put("ru.ecoteck.entity.ActualStatus", "actualStatusChannel")
                .build();
        PayloadTypeRouter router = new PayloadTypeRouter();
        router.setChannelMappings(routingMap);
        router.setDefaultOutputChannel(logChannel());
        return router;
    }

    @Bean(name = "actualStatusChannel")
    public MessageChannel actualStatusChannel() {
        return new DirectChannel();
    }

    @Bean(name = "actualStatusHandler")
    @ServiceActivator(inputChannel = "actualStatusChannel")
    public MessageHandler actualStatusHandler() {
        return new ActualStatusHandler(actualStatusRepository);
    }
}

So, the application starts read XML files, splits them into pieces, deserialize (by XStream) and then the object saves, I get an error that table actual_statuses doesn't exist. But in my @Entity annotated class I using a table with name ActualStatuses

@XStreamAlias("ActualStatus")
@Entity
@Table(name = "ActualStatuses")
public class ActualStatus {

    @XStreamAsAttribute
    @XStreamAlias("ACTSTATID")
    @Id
    @Column(name = "ACTSTATID", nullable = false)
    private int id;

    // . . .
}

ActualStatusHandler is just calling repository.save(message.getPayload) but with a couple of protection code. Seems like the problem only with searching @Entity classes.
Spring boot version is 2.1.5.RELEASE.
I have tried explicit annotation @EntityScan("my.package.entity"), but with no effect. I don't use any custom database layer configuration. Just application.properties

#database
spring.datasource.url=jdbc:postgresql://localhost:5432/fias
spring.datasource.username=fias
spring.datasource.password=fias
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL95Dialect
# for debug
spring.jpa.show-sql=true

What's going wrong?
Many thanks for helping me.

Body:
So, parameter

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

did the trick and now application works as expected. Thanks to Patrick for pointing me right direction to dig.


来源: stackexchange

问:
How to fix 'Failed to Update dependency information of the project. Please restore the project and try again'
I'm writing a new web API using .net core 2.2 and I connected an existing database using entity framework. but I keep getting an error saying above when I try to add a controller to the existing model using Scaffold new item.
here are the commands I used

```<code>Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
</code>```

Scaffold-DbContext to reverse engineer and create the EF model based on my existing database.

but keeps getting below error

"There was an error running the selected code generator: ' Failed to update dependency information for the project. Please restore the project and try again.'

I tried everything I could think of and I even gets the same error when I tries to add an empty controller also

答:
I met this issue and found nothing wrong in my project.

After deleting the bin and obj folder, this issue is gone.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a new web API using .net core 2.2 and I connected an existing database using entity framework. but I keep getting an error saying above when I try to add a controller to the existing model using Scaffold new item.
here are the commands I used

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Scaffold-DbContext to reverse engineer and create the EF model based on my existing database.

but keeps getting below error

"There was an error running the selected code generator: ' Failed to update dependency information for the project. Please restore the project and try again.'

I tried everything I could think of and I even gets the same error when I tries to add an empty controller also


问:
need to remove the last zeros in line
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this </p>

```<code>input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"
</code>```

答:
You can do this type of substitution with sed:

```<code>sed 's/0*$//' temp.txt
</code>```

This removes all the trailing zeros from each line. 0* matches "zero or more" 0s, and $ matches the end of the line.

If you only ever want to remove one 0, then remove the *.

If you prefer to do the same thing in the shell (I assume you use bash, since your attempt includes [[), you could do this:

```<code>#!/bin/bash

# match any line ending in one or more zeros
# capture everything up to the trailing 0s
re='(.*[^0])0+$'

while read -r line; do
  # use =~ for regex match
  if [[ $line =~ $re ]]; then
    # assign first capture group, discarding trailing 0s
    line=${BASH_REMATCH[1]}
  fi
  echo "$line"
done < temp.txt
</code>```

But this approach has the disadvantages of being more complicated and less portable, so I would go with the sed option.

Title: need to remove the last zeros in line

Body:
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this

input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"

Body:
You can do this type of substitution with sed:

sed 's/0*$//' temp.txt

This removes all the trailing zeros from each line. 0* matches "zero or more" 0s, and $ matches the end of the line.

If you only ever want to remove one 0, then remove the *.

If you prefer to do the same thing in the shell (I assume you use bash, since your attempt includes [[), you could do this:

#!/bin/bash

# match any line ending in one or more zeros
# capture everything up to the trailing 0s
re='(.*[^0])0+$'

while read -r line; do
  # use =~ for regex match
  if [[ $line =~ $re ]]; then
    # assign first capture group, discarding trailing 0s
    line=${BASH_REMATCH[1]}
  fi
  echo "$line"
done < temp.txt

But this approach has the disadvantages of being more complicated and less portable, so I would go with the sed option.


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

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

How would I achieve that?

Thanks

Edit:

Formula:

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

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

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

答:
Formula is correct, needed a little touch.

Don't cast float into int, data loss!

When going within the for go from the first person to the n-1

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

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

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

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

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

How would I achieve that?

Thanks

Edit:

Formula:

int people = 20;
float prize = 1000;

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

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

Body:
Formula is correct, needed a little touch.

Don't cast float into int, data loss!

When going within the for go from the first person to the n-1

int people = 20;
float prize = 1000;

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

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


问:
How to Setstate array in React Native
How to set state field in array.

Below is my code:

```<code>constructor() {
  super();
  arrayCheck: [
    isCheck = false
  ]
}

</code>```

I want to get isCheck and then set state to true.
How can I set it?

Below is my function setState

```<code>onCheckBoxChange(isCheck, index, item) {
  this.setState({........});
}
</code>```

答:
If you really want to update a state variable using array you can try this.
First, you need an array of object in state variable and update it like this

```<code>constructor () {
super();
this.state = {
     arrayCheck: [
        { isCheck : false }
    ]
  }
}
</code>```

then update its value like this

```<code>onCheckBoxChange(isCheck, index, item) {
   let arrayCheck = [...this.state.arrayCheck]
   arrayCheck[0].isCheck = true
   this.setState({
     arrayCheck
   })
}
</code>```

Title: How to Setstate array in React Native

Body:
How to set state field in array.

Below is my code:

constructor() {
  super();
  arrayCheck: [
    isCheck = false
  ]
}

I want to get isCheck and then set state to true.
How can I set it?

Below is my function setState

onCheckBoxChange(isCheck, index, item) {
  this.setState({........});
}

Body:
If you really want to update a state variable using array you can try this.
First, you need an array of object in state variable and update it like this

constructor () {
super();
this.state = {
     arrayCheck: [
        { isCheck : false }
    ]
  }
}

then update its value like this

onCheckBoxChange(isCheck, index, item) {
   let arrayCheck = [...this.state.arrayCheck]
   arrayCheck[0].isCheck = true
   this.setState({
     arrayCheck
   })
}


问:
What is the difference between implementing Deserializer and Serde in Kafka Consumer API?
I try to simulate Gwen (Chen) Shapira's kafka-clickstream-enrich kafka-stream project on GitHub (https://github.com/onurtokat/kafka-clickstream-enrich). When I consume a topic using consumer class using Deserializers, I encounter an error. The customized Serde class have serializer and deserializer. But, I try to understand why custom serde is used for deserializer, then consumer API gives error as it is not an instance of org.apache.kafka.common.serialization.Deserializer

The topic can be consumed using KTable with Serdes.Integer() Serializer and new ProfileSerde() Deserializer like below.

```<code>KTable<Integer, UserProfile> profiles = builder.table(Constants.USER_PROFILE_TOPIC,
                Consumed.with(Serdes.Integer(), new ProfileSerde()),
                Materialized.as("profile-store"));
</code>```

Customized Serde is defined as;

```<code>static public final class ProfileSerde extends WrapperSerde<UserProfile> {
        public ProfileSerde() {
            super(new JsonSerializer<UserProfile>(), new JsonDeserializer<UserProfile>(UserProfile.class));
        }
    }
</code>```

And generic Serde is customized liked below;

```<code>package com.onurtokat.serde;

import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serializer;

import java.util.Map;

public class WrapperSerde<T> implements Serde<T> {

    final private Serializer<T> serializer;
    final private Deserializer<T> deserializer;

    public WrapperSerde(Serializer<T> serializer, Deserializer<T> deserializer) {
        this.serializer = serializer;
        this.deserializer = deserializer;
    }

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {
        serializer.configure(configs, isKey);
        deserializer.configure(configs, isKey);
    }

    @Override
    public void close() {
        serializer.close();
        deserializer.close();
    }

    @Override
    public Serializer<T> serializer() {
        return serializer;
    }

    @Override
    public Deserializer<T> deserializer() {
        return deserializer;
    }
}
</code>```

My Consumer is so simple and can be seen below;

```<code>package com.onurtokat.consumers;

import com.onurtokat.ClickstreamEnrichment;
import com.onurtokat.Constants;
import com.onurtokat.model.UserProfile;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class ConsumeProfileData {

    public static void main(String[] args) {
        //prepare config
        Properties config = new Properties();
        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class.getName());
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ClickstreamEnrichment.ProfileSerde.class);

        KafkaConsumer<Integer, UserProfile> consumerProfileTopic = new KafkaConsumer<>(config);
        consumerProfileTopic.subscribe(Arrays.asList(Constants.USER_PROFILE_TOPIC));
        while (true) {
            ConsumerRecords<Integer, UserProfile> records = consumerProfileTopic.poll(Duration.ofMillis(100));
            for (ConsumerRecord<Integer, UserProfile> record : records) {
                System.out.println(record.key() + " " + record.value());
            }
        }
    }
}
</code>```

The error when I try to consume topic with my consumer is;

```<code>log4j:WARN No appenders could be found for logger (org.apache.kafka.clients.consumer.ConsumerConfig).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.apache.kafka.common.KafkaException: Failed to construct kafka consumer
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:811)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:659)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:639)
    at com.onurtokat.consumers.ConsumeProfileData.main(ConsumeProfileData.java:25)
Caused by: org.apache.kafka.common.KafkaException: com.onurtokat.ClickstreamEnrichment$ProfileSerde is not an instance of org.apache.kafka.common.serialization.Deserializer
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:304)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:712)
    ... 3 more
</code>```

答:
The difference is:

Serdes are used by Kafka's Streams API (aka Kafka Streams).  A Serde is a wrapper for a pair of (1) serializer and (2) deserializer for the same data type—see next two bullet points. That is, a Serde<T> has a Serializer<T> and a Deserializer<T>. The first code snippet you posted (with e.g. a KTable) is a Kafka Streams code snippet, that's why it needs a Serde. Kafka Streams needs a Serde because it both produces messages (for which it needs a Serializer) and reads messages (for which it needs a Deserializer).

Deserializers are used by Kafka's consumer API (aka consumer client) for reading messages. Your last code snippet (with e.g. a KafkaConsumer) is using the consumer client and therefore needs a Deserializer, not a Serde.

Serializers are used by Kafka's producer API (aka producer client) for writing messages.

Regarding:

```<code>Caused by: org.apache.kafka.common.KafkaException: com.onurtokat.ClickstreamEnrichment$ProfileSerde is not an instance of org.apache.kafka.common.serialization.Deserializer
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:304)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:712)
    ... 3 more
</code>```

Your Kafka consumer client code was given a Serde where it was expecting a Deserializer.

Body:
I try to simulate Gwen (Chen) Shapira's kafka-clickstream-enrich kafka-stream project on GitHub (https://github.com/onurtokat/kafka-clickstream-enrich). When I consume a topic using consumer class using Deserializers, I encounter an error. The customized Serde class have serializer and deserializer. But, I try to understand why custom serde is used for deserializer, then consumer API gives error as it is not an instance of org.apache.kafka.common.serialization.Deserializer

The topic can be consumed using KTable with Serdes.Integer() Serializer and new ProfileSerde() Deserializer like below.

KTable<Integer, UserProfile> profiles = builder.table(Constants.USER_PROFILE_TOPIC,
                Consumed.with(Serdes.Integer(), new ProfileSerde()),
                Materialized.as("profile-store"));

Customized Serde is defined as;

static public final class ProfileSerde extends WrapperSerde<UserProfile> {
        public ProfileSerde() {
            super(new JsonSerializer<UserProfile>(), new JsonDeserializer<UserProfile>(UserProfile.class));
        }
    }

And generic Serde is customized liked below;

package com.onurtokat.serde;

import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serializer;

import java.util.Map;

public class WrapperSerde<T> implements Serde<T> {

    final private Serializer<T> serializer;
    final private Deserializer<T> deserializer;

    public WrapperSerde(Serializer<T> serializer, Deserializer<T> deserializer) {
        this.serializer = serializer;
        this.deserializer = deserializer;
    }

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {
        serializer.configure(configs, isKey);
        deserializer.configure(configs, isKey);
    }

    @Override
    public void close() {
        serializer.close();
        deserializer.close();
    }

    @Override
    public Serializer<T> serializer() {
        return serializer;
    }

    @Override
    public Deserializer<T> deserializer() {
        return deserializer;
    }
}

My Consumer is so simple and can be seen below;

package com.onurtokat.consumers;

import com.onurtokat.ClickstreamEnrichment;
import com.onurtokat.Constants;
import com.onurtokat.model.UserProfile;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class ConsumeProfileData {

    public static void main(String[] args) {
        //prepare config
        Properties config = new Properties();
        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class.getName());
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ClickstreamEnrichment.ProfileSerde.class);

        KafkaConsumer<Integer, UserProfile> consumerProfileTopic = new KafkaConsumer<>(config);
        consumerProfileTopic.subscribe(Arrays.asList(Constants.USER_PROFILE_TOPIC));
        while (true) {
            ConsumerRecords<Integer, UserProfile> records = consumerProfileTopic.poll(Duration.ofMillis(100));
            for (ConsumerRecord<Integer, UserProfile> record : records) {
                System.out.println(record.key() + " " + record.value());
            }
        }
    }
}

The error when I try to consume topic with my consumer is;

log4j:WARN No appenders could be found for logger (org.apache.kafka.clients.consumer.ConsumerConfig).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.apache.kafka.common.KafkaException: Failed to construct kafka consumer
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:811)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:659)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:639)
    at com.onurtokat.consumers.ConsumeProfileData.main(ConsumeProfileData.java:25)
Caused by: org.apache.kafka.common.KafkaException: com.onurtokat.ClickstreamEnrichment$ProfileSerde is not an instance of org.apache.kafka.common.serialization.Deserializer
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:304)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:712)
    ... 3 more

Body:
The difference is:

Serdes are used by Kafka's Streams API (aka Kafka Streams).  A Serde is a wrapper for a pair of (1) serializer and (2) deserializer for the same data type—see next two bullet points. That is, a Serde<T> has a Serializer<T> and a Deserializer<T>. The first code snippet you posted (with e.g. a KTable) is a Kafka Streams code snippet, that's why it needs a Serde. Kafka Streams needs a Serde because it both produces messages (for which it needs a Serializer) and reads messages (for which it needs a Deserializer).

Deserializers are used by Kafka's consumer API (aka consumer client) for reading messages. Your last code snippet (with e.g. a KafkaConsumer) is using the consumer client and therefore needs a Deserializer, not a Serde.

Serializers are used by Kafka's producer API (aka producer client) for writing messages.

Regarding:

Caused by: org.apache.kafka.common.KafkaException: com.onurtokat.ClickstreamEnrichment$ProfileSerde is not an instance of org.apache.kafka.common.serialization.Deserializer
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:304)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:712)
    ... 3 more

Your Kafka consumer client code was given a Serde where it was expecting a Deserializer.


问:
jQuery - black & white image to color image (hover)
I have black and white image contained in a css:

http://cl.ly/3G0E0g1e2G2h3k3U3F2O

In the same file I put in color image:

http://cl.ly/1l2A2F0o1j3E1z2s223V

Now I wants to when you hover the mouse on this image has changed from black and white to color...

I put the function in jQuery:

```<code>    $("ul li").mouseover(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center bottom'
        }).stop().fadeTo(400, 0).show();

    });

    $("ul li").mouseout(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center top'
        }).stop().fadeTo(400, 1).show();

    });
</code>```

HTML:

```<code><span class="thumb"></span>
</code>```

CSS:

```<code>ul li span.thumb {background:url(image.png) no-repeat}
</code>```

Q: How I can do it differently? (that when you hover the mouse on the image did not disappear).

答:
Try CSS sprites: http://www.alistapart.com/articles/sprites

The basic technique is to combine both images to one background image and set it as the background of your html element. Then when a hover event occurs you only "move" the background image to the position where the coloured part of the background image is visible.
With the background-position css property you can control which part of the background image is visible.

The advantage is that there is no delay when hovering the first time as the bw as well as the coloured version of the image are loaded on page load.

ContentLicense: CC BY-SA 3.0

Body:
I have black and white image contained in a css:

http://cl.ly/3G0E0g1e2G2h3k3U3F2O

In the same file I put in color image:

http://cl.ly/1l2A2F0o1j3E1z2s223V

Now I wants to when you hover the mouse on this image has changed from black and white to color...

I put the function in jQuery:

    $("ul li").mouseover(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center bottom'
        }).stop().fadeTo(400, 0).show();

    });

    $("ul li").mouseout(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center top'
        }).stop().fadeTo(400, 1).show();

    });

HTML:

CSS:

ul li span.thumb {background:url(image.png) no-repeat}

Q: How I can do it differently? (that when you hover the mouse on the image did not disappear).


问:
How to make auto update into mysql through php
We have a table in database called validity and update 'inactive' automatically into database when validity will expire by current date

```<code>validity_from | validity_to | status
------------------------------------
28-05-2019    | 28-06-2019  | active
------------------------------------
</code>```

How can i achieve this function in php

Please suggest and help me.

答: you can create a cron job that runs in background and update 'status' filed accordingly</p>

Body:
We have a table in database called validity and update 'inactive' automatically into database when validity will expire by current date

validity_from | validity_to | status
------------------------------------
28-05-2019    | 28-06-2019  | active
------------------------------------

How can i achieve this function in php

Please suggest and help me.


问:
How to update data in table if data is match other then insert in mysql
Insert a row in sql if any match then update it.

I tried it

```<code>INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@s.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
</code>```

This is only work for checking duplicate entry. but i want if no enrty found then insert it or other than update it.

```<code>INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@somewhere.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+
</code>```

答:
You can use ON DUPLICATE KEY

first, you have to create unique index:
ALTER TABLE  testADD UNIQUE email(email`);

thus, if you insert a record with the same email value, it will update the record.

```<code>INSERT INTO test (name, email) VALUES("Rupert", "Somewhere@s.com")
ON DUPLICATE KEY UPDATE name="Rupert", email="Somewhere@s.com"
</code>```

if it's a new email, it will create a new record

Body:
Insert a row in sql if any match then update it.

I tried it

INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@s.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+

This is only work for checking duplicate entry. but i want if no enrty found then insert it or other than update it.

INSERT INTO test (name, email)
SELECT * FROM (SELECT 'Rupert', 'Somewhere@somewhere.com') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM test WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `test`;

+----+--------+-----------------+
| id | name   | email           |
+----+--------+-----------------+
|  1 | Rupert | Somewhere@s.com |
+----+--------+-----------------+

Body:
You can use ON DUPLICATE KEY

first, you have to create unique index:
ALTER TABLE  testADD UNIQUE email(email`);

thus, if you insert a record with the same email value, it will update the record.

INSERT INTO test (name, email) VALUES("Rupert", "Somewhere@s.com")
ON DUPLICATE KEY UPDATE name="Rupert", email="Somewhere@s.com"

if it's a new email, it will create a new record


问:
How to push values to local storage?
I have the following code in js. if I use static array everything works fine. Else I get:

Uncaught TypeError: myArray.push is not a function

```<code>function test(){
var myArray =  localStorage.getItem('articles')  ;
//myArray=[1,4,5];
needle = 2    ,
myArray.push(needle);
localStorage.setItem('articles', JSON.stringify(myArray))
console.log(localStorage.getItem('articles'));
}
</code>```

答:
Add checking if 'articles' exists in localStorage and if it is an array.
If it doesn't exist yet. Initialized a value for it ("[]");
You need to parse the JSON string first before push an item to the array. Then stringify it again before you update the localStorage.
Please see the code below.</p>

```<code>function test() {
  let myArray = localStorage.getItem("articles");
  //Check if localStorage has 'articles' and if that 'articles' is an array
  if (myArray && Array.isArray(JSON.parse(myArray))) {
    const needle = 2,
    myArray = JSON.parse(myArray).push(needle);
    localStorage.setItem("articles", JSON.stringify(myArray))
    console.log(localStorage.getItem("articles"));
  } else {
    //Initialized 'articles' in localStorage.
    localStorage.setItem("articles", "[]");
  }
}
</code>```

Title: How to push values to local storage?

Body:
I have the following code in js. if I use static array everything works fine. Else I get:

Uncaught TypeError: myArray.push is not a function

function test(){
var myArray =  localStorage.getItem('articles')  ;
//myArray=[1,4,5];
needle = 2    ,
myArray.push(needle);
localStorage.setItem('articles', JSON.stringify(myArray))
console.log(localStorage.getItem('articles'));
}

Body:
Add checking if 'articles' exists in localStorage and if it is an array.
If it doesn't exist yet. Initialized a value for it ("[]");
You need to parse the JSON string first before push an item to the array. Then stringify it again before you update the localStorage.
Please see the code below.

function test() {
  let myArray = localStorage.getItem("articles");
  //Check if localStorage has 'articles' and if that 'articles' is an array
  if (myArray && Array.isArray(JSON.parse(myArray))) {
    const needle = 2,
    myArray = JSON.parse(myArray).push(needle);
    localStorage.setItem("articles", JSON.stringify(myArray))
    console.log(localStorage.getItem("articles"));
  } else {
    //Initialized 'articles' in localStorage.
    localStorage.setItem("articles", "[]");
  }
}


问:
How to remove NotReady nodes from kubernetes cluster automatically
I'm running the kuberenets cluster on bare metal servers and my cluster nodes keep added and removed regularly. But when a node is removed, kubernetes does not remove it automatically from nodes list and kubectl get nodes keep showing NotReady nodes. Is there any automated way to achieve this? I want similar behavior for nodes as kubernetes does for pods.

答:
To remove a node follow the below steps</p>
```<code>Run on Master
# kubectl cordon <node-name>
# kubectl drain <node-name> --force --ignore-daemonsets  --delete-emptydir-data
# kubectl delete node <node-name>
</code>```

Body:
To remove a node follow the below steps

Run on Master
# kubectl cordon <node-name>
# kubectl drain <node-name> --force --ignore-daemonsets  --delete-emptydir-data
# kubectl delete node <node-name>


问:
Get multiple thumbnails from video
I'm using MediaMetadataRetriever to retrieve thumbnails at a specific time in video. This is how I achieve this:

```<code>MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
    try {
        metadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://packageName/raw/"+"test"));
        String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long time = Long.valueOf(duration)/3;
        Bitmap bitmap1 = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        imgone.setImageBitmap(bitmap1);

    }catch (Exception ex) {
        Toast.makeText(MainActivity.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
        }
</code>```

This returns a bitmap/thumbnail as expected, the problem is that if I want to get multiple thumbnails at different times in the video like this:

```<code>MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
    try {
        metadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://packageName/raw/"+"test"));
        String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long time = Long.valueOf(duration)/3;
        long time2 = time+time;
        long time3 = time+time+time;
        Bitmap bitmap1 = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap bitmap2 = metadataRetriever.getFrameAtTime(time2,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap bitmap3 = metadataRetriever.getFrameAtTime(time3,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        imgone.setImageBitmap(bitmap1);
        imgtwo.setImageBitmap(bitmap2);
        imgthree.setImageBitmap(bitmap3);

    }catch (Exception ex) {
        Toast.makeText(MainActivity.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
        }
</code>```

Then it still only returns the same thumbnail, I'm not sure if it is because there is only one thumbnail available for the video or what, but I've tried different video files with the same result.

I've tried changing MediaMetadataRetriever.OPTION_CLOSEST_SYNC to all the available options but still the same result.

Im not sure if FFMPEG would be a better option for this?

答:
Exactly a year later, I noticed that I never provided an answer.

In the original question I wanted to retrieve 3 thumbnails, I ended up retrieving 5. I also mentioned that I'm not sure if FFmpeg will be a suitable option, that's exactly what I used.

So, in OnCreate, I make sure that FFmpeg is supported and then I do the following:

```<code>if (FFmpeg.getInstance(getApplication()).isSupported()) {
      @SuppressLint("SimpleDateFormat")
      //ffmpeg expects the time format to be "00:00:00"
      Format formatter = new SimpleDateFormat("00:" + "mm:ss.SS");
      //Get the duration of the video
      long duration = player.getDuration();
      //Since I want 5 thumbnails, I divide the duration by 6 to get the first thumbnail position
      long img1 = duration / 6;
      //I format the first thumbnail time since ffmpeg expects "00:00:00" format
      String firstTumbTime = formatter.format(img1);

      //Scale the size of the thumbnail output (this can be improved/changed to your liking)
      String scaledSize = displayMetrics.widthPixels / 7 + ":" + displayMetrics.heightPixels / 7;
      //Set ffmpeg command (notice that I set vframes to one, since I only want 1 thumbnail/image)
      String[] a = {"-ss", firstTumbTime, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb1.bmp"};
      //start ffmpeg asynctask for the first thumbnail
      ExecuteThumbFFMPEG(a);

}  else {
     Toast.makeText(TestNewPlayer.this, "Your device doesn't support FFMPEG...", Toast.LENGTH_SHORT).show();
}
</code>```

The comments in the code above explains everything, now here is my ExecuteThumbFFMPEG method.

```<code>public void ExecuteThumbFFMPEG(String[] command) {

    ffmpegImages = FFmpeg.getInstance(this).execute(command, new ExecuteBinaryResponseHandler() {

        @Override
        public void onStart() {
            //ffmpeg started
        }

        @Override
        public void onProgress(String message) {
            //get ffmpeg progress
        }

        @Override
        public void onFailure(String message) {
            //ffmpeg failed
        }

        @Override
        public void onSuccess(String message) {
            //first thumbnail saved successfully, now to get the other 4

            //Scale the thumbnail output (Same as above)
            String scaledSize = displayMetrics.widthPixels / 7 + ":" + displayMetrics.heightPixels / 7;

            try {
                //I first set the path/name for each thumbnail, this will also be used to check if the thumbnail is available or if we should get it
                String imgPath1 = imageThumbsDirectory + "/" + "thumb1.bmp";
                String imgPath2 = imageThumbsDirectory + "/" + "thumb2.bmp";
                String imgPath3 = imageThumbsDirectory + "/" + "thumb3.bmp";
                String imgPath4 = imageThumbsDirectory + "/" + "thumb4.bmp";
                String imgPath5 = imageThumbsDirectory + "/" + "thumb5.bmp";

                //Set the format again (same as above)
                @SuppressLint("SimpleDateFormat")
                Format formatter = new SimpleDateFormat("00:" + "mm:ss.SS");

                //Get the length of the video
                long duration = Player.getDuration();

                //Divide the length of the video by 6 (same as above)
                long time = duration / 6;

                //Since I want 5 thumbnails evenly distributed throughout the video
                //I use the video length divided by 6 to accomplish that
                long img2 = time + time;
                long img3 = time + time + time;
                long img4 = time + time + time + time;
                long img5 = time + time + time + time + time;

                //Format the time (calculated above) for each thumbnail I want to retrieve
                String Img2Timeformat = formatter.format(img2);
                String Img3Timeformat = formatter.format(img3);
                String Img4Timeformat = formatter.format(img4);
                String Img5Timeformat = formatter.format(img5);

                //Get reference to the thumbnails (to see if they have been created before)
                File fileimgPath1 = new File(imgPath1);
                File fileimgPath2 = new File(imgPath2);
                File fileimgPath3 = new File(imgPath3);
                File fileimgPath4 = new File(imgPath4);
                File fileimgPath5 = new File(imgPath5);

                //If thumbnail 1 exist and thumbnail 2 doesn't then we need to get thumbnail 2
                if (fileimgPath1.exists() && !fileimgPath2.exists()) {
                    //Get/decode bitmap from the first thumbnail path to be able to set it to our ImageView that should hold the first thumbnail
                    Bitmap bmp1 = BitmapFactory.decodeFile(imgPath1);
                    //Set the first thumbnail to our first ImageView
                    imgone.setImageBitmap(bmp1);
                    //Set the ffmpeg command to retrieve the second thumbnail
                    String[] ffmpegCommandForThumb2 = {"-ss", Img2Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb2.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 2
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb2);
                }

                //If thumbnail 2 exist and thumbnail 3 doesn't then we need to get thumbnail 3
                if (fileimgPath2.exists() && !fileimgPath3.exists()) {
                    //Get/decode bitmap from the second thumbnail path to be able to set it to our ImageView that should hold the second thumbnail
                    Bitmap bmp2 = BitmapFactory.decodeFile(imgPath2);
                    //Set the second thumbnail to our second ImageView
                    imgTwo.setImageBitmap(bmp2);
                    //Set the ffmpeg command to retrieve the third thumbnail
                    String[] ffmpegCommandForThumb3 = {"-ss", Img3Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb3.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 3
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb3);
                }

                ////If thumbnail 3 exist and thumbnail 4 doesn't then we need to get thumbnail 4
                if (fileimgPath3.exists() && !fileimgPath4.exists()) {
                    //Get/decode bitmap from the third thumbnail path to be able to set it to our ImageView that should hold the third thumbnail
                    Bitmap bmp3 = BitmapFactory.decodeFile(imgPath3);
                    //Set the third thumbnail to our third ImageView
                    imgThree.setImageBitmap(bmp3);
                    //Set the ffmpeg command to retrieve the fourth thumbnail
                    String[] ffmpegCommandForThumb4 = {"-ss", Img4Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb4.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 4
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb4);
                }

                ////If thumbnail 4 exist and thumbnail 5 doesn't then we need to get thumbnail 5
                if (fileimgPath4.exists() && !fileimgPath5.exists()) {
                    //Get/decode bitmap from the first fourth path to be able to set it to our ImageView that should hold the fourth thumbnail
                    Bitmap bmp4 = BitmapFactory.decodeFile(imgPath4);
                    //Set the fourth thumbnail to our fourth ImageView
                    imgFour.setImageBitmap(bmp4);
                    //Set the ffmpeg command to retrieve the last thumbnail
                    String[] ffmpegCommandForThumb5 = {"-ss", Img5Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb5.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 5
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb5);
                }

                //If thumbnail 5 exist, then we are done and we need to set it to our ImageView
                if (fileimgPath5.exists()) {
                    Bitmap bmp5 = BitmapFactory.decodeFile(imgPath5);
                    imgFive.setImageBitmap(bmp5);
                }

            } catch (Exception ex) {
                Toast.makeText(Player.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFinish() {
            //ffmpeg is done
        }

    });

}
</code>```

When the user back out of the Activity or OnDestroy gets called, all the thumbnails should be deleted, I do this by calling the following method:

```<code>DeleteThumbs.deleteAllThumbnails(getBaseContext());
</code>```

Here is the DeleteThumbs class for deleting all the thumbnails/images

```<code>class DeleteThumbs {

    @SuppressWarnings("unused")
    static void deleteAllThumbnails(Context baseContext){
        //Directory where all the thumbnails are stored
        File imageThumbsDirectory = baseContext.getExternalFilesDir("ThumbTemp");
        //Path to each thumbnail
        File f1 = new File(imageThumbsDirectory + "/" + "thumb1.bmp");
        File f2 = new File(imageThumbsDirectory + "/" + "thumb2.bmp");
        File f3 = new File(imageThumbsDirectory + "/" + "thumb3.bmp");
        File f4 = new File(imageThumbsDirectory + "/" + "thumb4.bmp");
        File f5 = new File(imageThumbsDirectory + "/" + "thumb5.bmp");

        boolean d1 = f1.delete();
        boolean d2 = f2.delete();
        boolean d3 = f3.delete();
        boolean d4 = f4.delete();
        boolean d5 = f5.delete();
    }

}
</code>```

Since we know the name of each thumbnail, it's easy to delete them all at once.

This provides me with 5 thumbnail images that are scaled to reduce loading time into the ImageView's. Because I divided the duration of the video by 6, I get 5 images that are evenly "distributed" throughout the video.

NOTE:

This can be improved by caching the images into memory or using a library like picasso or glide to handle the image loading for us.

Title: Get multiple thumbnails from video

Body:
I'm using MediaMetadataRetriever to retrieve thumbnails at a specific time in video. This is how I achieve this:

MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
    try {
        metadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://packageName/raw/"+"test"));
        String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long time = Long.valueOf(duration)/3;
        Bitmap bitmap1 = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        imgone.setImageBitmap(bitmap1);

    }catch (Exception ex) {
        Toast.makeText(MainActivity.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
        }

This returns a bitmap/thumbnail as expected, the problem is that if I want to get multiple thumbnails at different times in the video like this:

MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
    try {
        metadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://packageName/raw/"+"test"));
        String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long time = Long.valueOf(duration)/3;
        long time2 = time+time;
        long time3 = time+time+time;
        Bitmap bitmap1 = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap bitmap2 = metadataRetriever.getFrameAtTime(time2,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        Bitmap bitmap3 = metadataRetriever.getFrameAtTime(time3,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        imgone.setImageBitmap(bitmap1);
        imgtwo.setImageBitmap(bitmap2);
        imgthree.setImageBitmap(bitmap3);

    }catch (Exception ex) {
        Toast.makeText(MainActivity.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
        }

Then it still only returns the same thumbnail, I'm not sure if it is because there is only one thumbnail available for the video or what, but I've tried different video files with the same result.

I've tried changing MediaMetadataRetriever.OPTION_CLOSEST_SYNC to all the available options but still the same result.

Im not sure if FFMPEG would be a better option for this?

Body:
Exactly a year later, I noticed that I never provided an answer.

In the original question I wanted to retrieve 3 thumbnails, I ended up retrieving 5. I also mentioned that I'm not sure if FFmpeg will be a suitable option, that's exactly what I used.

So, in OnCreate, I make sure that FFmpeg is supported and then I do the following:

if (FFmpeg.getInstance(getApplication()).isSupported()) {
      @SuppressLint("SimpleDateFormat")
      //ffmpeg expects the time format to be "00:00:00"
      Format formatter = new SimpleDateFormat("00:" + "mm:ss.SS");
      //Get the duration of the video
      long duration = player.getDuration();
      //Since I want 5 thumbnails, I divide the duration by 6 to get the first thumbnail position
      long img1 = duration / 6;
      //I format the first thumbnail time since ffmpeg expects "00:00:00" format
      String firstTumbTime = formatter.format(img1);

      //Scale the size of the thumbnail output (this can be improved/changed to your liking)
      String scaledSize = displayMetrics.widthPixels / 7 + ":" + displayMetrics.heightPixels / 7;
      //Set ffmpeg command (notice that I set vframes to one, since I only want 1 thumbnail/image)
      String[] a = {"-ss", firstTumbTime, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb1.bmp"};
      //start ffmpeg asynctask for the first thumbnail
      ExecuteThumbFFMPEG(a);

}  else {
     Toast.makeText(TestNewPlayer.this, "Your device doesn't support FFMPEG...", Toast.LENGTH_SHORT).show();
}

The comments in the code above explains everything, now here is my ExecuteThumbFFMPEG method.

public void ExecuteThumbFFMPEG(String[] command) {

    ffmpegImages = FFmpeg.getInstance(this).execute(command, new ExecuteBinaryResponseHandler() {

        @Override
        public void onStart() {
            //ffmpeg started
        }

        @Override
        public void onProgress(String message) {
            //get ffmpeg progress
        }

        @Override
        public void onFailure(String message) {
            //ffmpeg failed
        }

        @Override
        public void onSuccess(String message) {
            //first thumbnail saved successfully, now to get the other 4

            //Scale the thumbnail output (Same as above)
            String scaledSize = displayMetrics.widthPixels / 7 + ":" + displayMetrics.heightPixels / 7;

            try {
                //I first set the path/name for each thumbnail, this will also be used to check if the thumbnail is available or if we should get it
                String imgPath1 = imageThumbsDirectory + "/" + "thumb1.bmp";
                String imgPath2 = imageThumbsDirectory + "/" + "thumb2.bmp";
                String imgPath3 = imageThumbsDirectory + "/" + "thumb3.bmp";
                String imgPath4 = imageThumbsDirectory + "/" + "thumb4.bmp";
                String imgPath5 = imageThumbsDirectory + "/" + "thumb5.bmp";

                //Set the format again (same as above)
                @SuppressLint("SimpleDateFormat")
                Format formatter = new SimpleDateFormat("00:" + "mm:ss.SS");

                //Get the length of the video
                long duration = Player.getDuration();

                //Divide the length of the video by 6 (same as above)
                long time = duration / 6;

                //Since I want 5 thumbnails evenly distributed throughout the video
                //I use the video length divided by 6 to accomplish that
                long img2 = time + time;
                long img3 = time + time + time;
                long img4 = time + time + time + time;
                long img5 = time + time + time + time + time;

                //Format the time (calculated above) for each thumbnail I want to retrieve
                String Img2Timeformat = formatter.format(img2);
                String Img3Timeformat = formatter.format(img3);
                String Img4Timeformat = formatter.format(img4);
                String Img5Timeformat = formatter.format(img5);

                //Get reference to the thumbnails (to see if they have been created before)
                File fileimgPath1 = new File(imgPath1);
                File fileimgPath2 = new File(imgPath2);
                File fileimgPath3 = new File(imgPath3);
                File fileimgPath4 = new File(imgPath4);
                File fileimgPath5 = new File(imgPath5);

                //If thumbnail 1 exist and thumbnail 2 doesn't then we need to get thumbnail 2
                if (fileimgPath1.exists() && !fileimgPath2.exists()) {
                    //Get/decode bitmap from the first thumbnail path to be able to set it to our ImageView that should hold the first thumbnail
                    Bitmap bmp1 = BitmapFactory.decodeFile(imgPath1);
                    //Set the first thumbnail to our first ImageView
                    imgone.setImageBitmap(bmp1);
                    //Set the ffmpeg command to retrieve the second thumbnail
                    String[] ffmpegCommandForThumb2 = {"-ss", Img2Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb2.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 2
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb2);
                }

                //If thumbnail 2 exist and thumbnail 3 doesn't then we need to get thumbnail 3
                if (fileimgPath2.exists() && !fileimgPath3.exists()) {
                    //Get/decode bitmap from the second thumbnail path to be able to set it to our ImageView that should hold the second thumbnail
                    Bitmap bmp2 = BitmapFactory.decodeFile(imgPath2);
                    //Set the second thumbnail to our second ImageView
                    imgTwo.setImageBitmap(bmp2);
                    //Set the ffmpeg command to retrieve the third thumbnail
                    String[] ffmpegCommandForThumb3 = {"-ss", Img3Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb3.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 3
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb3);
                }

                ////If thumbnail 3 exist and thumbnail 4 doesn't then we need to get thumbnail 4
                if (fileimgPath3.exists() && !fileimgPath4.exists()) {
                    //Get/decode bitmap from the third thumbnail path to be able to set it to our ImageView that should hold the third thumbnail
                    Bitmap bmp3 = BitmapFactory.decodeFile(imgPath3);
                    //Set the third thumbnail to our third ImageView
                    imgThree.setImageBitmap(bmp3);
                    //Set the ffmpeg command to retrieve the fourth thumbnail
                    String[] ffmpegCommandForThumb4 = {"-ss", Img4Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb4.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 4
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb4);
                }

                ////If thumbnail 4 exist and thumbnail 5 doesn't then we need to get thumbnail 5
                if (fileimgPath4.exists() && !fileimgPath5.exists()) {
                    //Get/decode bitmap from the first fourth path to be able to set it to our ImageView that should hold the fourth thumbnail
                    Bitmap bmp4 = BitmapFactory.decodeFile(imgPath4);
                    //Set the fourth thumbnail to our fourth ImageView
                    imgFour.setImageBitmap(bmp4);
                    //Set the ffmpeg command to retrieve the last thumbnail
                    String[] ffmpegCommandForThumb5 = {"-ss", Img5Timeformat, "-i", mStringFilePath, "-vframes", "1", "-s", scaledSize, imageThumbsDirectory + "/" + "thumb5.bmp"};
                    //Start ffmpeg again, this time we will be getting thumbnail 5
                    ExecuteThumbFFMPEG(ffmpegCommandForThumb5);
                }

                //If thumbnail 5 exist, then we are done and we need to set it to our ImageView
                if (fileimgPath5.exists()) {
                    Bitmap bmp5 = BitmapFactory.decodeFile(imgPath5);
                    imgFive.setImageBitmap(bmp5);
                }

            } catch (Exception ex) {
                Toast.makeText(Player.this, String.valueOf(ex), Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFinish() {
            //ffmpeg is done
        }

    });

}

When the user back out of the Activity or OnDestroy gets called, all the thumbnails should be deleted, I do this by calling the following method:

DeleteThumbs.deleteAllThumbnails(getBaseContext());

Here is the DeleteThumbs class for deleting all the thumbnails/images

class DeleteThumbs {

    @SuppressWarnings("unused")
    static void deleteAllThumbnails(Context baseContext){
        //Directory where all the thumbnails are stored
        File imageThumbsDirectory = baseContext.getExternalFilesDir("ThumbTemp");
        //Path to each thumbnail
        File f1 = new File(imageThumbsDirectory + "/" + "thumb1.bmp");
        File f2 = new File(imageThumbsDirectory + "/" + "thumb2.bmp");
        File f3 = new File(imageThumbsDirectory + "/" + "thumb3.bmp");
        File f4 = new File(imageThumbsDirectory + "/" + "thumb4.bmp");
        File f5 = new File(imageThumbsDirectory + "/" + "thumb5.bmp");

        boolean d1 = f1.delete();
        boolean d2 = f2.delete();
        boolean d3 = f3.delete();
        boolean d4 = f4.delete();
        boolean d5 = f5.delete();
    }

}

Since we know the name of each thumbnail, it's easy to delete them all at once.

This provides me with 5 thumbnail images that are scaled to reduce loading time into the ImageView's. Because I divided the duration of the video by 6, I get 5 images that are evenly "distributed" throughout the video.

NOTE:

This can be improved by caching the images into memory or using a library like picasso or glide to handle the image loading for us.


问:
Remove link to single page from Woocommerce product page
I have been trying to remove the link to the single product page of the Woocommerce plugin. On this forum many people asking questions about it and have read most of them. But nearly all of these questions are old. However as far as I understand now I have to use the functions.php and content-page.php to achieve this.

So after reading all the info on the i-net I came up with this code in the functions.php (which is inside my child theme folder)

```<code>if ( !function_exists('add_remove_hooks')):
function add_remove_hooks() {
    remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
    }
endif;
add_action( 'init', 'add_remove_hooks' );
</code>```

I have tried all kind of variants like only put in the remove_action rows, not wrapt in a function or use an other action in the add_action function, but none of them seem to work. The syntax, however, is as it should be.

The (part of)content-page.php looks like

```<code><li <?php post_class( $classes ); ?>>
    <?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

        <?php
            /**
             * woocommerce_before_shop_loop_item_title hook
             *
             * @hooked woocommerce_show_product_loop_sale_flash - 10
             * @hooked woocommerce_template_loop_product_thumbnail - 10
             */
            do_action( 'woocommerce_before_shop_loop_item_title' ); ?>

        <?php if($product_style == 'classic') {
            do_action( 'woocommerce_shop_loop_item_title' );
            do_action( 'woocommerce_after_shop_loop_item_title' );
        } ?>

    <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>

</li>
</code>```

I don't know how to debug in PHP, but I know the files are "used" by WP because if I change something in one of these files I see it on screen. However, the links are still in place. The remove_action is not working.

Does anyobody have another suggestion on how to accomplish this? Of what to look for?

Used WP 5.2 and Woocommerce 3.0

UPDATE:

Thanks to Alfaraz I was able to solve the problem. Putting the remove_actions in the functions.php of the child theme now also works. I didn't realize I also had to set the active theme in WP to my Child theme. That did the trick in the end.

答:
Put below code in the functions.php file of your theme.

```<code>// Remove links to the product details pages from the product listing page of a WooCommerce store
remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
</code>```

Body:
I have been trying to remove the link to the single product page of the Woocommerce plugin. On this forum many people asking questions about it and have read most of them. But nearly all of these questions are old. However as far as I understand now I have to use the functions.php and content-page.php to achieve this.

So after reading all the info on the i-net I came up with this code in the functions.php (which is inside my child theme folder)

if ( !function_exists('add_remove_hooks')):
function add_remove_hooks() {
    remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
    }
endif;
add_action( 'init', 'add_remove_hooks' );

I have tried all kind of variants like only put in the remove_action rows, not wrapt in a function or use an other action in the add_action function, but none of them seem to work. The syntax, however, is as it should be.

The (part of)content-page.php looks like

<li <?php post_class( $classes ); ?>>
    <?php do_action( 'woocommerce_before_shop_loop_item' ); ?>

        <?php
            /**
             * woocommerce_before_shop_loop_item_title hook
             *
             * @hooked woocommerce_show_product_loop_sale_flash - 10
             * @hooked woocommerce_template_loop_product_thumbnail - 10
             */
            do_action( 'woocommerce_before_shop_loop_item_title' ); ?>

        <?php if($product_style == 'classic') {
            do_action( 'woocommerce_shop_loop_item_title' );
            do_action( 'woocommerce_after_shop_loop_item_title' );
        } ?>

    <?php do_action( 'woocommerce_after_shop_loop_item' ); ?>

I don't know how to debug in PHP, but I know the files are "used" by WP because if I change something in one of these files I see it on screen. However, the links are still in place. The remove_action is not working.

Does anyobody have another suggestion on how to accomplish this? Of what to look for?

Used WP 5.2 and Woocommerce 3.0

UPDATE:

Thanks to Alfaraz I was able to solve the problem. Putting the remove_actions in the functions.php of the child theme now also works. I didn't realize I also had to set the active theme in WP to my Child theme. That did the trick in the end.

Body:
Put below code in the functions.php file of your theme.

// Remove links to the product details pages from the product listing page of a WooCommerce store
remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );


问:
How to set a variable equivalent to single array object while iterating through array?
Noob question. I need to pass 3,000+ URLs from a CSV sheet to Selenium. I need Selenium to navigate to each one of these links, scrape information and then put that information into a CSV.

The issue I am running into is when I push my CSV URLS into an array, I cannot pass one single object (url) into Selenium at a time.

I know I likely need some sort of loop. I have tried setting up loops and selecting from the array using .map, .select. and just a do loop.

```<code>urls.map do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-
footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end
</code>```

In the above example, Selenium returns an "invalid URL" error message. De-bugging with Pry tells me that my 'url' object is not a single url, but rather still the entire array.

How can I set Selenium to visit each URL from the array one by one?

EDIT: ----------------
So, after extensive de-bugging with Pry, I found a couple issues. First being that my CSV was feeding a nested array to my loop which was causing the URL error. I had to flatten my array and un-nest it to get around that issue.

After that, I had to build a rescue into my loop so that my script didn't die when it encountered a page without the CSS element I was looking for.

Here's the finalized loop.

```<code>begin
        @urls1.each do |url|
          @driver.navigate.to(url)
          @driver.manage.timeouts.implicit_wait = 10

          name = @driver.find_element(:css, '.sites-embed-
          footer>a').attribute('href')
          puts name
          kb_link = name
          kb_array.push(kb_link)
          puts 'done'

         rescue Selenium::WebDriver::Error::NoSuchElementError
         puts 'no google doc'
         x = 'no google doc'
         kb_array.push(x)
         next
    end
</code>```

答:
First of all, it doesn't make much sense to use map if you don't use the result of the block somewhere. map, applied to an Enumerable, returns a new Array, and you don't do anything with the returned array (which in your case would contain just the return values of puts, which is usually nil, so you would get back just an array of nils with the side effect that something is written to stdout.

If you are only interested in the side effects, each or each_with_indexshould be used to traverse an Enumerable. Given the problems you have with map and with each, I wonder what is the actual content of your object urls. Did you ever inspect it? You could do a

```<code>p urls
</code>```

before entering the loop. With 3000 URLs, the output will be huge, but maybe you can run it on a simpler example with less URLs.

Body:
Noob question. I need to pass 3,000+ URLs from a CSV sheet to Selenium. I need Selenium to navigate to each one of these links, scrape information and then put that information into a CSV.

The issue I am running into is when I push my CSV URLS into an array, I cannot pass one single object (url) into Selenium at a time.

I know I likely need some sort of loop. I have tried setting up loops and selecting from the array using .map, .select. and just a do loop.

urls.map do |url|
    @driver.navigate.to #{url}
    name = @driver.find_element(:css, '.sites-embed-
footer>a').attribute('href')
    puts name
    kb_link = name
    kb_array.push(kb_link)
    puts 'urls is #{n}'
end

In the above example, Selenium returns an "invalid URL" error message. De-bugging with Pry tells me that my 'url' object is not a single url, but rather still the entire array.

How can I set Selenium to visit each URL from the array one by one?

EDIT: ----------------
So, after extensive de-bugging with Pry, I found a couple issues. First being that my CSV was feeding a nested array to my loop which was causing the URL error. I had to flatten my array and un-nest it to get around that issue.

After that, I had to build a rescue into my loop so that my script didn't die when it encountered a page without the CSS element I was looking for.

Here's the finalized loop.

begin
        @urls1.each do |url|
          @driver.navigate.to(url)
          @driver.manage.timeouts.implicit_wait = 10

          name = @driver.find_element(:css, '.sites-embed-
          footer>a').attribute('href')
          puts name
          kb_link = name
          kb_array.push(kb_link)
          puts 'done'

         rescue Selenium::WebDriver::Error::NoSuchElementError
         puts 'no google doc'
         x = 'no google doc'
         kb_array.push(x)
         next
    end

Body:
First of all, it doesn't make much sense to use map if you don't use the result of the block somewhere. map, applied to an Enumerable, returns a new Array, and you don't do anything with the returned array (which in your case would contain just the return values of puts, which is usually nil, so you would get back just an array of nils with the side effect that something is written to stdout.

If you are only interested in the side effects, each or each_with_indexshould be used to traverse an Enumerable. Given the problems you have with map and with each, I wonder what is the actual content of your object urls. Did you ever inspect it? You could do a

p urls

before entering the loop. With 3000 URLs, the output will be huge, but maybe you can run it on a simpler example with less URLs.


问:
How to get local source port from socket connect() in Linux Kernel Space?
I am manipulating the connect() function in Linux Kernel source code (net/socket.c file) and need to get the source and destination port of an established connection. The function takes a struct sockaddr __user* uservaddr parameter from which I already could get the destination port by casting it to a struct sockaddr_in. But where is the local source port stored? The function also declares a struct socket* sock, which possibly contains the data I need, but I couldn't find any variable with the source port. Any help?

答:
```<code>struct inet_sock *inet;
struct sock *sk = sock->sk;
inet = inet_sk(sk);
u16 post = ntohs(inet->inet_sport);
</code>```


问:
mongoose node.js, query with $lt and $gt not working
I want to get all the pupils whose last mark is between 15 and 20. To do so, I perform the following query in my mongoDB using mongoose:
The models are working fine (all the other queries are ok).

```<code>Pupils.find({"marks[-1].value": {'$lt' : 20 }, "marks[-1].value" : { '$gt' : 15 }}, function(err, things){
</code>```

This is not working, is there something I missed ?

* UPDATE *

I found something like:

```<code>Pupils.find({ "marks[-1].value": {$gt : 15, $lt : 20}});
</code>```

But this does not work either. Is there a way to get the last mark of the marks array in this case ?

答:
Lets consider your Pupils collection:

```<code>Pupils
{
  _id,
  Marks(integer),
  LatestMark(int)
}
</code>```

I suggest to add latest mark into Pupil document(as you can see at the document above), and update it each time when you adding new mark into nested collection.
Then you will able to query on it like this:

```<code>db.Pupils.find({ "LatestMark": {$gt : 15, $lt : 20}});
</code>```

Also you can query latest mark using $where, but be care because:

Javascript executes more slowly than
  the native operators, but is very flexible

Body:
I want to get all the pupils whose last mark is between 15 and 20. To do so, I perform the following query in my mongoDB using mongoose:
The models are working fine (all the other queries are ok).

Pupils.find({"marks[-1].value": {'$lt' : 20 }, "marks[-1].value" : { '$gt' : 15 }}, function(err, things){

This is not working, is there something I missed ?

* UPDATE *

I found something like:

Pupils.find({ "marks[-1].value": {$gt : 15, $lt : 20}});

But this does not work either. Is there a way to get the last mark of the marks array in this case ?

Body:
Lets consider your Pupils collection:

Pupils
{
  _id,
  Marks(integer),
  LatestMark(int)
}

I suggest to add latest mark into Pupil document(as you can see at the document above), and update it each time when you adding new mark into nested collection.
Then you will able to query on it like this:

db.Pupils.find({ "LatestMark": {$gt : 15, $lt : 20}});

Also you can query latest mark using $where, but be care because:

Javascript executes more slowly than
  the native operators, but is very flexible


问:
Confused about Typescript object types {} []
I have never worked with lists, object lists etc in Typescript and im not sure how they work. The below code doesnt do much except create a few objects and create some temp values for them through a loop, but i want the console log to print out the second objects name ("image1") followed by the second objects height (21).

What is wrong with the below code? Since undefined is being printed out.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  image = {};
  images = [this.image];

  constructor() {
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}
</code>```

答:
Nothing wrong perse, but you can simply access your array's objects as you are by doing this:

```<code>console.log(this.images[1].name)
console.log(this.images[1].height)
</code>```

You can use the names in there. If you're using TypeScript and an editor or IDE that supports TypeScript's language service; it'll even recommend values it knows are available!

Body:
I have never worked with lists, object lists etc in Typescript and im not sure how they work. The below code doesnt do much except create a few objects and create some temp values for them through a loop, but i want the console log to print out the second objects name ("image1") followed by the second objects height (21).

What is wrong with the below code? Since undefined is being printed out.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  image = {};
  images = [this.image];

  constructor() {
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

Body:
Nothing wrong perse, but you can simply access your array's objects as you are by doing this:

console.log(this.images[1].name)
console.log(this.images[1].height)

You can use the names in there. If you're using TypeScript and an editor or IDE that supports TypeScript's language service; it'll even recommend values it knows are available!


问:
How to access Map Key/value in DAML?
Trying to replace an element in the map but not sure how to get it done. Not sure what to do to access the key or the value.

Tried the below code but it complains that key or value is not recognized.

let map : Map Text OneElement = M.fromList (("0001", OneElement "one" 1 )::("0002", OneElement "two" 2 )::("0003", OneElement "three" 3 )::("0004", OneElement "four" 4 ):: [])
let result = fmap(\i -> if i.key=="0001" then (OneElement "somethingelse" 1111) else i.value) map
```

Also how to access key/value in TextMap.

Anyone can help? Thanks.

答:
The implementation of fmap for DA.Next.Map.Map maps values only, not key, value pairs: fmap : (v -> w) -> Map k v -> Map k w. You could do a find and replace on values as follows:

```<code>import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = fmap (\i -> if i == OneElement "one" 1 then OneElement "somethingelse" 1111 else i) mymap
</code>```

Note that I've renamed your map to mymap, as map overlaps with the standard library function map: (a -> b) -> [a] -> [b].

If you wanted to get your hands on key value pairs in a map-like function, you could write your own map function:

```<code>import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mapEntries : MapKey k => ((k, v) -> w) -> Map k v -> Map k w
mapEntries f = M.fromList . map (\e -> (e._1, f e)) . M.toList

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = mapEntries (\(k, v) -> if k == "0001" then OneElement "somethingelse" 1111 else v) mymap
</code>```

However, it looks like all you want to do is to replace the element at key "0001". For that, you have the insert function in DA.Next.Map.

```<code>import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = insert "0001" (OneElement "somethingelse" 1111) mymap
</code>```

Title: How to access Map Key/value in DAML?

Body:
Trying to replace an element in the map but not sure how to get it done. Not sure what to do to access the key or the value.

Tried the below code but it complains that key or value is not recognized.

let map : Map Text OneElement = M.fromList (("0001", OneElement "one" 1 )::("0002", OneElement "two" 2 )::("0003", OneElement "three" 3 )::("0004", OneElement "four" 4 ):: [])
let result = fmap(\i -> if i.key=="0001" then (OneElement "somethingelse" 1111) else i.value) map

Also how to access key/value in TextMap.

Anyone can help? Thanks.

Body:
The implementation of fmap for DA.Next.Map.Map maps values only, not key, value pairs: fmap : (v -> w) -> Map k v -> Map k w. You could do a find and replace on values as follows:

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = fmap (\i -> if i == OneElement "one" 1 then OneElement "somethingelse" 1111 else i) mymap

Note that I've renamed your map to mymap, as map overlaps with the standard library function map: (a -> b) -> [a] -> [b].

If you wanted to get your hands on key value pairs in a map-like function, you could write your own map function:

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mapEntries : MapKey k => ((k, v) -> w) -> Map k v -> Map k w
mapEntries f = M.fromList . map (\e -> (e._1, f e)) . M.toList

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = mapEntries (\(k, v) -> if k == "0001" then OneElement "somethingelse" 1111 else v) mymap

However, it looks like all you want to do is to replace the element at key "0001". For that, you have the insert function in DA.Next.Map.

import DA.Next.Map as M

data OneElement = OneElement with
  t : Text
  i : Int
    deriving (Eq, Show)

mymap : Map Text OneElement = M.fromList [("0001", OneElement "one" 1), ("0002", OneElement "two" 2), ("0003", OneElement "three" 3), ("0004", OneElement "four" 4)]
result = insert "0001" (OneElement "somethingelse" 1111) mymap


问:
How to get window (like dialog, popupmenu...)
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

```<code>((Activity)context).getWindow()
</code>```

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?

答:
You can use instanceof to check if context is Activity and then call context.getWindow()

```<code>if(context instanceof Activity)
{
  Window window = ((Activity)context).getWindow();
}
</code>```

Note: Activity and Dialog share same window so calling getWindow on dialog will return same object.

Body:
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

((Activity)context).getWindow()

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?

Body:
You can use instanceof to check if context is Activity and then call context.getWindow()

if(context instanceof Activity)
{
  Window window = ((Activity)context).getWindow();
}

Note: Activity and Dialog share same window so calling getWindow on dialog will return same object.


问:
Image has extra white space on left side. Anything helps
I have this invisible white space on the left of an image I can't get rid of. I've tried many things even the code below. I want the image to be able to cover the whole screen not have any white space around it.

```<code>html, style, body{
  margin:0;
  padding: 0;
}
</code>```

and still, get no results if anyone could help It would be very helpful.

```<code><html>
<head>
<style>

<link href="https://fonts.googleapis.com/css?family=Concert+One|Oswald&display=swap" rel="stylesheet">

.container {
  position: relative;
  text-align: center;
}
  /* TEXT SETTINGS*/
.text {
  position: absolute ;
  top: 15%;
  left: 40%;
  transform: translate(-30%, -50%);
  color: white;
  font-size: 100px;
  text-size-adjust: auto;
  font-family: 'Oswald', sans-serif;

}

.text2 {
  position: absolute ;
  top: 40%;
  left: 10%;
  transform: translate(0%, -50%);
  color: black;
  font-size:90px;
  text-size-adjust: auto;
  font-family: 'Concert One', cursive;

}

.text3 {
  position: absolute ;
  top: 70%;
  left: 10%;
  transform: translate(5%, -50%);
  color: white;
  font-size: 80px;
  text-size-adjust: auto;
  font-family: 'Concert One', cursive;

}

html, style, body{
  margin:0;
  padding: 0;
}

</style>
</head>
<body>

    <div class="container" >
    <img src="https://images.unsplash.com/photo-1495741738915-f877fcd5f5f7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2550&q=80;" alt="Rocky Mountains"margin="0" padding="0" width="1360px" height="800px">
  <div class="text" >TEXT</div>
  <div class="text2" ><strong>TEXT</strong></div>
  <div class="text3" >TEXT</div>
  </div>
</body>
</html>
</code>```

答:
Try with this code:</p>

```<code>body *{
    box-sizing:border-box;
}
</code>```

Body:
I have this invisible white space on the left of an image I can't get rid of. I've tried many things even the code below. I want the image to be able to cover the whole screen not have any white space around it.

html, style, body{
  margin:0;
  padding: 0;
}

and still, get no results if anyone could help It would be very helpful.

TEXT

TEXT

TEXT

Body:
Try with this code:

body *{
    box-sizing:border-box;
}


问:
Material-ui: How to stop propagation of click event in nested components
I have an IconMenu component inside a Paper component.
I would like to prevent the propagation of the click event on the inner component (the IconMenu).
That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

```<code>render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}
</code>```

答:
In addition to using event.stopPropagation();
It is useful to note that it should be written within a onClick event handler.

I made the mistake of writing it inside an onChange event handler, and that wasn't working.

I found that solution here

EDIT:

```<code><ListItem button onClick={this.handleListItemClick}>
-       <Checkbox onChange={this.handleCheckboxChange} />
+       <Checkbox onClick={this.handleCheckboxChange} />
      </ListItem>
</code>```

Body:
I have an IconMenu component inside a Paper component.
I would like to prevent the propagation of the click event on the inner component (the IconMenu).
That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}

Body:
In addition to using event.stopPropagation();
It is useful to note that it should be written within a onClick event handler.

I made the mistake of writing it inside an onChange event handler, and that wasn't working.

I found that solution here

EDIT:

<ListItem button onClick={this.handleListItemClick}>
-       <Checkbox onChange={this.handleCheckboxChange} />
+       <Checkbox onClick={this.handleCheckboxChange} />
      </ListItem>


答:
First off all I would recommend not to use inline css. But if you want no white sides add this to your css.

```<code>img {
  background-repeat: no-repeat;
  background-size: auto;
}
</code>```

this stretches your background and it won't repeat the image. This only works if you don't use inline css in your image otherwise use !important in the css

Title: Image has extra white space on left side. Anything helps

Body:
First off all I would recommend not to use inline css. But if you want no white sides add this to your css.

img {
  background-repeat: no-repeat;
  background-size: auto;
}

this stretches your background and it won't repeat the image. This only works if you don't use inline css in your image otherwise use !important in the css


问:
Using a play button ('Click Me') over default video poster not working
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

```<code>.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

<body>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
    </div>

    <div class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div class="banner-description">
            <p>Click Me</p>
        </div>
    </div>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
    </div>

</body>
</code>```

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

答:
Add (click) event to .video-banner and to the video and play() the video in function...

Also add class to click me onclick to hid it as [ngClass]="{'hide': isClicked}"

Here is working stackblitz

HTML

```<code><div>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
</div>

<div class="video-banner" (click)="play()">
    <video controls #videoPlayer>
        <source src="011-video-files.mp4">
    </video>
    <div class="banner-description" (click)="play()" [ngClass]="{'hide': isClicked}">
        <p>Click Me</p>
    </div>
</div>

<div>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
</div>
</code>```

TS

```<code>@ViewChild('videoPlayer') videoplayer: ElementRef;
isClicked=false;

play() {
    this.videoplayer.nativeElement.play();
    this.isClicked=true;
}
</code>```

CSS

```<code>.hide{
display:none;
}
</code>```

Body:
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!

        <video controls>
            <source src="011-video-files.mp4">
        </video>

Click Me

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

Body:
Add (click) event to .video-banner and to the video and play() the video in function...

Also add class to click me onclick to hid it as [ngClass]="{'hide': isClicked}"

Here is working stackblitz

HTML

<div>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
</div>

<div class="video-banner" (click)="play()">
    <video controls #videoPlayer>
        <source src="011-video-files.mp4">
    </video>
    <div class="banner-description" (click)="play()" [ngClass]="{'hide': isClicked}">
        <p>Click Me</p>
    </div>
</div>

<div>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
</div>

TS

@ViewChild('videoPlayer') videoplayer: ElementRef;
isClicked=false;

play() {
    this.videoplayer.nativeElement.play();
    this.isClicked=true;
}

CSS

.hide{
display:none;
}


答:
Try this:</p>

```<code>  images:any[] = []

  ngOnInit() {
    this.images = []
    for (let i = 0; i < 3; i++) {
      let image = { name: "image" + i, height: 20 + i };
      this.images.push(image)
    }

    console.log(this.images);
    console.log(this.images[1].name);
    console.log(this.images[1].height);
  }
</code>```

Title: Confused about Typescript object types {} []

Body:
Try this:

  images:any[] = []

  ngOnInit() {
    this.images = []
    for (let i = 0; i < 3; i++) {
      let image = { name: "image" + i, height: 20 + i };
      this.images.push(image)
    }

    console.log(this.images);
    console.log(this.images[1].name);
    console.log(this.images[1].height);
  }


问:
FluentValidation with ASP.NET Core: Ensure validation is active
We use FluentValidation for input validation in our ASP.NET Core MVC controllers. Since the validators are a critical part of the system from a security point of view, we'd like to create unit tests that ensure that validation in actually active, and that the right validator is used for each controller.

We enable FluentValidation as usual in Startup.cs:

```<code>services.AddMvc(...).AddFluentValidation(...);
</code>```

I haven't been able to find anything about this, only about unit testing the validators directly, which is a different case.

How do we unit-test the validation chain?

答:
Its expected behavior, validations are supposed to be tested separately from controller actions and to test your controller action simply you can simulate a model state error.

```<code>[Test]
public void Test_Validation_Error()
{

    //Arrange
    Controller controllerInstance = new Controller(); //Or use dependency injection in test project and use the instance thereafter.
    controllerInstance.ModelState.AddModelError("Model_Property_Name","Expected_Error_Message");
    CreatedModel model = new CreatedModel(); // Whose property we are validating.

    //Act
    ActionResult result = controllerInstance.Create(model);

    //Assert
    Assert.IsInstanceOfType(result,typeof(PartialViewResult));
}
</code>```

A controller doesn't know about fluent validation, the testing here should separately be here if validation error in model state of your controller action behaves correctly. For a chain of validation the different model properties on which the validations are supposed to be fired should be added in the "AddModelError" section.

Hope this helps !!
Happy coding :)

Body:
We use FluentValidation for input validation in our ASP.NET Core MVC controllers. Since the validators are a critical part of the system from a security point of view, we'd like to create unit tests that ensure that validation in actually active, and that the right validator is used for each controller.

We enable FluentValidation as usual in Startup.cs:

services.AddMvc(...).AddFluentValidation(...);

I haven't been able to find anything about this, only about unit testing the validators directly, which is a different case.

How do we unit-test the validation chain?

Body:
Its expected behavior, validations are supposed to be tested separately from controller actions and to test your controller action simply you can simulate a model state error.

[Test]
public void Test_Validation_Error()
{

    //Arrange
    Controller controllerInstance = new Controller(); //Or use dependency injection in test project and use the instance thereafter.
    controllerInstance.ModelState.AddModelError("Model_Property_Name","Expected_Error_Message");
    CreatedModel model = new CreatedModel(); // Whose property we are validating.

    //Act
    ActionResult result = controllerInstance.Create(model);

    //Assert
    Assert.IsInstanceOfType(result,typeof(PartialViewResult));
}

A controller doesn't know about fluent validation, the testing here should separately be here if validation error in model state of your controller action behaves correctly. For a chain of validation the different model properties on which the validations are supposed to be fired should be added in the "AddModelError" section.

Hope this helps !!
Happy coding :)