问:
getting 404 when consumiing spring controller service
I have created a spring application (Spring version 3.2.8). The application is working fine but the issue which I am facing is that when I try to consume the controller service through url I am getting 404 error

The url which I try to consume through browser url is given below, which I expect to return a test string

```<code>http://localhost/Spring3Sample/user/getPersonDetails
</code>```

My code is as given below

dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/" p:suffix=".jsp" />
</beans>
</code>```

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.controllers" />

</beans>
</code>```

UserController.java

```<code>package com.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final String APP_JSON = "application/json";

    @RequestMapping(value = "/getPersonDetails", method = RequestMethod.GET, produces = APP_JSON)
    public String getPersonDetails() {
        return "test";
    }
}
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3Sample</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
</web-app>
</code>```

Can anyone please tell me some solution for this

UPDATE 1

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <display-name>Spring3Sample</display-name>
:
:
:
</code>```

答:
I added this to my config class that extends WebMvcConfigurer:

```<code>  @Bean
    public ViewResolver viewResolver() {
        final InternalResourceViewResolver bean = new InternalResourceViewResolver();

        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/view/pages/");
        bean.setSuffix(".jsp");

        return bean;
    }
</code>```

You'll have to add this dependency for it to work:

```<code><dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
</dependency>
</code>```

Body:
I have created a spring application (Spring version 3.2.8). The application is working fine but the issue which I am facing is that when I try to consume the controller service through url I am getting 404 error

The url which I try to consume through browser url is given below, which I expect to return a test string

http://localhost/Spring3Sample/user/getPersonDetails

My code is as given below

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/" p:suffix=".jsp" />
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.controllers" />

</beans>

UserController.java

package com.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final String APP_JSON = "application/json";

    @RequestMapping(value = "/getPersonDetails", method = RequestMethod.GET, produces = APP_JSON)
    public String getPersonDetails() {
        return "test";
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3Sample</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
</web-app>

Can anyone please tell me some solution for this

UPDATE 1

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <display-name>Spring3Sample</display-name>
:
:
:

Body:
I added this to my config class that extends WebMvcConfigurer:

  @Bean
    public ViewResolver viewResolver() {
        final InternalResourceViewResolver bean = new InternalResourceViewResolver();

        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/view/pages/");
        bean.setSuffix(".jsp");

        return bean;
    }

You'll have to add this dependency for it to work:

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
</dependency>


来源: stackexchange

问:
Aggregating observations based on category in R
I have a set of agricultural data in R that looks something like this:

```<code>    State       District    Year    Crop      Production   Area
1   State A     District 1  2000    Banana    1254.00      2000.00
2   State A     District 1  2000    Apple     175.00       176.00
3   State A     District 1  2000    Wheat     321.00       641.00
4   State A     District 1  2000    Rice      1438.00      175.00
5   State A     District 1  2000    Cashew    154.00       1845.00
6   State A     District 1  2000    Peanut    2076.00      439.00
7   State B     District 2  2000    Banana    3089.00      1987.00
8   State B     District 2  2000    Apple     309.00       302.00
9   State B     District 2  2000    Wheat     401.00       230.00
10  State B     District 2  2000    Rice      1832.00      2134.00
11  State B     District 2  2000    Cashew    991.00       1845.00
12  State B     District 2  2000    Peanut    2311.00      1032.00
</code>```

I want to aggregate the area and production values by crop type, but keep the state, district and year details, so that it would look something like:

```<code>    State       District    Year    Crop      Production   Area
1   State A     District 1  2000    Fruit     1429.00      2176.00
2   State A     District 1  2000    Grain     1759.00      816.00
3   State A     District 1  2000    Nut       2230.00      2284.00
4   State B     District 2  2000    Fruit     3398.00      2289.00
5   State B     District 2  2000    Grain     2233.00      2364.00
6   State B     District 2  2000    Nut       3302.00      2877.00
</code>```

What's the best way to go about this?

答:
Using dplyr & forcats:

```<code>
library(dplyr)
library(forcats)

df %>%
   mutate(crop_type = fct_recode(Crop, fruit = "Apple", fruit = "Banana",
                                       grain = "Wheat", grain = "Rice",
                                       nut = "Cashew", nut = "Peanut")) %>%
   group_by(State, District, Year, Crop) %>%
   summarize(mean_production = mean(Production),
             mean_area = mean(Area))

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a set of agricultural data in R that looks something like this:

    State       District    Year    Crop      Production   Area
1   State A     District 1  2000    Banana    1254.00      2000.00
2   State A     District 1  2000    Apple     175.00       176.00
3   State A     District 1  2000    Wheat     321.00       641.00
4   State A     District 1  2000    Rice      1438.00      175.00
5   State A     District 1  2000    Cashew    154.00       1845.00
6   State A     District 1  2000    Peanut    2076.00      439.00
7   State B     District 2  2000    Banana    3089.00      1987.00
8   State B     District 2  2000    Apple     309.00       302.00
9   State B     District 2  2000    Wheat     401.00       230.00
10  State B     District 2  2000    Rice      1832.00      2134.00
11  State B     District 2  2000    Cashew    991.00       1845.00
12  State B     District 2  2000    Peanut    2311.00      1032.00

I want to aggregate the area and production values by crop type, but keep the state, district and year details, so that it would look something like:

    State       District    Year    Crop      Production   Area
1   State A     District 1  2000    Fruit     1429.00      2176.00
2   State A     District 1  2000    Grain     1759.00      816.00
3   State A     District 1  2000    Nut       2230.00      2284.00
4   State B     District 2  2000    Fruit     3398.00      2289.00
5   State B     District 2  2000    Grain     2233.00      2364.00
6   State B     District 2  2000    Nut       3302.00      2877.00

What's the best way to go about this?

Body:
Using dplyr & forcats:

library(dplyr)
library(forcats)

df %>%
   mutate(crop_type = fct_recode(Crop, fruit = "Apple", fruit = "Banana",
                                       grain = "Wheat", grain = "Rice",
                                       nut = "Cashew", nut = "Peanut")) %>%
   group_by(State, District, Year, Crop) %>%
   summarize(mean_production = mean(Production),
             mean_area = mean(Area))


问:
Replace active flag to the next item after filtering in Javascript
I have a response from an api that I need to filter. After filtering I need to set the active item. After the filtering there is case that no active item is set to true because the initial active has been filtered. I want to enable the next possible active element.

```<code>// This object array is always sorted with the same length.
const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
const filtered = data.filter(el => el.count < 3);

</code>```

How can I change the active flag of item 3 in the filtered array of objects to true?

So the output of filtered to be:

```<code>  { id: 241, name: "item 1",count: 0, active: false},
  { id: 343, name: "item 3",count: 0, active: true},
  { id: 129, name: "item 3",count: 0, active: false}
</code>```

答:
If mutating source data wouldn't bother you, you may do necessary side-effects from within filter():

const data = [
        { id: 241, name: "item 1",count: 0, active: false},
        { id: 221, name: "item 2",count: 4, active: true},
        { id: 343, name: "item 3",count: 0, active: false},
        { id: 129, name: "item 3",count: 0, active: false}
      ],

      filtered = data.filter(item =>
        item.count < 3 ?
        (shiftFlag ? (item.active = true, shiftFlag = false, true) : true) :
        (item.active ? (shiftFlag = true, item.active = false, false) : false),
        shiftFlag=false)

console.log(filtered)        ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

And, of course, above will not shift active flag to the next item if active item will go the last in the array and it must have been filtered out.

Body:
I have a response from an api that I need to filter. After filtering I need to set the active item. After the filtering there is case that no active item is set to true because the initial active has been filtered. I want to enable the next possible active element.

// This object array is always sorted with the same length.
const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
const filtered = data.filter(el => el.count < 3);

How can I change the active flag of item 3 in the filtered array of objects to true?

So the output of filtered to be:

  { id: 241, name: "item 1",count: 0, active: false},
  { id: 343, name: "item 3",count: 0, active: true},
  { id: 129, name: "item 3",count: 0, active: false}

Body:
If mutating source data wouldn't bother you, you may do necessary side-effects from within filter():

const data = [
        { id: 241, name: "item 1",count: 0, active: false},
        { id: 221, name: "item 2",count: 4, active: true},
        { id: 343, name: "item 3",count: 0, active: false},
        { id: 129, name: "item 3",count: 0, active: false}
      ],

      filtered = data.filter(item =>
        item.count < 3 ?
        (shiftFlag ? (item.active = true, shiftFlag = false, true) : true) :
        (item.active ? (shiftFlag = true, item.active = false, false) : false),
        shiftFlag=false)

console.log(filtered)

.as-console-wrapper{min-height:100%;}

And, of course, above will not shift active flag to the next item if active item will go the last in the array and it must have been filtered out.


问:
DMA_SxCR Enable bit unable to be written on stm32f412
I'm trying to start a DMA transfer on my stm32f412, and I've got everything set up to the point where I'm setting the control registers on the DMA channels/streams for TX and RX.  I am able to set the enable (Bit 0) on the TX, but not the RX.

The datasheet has 3 options for the bit being cleared by hardware: 1.) On a DMA end of transfer (stream ready to be configured) 2.) If a transfer error occurs on the AHB master buses 3.) When the FIFO threshold on memory AHB port is not compatible with the size of the burst.

I don't think it could be the first or the third, because the DMA transfer hasn't even started yet, and there isn't a burst configured, it's just a single transfer.  I'm not quite certain what the second means, but there aren't transfer errors marked in the error registers.

Any avenues to look into would be appreciated

Edit: Ugh, I was looking at the wrong registers for to find the DMA_LISR and _HISR.  There was a transfer error on my RX channel.

答:
From the description of DMA_SxCR_EN bit in the reference manual:

Note: Before setting EN bit to '1' to start a new transfer, the event flags corresponding to the
  stream in DMA_LISR or DMA_HISR register must be cleared.

In my experience, these event flags include not only the error flags, but also the regular event flags like Transfer Complete or Half Transfer. In some cases, I also ended up clearing FIFO error flag, although I can't remember the reason behind it.

This problem manifests itself as "DMA works only once". In your case, it doesn't work even once, so there can be other problems. Still, I think it's worth trying to clear all the status flags before enabling the stream.


问:
Node.js bcrypt compare returning false
I am working on a login script with Node.js and using bcrpyt to compare password hashes. When using the bcrpyt library, the compare function fails. However when I use the bcrpytjs library, the compare function succeeds. Below is the login function. I've included the hash and password for use is testing.

Password: LHLiiSGd1xLg

Hash: $2y$10$J47x5GEFtmULWem2nh3YvuZaAiZyFZlyTUFV97dAx2.dyb8Yst43y

```<code>function login(email, password, callback) {

    // Require depedencies
    const bcrypt = require("bcrypt")
    const mysql = require('mysql');

    // Create our mysql connection
    const connection = mysql.createConnection({
        host: configuration.host,
        user: configuration.user,
        password: configuration.password,
        database: configuration.database
    });

    // Connect to the database
    connection.connect();

    // Create the database query
    const query = 'SELECT id, firstname, lastname, email, password FROM tblclients WHERE email = ?';

    // Query the database
    connection.query(query, [ email ], function(err, results) {

        // If we have an error
        if (err) return callback(err);

        // If we have no results
        if (results.length === 0) return callback(new WrongUsernameOrPasswordError(email));

        // Define the user object
        const user = results[0];
        console.log('Query: ', results);

        // Compare the two hashes
        bcrypt.compare(password, user.password.toString(), function(err, isMatch) {

            // If the passwords do not match
            if (err) return callback(err);
            if (!isMatch) return callback('Passwords do not match');

            // Return the user
            callback(null, {
                user_id: user.id.toString(),
                nickname: user.firstname + ' ' + user.lastname,
                email: user.email
            });
        });
    });
}
</code>```

答:
I replaced the 2y prefix with 2a and the function now correctly works.</p>

```<code>user.password.toString().replace(/^\$2y/, "$2a")
</code>```

Title: Node.js bcrypt compare returning false

Body:
I am working on a login script with Node.js and using bcrpyt to compare password hashes. When using the bcrpyt library, the compare function fails. However when I use the bcrpytjs library, the compare function succeeds. Below is the login function. I've included the hash and password for use is testing.

Password: LHLiiSGd1xLg

Hash: $2y$10$J47x5GEFtmULWem2nh3YvuZaAiZyFZlyTUFV97dAx2.dyb8Yst43y

function login(email, password, callback) {

    // Require depedencies
    const bcrypt = require("bcrypt")
    const mysql = require('mysql');

    // Create our mysql connection
    const connection = mysql.createConnection({
        host: configuration.host,
        user: configuration.user,
        password: configuration.password,
        database: configuration.database
    });

    // Connect to the database
    connection.connect();

    // Create the database query
    const query = 'SELECT id, firstname, lastname, email, password FROM tblclients WHERE email = ?';

    // Query the database
    connection.query(query, [ email ], function(err, results) {

        // If we have an error
        if (err) return callback(err);

        // If we have no results
        if (results.length === 0) return callback(new WrongUsernameOrPasswordError(email));

        // Define the user object
        const user = results[0];
        console.log('Query: ', results);

        // Compare the two hashes
        bcrypt.compare(password, user.password.toString(), function(err, isMatch) {

            // If the passwords do not match
            if (err) return callback(err);
            if (!isMatch) return callback('Passwords do not match');

            // Return the user
            callback(null, {
                user_id: user.id.toString(),
                nickname: user.firstname + ' ' + user.lastname,
                email: user.email
            });
        });
    });
}

Body:
I replaced the 2y prefix with 2a and the function now correctly works.

user.password.toString().replace(/^\$2y/, "$2a")


问:
python word frequencies for dictionary with values and key
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

```<code>sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)
</code>```

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

```<code>Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}
</code>```

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

答:
Using a standard python dictionary you can make use of get(key[, default]) to deal with the case when the key you want to increment does not exist in the dictionary.

get(key[, default])

Return the value for key if key is in the dictionary, else default. If
  default is not given, it defaults to None, so that this method never
  raises a KeyError.

```<code>food = {
    2015: ["Apple", "Milk", "Cookie", "Banana", "Orange"],
    2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
    2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
    2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
    2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

counts = {}
for year in food:
    for item in food[year]:
        counts[item] = counts.get(item, 0) + 1

print(counts)
</code>```

Output:

```<code>{'Apple': 3, 'Milk': 2, 'Cookie': 2, 'Banana': 2, 'Orange': 4, 'Potato': 2, 'Chocolate': 2, 'Mango': 3, 'Fish': 2, 'Beef': 1, 'Porn': 1, 'Pork': 1}
</code>```

Body:
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

Body:
Using a standard python dictionary you can make use of get(key[, default]) to deal with the case when the key you want to increment does not exist in the dictionary.

get(key[, default])

Return the value for key if key is in the dictionary, else default. If
  default is not given, it defaults to None, so that this method never
  raises a KeyError.

food = {
    2015: ["Apple", "Milk", "Cookie", "Banana", "Orange"],
    2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
    2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
    2018: ["Beef", "Porn", "Fish", "Apple", "Cookie"],
    2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

counts = {}
for year in food:
    for item in food[year]:
        counts[item] = counts.get(item, 0) + 1

print(counts)

Output:

{'Apple': 3, 'Milk': 2, 'Cookie': 2, 'Banana': 2, 'Orange': 4, 'Potato': 2, 'Chocolate': 2, 'Mango': 3, 'Fish': 2, 'Beef': 1, 'Porn': 1, 'Pork': 1}


问:
Pyspark - ImportError: cannot import name 'SparkContext' from 'pyspark'
I am facing the below error when I am developing data pipeline using python and pyspark.

PS
  C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
  python test.py Traceback (most recent call last):      File "test.py",
  line 1, in
      from pyspark.conf import SparkConf   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark__init__.py",
  line 51, in
      from pyspark.context import SparkContext   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\context.py",
  line 43, in
      from pyspark.profiler import ProfilerCollector, BasicProfiler   File
  "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\profiler.py",
  line 18, in
      import cProfile   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\cProfile.py",
  line 10, in
      import profile as _pyprofile   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\profile.py",
  line 2, in
      from awsglue.context import GlueContext   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\awsglue__init__.py",
  line 13, in
      from .dynamicframe import DynamicFrame   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\awsglue\dynamicframe.py",
  line 20, in
      from pyspark.sql.dataframe import DataFrame   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql__init__.py",
  line 45, in
      from pyspark.sql.types import Row   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\types.py",
  line 36, in
      from pyspark import SparkContext ImportError: cannot import name 'SparkContext' from 'pyspark'
  (C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark__init__.py)

The code is a really simple one only to try it:

```<code>from pyspark.conf import SparkConf

print("hello world")
</code>```

Java, spark, python and pyspark are properly installed as below:

```<code>> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> java -version java version "1.8.0_241" Java(TM) SE Runtime Environment
> (build 1.8.0_241-b07) Java HotSpot(TM) 64-Bit Server VM (build
> 25.241-b07, mixed mode) PS C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data> python --version
> Python 3.7.6

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> spark-shell --version Welcome to
>       ____              __
>      / __/__  ___ _____/ /__
>     _\ \/ _ \/ _ `/ __/  '_/    /___/ .__/\_,_/_/ /_/\_\   version 2.4.3
>       /_/
>
> Using Scala version 2.11.12, Java HotSpot(TM) 64-Bit Server VM,
> 1.8.0_231 Branch heads/v2.4.3 Compiled by user vaviliv on 2019-09-17T17:31:05Z Revision c3e32bf06c35ba2580d46150923abfa795b4446a
> Url https://github.com/apache/spark Type --help for more information.

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> pyspark --version
>     Welcome to
>           ____              __
>          / __/__  ___ _____/ /__
>         _\ \/ _ \/ _ `/ __/  '_/
>        /___/ .__/\_,_/_/ /_/\_\   version 2.4.3
>           /_/
>
>     Using Scala version 2.11.12, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_231
>     Branch heads/v2.4.3
>     Compiled by user vaviliv on 2019-09-17T17:31:05Z
>     Revision c3e32bf06c35ba2580d46150923abfa795b4446a
>     Url https://github.com/apache/spark
>     Type --help for more information.
</code>```

Thank you in advance for your help.

答: I got it. I created a separated virtual environment because I had some version of python and spark in my computer.</p>

Body:
I am facing the below error when I am developing data pipeline using python and pyspark.

PS
  C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
  python test.py Traceback (most recent call last):      File "test.py",
  line 1, in
      from pyspark.conf import SparkConf   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark__init__.py",
  line 51, in
      from pyspark.context import SparkContext   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\context.py",
  line 43, in
      from pyspark.profiler import ProfilerCollector, BasicProfiler   File
  "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\profiler.py",
  line 18, in
      import cProfile   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\cProfile.py",
  line 10, in
      import profile as _pyprofile   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\profile.py",
  line 2, in
      from awsglue.context import GlueContext   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\awsglue__init__.py",
  line 13, in
      from .dynamicframe import DynamicFrame   File "C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data\awsglue\dynamicframe.py",
  line 20, in
      from pyspark.sql.dataframe import DataFrame   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql__init__.py",
  line 45, in
      from pyspark.sql.types import Row   File "C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\types.py",
  line 36, in
      from pyspark import SparkContext ImportError: cannot import name 'SparkContext' from 'pyspark'
  (C:\Users\folder\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark__init__.py)

The code is a really simple one only to try it:

from pyspark.conf import SparkConf

print("hello world")

Java, spark, python and pyspark are properly installed as below:

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> java -version java version "1.8.0_241" Java(TM) SE Runtime Environment
> (build 1.8.0_241-b07) Java HotSpot(TM) 64-Bit Server VM (build
> 25.241-b07, mixed mode) PS C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data> python --version
> Python 3.7.6

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> spark-shell --version Welcome to
>       ____              __
>      / __/__  ___ _____/ /__
>     _\ \/ _ \/ _ `/ __/  '_/    /___/ .__/\_,_/_/ /_/\_\   version 2.4.3
>       /_/
>
> Using Scala version 2.11.12, Java HotSpot(TM) 64-Bit Server VM,
> 1.8.0_231 Branch heads/v2.4.3 Compiled by user vaviliv on 2019-09-17T17:31:05Z Revision c3e32bf06c35ba2580d46150923abfa795b4446a
> Url https://github.com/apache/spark Type --help for more information.

> PS
> C:\Users\folder\Documents\folder\projects\code\etl-gd\src\jobs\greater-data>
> pyspark --version
>     Welcome to
>           ____              __
>          / __/__  ___ _____/ /__
>         _\ \/ _ \/ _ `/ __/  '_/
>        /___/ .__/\_,_/_/ /_/\_\   version 2.4.3
>           /_/
>
>     Using Scala version 2.11.12, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_231
>     Branch heads/v2.4.3
>     Compiled by user vaviliv on 2019-09-17T17:31:05Z
>     Revision c3e32bf06c35ba2580d46150923abfa795b4446a
>     Url https://github.com/apache/spark
>     Type --help for more information.

Thank you in advance for your help.


问:
visual studio 2019 schema compare no differences detected
I am using New Schema Comparison to compare 2 Databases
but this tools return " compare no differences detected "

I am using VS 2019

答: I just faced the same problem. In my case, it was because the database user did not have enough privileges. </p>


问:
Pass a value to another page to open the PDF
I pass a PDF file link to this page, when I print it is always present, but the page once reads the PDF file and when go back and do that agian does not read the link, I don't know why?

Can anyone help me to solve this problem?

```<code>class ReadPdf extends StatefulWidget {

  final String value;
  ReadPdf({Key key, this.value}) : super(key: key);

  @override
  _ReadPdfState createState() => _ReadPdfState();
}

class _ReadPdfState extends  State<ReadPdf>{
  PDFDocument document;
  var my_uid;
  loadFromUrl() async{
    document = await PDFDocument.fromURL('${widget.value}');
    print('yes' + widget.value);
  }

  @override
  void initState() {

    super.initState();
    loadFromUrl();

    FirebaseAuth.instance.currentUser().then((user){

      setState(() {
        my_uid = user.uid;
        print(user.uid);
      });
    }).catchError((e){
      print(e);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                child: document !=null ? PDFViewer(
                  document: document,
                ) : Text('Try agian'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
I think the problem is "async" operation that is not completed yet when the build method was called.

Instead of contidional document !=null, try put the loadFromUrl into FutureBuilder, like this:

```<code>  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                  child: FutureBuilder(
                future: loadFromUrl(),
                builder: (context, snapshot) {
                  if (snapshot.hasData == false) {
                    return CircularProgressIndicator();
                  }

                  //or snapshot.data if your loadFromUrl returns the document, I think that is more "correct"
                  return PDFViewer(document: document);
                },
              )),
            ),
          ],
        ),
      ),
    );
  }
</code>```

and your method has to return a future of something (PDFDocument in your case)

```<code>Future<String> loadFromUrl() async {
    await Future.delayed(Duration(seconds: 2));
  }
</code>```

Body:
I pass a PDF file link to this page, when I print it is always present, but the page once reads the PDF file and when go back and do that agian does not read the link, I don't know why?

Can anyone help me to solve this problem?

class ReadPdf extends StatefulWidget {

  final String value;
  ReadPdf({Key key, this.value}) : super(key: key);

  @override
  _ReadPdfState createState() => _ReadPdfState();
}

class _ReadPdfState extends  State<ReadPdf>{
  PDFDocument document;
  var my_uid;
  loadFromUrl() async{
    document = await PDFDocument.fromURL('${widget.value}');
    print('yes' + widget.value);
  }

  @override
  void initState() {

    super.initState();
    loadFromUrl();

    FirebaseAuth.instance.currentUser().then((user){

      setState(() {
        my_uid = user.uid;
        print(user.uid);
      });
    }).catchError((e){
      print(e);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                child: document !=null ? PDFViewer(
                  document: document,
                ) : Text('Try agian'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Body:
I think the problem is "async" operation that is not completed yet when the build method was called.

Instead of contidional document !=null, try put the loadFromUrl into FutureBuilder, like this:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                  child: FutureBuilder(
                future: loadFromUrl(),
                builder: (context, snapshot) {
                  if (snapshot.hasData == false) {
                    return CircularProgressIndicator();
                  }

                  //or snapshot.data if your loadFromUrl returns the document, I think that is more "correct"
                  return PDFViewer(document: document);
                },
              )),
            ),
          ],
        ),
      ),
    );
  }

and your method has to return a future of something (PDFDocument in your case)

Future<String> loadFromUrl() async {
    await Future.delayed(Duration(seconds: 2));
  }


问:
Converting to C++ from C#
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

```<code>private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}
</code>```

Recursive Function. Iterates the passed Key to find out necessary values.

```<code>private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }
</code>```

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

```<code>RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)
</code>```

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.

答:
If you search for the MSDN help on RegOpenKeyEx and then go up in the contents you'll find all the related methods: Registry methods

You probably want to use RegEnumKeyEx to enumerate subkeys.

ContentLicense: CC BY-SA 3.0

Title: Converting to C++ from C#

Body:
I have done pretty much all my programming using C# and very much a newbie to C++. However now I have to convert to C++ and is finding it a bit difficult. For example, I wrote a pretty simple program using C# to acquire a RegistryKey, then using a recursive function I iterate through my registry key to find a specific key and then get the values I want. No problem, I can write that program in 10 minutes using C#. Here is the code.

My primary function. It gets Bluetooth Registry Key and then call the recursive function.

private static void CheckOpenComPorts()
{
            RegistryKey blueToothPorts = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\Bluetooth");

            List<string> foundPorts = new List<string>();
            AddFoundPortsToList(blueToothPorts, ref foundPorts);

            //Rest of the program; not relevant here.
}

Recursive Function. Iterates the passed Key to find out necessary values.

private static void AddFoundPortsToList(RegistryKey regKey, ref List<string> ports)
        {
            try
            {
                string[] subKeys = regKey.GetSubKeyNames();

                if (subKeys != null)
                {
                    foreach (string subKey in subKeys)
                    {
                        AddFoundPortsToList(regKey.OpenSubKey(subKey), ref ports);
                    }
                }

                if (regKey.Name.EndsWith("Device Parameters"))
                {
                    string str = System.Convert.ToString(regKey.GetValue("PortName"));
                    if (String.IsNullOrEmpty(str) == false)
                    {
                        ports.Add(str);
                    }
                }
            }
            catch (System.Security.SecurityException ex)
            {
                ;
            }
        }

The above code works fine, but when I tried to convert it to C++, I'm pretty lost.
Note : I'm using a Win32 Console C++ Program.

I figured out that I can do something like the following to get the Bluetooth Registry Key.

RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\Bluetooth", 0, KEY_READ, &hKey)

But after that, I'm pretty lost about the recursive function. Specially, how do I get the available subkeys of the passed registry key when I do NOT know the subkey names?. Or in short, what is the equivalent behavior of RegistryKey.GetSubKeyNames() in C++?

As I am only beginning this thing a code sample with some explanations would be great.


问:
Change http / https protocol in browser settings
I changed it in the browser settings for a long time (I just don’t remember how) so that in the address of the pages it was always addressed as https (even if it was specified - http) after pressing Enter. Tell me how to change https to http in the Chrome settings and in ie11?</p>

答:
It may be caused by HSTS - HTTP Strict Transport Security. When a website sends this header in a response, then the browser will use a secure connection even if you explicitly specify http:// as the protocol.

This response header looks like this: Strict-Transport-Security: max-age=31536000

If this is the case, to clear those settings in Chrome you can go to the following address:

chrome://net-internals/#hsts

and try to modify entries for the domain you need within that panel.


问:
VideoWriter outputs corrupted video file
This is my code to save web_cam streaming. It is working but the problem with output video file.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
```

答:
Here's some simple code to save frames into a video file. I recommend creating another thread for obtaining the frames since cv2.VideoCapture.read() is blocking. This can be expensive and cause latency as the main thread has to wait until it has obtained a frame. By putting this operation into a separate thread that just focuses on grabbing frames and processing/saving the frames in the main thread, it dramatically improves performance due to I/O latency reduction. You also can experiment with other codecs but using MJPG should be safe since its built into OpenCV.

```<code>from threading import Thread
import cv2

class WebcamVideoWriter(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Default resolutions of the frame are obtained (system dependent)
        self.frame_width = int(self.capture.get(3))
        self.frame_height = int(self.capture.get(4))

        # Set up codec and output video settings
        self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
        self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            cv2.imshow('frame', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            self.output_video.release()
            cv2.destroyAllWindows()
            exit(1)

    def save_frame(self):
        # Save obtained frame into video output file
        self.output_video.write(self.frame)

if __name__ == '__main__':
    webcam_videowriter = WebcamVideoWriter()
    while True:
        try:
            webcam_videowriter.show_frame()
            webcam_videowriter.save_frame()
        except AttributeError:
            pass
</code>```

Body:
Here's some simple code to save frames into a video file. I recommend creating another thread for obtaining the frames since cv2.VideoCapture.read() is blocking. This can be expensive and cause latency as the main thread has to wait until it has obtained a frame. By putting this operation into a separate thread that just focuses on grabbing frames and processing/saving the frames in the main thread, it dramatically improves performance due to I/O latency reduction. You also can experiment with other codecs but using MJPG should be safe since its built into OpenCV.

from threading import Thread
import cv2

class WebcamVideoWriter(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Default resolutions of the frame are obtained (system dependent)
        self.frame_width = int(self.capture.get(3))
        self.frame_height = int(self.capture.get(4))

        # Set up codec and output video settings
        self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
        self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            cv2.imshow('frame', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            self.output_video.release()
            cv2.destroyAllWindows()
            exit(1)

    def save_frame(self):
        # Save obtained frame into video output file
        self.output_video.write(self.frame)

if __name__ == '__main__':
    webcam_videowriter = WebcamVideoWriter()
    while True:
        try:
            webcam_videowriter.show_frame()
            webcam_videowriter.save_frame()
        except AttributeError:
            pass


问:
Server-side Payment Token decryption for Apple Pay
There are third party libraries that provide support for decrypting Apple Pay token on the server side. Is there any such .NET library?

Third-paty Libraries

Ruby library for decrypting Apple Pay payment tokens

PHP library for decrypting Apple Pay payment tokens

What we're trying to accomplish

We're using Compass XML platform for payment processing, and the goad is to decrypt the payment token on our server and then use the Compass XML for final payment processing.

答:
I got it working in C# by creating a fork of a project and cleaning it up.
Here is the Github location:

https://github.com/fscopel/CSharpApplePayDecrypter


问:
How to compare the input of two columns in the same table to validate data input?
I'm trying to compare the text input for each row between two columns in the same table

This is my dax formula that I use:

```<code>Checkpoint = IF(AND(CONTAINSROW('tweedelijns melding'[Korte omschrijving (Details)], "ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag") && 'tweedelijns melding'[Object ID] = "Active directory" ||'tweedelijns melding'[Object ID] = "Citrix"), "Match", "No match")
</code>```

What I'm trying to achieve is the following:

The [Korte omschrijving (Details)] column contains a question and the object ID contains mostly one or two words.

I would like to check whether the column [Korte omschrijving (Details)] contains words like "ADW", "Wachtwoord","reset","Resetten" ..... and if the column [object ID] contain words such as "Active directory" or "Citrix" if so, then it will count as a match otherwise not.

This is the output that it should generates:

Output

答:
Here is a Power Query approach that seems to work.

Starting with your table as Table1:

I added a custom column:

Here's the M code for the custom column formula:

```<code>if List.ContainsAny(
    Text.Split(Text.Upper([Question])," "),
    List.Transform({"ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag"}, each Text.Upper(_))
)
    then if List.ContainsAny(
        Text.Split(Text.Upper([Categorie]),""),
        List.Transform({"Active directory", "citrix"}, each Text.Upper(_))
    )
    then "match"
    else "no match"
else "no match"
</code>```

What it does is it splits each of the Question column's row into a list of its words, then compares that list with a list of your words, {"ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag"}, to see if any of the words in your list of words are in that list created from the Question row. If there is a match, then it does the same with the Categorie column. But...for the Categorie column, it really only makes a one item list for each row. In other words... As an example, "Verzoek resetten wachtwoord", from Question becomes the list {"VERZOEK", "RESETTEN", "WACHTWOORD"} and "Active Directory", from Categorie becomes the list {"ACTIVE DIRECTORY"}. If there is a match in both lists, then "match" is returned. Otherwise, "no match" is returned.

The Text.Split is what converts to the list. The List.ContainsAny is what compares the list contents. I used Text.Upper to force the Question Categorie info to uppercase and I used List.Transform to force the lists of your words to uppercase, to ensure appropriate comparison for matching.

Here's my result:

Body:
I'm trying to compare the text input for each row between two columns in the same table

This is my dax formula that I use:

Checkpoint = IF(AND(CONTAINSROW('tweedelijns melding'[Korte omschrijving (Details)], "ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag") && 'tweedelijns melding'[Object ID] = "Active directory" ||'tweedelijns melding'[Object ID] = "Citrix"), "Match", "No match")

What I'm trying to achieve is the following:

The [Korte omschrijving (Details)] column contains a question and the object ID contains mostly one or two words.

I would like to check whether the column [Korte omschrijving (Details)] contains words like "ADW", "Wachtwoord","reset","Resetten" ..... and if the column [object ID] contain words such as "Active directory" or "Citrix" if so, then it will count as a match otherwise not.

This is the output that it should generates:

Output

Body:
Here is a Power Query approach that seems to work.

Starting with your table as Table1:

I added a custom column:

Here's the M code for the custom column formula:

if List.ContainsAny(
    Text.Split(Text.Upper([Question])," "),
    List.Transform({"ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag"}, each Text.Upper(_))
)
    then if List.ContainsAny(
        Text.Split(Text.Upper([Categorie]),""),
        List.Transform({"Active directory", "citrix"}, each Text.Upper(_))
    )
    then "match"
    else "no match"
else "no match"

What it does is it splits each of the Question column's row into a list of its words, then compares that list with a list of your words, {"ADW", "Wachtwoord","reset","Resetten", "Uitvraagscript", "Profile","Citrix", "Aanvraag"}, to see if any of the words in your list of words are in that list created from the Question row. If there is a match, then it does the same with the Categorie column. But...for the Categorie column, it really only makes a one item list for each row. In other words... As an example, "Verzoek resetten wachtwoord", from Question becomes the list {"VERZOEK", "RESETTEN", "WACHTWOORD"} and "Active Directory", from Categorie becomes the list {"ACTIVE DIRECTORY"}. If there is a match in both lists, then "match" is returned. Otherwise, "no match" is returned.

The Text.Split is what converts to the list. The List.ContainsAny is what compares the list contents. I used Text.Upper to force the Question Categorie info to uppercase and I used List.Transform to force the lists of your words to uppercase, to ensure appropriate comparison for matching.

Here's my result:


问:
Filter by String Embedded Documents from the main document using MongoEngine - Python Flask
I am trying to filter embedded documents by String (LIKE Query SQL equivalent) from the parent document.

Here's what I have now:

```<code>def resolve_friend(root, info, **kwargs):
    phone = kwargs.get('phone', None)
    search_string = kwargs.get('searchString', None)
    try:
        // I am retrieving the parent doucment by phone number first
        account = AccountModel.objects(phone=phone).first()

        if account is None:
            return ResponseMessageField(is_success=False, message="User does not exists.")

        top_friends = None

        // Now I want to filter the Friends field from the account by the search string.
        // In the friends' field, there are multiple documents.  The idea is to get the friends
        // matching the string from their first_name / last_name

        if search_string:
            regex = re.compile('.*' + search_string + '.*', re.IGNORECASE)

            //doesn't work any of these below
            # top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test')))
            top_friends = AccountModel.objects(friends__first_name__icontains='tes').all()

        all_friends = account.friends.filter(request_status="ACCEPTED")   //this works fine
        return retrieve_friend_list_graphql(top_friends=top_friends, all_friends=all_friends)
    except Exception as e:
        return ResponseMessageField(is_success=False, message="Account fetch error. " + str(e))
</code>```

These lines don't work

```<code>top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test')))
</code>```

```<code>top_friends = AccountModel.objects(friends__first_name__icontains='tes').all()
</code>```

I am unable to filter the account.friends.filter() with the search string in mongoengine.

Here's the full account document with the friends field.

```<code>{
  "_id": {
    "$oid": "5e3485c2dd26ea191faf2861"
  },
  "identity": "0b1170fc50979464c352c34c2e9fd7aa",
  "username": "Shuvro",
  "first_name": "",
  "middle_name": "",
  "last_name": "",
  "phone": "+8801521483999",
  "is_active": false,
  "is_activation_sent": true,
  "activation_code": "9815",
  "is_phone_confirmed": false,
  "is_email_active": false,
  "is_email_activation_sent": true,
  "email_activation_code": "7529c11c2b0eb55314fb01355d5cc78f",
  "is_email_confirmed": false,
  "friends": [
    {
      "identity": "bb30337b7fbcc5080b9fe3a2b6a60383",
      "username": "Shuvro",
      "first_name": "lord",
      "middle_name": "",
      "last_name": "",
      "email": "shuvro@test.com",
      "phone": "+8801521483720",
      "request_status": "PENDING",
      "request_type": "RECEIVED",
      "request_created_at": {
        "$date": {
          "$numberLong": "1580676652938"
        }
      }
    },
    {
      "identity": "06df8a2dd85c3ebc5b49817333f2aeff",
      "username": "",
      "first_name": "test",
      "middle_name": "",
      "last_name": "test last",
      "phone": "+8801521474747",
      "request_status": "PENDING",
      "request_type": "RECEIVED",
      "request_created_at": {
        "$date": {
          "$numberLong": "1581876704806"
        }
      }
    }
  ]
}
</code>```

Please help, how can I filter out the friends by their name from the parent document.
Thanks.

答:
You can try using a __raw__ query using the mongodb regex operator, for example:

```<code>AccountModel.objects(__raw__={"friends": { "$elemMatch": { "first_name": { "$regex": ".*test.*" } } } })
</code>```

Obviously, if you want to limit the results to only one user, you shall pass the account id together.

```<code>AccountModel.objects(__raw__={"friends": { "$elemMatch": { "first_name": { "$regex": ".*test.*" } } }, "_id" : account.id })
</code>```

Hope it suits you well.

Body:
I am trying to filter embedded documents by String (LIKE Query SQL equivalent) from the parent document.

Here's what I have now:

def resolve_friend(root, info, **kwargs):
    phone = kwargs.get('phone', None)
    search_string = kwargs.get('searchString', None)
    try:
        // I am retrieving the parent doucment by phone number first
        account = AccountModel.objects(phone=phone).first()

        if account is None:
            return ResponseMessageField(is_success=False, message="User does not exists.")

        top_friends = None

        // Now I want to filter the Friends field from the account by the search string.
        // In the friends' field, there are multiple documents.  The idea is to get the friends
        // matching the string from their first_name / last_name

        if search_string:
            regex = re.compile('.*' + search_string + '.*', re.IGNORECASE)

            //doesn't work any of these below
            # top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test')))
            top_friends = AccountModel.objects(friends__first_name__icontains='tes').all()

        all_friends = account.friends.filter(request_status="ACCEPTED")   //this works fine
        return retrieve_friend_list_graphql(top_friends=top_friends, all_friends=all_friends)
    except Exception as e:
        return ResponseMessageField(is_success=False, message="Account fetch error. " + str(e))

These lines don't work

top_friends = account.friends.filter((Q(first_name='test') | Q(last_name='test')))

top_friends = AccountModel.objects(friends__first_name__icontains='tes').all()

I am unable to filter the account.friends.filter() with the search string in mongoengine.

Here's the full account document with the friends field.

{
  "_id": {
    "$oid": "5e3485c2dd26ea191faf2861"
  },
  "identity": "0b1170fc50979464c352c34c2e9fd7aa",
  "username": "Shuvro",
  "first_name": "",
  "middle_name": "",
  "last_name": "",
  "phone": "+8801521483999",
  "is_active": false,
  "is_activation_sent": true,
  "activation_code": "9815",
  "is_phone_confirmed": false,
  "is_email_active": false,
  "is_email_activation_sent": true,
  "email_activation_code": "7529c11c2b0eb55314fb01355d5cc78f",
  "is_email_confirmed": false,
  "friends": [
    {
      "identity": "bb30337b7fbcc5080b9fe3a2b6a60383",
      "username": "Shuvro",
      "first_name": "lord",
      "middle_name": "",
      "last_name": "",
      "email": "shuvro@test.com",
      "phone": "+8801521483720",
      "request_status": "PENDING",
      "request_type": "RECEIVED",
      "request_created_at": {
        "$date": {
          "$numberLong": "1580676652938"
        }
      }
    },
    {
      "identity": "06df8a2dd85c3ebc5b49817333f2aeff",
      "username": "",
      "first_name": "test",
      "middle_name": "",
      "last_name": "test last",
      "phone": "+8801521474747",
      "request_status": "PENDING",
      "request_type": "RECEIVED",
      "request_created_at": {
        "$date": {
          "$numberLong": "1581876704806"
        }
      }
    }
  ]
}

Please help, how can I filter out the friends by their name from the parent document.
Thanks.

Body:
You can try using a __raw__ query using the mongodb regex operator, for example:

AccountModel.objects(__raw__={"friends": { "$elemMatch": { "first_name": { "$regex": ".*test.*" } } } })

Obviously, if you want to limit the results to only one user, you shall pass the account id together.

AccountModel.objects(__raw__={"friends": { "$elemMatch": { "first_name": { "$regex": ".*test.*" } } }, "_id" : account.id })

Hope it suits you well.


问:
Update a managed metadata column with multiple values using CSOM
I have the following code inside my remote event reciever, to create a new folder, and then populate the folder managed metadata fields with the current item (item that was added) values:-

```<code>ListItem listItem = context.Web.GetList(webrelativeurl +  "/"+i2["TemplateListUrl"]).AddItem(listItemCreationInformation);

listItem["FolderType"] = currentitem["FolderType"];
listItem["CorpType"] = currentitem["CorpType"];
</code>```

now the FodlerType on both the current item and the listitem is a managed metadata column which allow single value only, while the CorpType allow multiple values. my above code will assign a value for the FolderType correctly, but will raise this error when updating the CorpType:-

Microsoft.SharePoint.Client.ClientRequestException

  HResult=0x80131500   Message=The object is not associated with an
  object identity or the object identity is invalid.   Source=   StackTrace:

any advice?

答:
You need to get a TaxonomyFieldValueCollection use the SetFieldValueByValueCollection of the TaxonomyField object.

var field = item.ParentList.Fields.GetByInternalNameOrTitle("CorpType");
var corpTypeTaxField = context.CastTo<TaxonomyField>(field);
context.Load(item,i=>i[TaxKeywordFieldName]);
var valuesToCopy = corpTypeTaxField.GetFieldValueByValueCollection(currentitem["CorpType"].ToString());
corpTypeTaxField.SetFieldValueByValueCollection(listItem, valuesToCopy);

```

Note, this gets a lot messier if you have terms that you need to look up to construct a TaxonomyFieldValueCollection from scratch -- copying it from another item is definitely easier.

Body:
I have the following code inside my remote event reciever, to create a new folder, and then populate the folder managed metadata fields with the current item (item that was added) values:-

ListItem listItem = context.Web.GetList(webrelativeurl +  "/"+i2["TemplateListUrl"]).AddItem(listItemCreationInformation);

listItem["FolderType"] = currentitem["FolderType"];
listItem["CorpType"] = currentitem["CorpType"];

now the FodlerType on both the current item and the listitem is a managed metadata column which allow single value only, while the CorpType allow multiple values. my above code will assign a value for the FolderType correctly, but will raise this error when updating the CorpType:-

Microsoft.SharePoint.Client.ClientRequestException

  HResult=0x80131500   Message=The object is not associated with an
  object identity or the object identity is invalid.   Source=   StackTrace:

any advice?

Body:
You need to get a TaxonomyFieldValueCollection use the SetFieldValueByValueCollection of the TaxonomyField object.

var field = item.ParentList.Fields.GetByInternalNameOrTitle("CorpType");
var corpTypeTaxField = context.CastTo<TaxonomyField>(field);
context.Load(item,i=>i[TaxKeywordFieldName]);
var valuesToCopy = corpTypeTaxField.GetFieldValueByValueCollection(currentitem["CorpType"].ToString());
corpTypeTaxField.SetFieldValueByValueCollection(listItem, valuesToCopy);

Note, this gets a lot messier if you have terms that you need to look up to construct a TaxonomyFieldValueCollection from scratch -- copying it from another item is definitely easier.


问:
How to create a 0x appended hex string from a hex string for each byte of hex characters in golang?
Using the following as a starting point I was able to get something working.

How to insert a Character every X Characters in a String in Golang?

But I want to know if there is an idiomatic way to write golang for what I wan to do, which is the output of the first fmt.Println shown below:
```<code>package main

import (
    "bytes"
    "fmt"
)

func insertStringInto(s string, interval int, sep string) string {
    var buffer bytes.Buffer
    before := interval - 1
    last := len(s) - 1
    for i, char := range s {
        buffer.WriteRune(char)
        if i%interval == before && i != last {
            buffer.WriteString(sep)
        }
    }
    return buffer.String()
}

func main() {
    fmt.Println("0x" + insertStringInto("01234567891011121314151617181920", 2, ", 0x"))

    fmt.Println(insertStringInto("01234567891011121314151617181920", 2, ", 0x"))
}
</code>```

Produces the following:

```<code>0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
</code>```

Link to play.golang.org below:

https://play.golang.org/p/TvLFAKsrcCB

答:
You can use regex

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func AnotherWay(s string, after int, sep string) string {
    ex, _ := regexp.Compile(`([0-9]{2})`)
    return strings.TrimSuffix(ex.ReplaceAllString(s, sep+"$1, "), ", ")
}

func main() {
    fmt.Println(AnotherWay("01234567891011121314151617181920", 2, "0x"))
}
```

Body:
Using the following as a starting point I was able to get something working.

How to insert a Character every X Characters in a String in Golang?

But I want to know if there is an idiomatic way to write golang for what I wan to do, which is the output of the first fmt.Println shown below:

package main

import (
    "bytes"
    "fmt"
)

func insertStringInto(s string, interval int, sep string) string {
    var buffer bytes.Buffer
    before := interval - 1
    last := len(s) - 1
    for i, char := range s {
        buffer.WriteRune(char)
        if i%interval == before && i != last {
            buffer.WriteString(sep)
        }
    }
    return buffer.String()
}

func main() {
    fmt.Println("0x" + insertStringInto("01234567891011121314151617181920", 2, ", 0x"))

    fmt.Println(insertStringInto("01234567891011121314151617181920", 2, ", 0x"))
}

Produces the following:

0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20

Link to play.golang.org below:

https://play.golang.org/p/TvLFAKsrcCB


问:
how to call validation data from keras's ImageDataGenerator
I'm studying the MNIST dataset, and decided to try datageneration. Now directly:

I'm generating data using validation split as follows:

```<code>datagen = keras.preprocessing.image.ImageDataGenerator(... , validation_split=0.21, ...)

datagen.fit(train_x)
</code>```

but i don't know hot to call the validation split of this into the model's fit

```<code>hist = model.fit_generator(datagen.flow(train_x, train_y, batch_size =32),
                                steps_per_epoch=len(train_x)//32,
                                epochs = 70, verbose=0, callbacks= [PlotLossesKeras()],
                                validation_data= **???**, <-----
                                validation_steps=None,
                                validation_freq=1,
                                class_weight=None,
                                max_queue_size=10,
                                workers=1,
                                use_multiprocessing=False,
                                shuffle=True,
                                initial_epoch=0)
</code>```

I couldn't find an answer in the documentation nor elsewhere. Can you help me?

答:
You should state which subset you are using: subset = 'validation', as the Keras documentation says:

subset: Subset of data ("training" or "validation") if validation_split is set in ImageDataGenerator.

So, for example, you could do as follows:

```<code>datagen = keras.preprocessing.image.ImageDataGenerator(..., validation_split=0.21)

train_generator = datagen.flow(..., subset='training')
valid_generator = datagen.flow(..., subset='validation')

hist = model.fit_generator(...,
        generator = train_generator,
        validation_data = valid_generator,
        steps_per_epoch = len(train_generator),
        validation_steps = len(valid_generator),
)
</code>```

You can see some examples provided by Keras itself as well, right after ImageDataGenerator class documentation

Body:
I'm studying the MNIST dataset, and decided to try datageneration. Now directly:

I'm generating data using validation split as follows:

datagen = keras.preprocessing.image.ImageDataGenerator(... , validation_split=0.21, ...)

datagen.fit(train_x)

but i don't know hot to call the validation split of this into the model's fit

hist = model.fit_generator(datagen.flow(train_x, train_y, batch_size =32),
                                steps_per_epoch=len(train_x)//32,
                                epochs = 70, verbose=0, callbacks= [PlotLossesKeras()],
                                validation_data= **???**, <-----
                                validation_steps=None,
                                validation_freq=1,
                                class_weight=None,
                                max_queue_size=10,
                                workers=1,
                                use_multiprocessing=False,
                                shuffle=True,
                                initial_epoch=0)

I couldn't find an answer in the documentation nor elsewhere. Can you help me?

Body:
You should state which subset you are using: subset = 'validation', as the Keras documentation says:

subset: Subset of data ("training" or "validation") if validation_split is set in ImageDataGenerator.

So, for example, you could do as follows:

datagen = keras.preprocessing.image.ImageDataGenerator(..., validation_split=0.21)

train_generator = datagen.flow(..., subset='training')
valid_generator = datagen.flow(..., subset='validation')

hist = model.fit_generator(...,
        generator = train_generator,
        validation_data = valid_generator,
        steps_per_epoch = len(train_generator),
        validation_steps = len(valid_generator),
)

You can see some examples provided by Keras itself as well, right after ImageDataGenerator class documentation


问:
R- Every Other Number of a Sequence Negative
I'm trying to generate a series of vectors to calculate the approx. value of Pi using this formula given:
Pi = 4 (1- (1/3) + (1/5) -(1/7)...
for 7 terms.
I made a sequence for the denominator values as such

```<code>number.terms3c <-7
seq.vec3c <- seq(from = 1, by = 2 , length.out = number.terms3c)
</code>```

and would then use that vector to get the reciprocals with

```<code>recip.vec3c <- (1/ seq.vec3c)
</code>```

But in order to sum them, I was thinking I needed to get every other value to be negative (hence the alternating + and - values.

Is there a simple code I can learn to do this?

答:
Remember you can generate a sequence of n numbers in R with 1:n, and you can get any number modulo 2 by doing x %% 2. So 1:n %% 2 gives a repeating sequence of 1 0 1 0 1 0. Therefore multiplying this by 2 and subtracting 1 gives the repeating sequence 1 -1 1 -1 1 -1.... You can therefore use (2*(1:n %% 2) - 1) as your numerators.

Similarly, your denominators are just a sequence of odd numbers, given by 1:n * 2 - 1

This means you can write a simple arithmetic function to sum the first n terms of this expansion like this:

```<code>pi_fracts <- function(n) sum(4*(2*(1:n %% 2) - 1)/(1:n * 2 - 1))
</code>```

So you can do

```<code>pi_fracts(7)
#> [1] 3.283738
</code>```

or even

```<code>pi_fracts(1000000)
#> [1] 3.141592
</code>```

Body:
I'm trying to generate a series of vectors to calculate the approx. value of Pi using this formula given:
Pi = 4 (1- (1/3) + (1/5) -(1/7)...
for 7 terms.
I made a sequence for the denominator values as such

number.terms3c <-7
seq.vec3c <- seq(from = 1, by = 2 , length.out = number.terms3c)

and would then use that vector to get the reciprocals with

recip.vec3c <- (1/ seq.vec3c)

But in order to sum them, I was thinking I needed to get every other value to be negative (hence the alternating + and - values.

Is there a simple code I can learn to do this?

Body:
Remember you can generate a sequence of n numbers in R with 1:n, and you can get any number modulo 2 by doing x %% 2. So 1:n %% 2 gives a repeating sequence of 1 0 1 0 1 0. Therefore multiplying this by 2 and subtracting 1 gives the repeating sequence 1 -1 1 -1 1 -1.... You can therefore use (2*(1:n %% 2) - 1) as your numerators.

Similarly, your denominators are just a sequence of odd numbers, given by 1:n * 2 - 1

This means you can write a simple arithmetic function to sum the first n terms of this expansion like this:

pi_fracts <- function(n) sum(4*(2*(1:n %% 2) - 1)/(1:n * 2 - 1))

So you can do

pi_fracts(7)
#> [1] 3.283738

or even

pi_fracts(1000000)
#> [1] 3.141592


问:
How do I convert a component with a constructor function and props, to a functional component using hooks and props
I'm trying to optimize images on my web app on the go. I'm trying to modify code that works as a class function with a constructor, into a functional component that uses hooks.

The reason I need it to be a functional component is that I need props to be passed. I need it to be reusable. I need to do this: If I can do this in the code with the constructor, please please let me know or point me somewhere, that's a viable option.

I need to be reusable so that I can use it on all my img elements, in this respect:

I've only been able to achieve this with a functional component. This is why I'm trying to make this into a functional component. To achieve a specific problem I am unable to do because of that constructor function.

This is the working Constructor code:

```<code>import React from "react";
import ReactDOM from "react-dom";

import TestImage from "./test-image.png";

export default class ImgOptimise extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      width: 0
    };
    this.imgRef = React.createRef();
  }

  componentDidMount() {
    const width = this.imgRef.current.clientWidth;
    this.setState({
      width
    });
  }

  render() {
    // Destructure props and state
    const { src, alt, options = {}, ext = "jpg" } = this.props;
    const { width } = this.state;

    // Create an empty query string
    let queryString = "";

    // If width is specified, otherwise use auto-detected width
    options["w"] = options["w"] || width;

    // Loop through option object and build queryString
    Object.keys(options).map((option, i) => {
      return (queryString += `${i < 1 ? "?" : "&"}${option}=${
        options[option]
      }`);
    });

    return (
      <figure ref={this.imgRef}>
        {// If the container width has been set, display the image else null
        width > 0 ? (
          <>
            <img src={TestImage} alt="test" />
          </>
        ) : null}
      </figure>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ImgOptimise />, rootElement);

</code>```

This is my code for translating it to a functional component using hooks

https://codesandbox.io/live/Wr7V4

Full Code below:

```<code>import React, { useState, useEffect } from "react";
import TestImage from "./test-image.png";

const ImgOptimise = props => {
  // Destructure props and state
  const { src, alt, options = {}, ext = "jpg" } = useEffect(0);
  const [width] = useState(0);

  const imgRef = React.createRef();
  useEffect(() => {
    const width = imgRef.current.clientWidth;
  }, []);

  // Create an empty query string
  let queryString = "";
  // If width is specified, otherwise use auto-detected width
  options["w"] = options["w"] || width;
  // Loop through option object and build queryString
  Object.keys(options).map((option, i) => {
    return (queryString += `${i < 1 ? "?" : "&"}${option}=${options[option]}`);
  });
  return (
    // If the container width has been set, display the image else null
    <figure ref={imgRef}>
      {// If the container width has been set, display the image else null
      width > 0 ? (
        <>
          <img src={TestImage} />
        </>
      ) : null}
    </figure>
  );
};
export default ImgOptimise;

const rootElement = document.getElementById("root");
ReactDOM.render(<ImgOptimise />, rootElement);

</code>```

ERROR: TypeError: Cannot destructure property 'src' of 'Object(...)(...)' as it is undefined.

something to do with this, I'm not sure how to destructure it properly:

//Constructor
const { src, alt, options = {}, ext = "jpg" } = this.props;

//Hooks
const { src, alt, options = {}, ext = "jpg" } = useEffect(0);

I'm also not sure if I translated this properly

```<code>    this.imgRef = React.createRef();
  }

  componentDidMount() {
    const width = this.imgRef.current.clientWidth;
    this.setState({
      width
    });
  }
</code>```

to this:

```<code> const [width] = useState(0);
  // const [nameState , setNameState] = useState(props);
  const imgRef = React.createRef();
  useEffect(() => {
    const width = imgRef.current.clientWidth;
  }, []);
</code>```

Any Help changing this from a class component to a functional component will be greatly appreciated.

UPDATE

Turns out mine was a rookie mistake. I overlooked this

Even though my problem has been solved, I will leave the question open as it will be interesting to see this turned into a functional component, because, well, why not?

答:
If these are your props, you just need to destructure them, not apply useEffect().

```<code>const { src, alt, options = {}, ext = "jpg" } = props;
</code>```

For your state, you need to define a function along with your state variable.

```<code>const [width, setWidth] = useState(0);
</code>```

Then call that function to update width.

```<code>setWidth(imgRef.current.clientWidth);
</code>```

More info can be found by searching, e.g. https://duckduckgo.com/?q=how+to+convert+react+component+to+hooks&ia=web , which results in some good articles like https://alligator.io/react/converting-to-a-hook/

Body:
I'm trying to optimize images on my web app on the go. I'm trying to modify code that works as a class function with a constructor, into a functional component that uses hooks.

The reason I need it to be a functional component is that I need props to be passed. I need it to be reusable. I need to do this: If I can do this in the code with the constructor, please please let me know or point me somewhere, that's a viable option.

I need to be reusable so that I can use it on all my img elements, in this respect:

I've only been able to achieve this with a functional component. This is why I'm trying to make this into a functional component. To achieve a specific problem I am unable to do because of that constructor function.

This is the working Constructor code:

import React from "react";
import ReactDOM from "react-dom";

import TestImage from "./test-image.png";

export default class ImgOptimise extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      width: 0
    };
    this.imgRef = React.createRef();
  }

  componentDidMount() {
    const width = this.imgRef.current.clientWidth;
    this.setState({
      width
    });
  }

  render() {
    // Destructure props and state
    const { src, alt, options = {}, ext = "jpg" } = this.props;
    const { width } = this.state;

    // Create an empty query string
    let queryString = "";

    // If width is specified, otherwise use auto-detected width
    options["w"] = options["w"] || width;

    // Loop through option object and build queryString
    Object.keys(options).map((option, i) => {
      return (queryString += `${i < 1 ? "?" : "&"}${option}=${
        options[option]
      }`);
    });

    return (

        {// If the container width has been set, display the image else null
        width > 0 ? (
          <>

          </>
        ) : null}

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ImgOptimise />, rootElement);

This is my code for translating it to a functional component using hooks

https://codesandbox.io/live/Wr7V4

Full Code below:

import React, { useState, useEffect } from "react";
import TestImage from "./test-image.png";

const ImgOptimise = props => {
  // Destructure props and state
  const { src, alt, options = {}, ext = "jpg" } = useEffect(0);
  const [width] = useState(0);

  const imgRef = React.createRef();
  useEffect(() => {
    const width = imgRef.current.clientWidth;
  }, []);

  // Create an empty query string
  let queryString = "";
  // If width is specified, otherwise use auto-detected width
  options["w"] = options["w"] || width;
  // Loop through option object and build queryString
  Object.keys(options).map((option, i) => {
    return (queryString += `${i < 1 ? "?" : "&"}${option}=${options[option]}`);
  });
  return (
    // If the container width has been set, display the image else null

      {// If the container width has been set, display the image else null
      width > 0 ? (
        <>

        </>
      ) : null}

  );
};
export default ImgOptimise;

const rootElement = document.getElementById("root");
ReactDOM.render(<ImgOptimise />, rootElement);

ERROR: TypeError: Cannot destructure property 'src' of 'Object(...)(...)' as it is undefined.

something to do with this, I'm not sure how to destructure it properly:

//Constructor
const { src, alt, options = {}, ext = "jpg" } = this.props;

//Hooks
const { src, alt, options = {}, ext = "jpg" } = useEffect(0);

I'm also not sure if I translated this properly

    this.imgRef = React.createRef();
  }

  componentDidMount() {
    const width = this.imgRef.current.clientWidth;
    this.setState({
      width
    });
  }

to this:

 const [width] = useState(0);
  // const [nameState , setNameState] = useState(props);
  const imgRef = React.createRef();
  useEffect(() => {
    const width = imgRef.current.clientWidth;
  }, []);

Any Help changing this from a class component to a functional component will be greatly appreciated.

UPDATE

Turns out mine was a rookie mistake. I overlooked this

Even though my problem has been solved, I will leave the question open as it will be interesting to see this turned into a functional component, because, well, why not?

Body:
If these are your props, you just need to destructure them, not apply useEffect().

const { src, alt, options = {}, ext = "jpg" } = props;

For your state, you need to define a function along with your state variable.

const [width, setWidth] = useState(0);

Then call that function to update width.

setWidth(imgRef.current.clientWidth);

More info can be found by searching, e.g. https://duckduckgo.com/?q=how+to+convert+react+component+to+hooks&ia=web , which results in some good articles like https://alligator.io/react/converting-to-a-hook/


问:
Update Firestore values when App is minimised/closed
Trying to find which one of these Background Processing methods suits my case.

Case: How can I update fields on Firestore when application is running on the background or when it's closed?

Short Description: User inputs time (milliseconds) and when that time is over I want to update the fields in Firestore no matter if the app is running or closed, I currently have this code:

```<code> private void setTaskEndTime(long xEndTime) {
        long mLeftTime = xEndTime - mCurrentTime;

        new CountDownTimer(mLeftTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                //HERE <===================

            }
        }.start();

    }
</code>```

I have tried Firebase Cloud Function; so that when the time is over it was supposed to update the fields but the problem is the Cloud Function takes too much time before updating the fields (or at least my code):

```<code>const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();

exports.wtf = functions.region('europe-west1').firestore
    .document('Users/{userId}/Tasks/{docId}')
    .onUpdate((docSnapshot, context) => {
        var mUserID = context.params.userId;  //Document userID
        var mDocID = context.params.docId;    //Document taskID

        var oldSnapshot = docSnapshot.before.data();
        var oldCurrentStatus = oldSnapshot.taskCurrentStatus;
        var newSnapshot = docSnapshot.after.data();
        var newCurrentStatus = newSnapshot.taskCurrentStatus;

        var tempTime = newSnapshot.temporaryTime;

        let cityRef = db.collection('Users').doc(mUserID).collection('Tasks').doc(mDocID);

        if (newCurrentStatus !== oldCurrentStatus && newCurrentStatus > 0) {

            const myFunc = () => {
                //Gets dd/MM/yyyy date and stores it in 'today'
                var today = new Date();
                var dd = String(today.getDate()).padStart(2, '0');
                var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
                var yyyy = today.getFullYear();
                today = dd + '/' + mm + '/' + yyyy;

                let days = cityRef.update({
                    taskCompletedDays: admin.firestore.FieldValue.arrayUnion(today)
                });
                let hours = cityRef.update({
                    taskCompletedHours: admin.firestore.FieldValue.increment(tempTime)
                });
                let status = cityRef.update({ taskCurrentStatus: 0 });
            }

            setTimeout(myFunc, tempTime);

        }
        return true;
    });
</code>```

答:
Code scheduled with setTimeout is not guaranteed to execute correctly in Cloud Functions.  A background Cloud Function (including Firestore triggers) must return a promise that resolves when all of the asynchronous work is complete.  After that, any pending work might get canceled or simply not execute correctly.  In short, don't depend on setTimeout unless you're 1) willing to return a promise that resolves only after the work is complete, and 2) never going to exceed the maximum configurable 9 minute timeout for Cloud Functions.

What you should do instead is use Google Cloud Tasks to schedule a future invocation of another (HTTP) function after some elapsed amount of time has expired.  You can read a detailed description in this blog post.

Body:
Trying to find which one of these Background Processing methods suits my case.

Case: How can I update fields on Firestore when application is running on the background or when it's closed?

Short Description: User inputs time (milliseconds) and when that time is over I want to update the fields in Firestore no matter if the app is running or closed, I currently have this code:

 private void setTaskEndTime(long xEndTime) {
        long mLeftTime = xEndTime - mCurrentTime;

        new CountDownTimer(mLeftTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                //HERE <===================

            }
        }.start();

    }

I have tried Firebase Cloud Function; so that when the time is over it was supposed to update the fields but the problem is the Cloud Function takes too much time before updating the fields (or at least my code):

const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();

exports.wtf = functions.region('europe-west1').firestore
    .document('Users/{userId}/Tasks/{docId}')
    .onUpdate((docSnapshot, context) => {
        var mUserID = context.params.userId;  //Document userID
        var mDocID = context.params.docId;    //Document taskID

        var oldSnapshot = docSnapshot.before.data();
        var oldCurrentStatus = oldSnapshot.taskCurrentStatus;
        var newSnapshot = docSnapshot.after.data();
        var newCurrentStatus = newSnapshot.taskCurrentStatus;

        var tempTime = newSnapshot.temporaryTime;

        let cityRef = db.collection('Users').doc(mUserID).collection('Tasks').doc(mDocID);

        if (newCurrentStatus !== oldCurrentStatus && newCurrentStatus > 0) {

            const myFunc = () => {
                //Gets dd/MM/yyyy date and stores it in 'today'
                var today = new Date();
                var dd = String(today.getDate()).padStart(2, '0');
                var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
                var yyyy = today.getFullYear();
                today = dd + '/' + mm + '/' + yyyy;

                let days = cityRef.update({
                    taskCompletedDays: admin.firestore.FieldValue.arrayUnion(today)
                });
                let hours = cityRef.update({
                    taskCompletedHours: admin.firestore.FieldValue.increment(tempTime)
                });
                let status = cityRef.update({ taskCurrentStatus: 0 });
            }

            setTimeout(myFunc, tempTime);

        }
        return true;
    });


问:
Can UIView and UIImagView implement touch events simultaneously?
In the UIView, there is several sub views of UIImageView objects.

Since I need to detect the touch events from the UIImageView and from the remaining area of the UIView.

Can I implement touch events in UIView and UIImagView simultaneously ?

Thanks.

答:
Based on your comment, I think you should consider gesture recognizers. Use the UITapGestureRecognizer to identify and respond to taps on a view.

```<code>UITapGestureRecognizer *tapGesture;

tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnView:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
[view addGesture:tapGesture];
[tapGesture release];

...

tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnImage:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
[imageView addGesture:tapGesture];
[tapGesture release];

...
</code>```

define -(void)handleTapOnView:(UITapGestureRecognizer*)gesture and -(void)handleTapOnImage:(UITapGestureRecognizer*)gestureand handle the touches there.

There are other kinds of gestures too. You can read more about them here.

Body:
Based on your comment, I think you should consider gesture recognizers. Use the UITapGestureRecognizer to identify and respond to taps on a view.

UITapGestureRecognizer *tapGesture;

tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnView:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
[view addGesture:tapGesture];
[tapGesture release];

...

tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnImage:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
[imageView addGesture:tapGesture];
[tapGesture release];

...

define -(void)handleTapOnView:(UITapGestureRecognizer*)gesture and -(void)handleTapOnImage:(UITapGestureRecognizer*)gestureand handle the touches there.

There are other kinds of gestures too. You can read more about them here.