问:
Efficient way to handle string similarity?
I got stuck on some string similarity issues.

This is how my data looks like (the original data is huge):

```<code>SerialNumber                SubSerialID            Date

AGCC0775CFNDA1040TMT775     AVCC0775CFNDA1040     2018/01/08
AGCC0775CFNDA1040           AVCC0775CFNDA1040     2015/12/28
AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/31
</code>```

...

My target is:

```<code>SerialNumber                SubSerialID            Date

AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/31
</code>```

...

Serial Numbers AGCC0775CFNDA1040TMT775, AGCC0775CFNDA1040, and AGCC0775CFNDA10407EC are the same thing but caused by mistakes. I want to keep AGCC0775CFNDA10407EC because it has the latest date on record. However, I cannot use SubSerialID and Date directly to filter those Serial Numbers because if will remove 2658358.

I thought about using stringdist to find string similarity as another condition (i.e., filter out by abs (similarity) >1.5 and abs (similarity)<0.5) but cannot figure out an efficient way to handle it. The data it's huge and using for loop is unpragmatic. I got stuck for a while and hopefully, someone can give me some advice or suggestion with this matter.

答:
The following reproduces your expected output

```<code>library(dplyr)
library(purrr)
df %>%
    mutate(Date = as.Date(Date)) %>%
    mutate_if(is.factor, as.character) %>%
    mutate(dist = map2_dbl(SerialNumber, SubSerialID, adist)) %>%
    group_by(SubSerialID) %>%
    filter(all(dist > 5) | Date == max(Date)) %>%
    ungroup()
## A tibble: 5 x 4
#  SerialNumber             SubSerialID       Date        dist
#  <chr>                    <chr>             <date>     <dbl>
#1 AGCC0775CFNDA10407EC     AVCC0775CFNDA1040 2018-03-17     4
#2 CH~MT765E~C0765HFNCC1056 BGDC0865HFNKG1043 2019-01-07    15
#3 2658358                  BGDC0865HFNKG1043 2018-08-09    15
#4 MT765E~C0765KFNCD1044    C0765KFNCD10      2015-04-07     9
#5 187A126                  C0765KFNCD10      2017-11-30    11
</code>```

The idea is to keep all entries (per SubSerialID) if all Levenshtein distances between SubserialID and SerialNumber are greater than 5. If there is one distance <= 5, only keep the row with the largest Date. I've kept the dist column for debugging; you can remove the column with select(-dist).

I'm not sure how generalisable this is. You will have to play around with the Levenshtein distance threshold (which I set to 5 in this case).

Sample data

```<code>df <- read.table(text =
"SerialNumber                SubSerialID            Date

AGCC0775CFNDA1040TMT775     AVCC0775CFNDA1040     2018/01/08
AGCC0775CFNDA1040           AVCC0775CFNDA1040     2015/12/28
AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/30", header = T)
</code>```

Body:
I got stuck on some string similarity issues.

This is how my data looks like (the original data is huge):

SerialNumber                SubSerialID            Date

AGCC0775CFNDA1040TMT775     AVCC0775CFNDA1040     2018/01/08
AGCC0775CFNDA1040           AVCC0775CFNDA1040     2015/12/28
AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/31

...

My target is:

SerialNumber                SubSerialID            Date

AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/31

...

Serial Numbers AGCC0775CFNDA1040TMT775, AGCC0775CFNDA1040, and AGCC0775CFNDA10407EC are the same thing but caused by mistakes. I want to keep AGCC0775CFNDA10407EC because it has the latest date on record. However, I cannot use SubSerialID and Date directly to filter those Serial Numbers because if will remove 2658358.

I thought about using stringdist to find string similarity as another condition (i.e., filter out by abs (similarity) >1.5 and abs (similarity)<0.5) but cannot figure out an efficient way to handle it. The data it's huge and using for loop is unpragmatic. I got stuck for a while and hopefully, someone can give me some advice or suggestion with this matter.

Body:
The following reproduces your expected output

library(dplyr)
library(purrr)
df %>%
    mutate(Date = as.Date(Date)) %>%
    mutate_if(is.factor, as.character) %>%
    mutate(dist = map2_dbl(SerialNumber, SubSerialID, adist)) %>%
    group_by(SubSerialID) %>%
    filter(all(dist > 5) | Date == max(Date)) %>%
    ungroup()
## A tibble: 5 x 4
#  SerialNumber             SubSerialID       Date        dist
#  <chr>                    <chr>             <date>     <dbl>
#1 AGCC0775CFNDA10407EC     AVCC0775CFNDA1040 2018-03-17     4
#2 CH~MT765E~C0765HFNCC1056 BGDC0865HFNKG1043 2019-01-07    15
#3 2658358                  BGDC0865HFNKG1043 2018-08-09    15
#4 MT765E~C0765KFNCD1044    C0765KFNCD10      2015-04-07     9
#5 187A126                  C0765KFNCD10      2017-11-30    11

The idea is to keep all entries (per SubSerialID) if all Levenshtein distances between SubserialID and SerialNumber are greater than 5. If there is one distance <= 5, only keep the row with the largest Date. I've kept the dist column for debugging; you can remove the column with select(-dist).

I'm not sure how generalisable this is. You will have to play around with the Levenshtein distance threshold (which I set to 5 in this case).

Sample data

df <- read.table(text =
"SerialNumber                SubSerialID            Date

AGCC0775CFNDA1040TMT775     AVCC0775CFNDA1040     2018/01/08
AGCC0775CFNDA1040           AVCC0775CFNDA1040     2015/12/28
AGCC0775CFNDA10407EC        AVCC0775CFNDA1040     2018/03/17
CH~MT765E~C0765HFNCC1056    BGDC0865HFNKG1043     2019/01/07
2658358                     BGDC0865HFNKG1043     2018/08/09
MT765E~C0765KFNCD1044       C0765KFNCD10          2015/04/07
187A126                     C0765KFNCD10          2017/11/30", header = T)


来源: stackexchange

问:
WebSphere reverse proxy plugin - skipping domains
Hoping someone can give me some advice if possible.

We have a Linux box in our DMZ with the WebSphere plugin.  This points to a Windows box running WebSphere Application Server.

httpd config only contains the default virtualhost with no ServerAlias specified.  There is a redirect set up in the virtualhost in httpd.conf to forward any requests to service.domain.com to service.domain.com/wascontext1. Plugin-cfg.xml is set up with two uri groups, wascontext1 and wascontext2, but only 1 is actively used.

I want to use the Linux box as a reverse proxy for another application totally separate to WAS.  It would have a different domain (i.e. dimsim.domain.com) but point to the same IP.

I was going to add another virtualhost for this but am unsure exactly how the WebSphere plugin will behave with it.  From what I understand if I set this up and went to dimsim.domain.com/wascontext1 it would serve the WebSphere content as httpd forwards all requests to the plugin.

Is there a way to tell httpd to not send requests to the WebSphere plugin based on domain name or virtualhost?  Or would doing a rewrite on any requests to dimsim.domain.com/wascontext be considered ok?

thanks

jc

EDIT: Thanks for the responses!  I'll test changing the virtualhost name in plugin-cfg.xml on our second unused context and let you know how it goes.

答:
Sorry for the late response.

covener's answer of setting the following does what I need.

```<code>SetEnvIf Host ^dimsim\.domain\.com$ skipwas=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorry for the late response.

covener's answer of setting the following does what I need.

SetEnvIf Host ^dimsim\.domain\.com$ skipwas=1


问:
Python Pandas GroupBy Max Date
I have a very simple dataframe with columns: Index, Person, Item, Date. There are only 4 people and 3 items and random dates. All person/item/date combinations are unique. I am trying to get a simple pivot-table like df to print using:

```<code>import pandas as pd

mydf = pd.read_csv("Test_Data.csv",index_col=[0])
mydf = mydf.sort_values(by=['Date','Item','Person'], ascending=False)

print(mydf.groupby(['Person','Item'])['Date'].max())
</code>```

however, I noticed that while the structure is what I want, the data is not. It is not returning the max date for the Person/Item combination. I thought sorting things first would help, but it did not. Do I need to create a temp df first and then join to do what I'm trying to do?

Also to be clear, there are 28 rows of data (all test data) with some People/Items being repeated but with different dates. Index is just 0 through 27.

答:
Figured it out! Should have made sure the Date field was actually recognized as a date:</p>

```<code>mydf['Date'] = pd.to_datetime(mydf['Date'])
</code>```

Title: Python Pandas GroupBy Max Date

Body:
I have a very simple dataframe with columns: Index, Person, Item, Date. There are only 4 people and 3 items and random dates. All person/item/date combinations are unique. I am trying to get a simple pivot-table like df to print using:

import pandas as pd

mydf = pd.read_csv("Test_Data.csv",index_col=[0])
mydf = mydf.sort_values(by=['Date','Item','Person'], ascending=False)

print(mydf.groupby(['Person','Item'])['Date'].max())

however, I noticed that while the structure is what I want, the data is not. It is not returning the max date for the Person/Item combination. I thought sorting things first would help, but it did not. Do I need to create a temp df first and then join to do what I'm trying to do?

Also to be clear, there are 28 rows of data (all test data) with some People/Items being repeated but with different dates. Index is just 0 through 27.

Body:
Figured it out! Should have made sure the Date field was actually recognized as a date:

mydf['Date'] = pd.to_datetime(mydf['Date'])


问:
In a vectorized way in numpy: Cutting out chunks of data (of different sizes) conditionally dependent on whats inside the chunk
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
```

<p>(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.  </p>

<p>So in this example, the data I want to cut out is listed in bold:</p>

```8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1```

<p>(i.e., it's data that's inbetween the 8's that contains at least one 99)</p>

<p>So if I made a boolean mask to crop out this data it would look like:</p>

```Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T```

<p>And data after cropping look like:</p>

<pre class="lang-none prettyprint-override"><code>Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1
</code>```

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

```<code>inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()
</code>```

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

```<code>inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()
</code>```

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

Body:
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.

So in this example, the data I want to cut out is listed in bold:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(i.e., it's data that's inbetween the 8's that contains at least one 99)

So if I made a boolean mask to crop out this data it would look like:

Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T

And data after cropping look like:

Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

Body:
Another numpy approach:

def pp(a):
    m8 = a==8
    m99 = a==99
    m = m8|m99
    i = m.nonzero()[0]
    c8 = m8[i]
    i = i[c8]
    n8 = np.count_nonzero(c8)
    if n8 == 0:
        return np.ones(a.size,bool)
    if c8[-1]:
        d8 = np.empty(n8,bool)
        d8[-1] = False
        d8[:-1] = ~c8[1:][c8[:-1]]
    else:
        d8 = ~c8[1:][c8[:-1]]
    d8[1:]^=d8[:-1]
    m8[i] = d8
    m8[0]^=True
    return np.bitwise_xor.accumulate(m8)

For example:

a = np.array([8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1])
a[pp(a)]
# array([8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1])


问:
R Custom Order Output Of paste0
I desire to paste text in specific order. This is my attempt at it:

```<code>paste0("car",1:3, "conv",1:3)
</code>```

but this gives "car1conv1" "car2conv2" "car3conv3"

my desired outputs are:

"car1","conv1","car2","conv2","car3","conv3"

i am not sure how to do the ordering other than doing it manually but just imagine having to do this for 100 items, so i am seeking assitance in generating this type of output in 1 or 2 steps thanks so much.

答:
We can replicate one them and use paste0

```<code>paste0(c("car", "conv"), rep(1:3, each = 2))
#[1] "car1"  "conv1" "car2"  "conv2" "car3"  "conv3"
</code>```

Title: R Custom Order Output Of paste0

Body:
I desire to paste text in specific order. This is my attempt at it:

paste0("car",1:3, "conv",1:3)

but this gives "car1conv1" "car2conv2" "car3conv3"

my desired outputs are:

"car1","conv1","car2","conv2","car3","conv3"

i am not sure how to do the ordering other than doing it manually but just imagine having to do this for 100 items, so i am seeking assitance in generating this type of output in 1 or 2 steps thanks so much.

Body:
We can replicate one them and use paste0

paste0(c("car", "conv"), rep(1:3, each = 2))
#[1] "car1"  "conv1" "car2"  "conv2" "car3"  "conv3"


问:
What is an Unchecked Call in Java?
```<code>public class Main<T> {
     T obj;
     public Main(T input) {
         this.obj = input;
     }
     void set(T input) {
         this.obj = input;
     }
     void print() {
         System.out.println(this.obj);
     }
    public static void main(String[] args) {
        Main<Integer> tester = new Main<>(2);
        Main test = tester;
        test.print();
        test.set(3);
        test.print();
    }
}
</code>```

In the code above test.set(3) gives me a warning "Unchecked call to 'set(T)' as a member of raw type 'Main'". What is an unchecked call and why do I get it, even though the set method works and after the print statement is executed, 3 is printed.

答:
You haven't told the compiler what kind of Main the test variable refers to.  As far as the compiler is concerned, it could be Main<Integer> or Main<String> or Main<RahatsCrazyClass>.  So the compiler can't guarantee that test.set(3) makes sense - you could be trying to set an Integer object inside a Main<String>.

The warning tells you that the compiler has encountered a condition that it can't guarantee the sense of.  You should avoid having this kind of thing.  Better to declare test as a Main<Integer> than as just a Main.

Title: What is an Unchecked Call in Java?

Body:
public class Main<T> {
     T obj;
     public Main(T input) {
         this.obj = input;
     }
     void set(T input) {
         this.obj = input;
     }
     void print() {
         System.out.println(this.obj);
     }
    public static void main(String[] args) {
        Main<Integer> tester = new Main<>(2);
        Main test = tester;
        test.print();
        test.set(3);
        test.print();
    }
}

In the code above test.set(3) gives me a warning "Unchecked call to 'set(T)' as a member of raw type 'Main'". What is an unchecked call and why do I get it, even though the set method works and after the print statement is executed, 3 is printed.


问:
With closures as parameter and return values, is Fn or FnMut more idiomatic?
Continuing from How do I write combinators for my own parsers in Rust?, I stumbled into this question concerning bounds of functions that consume and/or yield functions/closures.

From these slides, I learned that to be convenient for consumers, you should try to take functions as FnOnce and return as Fn where possible. This gives the caller most freedom what to pass and what to do with the returned function.

In my example, FnOnce is not possible because I need to call that function multiple times. While trying to make it compile I arrived at two possibilities:

pub enum Parsed<'a, T> {
    Some(T, &'a str),
    None(&'a str),
}

impl<'a, T> Parsed<'a, T> {
    pub fn unwrap(self) -> (T, &'a str) {
        match self {
            Parsed::Some(head, tail) => (head, &tail),
            _ => panic!("Called unwrap on nothing."),
        }
    }

    pub fn is_none(&self) -> bool {
        match self {
            Parsed::None(_) => true,
            _ => false,
        }
    }
}

pub fn achar(character: char) -> impl Fn(&str) -> Parsed<char> {
    move |input|
        match input.chars().next() {
            Some(c) if c == character => Parsed::Some(c, &input[1..]),
            _ => Parsed::None(input),
        }
}

pub fn some_v1<T>(parser: impl Fn(&str) -> Parsed<T>) -> impl Fn(&str) -> Parsed<Vec<T>> {
    move |input| {
        let mut re = Vec::new();
        let mut pos = input;
        loop {
            match parser(pos) {
                Parsed::Some(head, tail) => {
                    re.push(head);
                    pos = tail;
                }
                Parsed::None(_) => break,
            }
        }
        Parsed::Some(re, pos)
    }
}

pub fn some_v2<T>(mut parser: impl FnMut(&str) -> Parsed<T>) -> impl FnMut(&str) -> Parsed<Vec<T>> {
    move |input| {
        let mut re = Vec::new();
        let mut pos = input;
        loop {
            match parser(pos) {
                Parsed::Some(head, tail) => {
                    re.push(head);
                    pos = tail;
                }
                Parsed::None(_) => break,
            }
        }
        Parsed::Some(re, pos)
    }
}

#[test]
fn try_it() {
    assert_eq!(some_v1(achar('#'))("##comment").unwrap(), (vec!['#', '#'], "comment"));
    assert_eq!(some_v2(achar('#'))("##comment").unwrap(), (vec!['#', '#'], "comment"));
}
```

playground

Now I don't know which version is to be preferred. Version 1 takes Fn which is less general, but version 2 needs its parameter mutable.

Which one is more idiomatic/should be used and what is the rationale behind?

Update: Thanks jplatte for the suggestion on version one. I updated the code here, that case I find even more interesting.

答:
Comparing some_v1 and some_v2 as you wrote them I would say version 2 should definitely be preferred because it is more general. I can't think of a good example for a parsing closure that would implement FnMut but not Fn, but there's really no disadvantage to parser being mut - as noted in the first comment on your question this doesn't constrain the caller in any way.

However, there is a way in which you can make version 1 more general (not strictly more general, just partially) than version 2, and that is by returning impl Fn(&str) -> … instead of impl FnMut(&str) -> …. By doing that, you get two functions that each are less constrained than the other in some way, so it might even make sense to keep both:

Version 1 with the return type change would be more restrictive in its argument (the callable can't mutate its associated data) but less restrictive in its return type (you guarantee that the returned callable doesn't mutate its associated data)

Version 2 would be less restrictive in its argument (the callable is allowed to mutate its associated data) but more restrictive in its return type (the returned callable might mutate its associated data)

Body:
Continuing from How do I write combinators for my own parsers in Rust?, I stumbled into this question concerning bounds of functions that consume and/or yield functions/closures.

From these slides, I learned that to be convenient for consumers, you should try to take functions as FnOnce and return as Fn where possible. This gives the caller most freedom what to pass and what to do with the returned function.

In my example, FnOnce is not possible because I need to call that function multiple times. While trying to make it compile I arrived at two possibilities:

pub enum Parsed<'a, T> {
    Some(T, &'a str),
    None(&'a str),
}

impl<'a, T> Parsed<'a, T> {
    pub fn unwrap(self) -> (T, &'a str) {
        match self {
            Parsed::Some(head, tail) => (head, &tail),
            _ => panic!("Called unwrap on nothing."),
        }
    }

    pub fn is_none(&self) -> bool {
        match self {
            Parsed::None(_) => true,
            _ => false,
        }
    }
}

pub fn achar(character: char) -> impl Fn(&str) -> Parsed<char> {
    move |input|
        match input.chars().next() {
            Some(c) if c == character => Parsed::Some(c, &input[1..]),
            _ => Parsed::None(input),
        }
}

pub fn some_v1<T>(parser: impl Fn(&str) -> Parsed<T>) -> impl Fn(&str) -> Parsed<Vec<T>> {
    move |input| {
        let mut re = Vec::new();
        let mut pos = input;
        loop {
            match parser(pos) {
                Parsed::Some(head, tail) => {
                    re.push(head);
                    pos = tail;
                }
                Parsed::None(_) => break,
            }
        }
        Parsed::Some(re, pos)
    }
}

pub fn some_v2<T>(mut parser: impl FnMut(&str) -> Parsed<T>) -> impl FnMut(&str) -> Parsed<Vec<T>> {
    move |input| {
        let mut re = Vec::new();
        let mut pos = input;
        loop {
            match parser(pos) {
                Parsed::Some(head, tail) => {
                    re.push(head);
                    pos = tail;
                }
                Parsed::None(_) => break,
            }
        }
        Parsed::Some(re, pos)
    }
}

#[test]
fn try_it() {
    assert_eq!(some_v1(achar('#'))("##comment").unwrap(), (vec!['#', '#'], "comment"));
    assert_eq!(some_v2(achar('#'))("##comment").unwrap(), (vec!['#', '#'], "comment"));
}

playground

Now I don't know which version is to be preferred. Version 1 takes Fn which is less general, but version 2 needs its parameter mutable.

Which one is more idiomatic/should be used and what is the rationale behind?

Update: Thanks jplatte for the suggestion on version one. I updated the code here, that case I find even more interesting.


问:
How to sum all values for numbers in rows in a file
I am creating a program which involves summing all numbers in  the rows of a .txt file. The file is randomly generated, and consists of 100 random numbers, each occupying their own row. What I would like to do is create a list of all the numbers in the rows and then take the sum of that list. For some reason, the code I have is not working:

```<code>import os
import math

filename = input("Enter file name: ")
if not os.path.exists(filename):
    print(filename, "does not exist")
else:
    fin = open(filename)
    counter = -1
    comments = 0
    total = 0

    for line in fin:
        if "#" in line:
            comments += 1
        counter = counter + 1

    newlist = [[]]
    fin = open(filename)

    for line in fin:
        newlist = [[]]
        val = []
        for value in line:
            val.append(value)
        newList.append(val)
        total = sum(newList)

    print("Count:", counter)
    print("Comments:", comments)
    print("Total:", total)
</code>```

The top part runs fine, but the function for the "total" value (the sum which I am trying to derive) is not working. Any advice would be greatly appreciated. Thanks!

答:
If you have a line of numbers separated by whitespace (as opposed to digits not separated), your dual for loop is not going to work as you think:

```<code>>>> line = '12 34 56 78 90'
>>> for value in line: print(value)
...
1
2

3
4

5
6

7
8

9
0
</code>```

As per above, iterating over a string (such as the line you input) will process it one character at a time.

To process whitespace-separated words in a string, you can use something like:

```<code>>>> for value in line.split(): print(int(value))
...
12
34
56
78
90
</code>```

You'll also want to turn them into integers (as shown) if you want to sum them.

Body:
I am creating a program which involves summing all numbers in  the rows of a .txt file. The file is randomly generated, and consists of 100 random numbers, each occupying their own row. What I would like to do is create a list of all the numbers in the rows and then take the sum of that list. For some reason, the code I have is not working:

import os
import math

filename = input("Enter file name: ")
if not os.path.exists(filename):
    print(filename, "does not exist")
else:
    fin = open(filename)
    counter = -1
    comments = 0
    total = 0

    for line in fin:
        if "#" in line:
            comments += 1
        counter = counter + 1

    newlist = [[]]
    fin = open(filename)

    for line in fin:
        newlist = [[]]
        val = []
        for value in line:
            val.append(value)
        newList.append(val)
        total = sum(newList)

    print("Count:", counter)
    print("Comments:", comments)
    print("Total:", total)

The top part runs fine, but the function for the "total" value (the sum which I am trying to derive) is not working. Any advice would be greatly appreciated. Thanks!

Body:
If you have a line of numbers separated by whitespace (as opposed to digits not separated), your dual for loop is not going to work as you think:

>>> line = '12 34 56 78 90'
>>> for value in line: print(value)
...
1
2

3
4

5
6

7
8

9
0

As per above, iterating over a string (such as the line you input) will process it one character at a time.

To process whitespace-separated words in a string, you can use something like:

>>> for value in line.split(): print(int(value))
...
12
34
56
78
90

You'll also want to turn them into integers (as shown) if you want to sum them.


问:
"UNPROTECTED PRIVATE KEY FILE!" Error using SSH into Amazon EC2 Instance (AWS)
I've created a new linux instance on Amazon EC2, and as part of that downloaded the .pem file to allow me to SSH in.

When I tried to ssh with:

```<code>ssh -i myfile.pem <public dns>
</code>```

I got:

```<code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'amazonec2.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: amazonec2.pem
Permission denied (publickey).
</code>```

Following this post I tried to chmod +600 the .pem file, but now when I ssh I just get

```<code>Permission denied (publickey).
</code>```

What school-boy error am I making here?
The .pem file is in my home folder (in macOS). Its permissions look like this:

```<code>-rw-------@   1 mattroberts  staff    1696 19 Nov 11:20 amazonec2.pem
</code>```

答:
.400 protects it by making it read only and only for the owner.

You can find the answer from the ASW guide.

```<code>chmod 400 yourPrivateKey.pem
</code>```

Body:
I've created a new linux instance on Amazon EC2, and as part of that downloaded the .pem file to allow me to SSH in.

When I tried to ssh with:

ssh -i myfile.pem <public dns>

I got:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'amazonec2.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: amazonec2.pem
Permission denied (publickey).

Following this post I tried to chmod +600 the .pem file, but now when I ssh I just get

Permission denied (publickey).

What school-boy error am I making here?
The .pem file is in my home folder (in macOS). Its permissions look like this:

-rw-------@   1 mattroberts  staff    1696 19 Nov 11:20 amazonec2.pem

Body:
.400 protects it by making it read only and only for the owner.

You can find the answer from the ASW guide.

chmod 400 yourPrivateKey.pem


问:
headbreaking problems with bottom margins css grid
Im trying to design my website. Sofar i did all the backend and now im struggling with the frontend.

sofar i've managed to do a simple layout without a navbar and a footer. It already looks as i have imagined it layoutwise, but there is a part where it bothers me  a lot and cant fiugre out why: the last element in the mobile view just doesnt want to keep a margin from the bottom border.

heres my code so far:

```<code><div class="container">

    <div class="grid">
        <div class="title">
            <span class="bold">
                <p>Edoardo Crescenti</p>
            </span>
            <span class="semibold">
                <p>.Net/C# Entwickler</p>
            </span>
        </div>
        <div class="item1 item">
            About me
        </div>
        <div class="item2 item">
            Ausbildung
        </div>
        <div class="item3 item">
            Arbeitserfahrung
        </div>
        <div class="item4 item">
            Portfolio
        </div>
        <div class="item5 item">
            Skills
        </div>
        <div class="item6 item">
            Sprachen
        </div>
        <div class="item7 item">
            Freizeit
        </div>
    </div>
</div>
</code>```

and the stylesheet

```<code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
}

body {
  background: #979395;
  font-size: 14px;
  line-height: 22px;
  color: black;
  font-family: "Roboto", sans-serif;
}
.item {
  padding: 1%;
  font-size: 1.5rem;
  text-align: center;
}
.container {
  width: auto;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding-bottom: 10px;
}
.title {
  grid-area: title;
  font-size: 2rem;
  width: 80vw;
  margin: 5% auto;
  align-self: flex-end;
  width: 100%;
}
.grid {
  width: 80vw;
  height: 90vh;
  max-width: 1000px;
  margin-bottom: 5%;
  align-self: center;
  display: grid;
}
.item1 {
  grid-area: item1;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #f7bc68;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item2 {
  grid-area: item2;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #120505;
  color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item3 {
  grid-area: item3;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item4 {
  grid-area: item4;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item5 {
  grid-area: item5;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item6 {
  grid-area: item6;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #9e2020;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item7 {
  grid-area: item7;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #508e83;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}

@media screen and (min-width: 1050px) {
  .grid {
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 0.5fr 1fr 1fr 1fr;
    grid-template-areas:
      "title title title title"
      "item1 item1 item2 item3"
      "item4 item4 item5 item6"
      "item7 item7 item5 item6";
    grid-gap: 0.5%;
  }
}
@media screen and (max-width: 1049px) and (min-width: 700px) {
  .grid {
    height: 90vh;
    grid-template-areas:
      "title title"
      "item1 item1"
      "item2 item3"
      "item2 item4"
      "item5 item6"
      "item5 item6"
      "item7 item7";
    grid-gap: 1%;
  }
}
@media screen and (max-width: 699px) {
  .titltle {
    display: none;
  }
  .container {
    justify-content: space-around;
  }
  .grid {
    height: auto;
    width: 95vw;
    margin: 2%;
    grid-template-rows: 100px 170px 170px 170px 170px 170px 170px 170px;
    grid-template-areas:
      "title"
      "item1"
      "item2"
      "item3"
      "item6"
      "item5"
      "item4"
      "item7";
    grid-gap: 1%;
    margin-bottom: 20px;
  }
}
</code>```

Im using node/ejs so the html code is just wrapped inside a body tag.

what am i missing?

答:
Using a percentage value as grid-gap is breaking the grid height, because in this case it is height: auto, not an explicit value.

A solution would be to use px in order to have a similar distance you want:

```<code>@media screen and (max-width: 699px)
.grid {
    height: auto;
    width: 95vw;
    margin: 2%;
    grid-template-rows: 100px 170px 170px 170px 170px 170px 170px 170px;
    grid-template-areas:
        "title"
        "item1"
        "item2"
        "item3"
        "item6"
        "item5"
        "item4"
        "item7";
    grid-gap: 25px;
    margin-bottom: 20px;
}
</code>```

Body:
Im trying to design my website. Sofar i did all the backend and now im struggling with the frontend.

sofar i've managed to do a simple layout without a navbar and a footer. It already looks as i have imagined it layoutwise, but there is a part where it bothers me  a lot and cant fiugre out why: the last element in the mobile view just doesnt want to keep a margin from the bottom border.

heres my code so far:

Edoardo Crescenti

.Net/C# Entwickler

            About me

            Ausbildung

            Arbeitserfahrung

            Portfolio

            Skills

            Sprachen

            Freizeit

and the stylesheet

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
}

body {
  background: #979395;
  font-size: 14px;
  line-height: 22px;
  color: black;
  font-family: "Roboto", sans-serif;
}
.item {
  padding: 1%;
  font-size: 1.5rem;
  text-align: center;
}
.container {
  width: auto;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding-bottom: 10px;
}
.title {
  grid-area: title;
  font-size: 2rem;
  width: 80vw;
  margin: 5% auto;
  align-self: flex-end;
  width: 100%;
}
.grid {
  width: 80vw;
  height: 90vh;
  max-width: 1000px;
  margin-bottom: 5%;
  align-self: center;
  display: grid;
}
.item1 {
  grid-area: item1;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #f7bc68;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item2 {
  grid-area: item2;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #120505;
  color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item3 {
  grid-area: item3;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item4 {
  grid-area: item4;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item5 {
  grid-area: item5;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #ffffff;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item6 {
  grid-area: item6;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #9e2020;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}
.item7 {
  grid-area: item7;
  box-shadow: 4px 0px 5px 3px rgba(0, 0, 0, 0.18);
  background-color: #508e83;
  border-color: #120505;
  border-style: solid;
  border-width: 1px;
}

@media screen and (min-width: 1050px) {
  .grid {
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 0.5fr 1fr 1fr 1fr;
    grid-template-areas:
      "title title title title"
      "item1 item1 item2 item3"
      "item4 item4 item5 item6"
      "item7 item7 item5 item6";
    grid-gap: 0.5%;
  }
}
@media screen and (max-width: 1049px) and (min-width: 700px) {
  .grid {
    height: 90vh;
    grid-template-areas:
      "title title"
      "item1 item1"
      "item2 item3"
      "item2 item4"
      "item5 item6"
      "item5 item6"
      "item7 item7";
    grid-gap: 1%;
  }
}
@media screen and (max-width: 699px) {
  .titltle {
    display: none;
  }
  .container {
    justify-content: space-around;
  }
  .grid {
    height: auto;
    width: 95vw;
    margin: 2%;
    grid-template-rows: 100px 170px 170px 170px 170px 170px 170px 170px;
    grid-template-areas:
      "title"
      "item1"
      "item2"
      "item3"
      "item6"
      "item5"
      "item4"
      "item7";
    grid-gap: 1%;
    margin-bottom: 20px;
  }
}

Im using node/ejs so the html code is just wrapped inside a body tag.

what am i missing?

Body:
Using a percentage value as grid-gap is breaking the grid height, because in this case it is height: auto, not an explicit value.

A solution would be to use px in order to have a similar distance you want:

@media screen and (max-width: 699px)
.grid {
    height: auto;
    width: 95vw;
    margin: 2%;
    grid-template-rows: 100px 170px 170px 170px 170px 170px 170px 170px;
    grid-template-areas:
        "title"
        "item1"
        "item2"
        "item3"
        "item6"
        "item5"
        "item4"
        "item7";
    grid-gap: 25px;
    margin-bottom: 20px;
}


问:
How can I add the logged in user's name in form django
I just want to put the username of the logged in user inside the author field and at the same time assign the author field as the user's username in the database.

```<code>def create_vacation(request):
    form = creationForm(request.POST or None)
    vacations = Vacation.objects.all()
    vacations.author=request.user.username
    if form.is_valid():
        form.save()

        return redirect('/vacations/all')

    return render(request, 'creationForm.html', {'form': form})
</code>```

and this is the vacation model

```<code>class Vacation(models.Model):
    vacationInformation = models.TextField()
    startDate= models.DateTimeField('start date')
    endDate = models.DateTimeField('end date')
    author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    def __str__(self):
        return self. vacationInformation
</code>```

this is the form template

```<code> <form method="post" novalidate>
        {% csrf_token %}

        {% for hidden_field in form.hidden_fields %}
            {{ hidden_field }}
        {% endfor %}

        {% if form.non_field_errors %}
        <div class="alert alert-danger" role="alert">
            {% for error in form.non_field_errors %}
                {{ error }}
            {% endfor %}
        </div>
        {% endif %}

        {% for field in form.visible_fields %}
        <div class="form-group">
            {{ field.label_tag }}

            {% if form.is_bound %}
            {% if field.errors %}
                {% render_field field class="form-control is-invalid" %}
            {% for error in field.errors %}
            <div class="invalid-feedback">
                {{ error }}
            </div>
            {% endfor %}
            {% else %}
                {% render_field field class="form-control is-valid" %}
            {% endif %}
            {% else %}
                {% render_field field class="form-control" %}
            {% endif %}

            {% if field.help_text %}
            <small class="form-text text-muted">{{ field.help_text }}</small>
            {% endif %}
            {% if vacation %}

        {% endif %}
        </div>
        {% endfor %}

        <button type="submit" class="btn btn-primary">Submit</button>

    </form>
</code>```

I can render all of the vacation data in the homepage normally except for sure the author name

```<code> {% for vacation in vacations %}
            <tr>
                <td>{{ vacation.vacationInformation }}</td>
                <td>{{ vacation.startDate }}</td>
                <td>{{ vacation.endDate }}</td>
                <td>{{ vacation.author }}</td>

</code>```

It is giving me the entire user names in the author field in the form but I just want the user whom is logged in.

答:
You need to get the currently logged in User. Then you can use the User to fill in the initial values in the form.

from django.contrib.auth import get_user
# ...

def create_vacation(request):
    if request.method == 'POST':
        form = creationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/vacations/all')
    else:
        # Get the currently logged-in User.
        user = get_user(request)
        # Provide User as initial data to the form
        form = creationForm(initial={'author': user})

    return render(request, 'creationForm.html', {'form': form})
```

Relevant documentation:

ModelForm - Providing initial values

django.contrib.auth.get_user

Body:
I just want to put the username of the logged in user inside the author field and at the same time assign the author field as the user's username in the database.

def create_vacation(request):
    form = creationForm(request.POST or None)
    vacations = Vacation.objects.all()
    vacations.author=request.user.username
    if form.is_valid():
        form.save()

        return redirect('/vacations/all')

    return render(request, 'creationForm.html', {'form': form})

and this is the vacation model

class Vacation(models.Model):
    vacationInformation = models.TextField()
    startDate= models.DateTimeField('start date')
    endDate = models.DateTimeField('end date')
    author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    def __str__(self):
        return self. vacationInformation

this is the form template

 <form method="post" novalidate>
        {% csrf_token %}

        {% for hidden_field in form.hidden_fields %}
            {{ hidden_field }}
        {% endfor %}

        {% if form.non_field_errors %}

            {% for error in form.non_field_errors %}
                {{ error }}
            {% endfor %}

        {% endif %}

        {% for field in form.visible_fields %}

            {{ field.label_tag }}

            {% if form.is_bound %}
            {% if field.errors %}
                {% render_field field class="form-control is-invalid" %}
            {% for error in field.errors %}

                {{ error }}

            {% endfor %}
            {% else %}
                {% render_field field class="form-control is-valid" %}
            {% endif %}
            {% else %}
                {% render_field field class="form-control" %}
            {% endif %}

            {% if field.help_text %}
            {{ field.help_text }}
            {% endif %}
            {% if vacation %}

        {% endif %}

        {% endfor %}

        <button type="submit" class="btn btn-primary">Submit</button>

    </form>

I can render all of the vacation data in the homepage normally except for sure the author name

 {% for vacation in vacations %}

                {{ vacation.vacationInformation }}
                {{ vacation.startDate }}
                {{ vacation.endDate }}
                {{ vacation.author }}

It is giving me the entire user names in the author field in the form but I just want the user whom is logged in.

Body:
You need to get the currently logged in User. Then you can use the User to fill in the initial values in the form.

from django.contrib.auth import get_user
# ...

def create_vacation(request):
    if request.method == 'POST':
        form = creationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/vacations/all')
    else:
        # Get the currently logged-in User.
        user = get_user(request)
        # Provide User as initial data to the form
        form = creationForm(initial={'author': user})

    return render(request, 'creationForm.html', {'form': form})

Relevant documentation:

ModelForm - Providing initial values

django.contrib.auth.get_user


问:
How to know the latest view controller in the view stack
Is there a way to know the current viewController in the memory. I am in a NSObject subclass which is being called from multiple view controllers. I do not want to add an extra parameter and pass it to my NSObject subclass. Is there any UIApplication method which I can call in my NSObject class to get the latest view controller in the memory.</p>

答:
No, because you're misunderstanding how view controllers work.  View controllers control a view.  That's it.  While a view may usually take up the entire screen, it doesn't have to.  For example, an iPad app with a split view controller and a visible UIPopoverController actually has (at least) 4 visible views all controlled by different view controllers.  There's the UISplitViewController and it's main content area, there's the UIViewController controlling the left ("master") area of the split view controller, another UIViewController controller the right ("detail") area of the split view controller, and a fourth view controller for controlling the contents of the popover.

Which one of those would you say is the "latest view controller"?

And the correct answer would be: none.

ContentLicense: CC BY-SA 3.0


答:
You are explicitly defeating the purpose of Generics, which implicitly specializes your generic class with Object type argument. In this case, you're defeating type-safety and setter method on the raw type Generic will be unchecked in compile-time, due to late binding. Compiler simply does not know at compile time what type of value is passed into setter method, as there is no type checking.

You should always try not to use raw type specialization in your Generic classes, unless it is really must to do.

Title: What is an Unchecked Call in Java?


问:
Using unaccent in tsvector trigger
I would like to use postgresql's unaccent contrib package in my tsvector column. I have successfully installed the package using create extension unaccent, and have checked that it works. I had set up a trigger to automatically update the tsvector column,

```<code>CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
ON artists FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(tsv_name, 'pg_catalog.simple', name);
</code>```

and then set the tsv_name column on all existing rows using the following

```<code>UPDATE artists SET tsv_name = (to_tsvector('simple', coalesce(name, '')));
</code>```

I thought that I'd be able to incorporate the unaccent package by simply replacing name by unaccent(name) in the above code, but that's throwing a syntax error in the create trigger code. How can I fix this to ensure that the tsvector column uses unaccented characters?

答:
I know this is a really old ticket, but along with @ErwinBrandstetter 's incredible answer (https://stackoverflow.com/a/11007216/5261969) and some PostgreSQL doc reading (https://www.postgresql.org/docs/9.3/functions-textsearch.html), I finally figured this out.

This is what my migration looks like (using Rails 5.2):

    # Erwin's wrapper code
    connection.execute(<<-EOSQL)
      CREATE OR REPLACE FUNCTION public.immutable_unaccent(regdictionary, text)
        RETURNS text LANGUAGE c IMMUTABLE STRICT AS
        '$libdir/unaccent', 'unaccent_dict';
    EOSQL

    connection.execute(<<-EOSQL)
      CREATE OR REPLACE FUNCTION public.f_unaccent(text)
        RETURNS text LANGUAGE sql IMMUTABLE STRICT AS
      $func$
      SELECT public.immutable_unaccent(regdictionary 'unaccent', $1)
      $func$;
    EOSQL

    # new trigger using f_unaccent
    connection.execute(<<-EOSQL)
      CREATE TRIGGER artists_name_tsvector_update BEFORE INSERT OR UPDATE
      OF name ON artists FOR EACH ROW EXECUTE PROCEDURE
      tsvector_update_trigger(
        tsv_name, 'public.f_unaccent(name)', name
      );

      UPDATE artists SET tsv_name = (to_tsvector('public.f_unaccent(name)', name));
    EOSQL
```

<p>This update allows users to search with special characters or not to yield the same results (e.g "Ønders" and "Onders" search query both return the correct artist.)</p>

<p>Note: I am also using <code>I18n.transliterate</code> to localize the incoming query param.</p>

<p><strong>Updated - upon running tests, I found that my UPDATE code was incorrect, so I had to alter my code to get it working. I'll keep the above in case it helps someone</strong></p>

<p>Updated migration using @EvanCarroll 's answer https://stackoverflow.com/a/50595181/5261969 - I couldn't figure out how to get the update trigger to stop complaining using Erwin's code. :/</p>

<pre class="lang-rb prettyprint-override"><code># create extension unaccent
    connection.execute(<<-EOSQL)
      CREATE TEXT SEARCH CONFIGURATION f_unaccent ( COPY = simple );
      ALTER TEXT SEARCH CONFIGURATION f_unaccent
        ALTER MAPPING FOR hword, hword_part, word
        WITH unaccent, simple;
    EOSQL

    # create updated trigger using unaccent for tsv_name
    # update existing tsv_names
    connection.execute(<<-EOSQL)
      CREATE TRIGGER artists_name_tsvector_update BEFORE INSERT OR UPDATE
      OF name ON artists FOR EACH ROW EXECUTE PROCEDURE
      tsvector_update_trigger(
        tsv_name, 'public.f_unaccent', name
      );

      UPDATE artists SET tsv_name = (to_tsvector('public.f_unaccent', name));
    EOSQL
</code>```

Title: Using unaccent in tsvector trigger

Body:
I would like to use postgresql's unaccent contrib package in my tsvector column. I have successfully installed the package using create extension unaccent, and have checked that it works. I had set up a trigger to automatically update the tsvector column,

CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
ON artists FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(tsv_name, 'pg_catalog.simple', name);

and then set the tsv_name column on all existing rows using the following

UPDATE artists SET tsv_name = (to_tsvector('simple', coalesce(name, '')));

I thought that I'd be able to incorporate the unaccent package by simply replacing name by unaccent(name) in the above code, but that's throwing a syntax error in the create trigger code. How can I fix this to ensure that the tsvector column uses unaccented characters?

Body:
I know this is a really old ticket, but along with @ErwinBrandstetter 's incredible answer (https://stackoverflow.com/a/11007216/5261969) and some PostgreSQL doc reading (https://www.postgresql.org/docs/9.3/functions-textsearch.html), I finally figured this out.

This is what my migration looks like (using Rails 5.2):

    # Erwin's wrapper code
    connection.execute(<<-EOSQL)
      CREATE OR REPLACE FUNCTION public.immutable_unaccent(regdictionary, text)
        RETURNS text LANGUAGE c IMMUTABLE STRICT AS
        '$libdir/unaccent', 'unaccent_dict';
    EOSQL

    connection.execute(<<-EOSQL)
      CREATE OR REPLACE FUNCTION public.f_unaccent(text)
        RETURNS text LANGUAGE sql IMMUTABLE STRICT AS
      $func$
      SELECT public.immutable_unaccent(regdictionary 'unaccent', $1)
      $func$;
    EOSQL

    # new trigger using f_unaccent
    connection.execute(<<-EOSQL)
      CREATE TRIGGER artists_name_tsvector_update BEFORE INSERT OR UPDATE
      OF name ON artists FOR EACH ROW EXECUTE PROCEDURE
      tsvector_update_trigger(
        tsv_name, 'public.f_unaccent(name)', name
      );

      UPDATE artists SET tsv_name = (to_tsvector('public.f_unaccent(name)', name));
    EOSQL

This update allows users to search with special characters or not to yield the same results (e.g "Ønders" and "Onders" search query both return the correct artist.)

Note: I am also using I18n.transliterate to localize the incoming query param.

Updated - upon running tests, I found that my UPDATE code was incorrect, so I had to alter my code to get it working. I'll keep the above in case it helps someone

Updated migration using @EvanCarroll 's answer https://stackoverflow.com/a/50595181/5261969 - I couldn't figure out how to get the update trigger to stop complaining using Erwin's code. :/

# create extension unaccent
    connection.execute(<<-EOSQL)
      CREATE TEXT SEARCH CONFIGURATION f_unaccent ( COPY = simple );
      ALTER TEXT SEARCH CONFIGURATION f_unaccent
        ALTER MAPPING FOR hword, hword_part, word
        WITH unaccent, simple;
    EOSQL

    # create updated trigger using unaccent for tsv_name
    # update existing tsv_names
    connection.execute(<<-EOSQL)
      CREATE TRIGGER artists_name_tsvector_update BEFORE INSERT OR UPDATE
      OF name ON artists FOR EACH ROW EXECUTE PROCEDURE
      tsvector_update_trigger(
        tsv_name, 'public.f_unaccent', name
      );

      UPDATE artists SET tsv_name = (to_tsvector('public.f_unaccent', name));
    EOSQL


问:
Cannot prepare proper labels in Matplotlib
I have very simple code:

```<code>from matplotlib import dates
import matplotlib.ticker as ticker
my_plot=df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90)
</code>```

I've got:

but I would like to have fewer labels on X axis. To do this I've add:

```<code>my_plot.xaxis.set_major_locator(ticker.MaxNLocator(12))
</code>```

It generates fewer labels but values of labels have wrong values (=first of few labels from whole list)
What am I doing wrong?

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  (YYYY-MM)

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

答:
I think there is a compatibility issue with Pandas plots and Matplotlib formatters.

With the following code:

```<code>df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
for l in labels:
    if i % 3 == 0:
        label = labels[i]
        i += 1
        new_labels.append(label)
    else:
        label = ''
        i += 1
        new_labels.append(label)
ax.set_xticklabels(new_labels)
plt.show()
</code>```

You get this chart:

But I notice that this is grouped by month instead of by day. It may not be what you wanted.

Adding the day component to the string 'Day' messes up the chart as there seems to be too many boxes.

```<code>df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m-%d')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
for l in labels:
    if i % 15 == 0:
        label = labels[i]
        i += 1
        new_labels.append(label)
    else:
        label = ''
        i += 1
        new_labels.append(label)
ax.set_xticklabels(new_labels)
plt.show()
</code>```

The for loop creates the tick labels every as many periods as desired. In the first chart they were set every 3 months. In the second one, every 15 days.

If you would like to see less grid lines:

```<code>df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m-%d')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
new_locs = list()
for l in labels:
    if i % 3 == 0:
        label = labels[i]
        loc = locs[i]
        i += 1
        new_labels.append(label)
        new_locs.append(loc)
    else:
        i += 1
ax.set_xticks(new_locs)
ax.set_xticklabels(new_labels)
ax.grid(axis='y')
plt.show()
</code>```

I've read about x_compat in Pandas plot in order to apply Matplotlib formatters, but I get an error when trying to apply it. I'll give it another shot later.

Old unsuccesful answer

The tick labels seem to be dates. If they are set as datetime in your dataframe, you can:

```<code>months = mdates.MonthLocator(1,4,7,10) #Choose the months you like the most
ax.xaxis.set_major_locator(months)
</code>```

Otherwise, you can let Matplotlib know they are dates by:

```<code>ax.xaxis_date()
</code>```

Your comment:

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  *(YYYY-MM) *

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

Based on your comment in italic above, I would use reg_Date as the input and the following lines:

```<code>days = mdates.DayLocator(interval=3)
daysFmt = mdates.DateFormatter('%Y-%m') #to format display
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(daysFmt)
</code>```

I forgot to mention that you will need to:

```<code>import matplotlib.dates as mdates
</code>```

Does this work?

Body:
I have very simple code:

from matplotlib import dates
import matplotlib.ticker as ticker
my_plot=df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90)

I've got:

but I would like to have fewer labels on X axis. To do this I've add:

my_plot.xaxis.set_major_locator(ticker.MaxNLocator(12))

It generates fewer labels but values of labels have wrong values (=first of few labels from whole list)
What am I doing wrong?

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  (YYYY-MM)

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

Body:
I think there is a compatibility issue with Pandas plots and Matplotlib formatters.

With the following code:

df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
for l in labels:
    if i % 3 == 0:
        label = labels[i]
        i += 1
        new_labels.append(label)
    else:
        label = ''
        i += 1
        new_labels.append(label)
ax.set_xticklabels(new_labels)
plt.show()

You get this chart:

But I notice that this is grouped by month instead of by day. It may not be what you wanted.

Adding the day component to the string 'Day' messes up the chart as there seems to be too many boxes.

df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m-%d')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
for l in labels:
    if i % 15 == 0:
        label = labels[i]
        i += 1
        new_labels.append(label)
    else:
        label = ''
        i += 1
        new_labels.append(label)
ax.set_xticklabels(new_labels)
plt.show()

The for loop creates the tick labels every as many periods as desired. In the first chart they were set every 3 months. In the second one, every 15 days.

If you would like to see less grid lines:

df = pd.read_csv('lt_stream-1001-full.csv', header=0, encoding='utf8')
df['reg_date'] = pd.to_datetime(df['reg_date'] , format='%Y-%m-%d %H:%M:%S')
df.set_index('reg_date', inplace=True)
df_h = df.resample(rule='H').mean()
df_h['Day']=df_h.index.strftime('%Y-%m-%d')
print(df_h)
f, ax = plt.subplots()
my_plot = df_h.boxplot(by='Day',figsize=(12,5), showfliers=False, rot=90, ax=ax)
locs, labels = plt.xticks()
i = 0
new_labels = list()
new_locs = list()
for l in labels:
    if i % 3 == 0:
        label = labels[i]
        loc = locs[i]
        i += 1
        new_labels.append(label)
        new_locs.append(loc)
    else:
        i += 1
ax.set_xticks(new_locs)
ax.set_xticklabels(new_labels)
ax.grid(axis='y')
plt.show()

I've read about x_compat in Pandas plot in order to apply Matplotlib formatters, but I get an error when trying to apply it. I'll give it another shot later.

Old unsuccesful answer

The tick labels seem to be dates. If they are set as datetime in your dataframe, you can:

months = mdates.MonthLocator(1,4,7,10) #Choose the months you like the most
ax.xaxis.set_major_locator(months)

Otherwise, you can let Matplotlib know they are dates by:

ax.xaxis_date()

Your comment:

I have add additional information:

I've forgoten to show what is inside DataFrame.
I have three columns:
 reg_Date - datetime64 (index)
 temperature - float64
 Day - date converted from reg_Date to string, it looks like '2017-10'  *(YYYY-MM) *

Box plot group date by 'Day' and I would like to show values 'Day" as a label but not all values
, for example every third one.

Based on your comment in italic above, I would use reg_Date as the input and the following lines:

days = mdates.DayLocator(interval=3)
daysFmt = mdates.DateFormatter('%Y-%m') #to format display
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(daysFmt)

I forgot to mention that you will need to:

import matplotlib.dates as mdates

Does this work?


Title: How to convert pixels stored in a list into an image with python?

Body:
pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

I have a bunch of pixels stored in the list and now I want to convert it to an image. How can I turn that list into an image? Thank you

Body:
Here's how to do it using OpenCV. By default, OpenCV uses Numpy arrays to display images so you can simply convert the list into a <class 'numpy.ndarray'>.

Result:

import numpy as np
import cv2

pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

# Convert to ndarray
img = np.array(pix).astype(np.uint8)

# Save image
cv2.imwrite('img.png', img)

# Display image
cv2.imshow('img', img)
cv2.waitKey()


问:
Invoke Lambda function from AWS DataPipeline
Is there a way to invoke a Lambda function from AWS DataPipeline? Looking at the activities available, there isn't a direct way to invoke a lambda from DataPipeline.</p>

答:
Technically speaking, you would use a shellCommandActivity to do this but this isn't the right service for what I think the use case is. You may be more interested in step functions.
https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html</p>


问:
can we use order by clause with group by
Hi
   I am using following query --

```<code>select * from table_name order by status desc
</code>```

It shows the desired result with all records,but as n when i use following query -

```<code>select * from table_name group by category order by status desc
</code>```

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....

答: It is because you're using group by. Order by doesn't change the result set itself, but changes the order of rows.

Body:
Hi
   I am using following query --

select * from table_name order by status desc

It shows the desired result with all records,but as n when i use following query -

select * from table_name group by category order by status desc

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....


问:
React .map not re-rendering
I'm building a sorting algorithm visualizer, and in my return, I'm creating divs to represent vertical bars, in animatedBubbleSort() I'm swapping values in the state array on a timeout, the array IS being sorted, but what I expected to happen was that the .map function would be re-rendered each time the state is changed with updateArray(). But the .map function does not re-fire at all. </p>

```<code>import React, { useState } from "react";
import "../styles/App.css";
import { Header } from "./Header";

export default function SortingVisualizer(props) {
    const LOWER_BOUND = 5;
    const UPPER_BOUND = 200;
    const ARRAY_SIZE = 200;

const [array, updateArray] = useState(fillArrayWithRandomValues);

// returns a random number between bounds inclusive
function randomNumberBetweenBounds() {
    return Math.floor(Math.random() * UPPER_BOUND) + LOWER_BOUND;
}

// fills array with random values
function fillArrayWithRandomValues() {
    let tempArray = [];
    for (let i = 0; i < ARRAY_SIZE; i++) {
        tempArray.push(randomNumberBetweenBounds());
    }
    return tempArray;
}

function animatedBubbleSort() {
    let tempArr = array;
    let len = tempArr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (tempArr[j] > tempArr[j + 1]) {
                let tmp = tempArr[j];
                tempArr[j] = tempArr[j + 1];
                tempArr[j + 1] = tmp;
                setTimeout(() => {
                    updateArray(tempArr);
                }, 300 * i);
            }
        }
    }
}

return (
    <div>
        <Header bubbleSort={animatedBubbleSort} />
        <div className="array-container">
            {array.map((value, idx) => {
                return (
                    <div
                        style={{ height: `${value * 2}px` }}
                        className="array-bar"
                        key={idx}
                    ></div>
                );
            })}
        </div>
    </div>
);
</code>```

<p>}</p>

答:
It's because you're using the index of the elements in the array as the key. React uses key to decide which elements to rerender; because your keys are always in the same order, React won't update anything. Try:

```<code>{array.map((value) => {
    return (
        <div
            style={{ height: `${value * 2}px` }}
            className="array-bar"
            key={value}
        ></div>
    );
})}
</code>```

See https://reactjs.org/docs/lists-and-keys.html#keys for more, specifically the following:

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

Title: React .map not re-rendering

Body:
I'm building a sorting algorithm visualizer, and in my return, I'm creating divs to represent vertical bars, in animatedBubbleSort() I'm swapping values in the state array on a timeout, the array IS being sorted, but what I expected to happen was that the .map function would be re-rendered each time the state is changed with updateArray(). But the .map function does not re-fire at all.

import React, { useState } from "react";
import "../styles/App.css";
import { Header } from "./Header";

export default function SortingVisualizer(props) {
    const LOWER_BOUND = 5;
    const UPPER_BOUND = 200;
    const ARRAY_SIZE = 200;

const [array, updateArray] = useState(fillArrayWithRandomValues);

// returns a random number between bounds inclusive
function randomNumberBetweenBounds() {
    return Math.floor(Math.random() * UPPER_BOUND) + LOWER_BOUND;
}

// fills array with random values
function fillArrayWithRandomValues() {
    let tempArray = [];
    for (let i = 0; i < ARRAY_SIZE; i++) {
        tempArray.push(randomNumberBetweenBounds());
    }
    return tempArray;
}

function animatedBubbleSort() {
    let tempArr = array;
    let len = tempArr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (tempArr[j] > tempArr[j + 1]) {
                let tmp = tempArr[j];
                tempArr[j] = tempArr[j + 1];
                tempArr[j + 1] = tmp;
                setTimeout(() => {
                    updateArray(tempArr);
                }, 300 * i);
            }
        }
    }
}

return (

            {array.map((value, idx) => {
                return (
                    <div
                        style={{ height: `${value * 2}px` }}
                        className="array-bar"
                        key={idx}
                    >

                );
            })}

);

}

Body:
It's because you're using the index of the elements in the array as the key. React uses key to decide which elements to rerender; because your keys are always in the same order, React won't update anything. Try:

{array.map((value) => {
    return (
        <div
            style={{ height: `${value * 2}px` }}
            className="array-bar"
            key={value}
        ></div>
    );
})}

See https://reactjs.org/docs/lists-and-keys.html#keys for more, specifically the following:

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.


问:
aws lambda function and correspond IAM role for stop and start EC2 instance in CloudFormation
I'm trying to launch a scheduled instance which will be stopped and start at a specified time in each day (in AWS CloudFormation template).
it's my IAM role and policy that I defined for the lambda function:

```<code>RootRole:
Type: 'AWS::IAM::Role'
Properties:
  AssumeRolePolicyDocument:
    Version: 2012-10-17
    Statement:
    - Effect: Allow
      Action:
       - logs:CreateLogGroup
       - logs:CreateLogStream
       - logs:PutLogEvents

      Resource: arn:aws:logs:*:*:*
    - Effect: Allow
      Action:
      - ec2:Start*
      - ec2:Stop*
      Resource: "*"
</code>```

when I create a stack, it return an error in the console(CREATE_FAILED) and the status reason is:

Has prohibited field Resource (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: 3094b9eb-9f45-4763-8f21-9c3f2496fc52)

And after this error all the services related to this role are failed by this error:

The following resource(s) failed to create: [InternetGateway, SNSTopicNameCreate, LambdaInvocationsAlarm, RootRole, VPC, LambdaInvocationsAnomalyDetector]. . Rollback requested by user.

答:
Your policy appears to be confusing the "Assume Role" section, which defines the Trust Policy, with the "Policy" section, which grants permissions to the IAM Role.

Try this:

```<code>AWSTemplateFormatVersion: 2010-09-09

Resources:
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: Lambda-Role
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: AllowLogsAndEC2
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: arn:aws:logs:*:*:*
              - Effect: Allow
                Action:
                - ec2:StartInstances
                - ec2:StopInstances
                Resource: "*"
</code>```

Typically, the easiest way to create a policy is to copy an existing policy and make minor changes, or use the policy editor in the IAM console to generate most of what you want. You can then tweak the policy it provides.

Body:
I'm trying to launch a scheduled instance which will be stopped and start at a specified time in each day (in AWS CloudFormation template).
it's my IAM role and policy that I defined for the lambda function:

RootRole:
Type: 'AWS::IAM::Role'
Properties:
  AssumeRolePolicyDocument:
    Version: 2012-10-17
    Statement:
    - Effect: Allow
      Action:
       - logs:CreateLogGroup
       - logs:CreateLogStream
       - logs:PutLogEvents

      Resource: arn:aws:logs:*:*:*
    - Effect: Allow
      Action:
      - ec2:Start*
      - ec2:Stop*
      Resource: "*"

when I create a stack, it return an error in the console(CREATE_FAILED) and the status reason is:

Has prohibited field Resource (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: 3094b9eb-9f45-4763-8f21-9c3f2496fc52)

And after this error all the services related to this role are failed by this error:

The following resource(s) failed to create: [InternetGateway, SNSTopicNameCreate, LambdaInvocationsAlarm, RootRole, VPC, LambdaInvocationsAnomalyDetector]. . Rollback requested by user.

Body:
Your policy appears to be confusing the "Assume Role" section, which defines the Trust Policy, with the "Policy" section, which grants permissions to the IAM Role.

Try this:

AWSTemplateFormatVersion: 2010-09-09

Resources:
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: Lambda-Role
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: AllowLogsAndEC2
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: arn:aws:logs:*:*:*
              - Effect: Allow
                Action:
                - ec2:StartInstances
                - ec2:StopInstances
                Resource: "*"

Typically, the easiest way to create a policy is to copy an existing policy and make minor changes, or use the policy editor in the IAM console to generate most of what you want. You can then tweak the policy it provides.


问:
jQuery UI Sortable without Ajax (submit order-data using regular form)
I'm using jQuery UI Sortable and I would like to submit the order of items using regular form (so, instead of using Ajax, I would like to have a form with submit button - when I submit the form, it will send the order-data to server-side).

Currently I have:

<form id="frmExample" method="post">

1

2

3

4

    <button id="btnSubmit" type="submit">Submit</button>
</form>

答:
Here is a basic example that halts the submission of the form just for this example snippet. Your code would not e.preventDefault().

$(function() {
  var $sortable = $("#sortable").sortable({
    update: function(event, ui) {
      var $data = $(this).sortable('toArray');
      $("#position").val(JSON.stringify($data));
    }
  });
  $sortable.disableSelection();
  $("#position").val(JSON.stringify($sortable.sortable("toArray")));
  $("#frmExample").submit(function(e) {
    e.preventDefault();
    console.log("Form Submit, position:", $("#position").val());
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form ul {
  list-style: none;
  padding: 0;
  width: 150px;
}

form ul li {
  padding: .2em;
  margin-bottom: -1px;
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<form id="frmExample" method="post">

Item 1

Item 2

Item 3

Item 4

  <input type="hidden" name="position" id="position" />
  <button id="btnSubmit" type="submit">Submit</button>
</form>```

Body:
Here is a basic example that halts the submission of the form just for this example snippet. Your code would not e.preventDefault().

$(function() {
  var $sortable = $("#sortable").sortable({
    update: function(event, ui) {
      var $data = $(this).sortable('toArray');
      $("#position").val(JSON.stringify($data));
    }
  });
  $sortable.disableSelection();
  $("#position").val(JSON.stringify($sortable.sortable("toArray")));
  $("#frmExample").submit(function(e) {
    e.preventDefault();
    console.log("Form Submit, position:", $("#position").val());
  });
});

form ul {
  list-style: none;
  padding: 0;
  width: 150px;
}

form ul li {
  padding: .2em;
  margin-bottom: -1px;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="frmExample" method="post">
  <ul id="sortable">
    <li id="task_1" class="ui-state-default">Item 1</li>
    <li id="task_2" class="ui-state-default">Item 2</li>
    <li id="task_3" class="ui-state-default">Item 3</li>
    <li id="task_4" class="ui-state-default">Item 4</li>
  </ul>
  <input type="hidden" name="position" id="position" />
  <button id="btnSubmit" type="submit">Submit</button>
</form>


问:
Converting WPF to .XBAP doesn't work!
Hello
 I want to integrate WPF with ASP.NET project I read about this problem, and I know I have to convert the WPF project to .xbap I tried to follow this http://www.xbap.org/tutorial.html on two projects :

1- as a test on a WPFBrowserApplication : the result was
 just a .xbap file when i run it a local host web page opened with " Hello XBAP "

but I want to convert the following WPF app

2- on this one https://msmvps.com/blogs/theproblemsolver/archive/2009/12/23/rehosting-the-workflow-designer-in-wf4.aspx I put the
 good from Step 4 it just gave me thr " Hello XBAP" on the WPF grid and run as a desktop app
even I changed every thing in xaml and xaml.cs from Window to Page

I really need help. Thank you

答:
You can try this tutorial:

http://www.charlespetzold.com/blog/2006/11/120718.html

Title: Converting WPF to .XBAP doesn't work!


问:
China not showing on chloropleth map in R
I am trying to make a simple chloropleth map in r. While I can create the map, China does not show up at all, leaving a giant hole in the map. I have checked that China is in the data, so I am not sure what is going on. here is my code:

```<code>library(tidyverse)
library(maps)

## load data ----
data(country.map, package = "choroplethrMaps")
co2 <- read.csv("https://raw.githubusercontent.com/acircleda/tmp/master/food emissions.csv") %>%
  mutate(region = tolower(country))

data<-co2 %>%
  left_join(country.map, by="region") %>%
  group_by(region) %>% mutate(
    c02sum = sum(co2_emmission)
  )

ggplot(data, aes(long, lat, group = group))+
  geom_polygon(aes(fill = c02sum), color = "white", na="grey80")+
  scale_fill_viridis_c(option = "C")

##no china

china<-data %>% filter(region == "china") ##china is in the data
</code>```

答:
The problem is your data join. What you actually want, is a right_join. NAs can be coloured in your scale_fill functions with na.value = .

library(tidyverse)
library(maps)

## load data ----
data(country.map, package = "choroplethrMaps")
co2 <- read_csv('your.csv')%>%
  mutate(region = tolower(country))

data <- co2 %>%
  right_join(country.map, by="region") %>% #critical
  group_by(region)

ggplot(data, aes(long, lat, group = group))+
  geom_polygon(aes(fill = co2_emmission), na.rm ="grey80") +
  scale_fill_continuous(na.value = 'grey')
```

Body:
I am trying to make a simple chloropleth map in r. While I can create the map, China does not show up at all, leaving a giant hole in the map. I have checked that China is in the data, so I am not sure what is going on. here is my code:

library(tidyverse)
library(maps)

## load data ----
data(country.map, package = "choroplethrMaps")
co2 <- read.csv("https://raw.githubusercontent.com/acircleda/tmp/master/food emissions.csv") %>%
  mutate(region = tolower(country))

data<-co2 %>%
  left_join(country.map, by="region") %>%
  group_by(region) %>% mutate(
    c02sum = sum(co2_emmission)
  )

ggplot(data, aes(long, lat, group = group))+
  geom_polygon(aes(fill = c02sum), color = "white", na="grey80")+
  scale_fill_viridis_c(option = "C")

##no china

china<-data %>% filter(region == "china") ##china is in the data


问:
Keycloak x509 client authentication configuration
I need some tips in order to understand how to perform a client authentication with x509 certificate against Keycloak.

We have a simple Spring Boot Web App (API REST) into a Kubernetes cluster.
This Web App is public exsposed through an API Gateway (Ambassador) and currently protected with a browser redirection to the Keycloak login page where user can input his username and password.

However this is not what we want.
What is necessary for us is a client authentication (React Native Mobile App) where:

Mobile App try to call our Server API REST endpoints

Ambassador check for a valid access token and (if not) respond with a 403 http status (no browser redirection)

Mobile App then redirect to Keycloak in order to perform the authentication

Keycloak doesn't show username/password login page but, instead, Mobile App pass a x509 user certificate through its Browser.

Unfortunately I can't understand how to generate a valid and trusted x509 certificate with user data (info, roles ecc.) in order to get an access token from the IdP.

And ... how can IdP check and validate this client certificate? Is it necessary a Server certificate counterpart somewhere installed on Keycloak?

What's the correct form (ex with CURL) to pass the client certificate to keycloak?
Is it neccessary to pass also the private key and why?

答:
Please check the section X.509 Client Certificate User Authentication in section 6 of Keycloak Server Administration Guide, which describes:

how to enable and configure client certificate authentication in Wildfly and Keycloak

how to map certificate fields to user attributes

the client certificate authentication workflow with Keycloak/Wildfly (Keycloak container).


问:
Device selection disabled in Xcode 4, green light in organizer
I'm trying to test an app on a 3G with 4.2.1 installed, but I'm unable to select the device in the scheme in Xcode (4.0.2).  The app is built on the 4.3 SDK, but targeted for deployment to 4.2.

Any ideas?

答: Try restarting Xcode with the device already connected. I also experience this problem on some installations of Xcode.</p>


问:
GetRef's memory consumption (garbage collection) changed with KB4525236
We experience out-of-memory issues after installing KB4525236 on our Windows 2016 Servers/Windows 10 Clients. This security fix seems to have changed the moment when memory is garbage collected when calling a function through GetRef.

Pré KB4525236

Each instance created in a function called through GetRef got garbage collected as soon as the instance variable was set to nothing

Post KB4525236

Each instance created in a function called through GetRef remains in memory and is garbage collected only when the entire function completes. When creating instances in a loop, this can quickly add up and lead to an out-of-memory, especially in a 32-bit process.

Questions

we can not find anything relevant online so we would like to get confirmation from others experiencing the same issue.

EDIT scratch that: this is the same issue but with no solution as of yet

(vbscript.dll class_terminate bug since KB4524570 (November 12, 2019) Windows 10 1903)

if anyone can verify and knows a workable solution, that would be awesome.

POC

following script running on a device with KB4525236 installed shows the difference in garbage collecting when

called directly: the second instance gets created only after the first instance is destroyed (this is our desired behavior)

called through GetRef: the second instance gets created before the first instance is destroyed so whe have two instances using memory.

save as: KB4525236.vbs

run as: wscript KB4525236.vbs

```<code>Dim Name, Log

Class IDummyInstance
  Dim FName
  Sub Class_Initialize
    FName = Name
    Log = Log & "Initialize " & FName & VbNewLine
  End Sub
  Sub Class_Terminate
    Log = Log & "Terminate " & FName & vbNewLine
  End Sub
End Class

Sub CreateDestroyTwoInstances
  Dim DummyInstance
  Name = "First Instance"
  Set DummyInstance = New IDummyInstance
  Set DummyInstance = Nothing
  Name = "Second Instance"
  Set DummyInstance = New IDummyInstance
  Set DummyInstance = Nothing
End Sub

Log = "(1) Direct Call :" & VbNewLine
Call CreateDestroyTwoInstances

Log = VbNewLine & Log & "(2) GetRef Call :" & vbNewLine
Set GetRefCall = GetRef ("CreateDestroyTwoInstances")
Call GetRefCall

MsgBox Log
</code>```

答:
Since I don't have a solution or an official source explaining the issue I was waiting the bounty to expire.

I've come up with an unpleasant workaround that can help until the bug is fixed.

The workaround is not to use any local variable to hold object instances in procedures that might be executed through GetRef.

Instead of implicit or explicit variables, using a local (or global if there's no recursion) dictionary object to hold object instances and calling them through that dictionary works.

```<code>Sub CreateDestroyTwoInstances
  Dim Refs
  Set Refs = CreateObject("Scripting.Dictionary")
  Name = "First Instance"
  Refs.Add "DummyInstance", New IDummyInstance
  ' Call Refs("DummyInstance").DoSomething()
  Refs.Remove "DummyInstance"
  Name = "Second Instance"
  Refs.Add "DummyInstance", New IDummyInstance
  ' Call Refs("DummyInstance").DoSomething()
  Refs.Remove "DummyInstance"
End Sub
</code>```

It seems to be worth using if you have a script that is not too complicated.

Body:
We experience out-of-memory issues after installing KB4525236 on our Windows 2016 Servers/Windows 10 Clients. This security fix seems to have changed the moment when memory is garbage collected when calling a function through GetRef.

Pré KB4525236

Each instance created in a function called through GetRef got garbage collected as soon as the instance variable was set to nothing

Post KB4525236

Each instance created in a function called through GetRef remains in memory and is garbage collected only when the entire function completes. When creating instances in a loop, this can quickly add up and lead to an out-of-memory, especially in a 32-bit process.

Questions

we can not find anything relevant online so we would like to get confirmation from others experiencing the same issue.

EDIT scratch that: this is the same issue but with no solution as of yet

(vbscript.dll class_terminate bug since KB4524570 (November 12, 2019) Windows 10 1903)

if anyone can verify and knows a workable solution, that would be awesome.

POC

following script running on a device with KB4525236 installed shows the difference in garbage collecting when

called directly: the second instance gets created only after the first instance is destroyed (this is our desired behavior)

called through GetRef: the second instance gets created before the first instance is destroyed so whe have two instances using memory.

save as: KB4525236.vbs

run as: wscript KB4525236.vbs

Dim Name, Log

Class IDummyInstance
  Dim FName
  Sub Class_Initialize
    FName = Name
    Log = Log & "Initialize " & FName & VbNewLine
  End Sub
  Sub Class_Terminate
    Log = Log & "Terminate " & FName & vbNewLine
  End Sub
End Class

Sub CreateDestroyTwoInstances
  Dim DummyInstance
  Name = "First Instance"
  Set DummyInstance = New IDummyInstance
  Set DummyInstance = Nothing
  Name = "Second Instance"
  Set DummyInstance = New IDummyInstance
  Set DummyInstance = Nothing
End Sub

Log = "(1) Direct Call :" & VbNewLine
Call CreateDestroyTwoInstances

Log = VbNewLine & Log & "(2) GetRef Call :" & vbNewLine
Set GetRefCall = GetRef ("CreateDestroyTwoInstances")
Call GetRefCall

MsgBox Log

Body:
Since I don't have a solution or an official source explaining the issue I was waiting the bounty to expire.

I've come up with an unpleasant workaround that can help until the bug is fixed.

The workaround is not to use any local variable to hold object instances in procedures that might be executed through GetRef.

Instead of implicit or explicit variables, using a local (or global if there's no recursion) dictionary object to hold object instances and calling them through that dictionary works.

Sub CreateDestroyTwoInstances
  Dim Refs
  Set Refs = CreateObject("Scripting.Dictionary")
  Name = "First Instance"
  Refs.Add "DummyInstance", New IDummyInstance
  ' Call Refs("DummyInstance").DoSomething()
  Refs.Remove "DummyInstance"
  Name = "Second Instance"
  Refs.Add "DummyInstance", New IDummyInstance
  ' Call Refs("DummyInstance").DoSomething()
  Refs.Remove "DummyInstance"
End Sub

It seems to be worth using if you have a script that is not too complicated.


问:
Don't emit until some other observable has emitted, then emit all previous values
I'm looking for a way to buffer values of an observable until some other observable has emitted, but then emit all the previous values. Something like skipUntil, if skipUntil also emitted skipped values as soon as the second observable emitted.</p>

```<code>--a--b----c-----d---e--- (source)
-----------1------------- (other1)
------------abc-d---e----(desired output)
</code>```

答:
You can use bufferWhen:</p>

```<code>import { fromEvent, interval } from 'rxjs';
import { bufferWhen } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const buffered = clicks.pipe(bufferWhen(() =>
  interval(1000 + Math.random() * 4000)
));
buffered.subscribe(x => console.log(x));
</code>```

Body:
I'm looking for a way to buffer values of an observable until some other observable has emitted, but then emit all the previous values. Something like skipUntil, if skipUntil also emitted skipped values as soon as the second observable emitted.

--a--b----c-----d---e--- (source)
-----------1------------- (other1)
------------abc-d---e----(desired output)

Body:
You can use bufferWhen:

import { fromEvent, interval } from 'rxjs';
import { bufferWhen } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const buffered = clicks.pipe(bufferWhen(() =>
  interval(1000 + Math.random() * 4000)
));
buffered.subscribe(x => console.log(x));


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答: I think your code is being run at a sufficiently high level of the call stack and it's blended with UI code. If this is really the case, you could return null in the catch block. However, if you are writing reusable code, you should refactor it so that it doesn't contain UI manipulation and handle the exception at a higher level in the call stack.

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

OwnerDisplayName: Mehrdad Afshari


问:
Order a list in Flutter
What's the best approach to order a list on a ListView (or similar widget)?

I'm using table_calendar to display events on the calendar so I need to order the different events on one day by date (this field is already created for each event).

答:
Example below shows how to order a list of dates in ascending or descending:

```<code>final list = [
      DateTime.now(),
      DateTime.now().subtract(Duration(days: 1)),
      DateTime.now().subtract(Duration(days: 2)),
      DateTime.now().subtract(Duration(days: 3)),
    ];

    //Order By Descending
    list.sort((a, b) => a.isAfter(b) ? -1 : 1);

    //Order By Ascending
    list.sort((a, b) => a.isBefore(b) ? -1 : 1);

    for (var item in list) {
      print(item);
    }
</code>```

sort can be used in any collection, use in your list of events comparing the date field

Title: Order a list in Flutter

Body:
Example below shows how to order a list of dates in ascending or descending:

final list = [
      DateTime.now(),
      DateTime.now().subtract(Duration(days: 1)),
      DateTime.now().subtract(Duration(days: 2)),
      DateTime.now().subtract(Duration(days: 3)),
    ];

    //Order By Descending
    list.sort((a, b) => a.isAfter(b) ? -1 : 1);

    //Order By Ascending
    list.sort((a, b) => a.isBefore(b) ? -1 : 1);

    for (var item in list) {
      print(item);
    }

sort can be used in any collection, use in your list of events comparing the date field