问:
Python create_task does not work in running event loop
I have a simple piece of code driving me crazy for a while. I have posted this question some days ago asking create_task is not working with input. Now I have figured out something related to this. I am running event loop in a separate thread and pushing tasks in it. Very straight forward code.

```<code>import asyncio
import threading

async def printer(message):
    print(f'[printer] {message}')

def loop_runner(loop):
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    t = threading.Thread(target=loop_runner, args=(event_loop,))
    t.start()

    for m in ['hello', 'world', 'foo', 'bar']:
        print(f'[loop running ?] {event_loop.is_running()}')
        event_loop.create_task(printer(m))
</code>```

Nothing gets printed but these log messages.

```<code>[loop running ?] True
[loop running ?] True
[loop running ?] True
[loop running ?] True
</code>```

Now if I block in event loop thread and let it run after a pause like this.

```<code>def loop_runner(loop):
    time.sleep(1 / 1000)
    loop.run_forever()
</code>```

Everything works and this gets printed

```<code>[loop running ?] False
[loop running ?] False
[loop running ?] False
[loop running ?] False
[printer] hello
[printer] world
[printer] foo
[printer] bar
</code>```

From surface it looks like tasks created in running event loop do not get executed. But why is that?

I have not seen anything regarding this in documentation. In most of the examples I have seen on internet people are creating tasks in loop from other coroutines and awaiting for them. But I think it is legal to use create tasks outside coroutine if you do not want to await for them.

答:
When creating task from outside the event loop thread, you need to use asyncio.run_coroutine_threadsafe. That function will schedule the coroutine in a thread-safe manner and notify the event loop that there is new work to be done. It will also return a concurrent.futures.Future object which you can use to block the current thread until the result is available.

From surface it looks like tasks created in running event loop do not get executed. But why is that?

Calling create_task is insufficient because it doesn't contain code to "wake up" the event loop. This is a feature - such wakeup is normally not needed, and adding it would just slow down the regular single-threaded use. When create_task is invoked from the event loop thread, it is inside an event loop callback, so the event loop can check its task queue as soon as it regains control, when it is done executing the callback. But when create_task is invoked from a different thread, the event loop is asleep waiting for IO, so run_coroutine_threadsafe is needed to wake it up.

To test this, you can create a "heartbeat" coroutine, which only contains an infinite loop that prints something and awaits asyncio.sleep(1). You'll see that the tasks created with create_task get executed along with the heartbeat, which also happens to wake up the event loop. In busy asyncio applications this effect can give the impression that create_task from another thread "works". However, this should never be relied on, as create_task fails to implement proper locking and could corrupt the event loop internals.

I have not seen anything regarding this in documentation.

Take a look at the concurrency and multithreading section.

Body:
I have a simple piece of code driving me crazy for a while. I have posted this question some days ago asking create_task is not working with input. Now I have figured out something related to this. I am running event loop in a separate thread and pushing tasks in it. Very straight forward code.

import asyncio
import threading

async def printer(message):
    print(f'[printer] {message}')

def loop_runner(loop):
    loop.run_forever()

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    t = threading.Thread(target=loop_runner, args=(event_loop,))
    t.start()

    for m in ['hello', 'world', 'foo', 'bar']:
        print(f'[loop running ?] {event_loop.is_running()}')
        event_loop.create_task(printer(m))

Nothing gets printed but these log messages.

[loop running ?] True
[loop running ?] True
[loop running ?] True
[loop running ?] True

Now if I block in event loop thread and let it run after a pause like this.

def loop_runner(loop):
    time.sleep(1 / 1000)
    loop.run_forever()

Everything works and this gets printed

[loop running ?] False
[loop running ?] False
[loop running ?] False
[loop running ?] False
[printer] hello
[printer] world
[printer] foo
[printer] bar

From surface it looks like tasks created in running event loop do not get executed. But why is that?

I have not seen anything regarding this in documentation. In most of the examples I have seen on internet people are creating tasks in loop from other coroutines and awaiting for them. But I think it is legal to use create tasks outside coroutine if you do not want to await for them.


来源: stackexchange

问:
how to parse multi index values and create a csv file while parsing json data in python
I have few static key columns EmployeeId,type and few columns coming from first FOR loop.

While in the second FOR loop if i have a specific key then only values should be appended to the existing data frame columns else whatever the columns getting fetched from first for loop should remain same.

First For Loop Output:

```<code>"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","","",""
</code>```

After Second For Loop i have below output:

```<code>"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","AMAZON","1",""
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","FLIPKART","2",""
</code>```

As per code if i have Employee tag available , i have got above 2 records but i may have few json files without Employee tag then output should remain same as per First Loop Output.

But i am getting 0 records as per my code. Please help me if my way of coding is wrong.

Really sorry -- If the way of asking question is not clear , as i am new to python .  Please find the code in the below hyper link

Please find below code

```<code>    for i in range(len(json_file['enty'])):
        temp = {}
        temp['EmployeeId'] = json_file['enty'][i]['id']
        temp['type'] = json_file['enty'][i]['type']
        for key in json_file['enty'][i]['data']['attributes'].keys():
            try:
                temp[key] = json_file['enty'][i]['data']['attributes'][key]['values'][0]['value']
            except:
                temp[key] = None

        for key in json_file['enty'][i]['data']['attributes'].keys():
            if(key == 'Employee'):
                for j in range(len(json_file['enty'][i]['data']['attributes']['Employee']['group'])):
                    for key in json_file['enty'][i]['data']['attributes']['Employee']['group'][j].keys():
                        try:
                            temp[key] = json_file['enty'][i]['data']['attributes']['Employee']['group'][j][key]['values'][0]['value']
                        except:
                            temp[key] = None

                    temp_df = pd.DataFrame([temp])
                    df = pd.concat([df, temp_df], sort=True)

    # Rearranging columns
    df = df[['EmployeeId', 'type'] + [col for col in df.columns if col not in ['EmployeeId', 'type']]]

    # Writing the dataset
    df[columns_list].to_csv("Test22.csv", index=False, quotechar='"', quoting=1)
</code>```

If Employee Tag is not available i am getting 0 records as output but i am expecting 1 record as per output of first FOR loop. If the "Employee tag" is available then i am expecting 2 records along with my static columns "EmployeeId","type","KeyColumn","Start","End", else if the tag is not available then all the static columns "EmployeeId","type","KeyColumn","Start","End", and remaining columns as blanks

enter link description here

答:
A long solution with modifying your code, so adding one more loop, changing indexes, as well as modifying the range parameters:

```<code>df = pd.DataFrame()

num = max([len(v) for k,v in json_file['data'][0]['data1'].items()])
for i in range(num):
    temp = {}
    temp['Empid'] = json_file['data'][0]['Empid']
    temp['Empname'] = json_file['data'][0]['Empname']
    for key in json_file['data'][0]['data1'].keys():
        if key not in temp:
            temp[key] = []
        try:
            for j in range(len(json_file['data'][0]['data1'][key])):
                temp[key].append(json_file['data'][0]['data1'][key][j]['relative']['id'])
        except:
            temp[key] = None
    temp_df = pd.DataFrame([temp])
    df = pd.concat([df, temp_df],ignore_index=True)
for i in json_file['data'][0]['data1'].keys():
    df[i] = pd.Series([x for y in df[i].tolist() for x in y]).drop_duplicates()
</code>```

And now:

```<code>print(df)
</code>```

Is:

```<code>  Empid Empname    XXXX   YYYYY
0  1234     ABC  Naveen   Kumar
1  1234     ABC     NaN  Rajesh
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have few static key columns EmployeeId,type and few columns coming from first FOR loop.

While in the second FOR loop if i have a specific key then only values should be appended to the existing data frame columns else whatever the columns getting fetched from first for loop should remain same.

First For Loop Output:

"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","","",""

After Second For Loop i have below output:

"EmployeeId","type","KeyColumn","Start","End","Country","Target","CountryId","TargetId"
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","AMAZON","1",""
"Emp1","Metal","1212121212","2000-06-17","9999-12-31","","FLIPKART","2",""

As per code if i have Employee tag available , i have got above 2 records but i may have few json files without Employee tag then output should remain same as per First Loop Output.

But i am getting 0 records as per my code. Please help me if my way of coding is wrong.

Really sorry -- If the way of asking question is not clear , as i am new to python .  Please find the code in the below hyper link

Please find below code

    for i in range(len(json_file['enty'])):
        temp = {}
        temp['EmployeeId'] = json_file['enty'][i]['id']
        temp['type'] = json_file['enty'][i]['type']
        for key in json_file['enty'][i]['data']['attributes'].keys():
            try:
                temp[key] = json_file['enty'][i]['data']['attributes'][key]['values'][0]['value']
            except:
                temp[key] = None

        for key in json_file['enty'][i]['data']['attributes'].keys():
            if(key == 'Employee'):
                for j in range(len(json_file['enty'][i]['data']['attributes']['Employee']['group'])):
                    for key in json_file['enty'][i]['data']['attributes']['Employee']['group'][j].keys():
                        try:
                            temp[key] = json_file['enty'][i]['data']['attributes']['Employee']['group'][j][key]['values'][0]['value']
                        except:
                            temp[key] = None

                    temp_df = pd.DataFrame([temp])
                    df = pd.concat([df, temp_df], sort=True)

    # Rearranging columns
    df = df[['EmployeeId', 'type'] + [col for col in df.columns if col not in ['EmployeeId', 'type']]]

    # Writing the dataset
    df[columns_list].to_csv("Test22.csv", index=False, quotechar='"', quoting=1)

If Employee Tag is not available i am getting 0 records as output but i am expecting 1 record as per output of first FOR loop. If the "Employee tag" is available then i am expecting 2 records along with my static columns "EmployeeId","type","KeyColumn","Start","End", else if the tag is not available then all the static columns "EmployeeId","type","KeyColumn","Start","End", and remaining columns as blanks

enter link description here

Body:
A long solution with modifying your code, so adding one more loop, changing indexes, as well as modifying the range parameters:

df = pd.DataFrame()

num = max([len(v) for k,v in json_file['data'][0]['data1'].items()])
for i in range(num):
    temp = {}
    temp['Empid'] = json_file['data'][0]['Empid']
    temp['Empname'] = json_file['data'][0]['Empname']
    for key in json_file['data'][0]['data1'].keys():
        if key not in temp:
            temp[key] = []
        try:
            for j in range(len(json_file['data'][0]['data1'][key])):
                temp[key].append(json_file['data'][0]['data1'][key][j]['relative']['id'])
        except:
            temp[key] = None
    temp_df = pd.DataFrame([temp])
    df = pd.concat([df, temp_df],ignore_index=True)
for i in json_file['data'][0]['data1'].keys():
    df[i] = pd.Series([x for y in df[i].tolist() for x in y]).drop_duplicates()

And now:

print(df)

Is:

  Empid Empname    XXXX   YYYYY
0  1234     ABC  Naveen   Kumar
1  1234     ABC     NaN  Rajesh


问:
How do I initialize a result variable?
I need to make the result variable so that it is concatenated with my other strings to print my result and I tried multiple ways that are not working.

I have included my set of strings and first if statement to give an idea of my project.

My project rubric states "Initialize 'result' as a single string using concatenation. This string will contain the event type, party size, as as meal and preparation suggestions. Prints the result variable to the console." It also says " 'result' is a string that will be printed to the console.

```<code>import java.util.Scanner;

public class whatToEat {

    public static void main (String[] args) {
        int partySize;
        String eventType;

        System.out.println("Is your event Casual, Semi-Formal, or Formal?");
        Scanner sc = new Scanner(System.in);
        eventType = sc.next();

        System.out.println("How many people will your event have?");
        partySize = sc.nextInt();

        if (eventType.equals("Casual") && partySize == 1) {

            System.out.println("Since you're hosting a casual event for "
                    + partySize +
                    " person, you should serve sandwiches prepared in the mircowave. ");
</code>```

答:
Because it says that 'result' is a string that you print in console, I suggest you saving your information in a String first:

String result = "";

Then:

result = "Since you're hosting a casual event for "
+ partySize +
" person, you should serve sandwiches prepared in the mircowave."

Finally:

System.out.println(result);

Title: How do I initialize a result variable?

Body:
I need to make the result variable so that it is concatenated with my other strings to print my result and I tried multiple ways that are not working.

I have included my set of strings and first if statement to give an idea of my project.

My project rubric states "Initialize 'result' as a single string using concatenation. This string will contain the event type, party size, as as meal and preparation suggestions. Prints the result variable to the console." It also says " 'result' is a string that will be printed to the console.

import java.util.Scanner;

public class whatToEat {

    public static void main (String[] args) {
        int partySize;
        String eventType;

        System.out.println("Is your event Casual, Semi-Formal, or Formal?");
        Scanner sc = new Scanner(System.in);
        eventType = sc.next();

        System.out.println("How many people will your event have?");
        partySize = sc.nextInt();

        if (eventType.equals("Casual") && partySize == 1) {

            System.out.println("Since you're hosting a casual event for "
                    + partySize +
                    " person, you should serve sandwiches prepared in the mircowave. ");


问:
Phantom
 within carousel
Having more trouble with this infographic. There seems to be a phantom
 appearing at the end of the carousel. Does anyone know how this has appeared?

http://weaver-wp.weavertest.com/radiation-infographic/

Cheers,
Dave

答:
Might this be the cause?

```<code><div id="carousel">
<ul>
    <li></li>
</ul>
</code>```

Validator also says there is an unclose div ( wrapper div ) Doubt thats the issue though

ContentLicense: CC BY-SA 3.0

Title: Phantom <li> within carousel

Body:
Might this be the cause?

<div id="carousel">
<ul>
    <li></li>
</ul>

Validator also says there is an unclose div ( wrapper div ) Doubt thats the issue though


问:
How to print all the button texts within the url using Selenium through Java
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

```<code>package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}
</code>```

答:
Instead of using By.tagName method I used By.cssSelector method

here is the Working code...

```<code>package stackOverflow;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ToolsqaCom {

public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "D:\\Tushar\\JARs\\selenium\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    driver.get("https://www.toolsqa.com/automation-practice-switch-windows");
    driver.manage().window().maximize();

    // ArrayList<String> l1 = new ArrayList<String>();
    // WebElement b1 = driver.findElement(By.id("button1"));
    // l1.add(b1.getText());

    java.util.List<WebElement> b2 = driver.findElements(By.cssSelector("p button"));

    for (int i = 0; i < b2.size() - 1; i++) {
        String string = b2.get(i).getText();
        System.out.println(string);

    }}}
</code>```

Following is the Output:

New Browser Window

New Message Window

New Browser Tab

Alert Box

Timing Alert

Change Color

Change Color

Disabled

Body:
Steps:

Go to the site > https://www.toolsqa.com/automation-practice-switch-windows/

Get a list of buttons from that page

Print the name of the buttons that are displayed on the page.

Code trial:

package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }}}}

Body:
Instead of using By.tagName method I used By.cssSelector method

here is the Working code...

package stackOverflow;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ToolsqaCom {

public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "D:\\Tushar\\JARs\\selenium\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    driver.get("https://www.toolsqa.com/automation-practice-switch-windows");
    driver.manage().window().maximize();

    // ArrayList<String> l1 = new ArrayList<String>();
    // WebElement b1 = driver.findElement(By.id("button1"));
    // l1.add(b1.getText());

    java.util.List<WebElement> b2 = driver.findElements(By.cssSelector("p button"));

    for (int i = 0; i < b2.size() - 1; i++) {
        String string = b2.get(i).getText();
        System.out.println(string);

    }}}

Following is the Output:

New Browser Window

New Message Window

New Browser Tab

Alert Box

Timing Alert

Change Color

Change Color

Disabled


问:
compare string column with other column by row wise
I have a data frame as below,how to compare values from 2 columns.i.e row 1 has common string("SZY")in both col a & b and extra in string in col a (ABC)
for row 5 common string is "BNM" and extra strings in both col a and b.

```<code>a=c("ABC,SZY","XYZ",NA,NA,"ABC,BNM,JKL","DEF","XCV")
b=c("SZY","XYZ,IOP","QWE",NA,"BNM,JKL,STU","DEF","HJK")
df = data.frame(a,b)
</code>```

output should be as follows

```<code>output = c("COMMON+column_a","COMMON+column_b","DIFFERENT",NA,"COMMON+column_a+column_b","COMMON","DIFFERENT")
df = cbind(df,output)
</code>```

答:
Here is one option with cSplit where we split the dataset columns into 'long' format at the delimiter , after creating a row names columns.  Then grouped by 'rn', get the union of the column elements with Reduce and assign that column as 'output' in the original dataset

```<code>library(data.table)
library(splitstackshape)
df$output <- cSplit(setDT(df, keep.rownames = TRUE), c("a", "b"), ",",
      "long")[, toString(Reduce(union, lapply(.SD, na.omit))), rn]$V1
df
#   rn           a           b             output
#1:  1     ABC,SZY         SZY           ABC, SZY
#2:  2         XYZ     XYZ,IOP           XYZ, IOP
#3:  3        <NA>         QWE                QWE
#4:  4        <NA>        <NA>
#5:  5 ABC,BNM,JKL BNM,JKL,STU ABC, BNM, JKL, STU
#6:  6         DEF         DEF                DEF
#7:  7         XCV         HJK           XCV, HJK
</code>```

Or using tidyverse, we gather the data into 'long' format after creating a row names column, separate the rows of 'val' at the delimiter ,, replace the NA elements with ,, get the distinct rows based on 'rn' and 'val' column, paste the strings together (str_c) grouped by 'rn' and bind the column 'output' with the original dataset

```<code>library(tidyverse)
rownames_to_column(df, 'rn') %>%
   gather(key, val, -rn) %>%
   separate_rows(val) %>%
   mutate(val = replace_na(val, "")) %>%
   distinct(rn, val) %>%
   group_by(rn) %>%
   summarise(val = str_c(val, collapse=",")) %>%
   select(-rn) %>%
   bind_cols(df, .)
</code>```

Or with base R, we split the columns with strsplit at the delimiter ,, get the union of the list elements using Map and paste it into a single string, unlist the list into a vector and assign it to create the 'output' column

```<code>df$output <- unlist(do.call(Map, c(f = function(...)
        toString(union(...)), unname(lapply(df, strsplit, ",")))))
</code>```

data

```<code>df <- structure(list(a = c("ABC,SZY", "XYZ", NA, NA, "ABC,BNM,JKL",
"DEF", "XCV"), b = c("SZY", "XYZ,IOP", "QWE", NA, "BNM,JKL,STU",
"DEF", "HJK")), row.names = c(NA, -7L), class = "data.frame")
</code>```

Body:
I have a data frame as below,how to compare values from 2 columns.i.e row 1 has common string("SZY")in both col a & b and extra in string in col a (ABC)
for row 5 common string is "BNM" and extra strings in both col a and b.

a=c("ABC,SZY","XYZ",NA,NA,"ABC,BNM,JKL","DEF","XCV")
b=c("SZY","XYZ,IOP","QWE",NA,"BNM,JKL,STU","DEF","HJK")
df = data.frame(a,b)

output should be as follows

output = c("COMMON+column_a","COMMON+column_b","DIFFERENT",NA,"COMMON+column_a+column_b","COMMON","DIFFERENT")
df = cbind(df,output)

Body:
Here is one option with cSplit where we split the dataset columns into 'long' format at the delimiter , after creating a row names columns.  Then grouped by 'rn', get the union of the column elements with Reduce and assign that column as 'output' in the original dataset

library(data.table)
library(splitstackshape)
df$output <- cSplit(setDT(df, keep.rownames = TRUE), c("a", "b"), ",",
      "long")[, toString(Reduce(union, lapply(.SD, na.omit))), rn]$V1
df
#   rn           a           b             output
#1:  1     ABC,SZY         SZY           ABC, SZY
#2:  2         XYZ     XYZ,IOP           XYZ, IOP
#3:  3        <NA>         QWE                QWE
#4:  4        <NA>        <NA>
#5:  5 ABC,BNM,JKL BNM,JKL,STU ABC, BNM, JKL, STU
#6:  6         DEF         DEF                DEF
#7:  7         XCV         HJK           XCV, HJK

Or using tidyverse, we gather the data into 'long' format after creating a row names column, separate the rows of 'val' at the delimiter ,, replace the NA elements with ,, get the distinct rows based on 'rn' and 'val' column, paste the strings together (str_c) grouped by 'rn' and bind the column 'output' with the original dataset

library(tidyverse)
rownames_to_column(df, 'rn') %>%
   gather(key, val, -rn) %>%
   separate_rows(val) %>%
   mutate(val = replace_na(val, "")) %>%
   distinct(rn, val) %>%
   group_by(rn) %>%
   summarise(val = str_c(val, collapse=",")) %>%
   select(-rn) %>%
   bind_cols(df, .)

Or with base R, we split the columns with strsplit at the delimiter ,, get the union of the list elements using Map and paste it into a single string, unlist the list into a vector and assign it to create the 'output' column

df$output <- unlist(do.call(Map, c(f = function(...)
        toString(union(...)), unname(lapply(df, strsplit, ",")))))

data

df <- structure(list(a = c("ABC,SZY", "XYZ", NA, NA, "ABC,BNM,JKL",
"DEF", "XCV"), b = c("SZY", "XYZ,IOP", "QWE", NA, "BNM,JKL,STU",
"DEF", "HJK")), row.names = c(NA, -7L), class = "data.frame")


问:
How to convert List<String> to Map<String,List<String>> based on a delimeter
I have a List of String like:

```<code>List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
</code>```

And I want to convert in Map<String, List<String>> as like:

```<code>AU = [5631]
CA = [1326]
US = [5423, 6321]
</code>```

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

```<code>List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));
</code>```

GeoLocation.java

```<code>private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
</code>```

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

答:
You may do it like so:

```<code>Map<String, List<String>> locationMap = locations.stream()
        .map(s -> s.split(":"))
        .collect(Collectors.groupingBy(a -> a[0],
                Collectors.mapping(a -> a[1], Collectors.toList())));
</code>```

A much more better approach would be,

```<code>private static final Pattern DELIMITER = Pattern.compile(":");

Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
        .collect(Collectors.groupingBy(a -> a[0],
            Collectors.mapping(a -> a[1], Collectors.toList())));
</code>```

Update

As per the following comment, this can be further simplified to,

```<code>Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toList())));
</code>```

Body:
I have a List of String like:

List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

And I want to convert in Map<String, List<String>> as like:

AU = [5631]
CA = [1326]
US = [5423, 6321]

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));

GeoLocation.java

private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

Body:
You may do it like so:

Map<String, List<String>> locationMap = locations.stream()
        .map(s -> s.split(":"))
        .collect(Collectors.groupingBy(a -> a[0],
                Collectors.mapping(a -> a[1], Collectors.toList())));

A much more better approach would be,

private static final Pattern DELIMITER = Pattern.compile(":");

Map<String, List<String>> locationMap = locations.stream()
    .map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
        .collect(Collectors.groupingBy(a -> a[0],
            Collectors.mapping(a -> a[1], Collectors.toList())));

Update

As per the following comment, this can be further simplified to,

Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toList())));


问:
I am making an app using react & node, how should I design my database (Schema)
How should I approach to schema design for my app? What are the important points to  remember when doing schema design and how should be different models in my node app relate to each other. Any explanation for simple CRUD app?</p>

答:
When you start designing your data model there are two things that I find very important. Cardinality and Association.

Cardinality just means how many of one thing is associated to another thing. For example, in a library application, a Book includes zero or many Chapters.

Associated is just what's related to what. Again, Chapters are associated to a Book. Pages are associated to Chapters. A Book definitely has at least one Author.

When you start designing the schema, you need to realize the relationship which is either 1-1, 1-many or many-many. For example:

A Book might have multiple Authors and each Author might have written many Books. So this is a many-many relationship.

A Book might have many Chapters but the same exact Chapter only appears in that Book. So this is a 1-many relationship.

Once you have these figured out you can create tables. For 1-m you just use a Foreign Key of the 1 side in the m side table. For the m-m, you usually create an intermediate table that holds the Primary key of each side.

If you had given more info on what you are trying to make, I could use a more familiar example. Good luck.


问:
Winforms Placeholder Text is Overwritten
I am attempting to give a winforms Textbox control placeholder text by programmatically setting the respective control's text during the GetFocus and LostFocus events. However, for whatever reason the control never reflects the updated text.

This is what I'm attempting:

```<code>Private Sub TextBoxEmail_GotFocus(ByVal sender As Object, ByVal e As EventArgs) Handles TextBoxEmail.GotFocus
    Dim this As TextBox = DirectCast(sender, TextBox)
    With this
        If .Text = "Email Address" Then
            .ForeColor = Bootstrap.Utilities.Color.TextBody
            .Text = String.Empty
        End If
    End With
End Sub

Private Sub TextBoxEmail_LostFocus(ByVal sender As Object, ByVal e As EventArgs) Handles TextBoxEmail.LostFocus
    Dim this As TextBox = DirectCast(sender, TextBox)
    With this
        .ForeColor = Bootstrap.Utilities.Color.TextLight
        If String.IsNullOrWhiteSpace(.Text) Then
            .Text = "Email Address"
        End If
    End With
End Sub
</code>```

What is odd is that if I setup a breakpoint in the LostFocus event handler and step through the code using the F11 shortcut, it is constantly cycles through the GotFocus and LostFocus events.

答:
It happens because you are debugging the code.

When your text box gets focus at that time GetFocus event will call unfortunately you have put a breakpoint in GetFocus as well as LostFocus event. so your form Lose the focus and that focus comes to the visual studio so LostFocus event will occur after that again after the debuging process is complete your text box get focused again so again GetFocus  event will call and its process will create Cycle while you debug the code.

I hope this will help you.

Body:
I am attempting to give a winforms Textbox control placeholder text by programmatically setting the respective control's text during the GetFocus and LostFocus events. However, for whatever reason the control never reflects the updated text.

This is what I'm attempting:

Private Sub TextBoxEmail_GotFocus(ByVal sender As Object, ByVal e As EventArgs) Handles TextBoxEmail.GotFocus
    Dim this As TextBox = DirectCast(sender, TextBox)
    With this
        If .Text = "Email Address" Then
            .ForeColor = Bootstrap.Utilities.Color.TextBody
            .Text = String.Empty
        End If
    End With
End Sub

Private Sub TextBoxEmail_LostFocus(ByVal sender As Object, ByVal e As EventArgs) Handles TextBoxEmail.LostFocus
    Dim this As TextBox = DirectCast(sender, TextBox)
    With this
        .ForeColor = Bootstrap.Utilities.Color.TextLight
        If String.IsNullOrWhiteSpace(.Text) Then
            .Text = "Email Address"
        End If
    End With
End Sub

What is odd is that if I setup a breakpoint in the LostFocus event handler and step through the code using the F11 shortcut, it is constantly cycles through the GotFocus and LostFocus events.


问:
Swift 4: validating credit card expiration date
I am writing code to check whether the credit card has expired or not.

Here is what I have

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}
</code>```

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?

答:
```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!)

//Also convert the current date in the entered date format and then checks that the date is valid if enteredDate month or year is greater than current date.
let currentDate = dateFormatter.date(from: dateFormatter.string(from: Date()))

if enteredDate.compare(now) != ComparisonResult.orderedAscending {
    print("Valid")
} else {
    print("Not Valid")
}
</code>```

As this only compares the month and year so it will resolve your issue of first or last date of month.

Body:
I am writing code to check whether the credit card has expired or not.

Here is what I have

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?

Body:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!)

//Also convert the current date in the entered date format and then checks that the date is valid if enteredDate month or year is greater than current date.
let currentDate = dateFormatter.date(from: dateFormatter.string(from: Date()))

if enteredDate.compare(now) != ComparisonResult.orderedAscending {
    print("Valid")
} else {
    print("Not Valid")
}

As this only compares the month and year so it will resolve your issue of first or last date of month.


答:
Try this</p>

```<code>Map<String, List<String>> locationMap = locations.stream()
            .map(s ->  new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                     Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
</code>```

Title: How to convert List<String> to Map<String,List<String>> based on a delimeter

Body:
Try this

Map<String, List<String>> locationMap = locations.stream()
            .map(s ->  new AbstractMap.SimpleEntry<String,String>(s.split(":")[0], s.split(":")[1]))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                     Collectors.mapping(Map.Entry::getValue, Collectors.toList())));


问:
Building a tree recursively in JavaScript
I am trying to build a tree recursively from an array of objects. I am currently using the reduce() method to iterate through the items in the array and figure out which children belong to a particular item and populating it, then recursively populating the children of those children and so on. However, I have been unable to take the last nodes(e.g persian and siamese in this case) and put them in array(see expected and current output below)

```<code>    let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
               tree[currentItem.id] = reduceTree(categories, currentItem.id);
            }

            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));
</code>```

expected output:

```<code>{
    "animals": {
        "mammals": {
            "cats": [     // <-- an array of cat strings
                "persian",
                "siamese"
            ],
            "dogs": [     // <-- an array of dog strings
                "chihuahua",
                "labrador"
            ]
        }
    }
}
</code>```

current output:

```<code>{
    "animals": {
        "mammals": {
            "cats": {       // <-- an object with cat keys
                "persian": {},
                "siamese": {}
            },
            "dogs": {       // <-- an object with dog keys
                "chihuahua": {},
                "labrador": {}
            }
          }
     }
}
</code>```

How should I go about solving the problem?

答:
Here is a solution without recursion:

const categories = [{ id: 'animals', parent: null },{ id: 'mammals', parent: 'animals' },{ id: 'cats', parent: 'mammals' },{ id: 'dogs', parent: 'mammals' },{ id: 'chihuahua', parent: 'dogs' },{ id: 'labrador', parent: 'dogs' },{ id: 'persian', parent: 'cats' },{ id: 'siamese', parent: 'cats' }];

// Create properties for the parents (their values are empty objects)
let res = Object.fromEntries(categories.map(({parent}) => [parent, {}]));
// Overwrite the properties for the parents of leaves to become arrays
categories.forEach(({id, parent}) => res[id] || (res[parent] = []));
// assign children to parent property, either as property of parent object or as array entry in it
categories.forEach(({id, parent}) => res[parent][res[id] ? id : res[parent].length] = res[id] || id);
// Extract the tree for the null-entry:
res = res.null;

console.log(res);```

Body:
I am trying to build a tree recursively from an array of objects. I am currently using the reduce() method to iterate through the items in the array and figure out which children belong to a particular item and populating it, then recursively populating the children of those children and so on. However, I have been unable to take the last nodes(e.g persian and siamese in this case) and put them in array(see expected and current output below)

    let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
               tree[currentItem.id] = reduceTree(categories, currentItem.id);
            }

            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));

expected output:

{
    "animals": {
        "mammals": {
            "cats": [     // <-- an array of cat strings
                "persian",
                "siamese"
            ],
            "dogs": [     // <-- an array of dog strings
                "chihuahua",
                "labrador"
            ]
        }
    }
}

current output:

{
    "animals": {
        "mammals": {
            "cats": {       // <-- an object with cat keys
                "persian": {},
                "siamese": {}
            },
            "dogs": {       // <-- an object with dog keys
                "chihuahua": {},
                "labrador": {}
            }
          }
     }
}

How should I go about solving the problem?


问:
Retrieve Identity Claims in a Single Sign On project
We have three ASP.NET MVC 5 projects working alongside. For authentication, we came up using Single Sign On, following the very simple tutorial:

Implementation of Single Sign On (SSO) in ASP.NET MVC

The main idea is to create a MachineKey shared between 3, and add the same authentication settings in 3 web.config files.

So now we have 3 sites called:

SSO

WebApp1

WebApp2

One of our projects (SSO) does the job and two other depend on it. It works and we were happy but...

We are using Identity 2 claims-based authentication in the SSO project and when a user logs in, we add some custom claims to his "identity". This way, we have 2 separate cookies: one for Single Sign On process, and a second one for saving claims.

Here is the C# code:

```<code>    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string fromSite, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                // here the cookie which contains claims *is created* by Identity 2

                // here we create the cookie used for Single Sing On
                FormsAuthentication.SetAuthCookie(username, false);

                // redirecting
                if (string.IsNullOrWhiteSpace(fromSite))
                {
                    if (string.IsNullOrWhiteSpace(returnUrl)) return RedirectToAction("Index", "Home");
                    return RedirectToLocal(returnUrl);
                }

                return Redirect(string.Format("{0}{1}", fromSite, returnUrl));

                // other cases inside switch
                .
                .
                .
        }
    }
</code>```

When a user goes from SSO site to another, say WebApp1, he remains logged in but we lost claims.

Is there any way to "merge" these 2 cookies and retrieve the claims in another site?

答:
Consider we have 4 projects.

WebAppMain(This project contains the login page)

App2

App3

App4

If you are using ASP.Net Identity you need to add code for that in Startup class(Not in main project, this for App2, 3 and 4).

One important thing is, keep all Owin related dlls in same version.
  Otherwise SSO won't work.

```<code>[assembly: OwinStartupAttribute(typeof(ABC.Startup))]
namespace ABC
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

                app.CreatePerOwinContext(ApplicationDbContext.Create);
                app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
                app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    CookieDomain = ConfigurationManager.AppSettings["DomainNameForSSO"],
                    CookieName = "SSOCookie",

                });

        }
    }
}
</code>```

Use a appsettings variable to store domain

```<code><add key="DomainNameForSSO" value=".test.com"/>
</code>```

Use the same CookieName and CookieDomain in main project Startup.Auth.cs file.

Add a common machine key to all project's web.config file.

```<code><machineKey
       validationKey="{Update this value}"
       decryptionKey="{Update this value}"
       validation="SHA1"
       decryption="AES"
    />
</code>```

you can generate machine using online tools or custom code is available on internet.

Once it is done, create a Custom Authorize attribute like below.

```<code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class CustomAuthorize : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if (skipAuthorization) return;

            var authManager = HttpContext.Current.GetOwinContext().Authentication;
            if (authManager == null || authManager.User == null || authManager.User.Identity == null || !authManager.User.Identity.IsAuthenticated)
            {
                UnAuthorizedProcess(filterContext);// handle unathorized request here, we can redirect the request to main project from here
            }
            else
            {
                AuthorizedProcess(filterContext);// Do the default action or if we have any custom validation, write here.
            }
        }
}
</code>```

Add attribute in all actions/controllers need to authorized.

```<code> [CustomAuthorize]
 public ActionResult Dashboard()
 {
    return View();
 }
</code>```

you have to give full URL as returnURL parameter to the main website.

Body:
We have three ASP.NET MVC 5 projects working alongside. For authentication, we came up using Single Sign On, following the very simple tutorial:

Implementation of Single Sign On (SSO) in ASP.NET MVC

The main idea is to create a MachineKey shared between 3, and add the same authentication settings in 3 web.config files.

So now we have 3 sites called:

SSO

WebApp1

WebApp2

One of our projects (SSO) does the job and two other depend on it. It works and we were happy but...

We are using Identity 2 claims-based authentication in the SSO project and when a user logs in, we add some custom claims to his "identity". This way, we have 2 separate cookies: one for Single Sign On process, and a second one for saving claims.

Here is the C# code:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string fromSite, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                // here the cookie which contains claims *is created* by Identity 2

                // here we create the cookie used for Single Sing On
                FormsAuthentication.SetAuthCookie(username, false);

                // redirecting
                if (string.IsNullOrWhiteSpace(fromSite))
                {
                    if (string.IsNullOrWhiteSpace(returnUrl)) return RedirectToAction("Index", "Home");
                    return RedirectToLocal(returnUrl);
                }

                return Redirect(string.Format("{0}{1}", fromSite, returnUrl));

                // other cases inside switch
                .
                .
                .
        }
    }

When a user goes from SSO site to another, say WebApp1, he remains logged in but we lost claims.

Is there any way to "merge" these 2 cookies and retrieve the claims in another site?

Body:
Consider we have 4 projects.

WebAppMain(This project contains the login page)

App2

App3

App4

If you are using ASP.Net Identity you need to add code for that in Startup class(Not in main project, this for App2, 3 and 4).

One important thing is, keep all Owin related dlls in same version.
  Otherwise SSO won't work.

[assembly: OwinStartupAttribute(typeof(ABC.Startup))]
namespace ABC
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

                app.CreatePerOwinContext(ApplicationDbContext.Create);
                app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
                app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    CookieDomain = ConfigurationManager.AppSettings["DomainNameForSSO"],
                    CookieName = "SSOCookie",

                });

        }
    }
}

Use a appsettings variable to store domain

<add key="DomainNameForSSO" value=".test.com"/>

Use the same CookieName and CookieDomain in main project Startup.Auth.cs file.

Add a common machine key to all project's web.config file.

<machineKey
       validationKey="{Update this value}"
       decryptionKey="{Update this value}"
       validation="SHA1"
       decryption="AES"
    />

you can generate machine using online tools or custom code is available on internet.

Once it is done, create a Custom Authorize attribute like below.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class CustomAuthorize : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if (skipAuthorization) return;

            var authManager = HttpContext.Current.GetOwinContext().Authentication;
            if (authManager == null || authManager.User == null || authManager.User.Identity == null || !authManager.User.Identity.IsAuthenticated)
            {
                UnAuthorizedProcess(filterContext);// handle unathorized request here, we can redirect the request to main project from here
            }
            else
            {
                AuthorizedProcess(filterContext);// Do the default action or if we have any custom validation, write here.
            }
        }
}

Add attribute in all actions/controllers need to authorized.

 [CustomAuthorize]
 public ActionResult Dashboard()
 {
    return View();
 }

you have to give full URL as returnURL parameter to the main website.


答:
rmaddy's answer is perfect. Here is how I thought of using Calendar to handle the validation. Perhaps, I wrote it in more complex way.

```<code>enum ExpiryValidation {
    case valid, invalidInput, expired
}

func validateCreditCardExpiry(_ input: String) -> ExpiryValidation {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/yyyy"

    guard let enteredDate = dateFormatter.date(from: input) else {
        return .invalidInput
    }
    let calendar = Calendar.current
    let components = Set([Calendar.Component.month, Calendar.Component.year])
    let currentDateComponents = calendar.dateComponents(components, from: Date())
    let enteredDateComponents = calendar.dateComponents(components, from: enteredDate)

    guard let eMonth = enteredDateComponents.month, let eYear = enteredDateComponents.year, let cMonth = currentDateComponents.month, let cYear = currentDateComponents.year, eMonth >= cMonth, eYear >= cYear else {
        return .expired
    }
    return .valid
}

let invalidInput = validateCreditCardExpiry("hello")
let validInput = validateCreditCardExpiry("09/2020")
let expiredInput = validateCreditCardExpiry("04/2010")
</code>```

Title: Swift 4: validating credit card expiration date

Body:
rmaddy's answer is perfect. Here is how I thought of using Calendar to handle the validation. Perhaps, I wrote it in more complex way.

enum ExpiryValidation {
    case valid, invalidInput, expired
}

func validateCreditCardExpiry(_ input: String) -> ExpiryValidation {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/yyyy"

    guard let enteredDate = dateFormatter.date(from: input) else {
        return .invalidInput
    }
    let calendar = Calendar.current
    let components = Set([Calendar.Component.month, Calendar.Component.year])
    let currentDateComponents = calendar.dateComponents(components, from: Date())
    let enteredDateComponents = calendar.dateComponents(components, from: enteredDate)

    guard let eMonth = enteredDateComponents.month, let eYear = enteredDateComponents.year, let cMonth = currentDateComponents.month, let cYear = currentDateComponents.year, eMonth >= cMonth, eYear >= cYear else {
        return .expired
    }
    return .valid
}

let invalidInput = validateCreditCardExpiry("hello")
let validInput = validateCreditCardExpiry("09/2020")
let expiredInput = validateCreditCardExpiry("04/2010")


问:
How to add image/icon for right side of a button?
These days I am developing flutter mobile application for the Android platform. I want to add a button with text an icon/image. That image must be the right side of the button text.

I have already attached the image here.

This is my code.

```<code>child: FlatButton.icon(
     icon: Image.asset("images/notesicon.png", width: 20.0,height: 20.0,),
     label: Text("Add Note",
        style: TextStyle(
           fontSize: 11.0,
           fontFamily: "Raleway"
        ),
     ),
     textColor: Colors.white,
     color: Color(0xFF226597),
     shape: OutlineInputBorder(borderSide: BorderSide(
               style: BorderStyle.solid,
               width: 1.0,
               color: Colors.black),
            borderRadius: new BorderRadius.circular(20.0)
      ),
    ),
</code>```

答:
You can do something like this

```<code> Container(
                width: 150,
                height: 100,
                    padding: EdgeInsets.all(10),
                    decoration: new BoxDecoration(
                      color: Colors.blue[400],
                      border: Border.all(color: Colors.blue[800], width: 4.0),
                      borderRadius:
                      new BorderRadius.all(Radius.circular(40.0)),
                    ),
                    child:Center(child: FlatButton(
                      onPressed: () => {},
                      padding: EdgeInsets.all(5.0),
                      child:Center(child:  Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          Text("Make A Note"),
                          Icon(Icons.note_add),
                        ],
                      ),),),)),
</code>```

Body:
These days I am developing flutter mobile application for the Android platform. I want to add a button with text an icon/image. That image must be the right side of the button text.

I have already attached the image here.

This is my code.

child: FlatButton.icon(
     icon: Image.asset("images/notesicon.png", width: 20.0,height: 20.0,),
     label: Text("Add Note",
        style: TextStyle(
           fontSize: 11.0,
           fontFamily: "Raleway"
        ),
     ),
     textColor: Colors.white,
     color: Color(0xFF226597),
     shape: OutlineInputBorder(borderSide: BorderSide(
               style: BorderStyle.solid,
               width: 1.0,
               color: Colors.black),
            borderRadius: new BorderRadius.circular(20.0)
      ),
    ),

Body:
You can do something like this

 Container(
                width: 150,
                height: 100,
                    padding: EdgeInsets.all(10),
                    decoration: new BoxDecoration(
                      color: Colors.blue[400],
                      border: Border.all(color: Colors.blue[800], width: 4.0),
                      borderRadius:
                      new BorderRadius.all(Radius.circular(40.0)),
                    ),
                    child:Center(child: FlatButton(
                      onPressed: () => {},
                      padding: EdgeInsets.all(5.0),
                      child:Center(child:  Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          Text("Make A Note"),
                          Icon(Icons.note_add),
                        ],
                      ),),),)),


问:
How to introspect all available methods and members of a Rust type?
Is there a way to print out a complete list of available members of a type or instance in Rust?

For example:

In Python, I can use print(dir(object))

In C, Clang has a Python API that can parse C code and introspect it.

Being unfamiliar with Rust tools, I'm interested to know if there is some way to do this, either at run-time or compile-time, either with compiler features (macros for example), or using external tools.

This question is intentionally broad because the exact method isn't important. It is common in any language to want to find all of a variable's methods/functions. Not knowing Rust well, I'm not limiting the question to specific methods for discovery.

The reason I don't define the exact method is that I assume IDEs will need this information, so there will need to be some kinds of introspection available to support this (eventually). For all I know, Rust has something similar.

I don't think this is a duplicate of Get fields of a struct type in a macro since this answer could include use of external tools (not necessarily macros).

答:
Is there a way to print out a complete list of available members of a type or instance in Rust?

Currently, there is no such built-in API that you can get the fields at runtime. However you can retrieve fields by using two different ways.

Declarative Macros

Procedural Macros

Solution By Using Declarative Macro

macro_rules! generate_struct {
    ($name:ident {$($field_name:ident : $field_type:ty),+}) => {
        struct $name { $($field_name: $field_type),+ }
        impl $name {
            fn introspect() {
            $(
            let field_name = stringify!($field_name);
            let field_type = stringify!($field_type);
               println!("Field Name: {:?} , Field Type: {:?}",field_name,field_type);
            )*
            }
        }
    };
}

generate_struct! { MyStruct { num: i32, s: String } }

fn main() {
    MyStruct::introspect();
}
```

<p>This will give you the output:</p>

<pre class="lang-none prettyprint-override"><code>Field Name: "num" , Field Type: "i32"
Field Name: "s" , Field Type: "String"
</code>```

Playground

Solution Using Procedural Macro

Since procedural macros are  more complicated from the declarative macros, you better to read some references(ref1, ref2, ref3) before starting.

We are going to write a custom derive which is named "Instrospect". To create this custom derive, we need to parse our struct as a TokenStream with the help of syn crate.

#[proc_macro_derive(Introspect)]
pub fn derive_introspect(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemStruct);

    // ...
}
```

<p>Since our input can be parsed as <code>ItemStruct</code> and <code>ItemStruct</code> has the <code>fields()</code> method in it, we can use this to get fields of our struct. </p>

<p>After we get these fields, we can parse them as named and we can print their <code>field name</code> and <code>field type</code> accordingly.</p>

<pre class="lang-rust prettyprint-override"><code>input
    .fields
    .iter()
    .for_each(|field| match field.parse_named() {
        Ok(field) => println!("{:?}", field),
        Err(_) => println!("Field can not be parsed successfully"),
    });
</code>```

If you want to attach this behavior to your custom derive you can use the following with the help of the quote crate:

let name = &input.ident;

let output = quote! {
    impl #name {
        pub fn introspect(){
            input
            .fields
            .iter()
            .for_each(|field| match field.parse_named() {
                Ok(field) => println!("{:?}", field),
                Err(_) => println!("Field can not be parsed successfully"),
             });
        }
    }
};

// Return output TokenStream so your custom derive behavior will be attached.
TokenStream::from(output)
```

<p>Since the behaviour injected to your struct as introspect function, you can call it in your application like following:</p>

<pre class="lang-rust prettyprint-override"><code>#[derive(Introspect)]
struct MyStruct {
    num: i32,
    text: String
}

MyStruct::introspect();
</code>```

Note: Since the example you are looking for similar to this question. This Proc Macro Answer  and Declarative Macro Answer  should give you insight as well

Body:
Is there a way to print out a complete list of available members of a type or instance in Rust?

Currently, there is no such built-in API that you can get the fields at runtime. However you can retrieve fields by using two different ways.

Declarative Macros

Procedural Macros

Solution By Using Declarative Macro

macro_rules! generate_struct {
    ($name:ident {$($field_name:ident : $field_type:ty),+}) => {
        struct $name { $($field_name: $field_type),+ }
        impl $name {
            fn introspect() {
            $(
            let field_name = stringify!($field_name);
            let field_type = stringify!($field_type);
               println!("Field Name: {:?} , Field Type: {:?}",field_name,field_type);
            )*
            }
        }
    };
}

generate_struct! { MyStruct { num: i32, s: String } }

fn main() {
    MyStruct::introspect();
}

This will give you the output:

Field Name: "num" , Field Type: "i32"
Field Name: "s" , Field Type: "String"

Playground

Solution Using Procedural Macro

Since procedural macros are  more complicated from the declarative macros, you better to read some references(ref1, ref2, ref3) before starting.

We are going to write a custom derive which is named "Instrospect". To create this custom derive, we need to parse our struct as a TokenStream with the help of syn crate.

#[proc_macro_derive(Introspect)]
pub fn derive_introspect(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemStruct);

    // ...
}

Since our input can be parsed as ItemStruct and ItemStruct has the fields() method in it, we can use this to get fields of our struct.

After we get these fields, we can parse them as named and we can print their field name and field type accordingly.

input
    .fields
    .iter()
    .for_each(|field| match field.parse_named() {
        Ok(field) => println!("{:?}", field),
        Err(_) => println!("Field can not be parsed successfully"),
    });

If you want to attach this behavior to your custom derive you can use the following with the help of the quote crate:

let name = &input.ident;

let output = quote! {
    impl #name {
        pub fn introspect(){
            input
            .fields
            .iter()
            .for_each(|field| match field.parse_named() {
                Ok(field) => println!("{:?}", field),
                Err(_) => println!("Field can not be parsed successfully"),
             });
        }
    }
};

// Return output TokenStream so your custom derive behavior will be attached.
TokenStream::from(output)

Since the behaviour injected to your struct as introspect function, you can call it in your application like following:

#[derive(Introspect)]
struct MyStruct {
    num: i32,
    text: String
}

MyStruct::introspect();

Note: Since the example you are looking for similar to this question. This Proc Macro Answer  and Declarative Macro Answer  should give you insight as well


问:
How can I include the jboss-client.jar present in the Wildfly bin/client folder to my maven project?
I have a maven project to which I have to add a external jar jboss-client.jar which is located in Jboss Wildfly 10 bin folder(bin/client). There is no version specified in the jar name.

When I add the jar manually in build path-it works fine.

However, since this is a maven project, I require a better way of doing this.

Note: The project works with only this jar and not other versions specified in pom.xml which I tried downloading.

Also, if I try to specify the external dependency in pom.xml, it asks for version of the dependency. However, I cannot specify the same as it is not mentioned in the jar.

My ultimate aim is to deploy this project in Jboss Wildfly 10.

Is there any other alternate way, I can add the jar?

答:
Copy your jar to some other location and unzip/decompress it, then find Manifest file  located at META-INF\MANIFEST.MF path.

Open it in text editor and look for Implementation-Version.

It will give you the version.

Reference


问:
Refreshing datatables.net table data in Angular 7 keeps a copy of the old data from table's first loading
I'm trying to make a live reporting from a REST API request using the datatables.net library in Angular 7. If I make a data update into the database, the data in the table is updated. However, If I touch the table (i.e. reorder, search for something, change the page, etc), on data reloading (which occurs every 5 seconds), in the table is added the data from the first load of the table. If I touch the table again, the updated data disappears, and only the old data remains, until the next data update, when the new data is added again in the table.

This is the state of the table when the page loads

This is the state of the table when the data in the database is updated

This is the behavior of the table when any change is made on the table (i.e. sort, search, switch page, etc)

This is the code for the component:

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DownloadService } from '../services/download/download.service';
import { stringify } from 'querystring';
import { Router } from '@angular/router';

@Component({
  selector: 'app-downloads',
  templateUrl: './downloads.component.html',
  styleUrls: ['./downloads.component.css']
})

export class DownloadsComponent implements OnInit {

  downloadData$: any[] = [];
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();
  interval: any;

  constructor(private http: HttpClient, private data: DownloadService, private router: Router) { }

  ngOnInit() {
    this.dtOptions = {
      responsive: true
    };

    this.data.GetDownloads().subscribe(data => {
      this.downloadData$ = data;
      this.dtTrigger.next();
    });

    this.interval = setInterval(() => {
      this.refreshData();
    }, 5000);
  }

  refreshData() {
    this.data.GetDownloads().subscribe(data => {
      this.downloadData$ = data;
    });
  }

  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }
}
</code>```

and this is the html file

```<code><div>
  <table style="text-align: center;" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%"
    datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
    <thead>
      <tr>
        <th>Logger Name</th>
        <th>Progress</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let download of downloadData$">
        <td>{{ download.logger.name }}</td>
        <td [attr.data-order]="download.progress"><progress [attr.value]="download.progress" max="100"></progress>
          {{ download.progress }}%</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

答:
You have to destroy the table first and re render. You can refer the article here.
A code snippet if link gets disabled in future.

```<code>rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
  // Destroy the table first
  dtInstance.destroy();
  // Call the dtTrigger to rerender again
  this.dtTrigger.next();
});
}
</code>```

Another solution is as discussed here

Let me know if this solution works or if you have any query.

Body:
I'm trying to make a live reporting from a REST API request using the datatables.net library in Angular 7. If I make a data update into the database, the data in the table is updated. However, If I touch the table (i.e. reorder, search for something, change the page, etc), on data reloading (which occurs every 5 seconds), in the table is added the data from the first load of the table. If I touch the table again, the updated data disappears, and only the old data remains, until the next data update, when the new data is added again in the table.

This is the state of the table when the page loads

This is the state of the table when the data in the database is updated

This is the behavior of the table when any change is made on the table (i.e. sort, search, switch page, etc)

This is the code for the component:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DownloadService } from '../services/download/download.service';
import { stringify } from 'querystring';
import { Router } from '@angular/router';

@Component({
  selector: 'app-downloads',
  templateUrl: './downloads.component.html',
  styleUrls: ['./downloads.component.css']
})

export class DownloadsComponent implements OnInit {

  downloadData$: any[] = [];
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();
  interval: any;

  constructor(private http: HttpClient, private data: DownloadService, private router: Router) { }

  ngOnInit() {
    this.dtOptions = {
      responsive: true
    };

    this.data.GetDownloads().subscribe(data => {
      this.downloadData$ = data;
      this.dtTrigger.next();
    });

    this.interval = setInterval(() => {
      this.refreshData();
    }, 5000);
  }

  refreshData() {
    this.data.GetDownloads().subscribe(data => {
      this.downloadData$ = data;
    });
  }

  ngOnDestroy(): void {
    this.dtTrigger.unsubscribe();
  }
}

and this is the html file

        Logger Name
        Progress

        {{ download.logger.name }}
        <progress [attr.value]="download.progress" max="100"></progress>
          {{ download.progress }}%

Body:
You have to destroy the table first and re render. You can refer the article here.
A code snippet if link gets disabled in future.

rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
  // Destroy the table first
  dtInstance.destroy();
  // Call the dtTrigger to rerender again
  this.dtTrigger.next();
});
}

Another solution is as discussed here

Let me know if this solution works or if you have any query.


问:
How can i invert UIImageView?
Hy everybody!
I load black and white image to UIImageView and i don't know how can i invert the colors with a button.

I load the image with this code:

```<code>ImageView.image = [UIImage imageNamed:@"image.png"];
</code>```

Anyone know that?

Thanks for the help!

答:
Try playing with differnt blend modes in the UIImage method:

```<code>- (void)drawAtPoint:(CGPoint)point blendMode:(CGBlendMode)blendMode alpha:(CGFloat)alpha
</code>```

I haven't actually used it but maybe one of the modes will give you the result you need.

Title: How can i invert UIImageView?

Body:
Hy everybody!
I load black and white image to UIImageView and i don't know how can i invert the colors with a button.

I load the image with this code:

ImageView.image = [UIImage imageNamed:@"image.png"];

Anyone know that?

Thanks for the help!

Body:
Try playing with differnt blend modes in the UIImage method:

- (void)drawAtPoint:(CGPoint)point blendMode:(CGBlendMode)blendMode alpha:(CGFloat)alpha

I haven't actually used it but maybe one of the modes will give you the result you need.


问:
Find first occurrence of a string after the first occurrence of another string with bash
I have an input file that looks like this and i want the first occurrence of words but only after the first occurrence of special

The numbers are only there so i know i got the right string

EDIT: I realized that it matters the strings have /'s

```<code>words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2
words/random #5
</code>```

Im trying to find the first occurrence of "word" after i find the first occurrence of "special"

The output should be

```<code>words/i/need/you/i.really.need.you #4
</code>```

Ive tried the following

```<code>grep -m1 special file | grep -m1 words file

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file
</code>```

答:
Could you please try following.</p>

```<code>awk '
$0=="words"{
  count++
  if(special_count==1){
    print "String words count is: "count
    exit
  }
}
/special/{
  special_count++
}
'  Input_file
</code>```

Body:
I have an input file that looks like this and i want the first occurrence of words but only after the first occurrence of special

The numbers are only there so i know i got the right string

EDIT: I realized that it matters the strings have /'s

words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2
words/random #5

Im trying to find the first occurrence of "word" after i find the first occurrence of "special"

The output should be

words/i/need/you/i.really.need.you #4

Ive tried the following

grep -m1 special file | grep -m1 words file

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file

Body:
Could you please try following.

awk '
$0=="words"{
  count++
  if(special_count==1){
    print "String words count is: "count
    exit
  }
}
/special/{
  special_count++
}
'  Input_file


问:
Can't Change Android Button Padding
I have a table of buttons and am attempting to dynamically create and set the padding around the text of each with the following function:

```<code>public static void AddChartColBtn(TableRow row, String txt, String style) {
    Button note_chart_btn;
    note_chart_btn = new Button(ctx);
    note_chart_btn.setText(txt);
    TableRow.LayoutParams params = new TableRow.LayoutParams();
    params.setMargins(0, 0, 0, 0);
    note_chart_btn.setLayoutParams(params);
    row.addView(note_chart_btn);
}
</code>```

I've tried working with LayoutParams classes to set margins and paddings, etc...but no matter what I try the button always fills the entire space of the current table cell, ignoring any padding. The Button class doesn't appear to have layout params, padding that can be manipulated directly. How can dynamically create and declare a button with 0 padding around it's text?

答:
setPadding should after the setBackgroundResource

Like this:

```<code>button.setBackgroundResource(R.mipmap.btn_bg)
button.setPadding(100, 0, 100, paddingBo0tom)
</code>```

Title: Can't Change Android Button Padding

Body:
I have a table of buttons and am attempting to dynamically create and set the padding around the text of each with the following function:

public static void AddChartColBtn(TableRow row, String txt, String style) {
    Button note_chart_btn;
    note_chart_btn = new Button(ctx);
    note_chart_btn.setText(txt);
    TableRow.LayoutParams params = new TableRow.LayoutParams();
    params.setMargins(0, 0, 0, 0);
    note_chart_btn.setLayoutParams(params);
    row.addView(note_chart_btn);
}

I've tried working with LayoutParams classes to set margins and paddings, etc...but no matter what I try the button always fills the entire space of the current table cell, ignoring any padding. The Button class doesn't appear to have layout params, padding that can be manipulated directly. How can dynamically create and declare a button with 0 padding around it's text?

Body:
setPadding should after the setBackgroundResource

Like this:

button.setBackgroundResource(R.mipmap.btn_bg)
button.setPadding(100, 0, 100, paddingBo0tom)


问:
Nested lists into smalls lists (splitted by category)
This is my code, which is inside of a function:

```<code>xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray
</code>```

It prints me a big list, with the following result:

```<code>[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]
</code>```

I am trying to split it up and get small subsets of the big list, something like:

```<code>Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]
</code>```

答:
```<code>big_list = [['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

authors_list = [[n.strip() for n in l[0].split('-')[0].split(',')] for l in big_list]
years_list = [int(l[0].split('-')[1].split(',')[-1]) for l in big_list]
publishers_list = [l[0].split('-')[2].strip() for l in big_list]
</code>```

Body:
This is my code, which is inside of a function:

xArray = []

for t in range(npapers):

  nHeader = []
  headers = browser.find_elements_by_xpath("(//div[@class='gs_a'])[%s]"%(t+1))

  for nheaders in headers:
     nHeader.append(nheaders.text)
  xArray.append(nHeader)

  return xArray

It prints me a big list, with the following result:

[['LR Hirsch, AM Gobin, AR Lowery, F Tam… - Annals of biomedical …, 2006 - Springer'],
 ['C Loo, A Lowery, N Halas, J West, R Drezek - Nano letters, 2005 - ACS Publications'],
 ['SJ Oldenburg, JB Jackson, SL Westcott… - Applied Physics …, 1999 - aip.scitation.org'],
 ['RD Averitt, SL Westcott, NJ Halas - JOSA B, 1999 - osapublishing.org'],
 ['LR Hirsch, JB Jackson, A Lee, NJ Halas… - Analytical …, 2003 - ACS Publications'],
 ['SJ Oldenburg, RD Averitt, NJ Halas - US Patent 6,344,272, 2002 - Google Patents'],
 ['AM Gobin, MH Lee, NJ Halas, WD James… - Nano …, 2007 - ACS Publications'],
 ['JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl… - Nano …, 2008 - ACS Publications'],
 ['JB Jackson, NJ Halas - The Journal of Physical Chemistry B, 2001 - ACS Publications'],
 ['RD Averitt, D Sarkar, NJ Halas - Physical Review Letters, 1997 - APS']]

I am trying to split it up and get small subsets of the big list, something like:

Authors = [LR Hirsch, AM Gobin, AR Lowery, F Tam],[C Loo, A Lowery, N Halas, J West, R Drezek],[SJ Oldenburg, JB Jackson, SL Westcott],[RD Averitt, SL Westcott, NJ Halas],[LR Hirsch, JB Jackson, A Lee, NJ Halas],[SJ Oldenburg, RD Averitt, NJ Halas],[AM Gobin, MH Lee, NJ Halas, WD James],[JB Lassiter, J Aizpurua, LI Hernandez, DW Brandl],[JB Jackson, NJ Halas],[RD Averitt, D Sarkar, NJ Halas]]
Year = [[2006],[2005],[1999],[1999],[2003],[2002],[2007],[2008],[2001],[1997]]
Publisher =[[Springer],[ACS Publications],[aip.scitation.org],[ACS Publications][osapublishing.org],[Google Patents],[ACS Publications],[ACS Publications],[ACS Publications],[APS]]


问:
"Access to Font..has been blocked by CORS policy" on only one file

Note: I am using Wordpress and serving the media files, css, js, etc. through Amazon CloudFront/S3.

Hello,

I know there are a lot of posts like this but I am still struggling. I was able to fix this issue for a majority of the font files that I am loading, however, this one continues to be an issue.

```<code>Access to Font at 'http://mycloudfrontID.cloudfront.net/wp-content/themes/bridge/css/font-awesome/fonts/fontawesome-webfont.woff2?v=4.6.3' from origin 'http://mydomainname' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://maxmajor.net' is therefore not allowed access.
</code>```

The other font files are fine after I added this to my CORS policy on AWS S3:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

and this is in my .htaccess:

```<code><FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$">
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
</code>```

Any ideas why this error is still firing?

Thanks,
Brian

答:
Have you considered referring the following thread?

CORS Issue with woff2 fonts behind CDN in Chrome

It says

Turns out that the problem was actually with the Content-Type. As soon as I changed the content type to application/font-woff2 and invalidated the cache of these woff2 files, everything went through smoothly.

Body:
Note: I am using Wordpress and serving the media files, css, js, etc. through Amazon CloudFront/S3.

Hello,

I know there are a lot of posts like this but I am still struggling. I was able to fix this issue for a majority of the font files that I am loading, however, this one continues to be an issue.

Access to Font at 'http://mycloudfrontID.cloudfront.net/wp-content/themes/bridge/css/font-awesome/fonts/fontawesome-webfont.woff2?v=4.6.3' from origin 'http://mydomainname' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://maxmajor.net' is therefore not allowed access.

The other font files are fine after I added this to my CORS policy on AWS S3:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

and this is in my .htaccess:

<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$">
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>

Any ideas why this error is still firing?

Thanks,
Brian


答:
You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first</p>

```<code>Map<String, List<String>> locationMap = locations
            .stream()
            .map(s -> s.split(":"))
            .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );
</code>```

Body:
I have a List of String like:

List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

And I want to convert in Map<String, List<String>> as like:

AU = [5631]
CA = [1326]
US = [5423, 6321]

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));

GeoLocation.java

private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

Body:
You can just put the code in grouping by part where you put first group as key and second as value instead of mapping it first

Map<String, List<String>> locationMap = locations
            .stream()
            .map(s -> s.split(":"))
            .collect( Collectors.groupingBy( s -> s[0], Collectors.mapping( s-> s[1], Collectors.toList() ) ) );


问:
Regular expression for an alphanumeric word start with alphabet
I have a requirement to find and return the first occurrence of the pattern from a string.

Example: Please find my model number RT21M6211SR/SS and save it

Expected output: RT21M6211SR/SS

Condition for the pattern to match

Combination of digits and alphabets

Character length between 6 to 14

May or may not contain special characters like '-' or '/'

Starts with always alphabet

What I tried, but it didn't work for 4th condition

```<code>var str = 'Please find my model number RT21M6211SR/SS and save it';
var reg = /\b(\w|\d)[\d|\w-\/]{6,14}\b/;
var extractedMNO = '';
var mg = str.match(reg) || [""];
console.log('regular match mno', mg[0]);
</code>```

答:
\w matches word characters, which includes _ and digits as well. If you only want to match alphabetical characters, use [a-z] to match the first character.

Also, because you want to match lengths of 6-14, after matching the first character, you should repeat the character set with {5,13}, so that the repeated characters plus the first character comes out to a length of 6-14 characters.

var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z][a-z0-9\/-]{5,13}/gi)[2]);```
</div>
</div>
</p>

<p>But since the matched string <em>must</em> contain digits (and doesn't just <em>permit</em> digits), then you need to make sure a digit exists in the matched substring as well, which you can accomplish by using lookahead for a digit right after matching the alphabetical at the start:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z](?=[a-z\/-]{0,12}[0-9])[a-z0-9\/-]{5,13}/gi));
//                            ^^^^^^^^^^^^^^^^^^^^^^^</code>```

If you want to permit other special characters, just add them to the character set(s).

Body:
I have a requirement to find and return the first occurrence of the pattern from a string.

Example: Please find my model number RT21M6211SR/SS and save it

Expected output: RT21M6211SR/SS

Condition for the pattern to match

Combination of digits and alphabets

Character length between 6 to 14

May or may not contain special characters like '-' or '/'

Starts with always alphabet

What I tried, but it didn't work for 4th condition

var str = 'Please find my model number RT21M6211SR/SS and save it';
var reg = /\b(\w|\d)[\d|\w-\/]{6,14}\b/;
var extractedMNO = '';
var mg = str.match(reg) || [""];
console.log('regular match mno', mg[0]);

Body:
\w matches word characters, which includes _ and digits as well. If you only want to match alphabetical characters, use [a-z] to match the first character.

Also, because you want to match lengths of 6-14, after matching the first character, you should repeat the character set with {5,13}, so that the repeated characters plus the first character comes out to a length of 6-14 characters.

var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z][a-z0-9\/-]{5,13}/gi)[2]);

But since the matched string must contain digits (and doesn't just permit digits), then you need to make sure a digit exists in the matched substring as well, which you can accomplish by using lookahead for a digit right after matching the alphabetical at the start:

var str = 'Please find my model number RT21M6211SR/SS and save it';
console.log(str.match(/\b[a-z](?=[a-z\/-]{0,12}[0-9])[a-z0-9\/-]{5,13}/gi));
//                            ^^^^^^^^^^^^^^^^^^^^^^^

If you want to permit other special characters, just add them to the character set(s).


问:
How To Redirect .htaccess domain, http to https. cant find what works for me in any thread
I finished setting up a script on a domain with ssl on it but i ca't get it to redirect

I already tried using the redirect option in my cpanel, i noticed some codes were added to the .htaccess file but when i try to run the site, it actually redirects but instead of loading, it says too many redirects

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTPS:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{HTTP_HOST} ^dayret\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.dayret\.com$
RewriteRule ^(.*)$ "https\:\/\/dayret\.com\/$1" [R=301,L]

</IfModule>
</code>```

After running the above code i get the site redirecting to https but stops and brings up "This page isn’t working dayret.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS"

答:
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]</p>

Body:
I finished setting up a script on a domain with ssl on it but i ca't get it to redirect

I already tried using the redirect option in my cpanel, i noticed some codes were added to the .htaccess file but when i try to run the site, it actually redirects but instead of loading, it says too many redirects

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTPS:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{HTTP_HOST} ^dayret\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.dayret\.com$
RewriteRule ^(.*)$ "https\:\/\/dayret\.com\/$1" [R=301,L]

</IfModule>

After running the above code i get the site redirecting to https but stops and brings up "This page isn’t working dayret.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS"


问:
Not able to import Python module
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

```<code>project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py
</code>```

This is my testing code

```<code>"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200
</code>```

But when i run it it shows:

```<code>Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'
</code>```

What am I doing wrong here.

答:
First you have to set the add your project directory to the PYTHONPATH or put your project inside a directory that is already added. This lets python to use your package.

You can add the directory using setcommand on cmd. For example if you want to add C:\Python use command set PYTHONPATH = C:\Python

Now to import server.py you have to type import project.server or from project import server.

If you type import project.server, to use a function in server you will have to type in project.server.<fuction>() and if you used from project import server you will have to use server.<function>().

Title: Not able to import Python module

Body:
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py

This is my testing code

"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200

But when i run it it shows:

Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'

What am I doing wrong here.